diff --git a/.agents/skills/actor-lifecycle-triage/SKILL.md b/.agents/skills/actor-lifecycle-triage/SKILL.md new file mode 100644 index 0000000000..e3d86a3b63 --- /dev/null +++ b/.agents/skills/actor-lifecycle-triage/SKILL.md @@ -0,0 +1,117 @@ +--- +name: actor-lifecycle-triage +description: Finds why an Agent Substrate actor is stuck in a state, CRASHED, refuses a lifecycle call, or is RUNNING but not answering. Use after the troubleshoot skill picks the actor lifecycle area, or directly when one actor's state looks wrong. Reads the actor, its worker and atelet, matches the symptom against the reference tables, and reports the root cause with evidence. Read-only. +--- + +# Actor lifecycle triage + +Follow the rules, fact collection, and report format in the +[troubleshoot](../troubleshoot/SKILL.md) skill. This skill covers one actor. + +Actor states are RESUMING, RUNNING, SUSPENDING, SUSPENDED, CRASHED, DELETING, +and REVERTING. New actors start SUSPENDED. A resume call (or an incoming +request through `atenet-router`) moves an actor to RUNNING, and it stays +RUNNING until explicitly suspended. The only way out of CRASHED is +`kubectl ate revert actor`, which resets the actor to SUSPENDED at its last +uploaded snapshot. + +## 1. Read the actor + +```bash +kubectl ate get actor -a -o yaml +``` + +Note: + +- `status.state`, and how long it has stayed there. +- `status.crash.message` and `status.crash.crashTime`, if CRASHED. +- `status.workerAssignment`: the worker pod, its namespace and pool (cleared + when the actor is CRASHED). +- `status.assignedNode` (kept even when CRASHED). + +## 2. Check the worker and atelet + +A resume, suspend, or revert calls `atelet` on the assigned node, which calls +the worker. Check `atelet` on `status.assignedNode`, and check the worker pod +if `status.workerAssignment` is set: + +```bash +kubectl -n get pod -o wide +kubectl -n ate-system get pods -l app=atelet -o wide --field-selector spec.nodeName= +kubectl ate get workers +``` + +When the actor is CRASHED, `status.workerAssignment` is empty, while +`status.assignedNode` still names the node for the `atelet` lookup. + +For worker-caused crashes (pod gone, worker restarted, or a sandbox crash +reported by the worker), find the former worker in `ate-api-server` logs near +`status.crash.crashTime` under `Releasing actor from a worker whose pod is +gone`, `Releasing actor from a restarted worker`, or `Worker reported an actor +crash`. Each line carries a `worker` attribute (the Worker name, which is also +the worker pod's UID): + +```bash +# If the Worker still exists, this gives its pod name and namespace: +kubectl ate get worker -o yaml +# If the worker pod was deleted, look up its events by UID. +# Kubernetes keeps events for about an hour by default, so an empty result for +# an older crash does not rule out eviction or deletion: +kubectl get events -A --field-selector involvedObject.uid= +``` + +For other crashes (`atelet` errors, draining or ineligible workers, snapshot +state conflicts), those three lines do not appear. Use `status.assignedNode` to +check `atelet` logs and inspect `ate-api-server` logs for the actor near +`status.crash.crashTime`. + +A missing worker pod or an unready `atelet` on the node causes most stuck and +crashed actors. Note what you find for step 3. + +## 3. Match the symptom + +Pick the section of [references/states.md](references/states.md) that matches +the actor: + +| Symptom | Section | +|---|---| +| Stuck in RESUMING, SUSPENDING, REVERTING, or DELETING | [Stuck in a transition](references/states.md#stuck-in-a-transition) | +| CRASHED | [CRASHED](references/states.md#crashed), by `status.crash.message` | +| Call refused with `FailedPrecondition` | [Call refused](references/states.md#call-refused) | +| RUNNING, but requests or logs show it is not working | [RUNNING but not working](references/states.md#running-but-not-working) | + +Run the Confirm check before calling a root cause. Treat state-changing steps +like `revert` and `resume` as recommendations and confirm with the user before +running them. These logs are useful across all cases: + +```bash +# ate-api-server runs every lifecycle call and logs each one as `Handle RPC`, +# with the request and the error. It runs more than one replica. +kubectl -n ate-system logs -l app=ate-api-server -c ate-api-server \ + --since=1h --tail=-1 --prefix | grep '' +# The actor's lifecycle events on its current worker. Works only while RUNNING. +kubectl ate logs actor -a --source=lifecycle +``` + +## 4. Known gaps + +- If an application process exits while its sandbox stays up (#2972), or a + process inside the sandbox or guest is OOM-killed without killing the sandbox + (#3615), the actor stays RUNNING (see #2211). +- A dead sandbox or microVM, or one killed for exceeding its memory limit, is + usually reported as CRASHED, but the actor stays RUNNING when reporting + fails: on gVisor if the worker could not watch the sandbox (`Cannot watch the + sandbox, a crash will go unreported`), or on either runtime if reporting + fails for 5 minutes (`Failed to report the actor crashed`). +- `ate-api-server` does not retry failed lifecycle calls. After a retriable + error, the actor stays in its transition state until the caller retries. +- During an `atelet` rollout, a resume or suspend hitting that node fails with + `Unavailable` (or `Internal` with `no atelet pod found on node` while no pod + exists). Running actors are not affected. +- `kubectl ate logs actor` streams only while the actor is RUNNING. For + earlier logs, use the cluster's log backend. + +## 5. Report + +Use the report format in [troubleshoot](../troubleshoot/SKILL.md#4-report), +with Area: actor lifecycle. diff --git a/.agents/skills/actor-lifecycle-triage/references/states.md b/.agents/skills/actor-lifecycle-triage/references/states.md new file mode 100644 index 0000000000..08b665859d --- /dev/null +++ b/.agents/skills/actor-lifecycle-triage/references/states.md @@ -0,0 +1,71 @@ +# Actor states + +Each table starts from what the user sees. Run the Confirm check before you +name the root cause. Ask the user to confirm before running any command that +changes actor state. + +In the commands, ``, ``, and `` come from +the actor's `status.workerAssignment` and `status.assignedNode`. A crash clears +`status.workerAssignment` while keeping `status.assignedNode`; see +[step 2](../SKILL.md#2-check-the-worker-and-atelet) for how to find `` +or fall back to `atelet` logs when the actor is CRASHED. The atelet pod is from +`kubectl -n ate-system get pods -l app=atelet -o wide --field-selector +spec.nodeName=`. + +## Stuck in a transition + +Lifecycle calls move an actor into RESUMING, SUSPENDING, REVERTING, or DELETING +while in progress. If a step fails with a retriable error, the actor stays in +that state and retrying the same call resumes from where it stopped. + +| Symptom | Root cause | Confirm | Fix | +|---|---|---|---| +| RESUMING or SUSPENDING, and the call returned `Unavailable` or `Internal` | A call to atelet failed with a retriable error, for example while atelet or the worker restarted | The `Handle RPC` line for the call in ate-api-server's log has `while calling atelet` or `no atelet pod found on node` in its error; the atelet pod on the node isn't Ready, or is new | Once atelet is Ready, retry the call | +| RESUMING, SUSPENDING or REVERTING, and the worker pod is gone | The worker pod was deleted. ate-controller then deletes its Worker, which moves the actor to CRASHED | `kubectl -n get pod ` returns NotFound | Wait for CRASHED with `worker pod went away while hosting the actor`, then follow that row | +| DELETING for minutes | A delete step failed, such as stopping the sandbox on atelet or detaching volumes | ate-api-server log for the actor; the delete call returned an error | Retry delete | + +## CRASHED + +`status.crash.message` gives the reason. When a crash happens during a +lifecycle operation, `ate-api-server` prefixes the message with ` +failed: ` (for example `resume failed: assigned worker is draining` or `suspend +failed: atelet Checkpoint: ...`). Crashes while RUNNING have no prefix. Match +the table below on the text after any ` failed: ` prefix. + +Mitigation is `kubectl ate revert actor -a ` followed by +resume. Revert resets the actor to SUSPENDED at its last uploaded snapshot, +discarding any work after that snapshot, and can disrupt the actor's expected +behavior. + +| Symptom (`status.crash.message`, after any ` failed: ` prefix) | Root cause | Confirm | Mitigation | +|---|---|---|---| +| `worker pod went away while hosting the actor` | The worker pod was deleted or evicted while it hosted the actor: a WorkerPool rollout, node upgrade, scale-down or Spot preemption | `ate-api-server` log `Releasing actor from a worker whose pod is gone` near `crashTime` for ``; `kubectl get events -A --field-selector involvedObject.uid=` (events expire after about 1h, so empty output on an older crash does not rule out eviction) | Revert, then resume. To keep state through an eviction, the actor needs a SIGTERM handler that gets it suspended within 30 minutes; see [Eviction](../../../../docs/reference/api-guide.md#eviction) | +| `worker restarted while hosting the actor` | The worker process restarted, so its sandboxes are gone | `ate-api-server` log `Releasing actor from a restarted worker` for ``, `kubectl ate get worker -o yaml` for its pod, then RESTARTS and `kubectl -n logs --previous` | Revert, then resume. Use the previous log to find why the worker exited | +| `killed for exceeding its memory limit` (on gVisor, also `atelet Run:` / `atelet Restore:` containing that text) | The actor's gVisor sandbox or microVM exceeded its memory limit and the worker killed it | `ate-api-server` log `Worker reported an actor crash` near `crashTime` (while RUNNING), or `Setting Actor to crashed due to Atelet error` if killed during gVisor `Run` or `Restore` | Raise the actor's memory limit or investigate memory growth, then revert and resume | +| `gVisor sandbox exited`, or starts with `cloud-hypervisor exited:` or `virtiofsd exited:` | The sandbox or microVM process exited while the actor was RUNNING | `ate-api-server` log `Worker reported an actor crash` for ``; worker pod logs (`Sandbox died` on gVisor, `Micro-VM died` on microVM) | Inspect the worker logs for why the sandbox exited, then revert and resume | +| `assigned worker is draining` | A resume was retried after its worker started draining | `ate-api-server` log `Assigned worker is draining; crashing actor` near `crashTime` (its `worker` attribute is `/`); match that pod in `kubectl ate get workers` to confirm DRAINING | Revert, then resume. It will be assigned to another worker | +| `assigned worker no longer satisfies the actor's placement constraints` | The actor's worker selector changed between a failed resume and its retry | Compare the actor's worker selector with the eligible WorkerPools | Revert, then resume | +| Starts with `node holding the actor's latest snapshot no longer exists` | The last suspend was async, and the node holding its snapshot went away before the upload finished | `kubectl get node ` returns NotFound | Revert, then resume. The async snapshot is lost. Use `kubectl ate suspend actor --mode=sync` when a snapshot has to survive its node | +| `node holding the actor's local snapshot is unknown`, `actor has no local snapshot`, `actor has no durable snapshot`, or `atelet's snapshot state conflicts with the actor's record` | The actor's snapshot record is in an inconsistent state that retries cannot fix | ate-api-server log for the actor near `crashTime` | Revert, then resume. File an issue with the log, as this should not happen in normal operation | +| Starts with `atelet :`, such as `atelet Restore:` | atelet or the worker returned a non-retriable error for that call (on gVisor, if it includes `killed for exceeding its memory limit`, see the memory-limit row above) | ate-api-server log `Setting Actor to crashed due to Atelet error`; `kubectl -n ate-system logs -c atelet --since=1h \| grep ''` | Check the atelet error, then revert and resume. If it crashes the same way again, file an issue with the atelet log | + +## Call refused + +`ate-api-server` checks the current state before running a call. Resuming a +RUNNING actor or suspending a SUSPENDED one is a no-op. + +| Symptom | Root cause | Confirm | Fix | +|---|---|---|---| +| Resume fails with `AssignWorker prerequisite not met ... want ACTOR_STATE_SUSPENDED` | Actor must be SUSPENDED to resume (it is CRASHED or in a transition) | `status.state` | CRASHED: revert first. In a transition: wait, or see [Stuck in a transition](#stuck-in-a-transition) | +| Resume fails with `the actor is larger than every eligible worker` | The actor's resource limits exceed the capacity of every worker matching its selector | Compare the actor's resource limits with eligible WorkerPools | Lower the actor's resource limits, or add a WorkerPool with larger workers | +| Suspend fails with `MarkSuspending prerequisite not met ... want ACTOR_STATE_RUNNING` | Actor must be RUNNING to suspend | `status.state` | RESUMING: wait for RUNNING. CRASHED: revert, which already leaves it SUSPENDED | +| Revert fails with `is not in a revertable state` | Revert accepts RUNNING, CRASHED, or SUSPENDED with a snapshot that is still only on the node | `status.state` | If the actor is SUSPENDED and its snapshot is already uploaded, there is nothing to revert | +| Tag fails with `must be ACTOR_STATE_SUSPENDED to be tagged` | Actor must be SUSPENDED to tag | `status.state` | Suspend the actor first | + +## RUNNING but not working + +| Symptom | Root cause | Confirm | Fix | +|---|---|---|---| +| Requests fail or hang, and the actor's processes are gone | An app process exited while the sandbox stayed up (#2972), a process inside the sandbox or guest was OOM-killed (#3615), or a dead sandbox failed to report CRASHED (#2211) | `kubectl ate logs actor -a ` for app exit or errors; `kubectl -n logs ` for `Sandbox has no processes left while the actor is hosted`, `Cannot watch the sandbox, a crash will go unreported`, or `Failed to report the actor crashed` | Share the logs with the actor's owner, or revert and resume | +| Requests reach the actor, and it returns errors | Error in the actor's application | `kubectl ate logs actor -a ` shows the errors | Give the logs to the actor's owner | +| Requests fail before they reach the actor | Networking | The router's response or the client error | Go back to [troubleshoot](../../troubleshoot/SKILL.md) step 2 | diff --git a/.agents/skills/triage-issues/SKILL.md b/.agents/skills/triage-issues/SKILL.md index a2f283261a..64754fc2d3 100644 --- a/.agents/skills/triage-issues/SKILL.md +++ b/.agents/skills/triage-issues/SKILL.md @@ -79,8 +79,8 @@ Do not guess. ### Status labels -Apply only when clearly appropriate. Never add `wontfix`, `duplicate`, or `invalid` -yourself — those are maintainer decisions. +Apply only when clearly appropriate. Never add `ready-for-pr`, `wontfix`, `duplicate`, +or `invalid` yourself, as those are maintainer decisions. | Label | When | |---|---| @@ -108,10 +108,10 @@ Keywords: "Design discussion", "Investigate", "Explore options", "Identify what" "Measure", "Research". The clearest way to distinguish `kind/design` from `kind/feature`: -- **`kind/feature`**: you could open a PR today — the *what* and *how* are known. -- **`kind/design`**: a decision or investigation must happen first; a PR cannot be written yet. +- **`kind/feature`**: the *what* and *how* are already clear enough to implement once a maintainer adds `ready-for-pr`. +- **`kind/design`**: a decision or investigation must happen first before implementation can be scoped. -When in doubt, ask: *"Could someone reasonably start coding this issue right now?"* +When in doubt, ask: *"Is the design settled well enough that someone could implement this once approved?"* If yes → `kind/feature`. If no → `kind/design`. **4. Is it a code quality improvement with no behavior change?** diff --git a/.agents/skills/troubleshoot/SKILL.md b/.agents/skills/troubleshoot/SKILL.md new file mode 100644 index 0000000000..910e1406fc --- /dev/null +++ b/.agents/skills/troubleshoot/SKILL.md @@ -0,0 +1,100 @@ +--- +name: troubleshoot +description: Starting point for troubleshooting an Agent Substrate installation. Use when an operator or support engineer reports a problem with Substrate, such as an actor that is stuck or CRASHED, failing requests, or a failed install or upgrade. Collects the facts every area needs, picks the area skill to follow, checks the repo's issues for a known match, and writes the report. Read-only. +--- + +# Troubleshoot + +Find the area the problem is in, follow that area's skill, and report the root +cause with evidence. + +Rules: + +1. **Read-only.** For cluster and cloud commands, run only read-only queries + (`kubectl` `get`/`describe`/`logs`/`top`, `kubectl ate` `get`/`logs`, and + `gcloud` `describe`/`list`). Ask before anything that changes cluster or + actor state, including restarts and `kubectl ate` lifecycle commands + (`resume`, `suspend`, `revert`, `delete`). +2. **No `kubectl ate` access.** `ate-api-server` enforces the installation's + access policy on every call. If `kubectl ate` fails with `permission denied`, + give the user the commands to hand to someone with access and keep going + with what `kubectl` can read. +3. **Cite evidence.** Back each conclusion with the user's error, a log line, + or an object field. Say when you are guessing. +4. **Protect customer data.** The upstream repo is public. Replace atespace and + actor names, IPs, and hostnames before drafting a GitHub issue. + +## 1. Collect facts + +Ask the user for what's missing: + +- The exact error text, or the state that looks wrong. +- Atespace and actor (if one is involved) and the time window. +- Scope: one actor, one WorkerPool, or every actor. +- What changed right before it started (install, upgrade, node pool change, or + new policy). + +Then check the cluster: + +```bash +# Substrate version, from the image tags. A from-source install has +# digest-only images and no tag. +kubectl -n ate-system get deploy,ds \ + -o 'custom-columns=NAME:.metadata.name,IMAGE:.spec.template.spec.containers[*].image' +kubectl version +kubectl get nodes -o wide +kubectl -n ate-system get pods -o wide +kubectl -n podcertificate-controller-system get pods +kubectl get workerpool -A +kubectl ate get workers +``` + +## 2. Pick the area + +| What the user sees | Skill | +|---|---| +| An actor is stuck in a state, CRASHED, refuses a lifecycle call, or is RUNNING but not answering | [actor-lifecycle-triage](../actor-lifecycle-triage/SKILL.md) | + +There is no dedicated skill yet for other areas (install, upgrade, networking, +auth, storage, runtimes, or observability). For those, check that the pods in +`ate-system` are Running and Ready, read their logs for the time window, and +continue to step 3. + +## 3. Check known issues + +Search the repo's issues and merged PRs with the exact error text or log line, +then with the symptom in plain words: + +```bash +gh issue list --repo agent-substrate/substrate --state all --search '""' +gh pr list --repo agent-substrate/substrate --state merged --search '""' \ + --json number,title,mergeCommit +gh issue view --repo agent-substrate/substrate --comments +``` + +Classify what you find: + +- **Match:** same symptom and root cause. If a merged PR fixes it, fetch + upstream tags, run + `git tag --list 'v*' --contains --sort=v:refname | head -1` + to find the first release containing the fix, and compare it to the installed + version. +- **Similar:** same symptom, but a different trigger, version, or root cause. + Note what differs. +- **None:** if nothing matches, list the searches you ran. + +Don't comment on or open issues without approval. + +## 4. Report + +``` +Area: +Root cause: +User saw: +Cluster: , Substrate +Evidence: log lines and object fields, with their source +Ruled out: what you checked and cleared +Known issue: # match | similar | none found; fixed in , installed +Confidence: high | medium | low +Next steps: commands or a workaround, and who has to run them +``` diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000..07bc1fa043 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,21 @@ +# Copyright 2026 The Agent Substrate 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. + +# The benchmarking runner images build with the repo root as context. +# Keep the clone metadata, local environments and cluster secrets out of it. +.git +.ate-dev-env.sh +**/venv +**/.venv +**/__pycache__ diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index 7509dc0cee..5e88fecfcd 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -1,7 +1,9 @@ + -Why is this needed? (Or link the issue. Open one first for features, API, install or CI changes.) +Why is this needed? + Fixes # diff --git a/.github/scripts/stage-gvisor-assets-kind.sh b/.github/scripts/stage-gvisor-assets-kind.sh new file mode 100755 index 0000000000..9a317a4cfb --- /dev/null +++ b/.github/scripts/stage-gvisor-assets-kind.sh @@ -0,0 +1,80 @@ +#!/usr/bin/env bash + +# Copyright 2026 The Agent Substrate 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. + +set -o errexit -o nounset -o pipefail + +ROOT="$(git rev-parse --show-toplevel)" +KUBECTL_CONTEXT="${KUBECTL_CONTEXT:-kind-kind}" +BUCKET_NAME="${BUCKET_NAME:-ate-snapshots}" +ARCH="$(go env GOARCH)" +CACHE_DIR="${ROOT}/bin/gvisor-assets/${ARCH}" + +kubectl --context="${KUBECTL_CONTEXT}" -n ate-system wait \ + --for=condition=complete job/rustfs-bucket-init --timeout=120s + +node="$(kubectl --context="${KUBECTL_CONTEXT}" -n ate-system get pod \ + -l app=rustfs --field-selector=status.phase=Running \ + -o jsonpath='{.items[0].spec.nodeName}')" +cluster_ip="$(kubectl --context="${KUBECTL_CONTEXT}" -n ate-system get service rustfs \ + -o jsonpath='{.spec.clusterIP}')" +aws_image="$(kubectl --context="${KUBECTL_CONTEXT}" -n ate-system get job rustfs-bucket-init \ + -o jsonpath='{.spec.template.spec.containers[0].image}')" + +endpoint="http://${cluster_ip}:9000" +if [[ "${cluster_ip}" == *:* ]]; then + endpoint="http://[${cluster_ip}]:9000" +fi +aws_cli=( + docker run --rm -i + --network "container:${node}" + -e AWS_ACCESS_KEY_ID=rustfsadmin + -e AWS_SECRET_ACCESS_KEY=rustfsadmin + -e AWS_REGION=us-east-1 + -e "AWS_ENDPOINT_URL=${endpoint}" + "${aws_image}" +) + +mkdir -p "${CACHE_DIR}" +assets="$( + kubectl --context="${KUBECTL_CONTEXT}" get sandboxconfig gvisor-default \ + -o go-template="{{range \$i, \$v := .spec.versions}}{{if ne \$v.state \"Disabled\"}}{{\$asset := index (index \$v.assets \"${ARCH}\") \"gvisor\"}}{{\$i}}{{\"\\t\"}}{{\$v.name}}{{\"\\t\"}}{{\$asset.url}}{{\"\\t\"}}{{\$asset.sha256}}{{\"\\n\"}}{{end}}{{end}}" +)" +if [[ -z "${assets}" ]]; then + echo "error: gvisor-default has no enabled ${ARCH} assets" >&2 + exit 1 +fi +while IFS=$'\t' read -r index version url sha; do + object="${url#gs://}" + if [[ "${object}" == "${url}" ]]; then + echo "error: gVisor asset URL is not a gs:// URL: ${url}" >&2 + exit 1 + fi + name="${url##*/}" + file="${CACHE_DIR}/${sha}-${name}" + if [[ ! -f "${file}" ]] || [[ "$(sha256sum "${file}" | cut -d ' ' -f 1)" != "${sha}" ]]; then + curl --fail --location --retry 3 "https://storage.googleapis.com/${object}" -o "${file}" + fi + if [[ "$(sha256sum "${file}" | cut -d ' ' -f 1)" != "${sha}" ]]; then + echo "error: checksum mismatch for ${url}" >&2 + exit 1 + fi + + key="gvisor-assets/${ARCH}/${sha}/${name}" + "${aws_cli[@]}" s3 cp - "s3://${BUCKET_NAME}/${key}" < "${file}" + kubectl --context="${KUBECTL_CONTEXT}" patch sandboxconfig gvisor-default --type=json \ + -p="[{\"op\":\"replace\",\"path\":\"/spec/versions/${index}/assets/${ARCH}/gvisor/url\",\"value\":\"s3://${BUCKET_NAME}/${key}\"}]" + echo "Staged ${version}/${ARCH}/gvisor" +done <<< "${assets}" diff --git a/.github/workflows/govulncheck.yaml b/.github/workflows/govulncheck.yaml index 3bd2c96b9b..8451ad5e64 100644 --- a/.github/workflows/govulncheck.yaml +++ b/.github/workflows/govulncheck.yaml @@ -36,6 +36,8 @@ jobs: - id: govulncheck uses: golang/govulncheck-action@032d45514ae346b1db93c04b0c90b841c370344f # v1.1.0 with: + # Scan with the Go we build with. The default, stable, overrides go-version-file. + go-version-input: "" go-version-file: go.mod go-package: ./... work-dir: ${{ matrix.work-dir }} diff --git a/.github/workflows/pr-workflow.yaml b/.github/workflows/pr-workflow.yaml index 4e6c2d3b1c..3a213e2926 100644 --- a/.github/workflows/pr-workflow.yaml +++ b/.github/workflows/pr-workflow.yaml @@ -17,7 +17,7 @@ on: pull_request: merge_group: push: - branches: [main, release-1.0] + branches: [main, 'release-[0-9]+.[0-9]+'] schedule: # Weekly run on the default branch keeps the micro-VM asset cache warm (GitHub # evicts caches idle for 7 days). The push-to-main run populates the cache that @@ -28,10 +28,13 @@ on: permissions: contents: read # Superseded pushes to a pull request are cancelled; every commit that lands on -# main still gets its own full run. +# main or a release branch still gets its own full run. concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: ${{ github.event_name == 'pull_request' }} +# Caches are only saved from main. PRs and the merge queue restore main's +# caches and save nothing, their entries are only visible to their own ref and +# would evict main's under the 10GB repo limit. jobs: run-tests: runs-on: ubuntu-latest @@ -51,15 +54,13 @@ jobs: uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: 'go.mod' - # setup-go keys its cache on go.sum with no fallback, so a PR that - # changes go.sum starts cold. Restore the latest main build instead. + # setup-go saves from any ref, and only when go.sum changes cache: false - name: Restore Go build cache uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: | ~/.cache/go-build - ~/.cache/golangci-lint ~/go/pkg/mod key: unit-go-${{ runner.os }}-${{ github.sha }} restore-keys: unit-go-${{ runner.os }}- @@ -97,8 +98,9 @@ jobs: --jsonfile "${ARTIFACTS}/junittool.json" \ --format pkgname-and-test-fails --format-hide-empty-pkg \ -- -race ./... - - name: Cache cargo - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + - name: Restore cargo cache + id: cargo-cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: | ~/.cargo/registry/index @@ -107,14 +109,29 @@ jobs: cmd/dataplane/envoy/dynamic-modules/target key: cargo-${{ runner.os }}-${{ hashFiles('cmd/dataplane/envoy/dynamic-modules/Cargo.lock') }} restore-keys: cargo-${{ runner.os }}- + # the runner image already has clang and libclang, apt-get can stall for minutes - name: dynamic module tests run: | - sudo apt-get update -qq - sudo apt-get install -y -qq --no-install-recommends clang libclang-dev + if ! compgen -G '/usr/lib/llvm-*/lib/libclang-*.so.*' >/dev/null || ! command -v clang >/dev/null; then + sudo apt-get update -qq + sudo apt-get install -y -qq --no-install-recommends clang libclang-dev + fi hack/test-dynamic-modules.sh + - name: Save cargo cache + if: ${{ github.ref == 'refs/heads/main' && steps.cargo-cache.outputs.cache-hit != 'true' }} + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: | + ~/.cargo/registry/index + ~/.cargo/registry/cache + ~/.cargo/git/db + cmd/dataplane/envoy/dynamic-modules/target + key: ${{ steps.cargo-cache.outputs.cache-primary-key }} # Root-gated tests (overlay mounts, whiteout mknod, trusted.* xattrs, ...) # skip for the unprivileged runner user above; rerun the packages that # contain them (any test importing internal/roottest) under sudo. + - name: Verify goldens + run: hack/verify-goldens.sh - name: root-gated tests env: ROOT_JUNIT_FILE: ${{ github.workspace }}/_artifacts/root.xml @@ -135,11 +152,42 @@ jobs: name: test-results-unit path: ${{ env.ARTIFACTS }} if-no-files-found: error + - name: Save Go build cache + if: ${{ !cancelled() && github.ref == 'refs/heads/main' }} + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: | + ~/.cache/go-build + ~/go/pkg/mod + key: unit-go-${{ runner.os }}-${{ github.sha }} + # Separate from run-tests so the two run in parallel. + verify: + runs-on: ubuntu-latest + timeout-minutes: 30 + steps: + - name: Checkout + uses: actions/checkout@fbc6f3992d24b796d5a048ff273f7fcc4a7b6c09 # v5.1.0 + with: + # proto-breaking.sh compares against a release tag. + fetch-depth: 0 + - name: Setup Go + uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 + with: + go-version-file: 'go.mod' + cache: false + # the tools verify builds (go tool -n) and golangci-lint results + - name: Restore Go build cache + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: | + ~/.cache/go-build + ~/.cache/golangci-lint + ~/go/pkg/mod + key: verify-go-${{ runner.os }}-${{ github.sha }} + restore-keys: verify-go-${{ runner.os }}- - name: verify run: hack/verify-all.sh - name: Save Go build cache - # Main only, so PRs restore the latest main build rather than each - # storing its own copy. if: ${{ !cancelled() && github.ref == 'refs/heads/main' }} uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: @@ -147,7 +195,7 @@ jobs: ~/.cache/go-build ~/.cache/golangci-lint ~/go/pkg/mod - key: unit-go-${{ runner.os }}-${{ github.sha }} + key: verify-go-${{ runner.os }}-${{ github.sha }} verify-migrations: if: github.event_name == 'pull_request' || github.event_name == 'merge_group' runs-on: ubuntu-latest @@ -162,23 +210,44 @@ jobs: env: BASE_REF: ${{ github.base_ref || github.event.merge_group.base_ref }} run: hack/verify/postgresql-migrations.sh "origin/${BASE_REF#refs/heads/}" - # One kind cluster exercises BOTH runtimes. Free x86-64 ubuntu-latest runners - # expose /dev/kvm (with a udev rule), so create-kind-cluster.sh mounts it and the - # micro-VM (kata + cloud-hypervisor) sandbox class works alongside gVisor. - # Each preview mode runs on a fresh cluster with agentgateway. - # The default install retains the required e2e-test check name. - e2e-test: - name: ${{ matrix.preview == 'off' && 'e2e-test' || 'e2e-test (preview)' }} + # Free x86-64 ubuntu-latest runners expose /dev/kvm (with a udev rule), so + # create-kind-cluster.sh mounts it and the micro-VM (kata + cloud-hypervisor) + # sandbox class works alongside gVisor. + # + # Each matrix entry is an independent job on a fresh cluster with + # agentgateway, so the steps below run for every sandbox class, IP family and + # preview mode. The e2e-test job below reports the required checks. + e2e: + name: >- + ${{ format('e2e ({0}, {1}{2}{3})', matrix.dataplane, matrix.sandbox, + matrix.ip_family != 'ipv4' && format(', {0}', matrix.ip_family) || '', + matrix.preview == 'on' && ', preview' || '') }} runs-on: ubuntu-latest - # Cluster bring-up, image builds and two sequential lanes; generous, but far - # short of the six-hour platform default a hung lane would otherwise consume. + # Cluster bring-up, image builds and one lane; generous, but far short of + # the six-hour platform default a hung lane would otherwise consume. timeout-minutes: 120 strategy: fail-fast: false matrix: dataplane: ['agentgateway'] + # "off" enables no unrelated preview features; "on" enables all of them. preview: ['off', 'on'] + sandbox: [gvisor, microvm] + # IPv4 and IPv6-only run presubmit. Dual-stack joins them after merge + # and on the weekly schedule. + ip_family: >- + ${{ fromJSON( + (github.event_name != 'pull_request' && github.event_name != 'merge_group') + && '["ipv4", "ipv6", "dual"]' + || '["ipv4", "ipv6"]' + ) }} + exclude: + - preview: 'on' + ip_family: ipv6 + - preview: 'on' + ip_family: dual env: + IP_FAMILY: ${{ matrix.ip_family }} E2E_ATENET_DATAPLANE: ${{ matrix.dataplane }} # Apply the e2e test component (short atelet snapshot delays) during the # control-plane install. @@ -187,26 +256,28 @@ jobs: # bundled Kubernetes Secrets provider with the control plane. Job-wide so # every ate-setup invocation in this job sees the same selection. ATE_CREDENTIAL_PROVIDER: '{"name":"k8s.io"}' - # Job-wide for the same reason. Empty is an explicit "no preview - # features", not an unset value. The e2e steps pass it to the suites as - # --preview, so tests of a disabled gate skip themselves (see - # internal/e2e/preview.go). - ATE_PREVIEW: ${{ matrix.preview == 'on' && 'ALL' || '' }} + # Job-wide for the same reason. The e2e steps pass it to the suites as + # --preview, so tests see the same gates as the install. + ATE_PREVIEW: >- + ${{ matrix.preview == 'on' && 'ALL' + || matrix.ip_family != 'ipv4' && 'ActorIPv6' + || '' }} # The suites' router client (internal/e2e/ingressauth.go). Only e2e # installs allowlist it, so the suites can reach actors through the # router's mTLS listeners. ATE_INGRESS_ALLOWED_SPIFFE_IDS: spiffe://cluster.local/ns/ate-e2e-router-client/sa/router-client - # Appended to the lane and artifact names: e2e-gvisor runs without - # preview features, e2e-gvisor-preview with them. - LANE_SUFFIX: ${{ matrix.preview == 'on' && '-preview' || '' }} - # E2E_JUNIT_FILE is set per step, not here: the lanes below share this - # job, so one job-level path would have each overwrite the last. + # The lane name is also used for its JUnit file. + LANE: >- + ${{ format('e2e-{0}{1}{2}', matrix.sandbox, + matrix.ip_family != 'ipv4' && format('-{0}', matrix.ip_family) || '', + matrix.preview == 'on' && '-preview' || '') }} ARTIFACTS: ${{ github.workspace }}/_artifacts # Cache the envoy-dataplane Rust build. Only main writes it, so PRs # share one copy instead of each storing their own. DOCKER_BUILD_FLAGS: >- --cache-from type=gha,scope=envoy-dataplane ${{ github.ref == 'refs/heads/main' && matrix.preview == 'off' + && matrix.sandbox == 'gvisor' && matrix.ip_family == 'ipv4' && '--cache-to type=gha,mode=max,scope=envoy-dataplane,ignore-error=true' || '' }} steps: - name: Checkout @@ -215,9 +286,8 @@ jobs: uses: actions/setup-go@b7ad1dad31e06c5925ef5d2fc7ad053ef454303e # v7.0.0 with: go-version-file: 'go.mod' - # Use the e2e cache below instead. setup-go's cache key is shared with - # run-tests, whose unit-test builds don't match ko's flags - # (CGO_ENABLED=0, -trimpath), so ko got no cache hits from it. + # ko's flags (CGO_ENABLED=0, -trimpath) don't match the unit test + # builds, so e2e has its own cache below cache: false - name: Restore Go build cache uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 @@ -245,9 +315,9 @@ jobs: for (const [key, value] of Object.entries(process.env)) { if (key.startsWith('ACTIONS_')) core.exportVariable(key, value); } - - name: Cache micro-VM assets + - name: Restore microVM assets id: microvm-assets - uses: actions/cache@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + uses: actions/cache/restore@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: # Assembling the assets (download kata-static + cloud-hypervisor) is # pinned by the SHA-256 digests in @@ -273,6 +343,18 @@ jobs: env: ATE_ATENET_DATAPLANE: ${{ matrix.dataplane }} run: go run ./cmd/ate-setup --kind deploy ate-system --rollout-timeout=300s + - name: Stage gVisor assets for IPv6-only CI + if: ${{ matrix.ip_family == 'ipv6' && matrix.sandbox == 'gvisor' }} + run: .github/scripts/stage-gvisor-assets-kind.sh + - name: Save microVM assets + if: >- + ${{ github.ref == 'refs/heads/main' && steps.microvm-assets.outputs.cache-hit != 'true' + && matrix.preview == 'off' && matrix.sandbox == 'microvm' + && matrix.ip_family == 'ipv4' }} + uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 + with: + path: bin/microvm-assets + key: ${{ steps.microvm-assets.outputs.cache-primary-key }} - name: Enable NFS # Load NFS kernel modules so in-cluster NFS server and CSI driver can run. run: | @@ -280,43 +362,29 @@ jobs: sudo modprobe nfsd || true - name: Install CSI NFS driver run: go run ./cmd/ate-setup --kind setup csi nfs - - name: Deploy micro-VM counter demo - run: go run ./cmd/ate-setup --kind deploy demo counter-microvm - - name: Deploy gVisor counter demo - run: go run ./cmd/ate-setup --kind deploy demo counter - - name: Deploy egress demos - # TestActorEgress in the networking suite builds its Actor from the egress - # ActorTemplate for the class under test, so both fixtures have to exist - # before their respective lane runs. The demo's actors trust the CA the - # gateway mints its leaves from. + # Deploy only the demos for the class under test. The suites build their + # actors from the counter and egress ActorTemplates for that class. The + # egress demo's actors trust the CA the gateway mints its leaves from. + - name: Deploy demos (${{ matrix.sandbox }}) + env: + DEMO_SUFFIX: ${{ matrix.sandbox == 'microvm' && '-microvm' || '' }} run: | - go run ./cmd/ate-setup --kind deploy demo egress - go run ./cmd/ate-setup --kind deploy demo egress-microvm + go run ./cmd/ate-setup --kind deploy demo "counter${DEMO_SUFFIX}" + go run ./cmd/ate-setup --kind deploy demo "egress${DEMO_SUFFIX}" - name: Trust local TLS origins in egress gateway run: hack/setup-e2e-egress-tls-kind.sh - # scale the idle sandbox class's demo pools to zero so each lane has the node - - name: Focus the node on gVisor - run: hack/e2e-focus-sandbox-class.sh gvisor - - name: Run E2E tests (gVisor) - env: - E2E_PARALLELISM: 8 - E2E_JUNIT_FILE: ${{ github.workspace }}/_artifacts/e2e-gvisor${{ env.LANE_SUFFIX }}.xml - run: hack/run-e2e-kind.sh -args --no-color --preview="${ATE_PREVIEW}" - - name: Focus the node on micro-VM - run: hack/e2e-focus-sandbox-class.sh microvm - - name: Run E2E tests (micro-VM) - # The same suites again, with every fixture repointed at its micro-VM - # variant by the single E2E_SANDBOX_CLASS knob (see internal/e2e/sandbox.go). + - name: Run E2E tests (${{ matrix.sandbox }}) + # E2E_SANDBOX_CLASS repoints every fixture at its micro-VM variant (see + # internal/e2e/sandbox.go). Empty selects gVisor. env: - E2E_SANDBOX_CLASS: microvm + E2E_SANDBOX_CLASS: ${{ matrix.sandbox == 'microvm' && 'microvm' || '' }} E2E_PARALLELISM: 8 - E2E_JUNIT_FILE: ${{ github.workspace }}/_artifacts/e2e-microvm${{ env.LANE_SUFFIX }}.xml + E2E_JUNIT_FILE: ${{ github.workspace }}/_artifacts/${{ env.LANE }}.xml run: hack/run-e2e-kind.sh -args --no-color --preview="${ATE_PREVIEW}" - # Every lane must have reported tests; a `-run` filter that stops matching - # otherwise leaves its lane green and empty. The set comes from the manifest - # each lane registers itself in, so adding a lane needs no change here, and - # run-e2e.sh refuses to run in CI without E2E_JUNIT_FILE. - - name: Require every lane to have run tests + # The lane must have reported tests; a `-run` filter that stops matching + # otherwise leaves it green and empty. run-e2e.sh registers the lane in the + # manifest, and refuses to run in CI without E2E_JUNIT_FILE. + - name: Require the lane to have run tests if: always() run: go -C tools/junittool run . verify -manifest "${ARTIFACTS}/expected-junit.txt" - name: Summarize test failures @@ -325,7 +393,7 @@ jobs: - name: Save Go build cache # Main only, so PRs restore the latest main build rather than each # storing its own copy. - if: ${{ !cancelled() && github.ref == 'refs/heads/main' && matrix.preview == 'off' }} + if: ${{ !cancelled() && github.ref == 'refs/heads/main' && matrix.preview == 'off' && matrix.sandbox == 'gvisor' && matrix.ip_family == 'ipv4' }} uses: actions/cache/save@0057852bfaa89a56745cba8c7296529d2fc39830 # v4.3.0 with: path: | @@ -336,7 +404,10 @@ jobs: if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4.6.2 with: - name: test-results-e2e-${{ matrix.dataplane }}${{ env.LANE_SUFFIX }} + name: >- + ${{ format('test-results-e2e-{0}-{1}{2}{3}', matrix.dataplane, matrix.sandbox, + matrix.ip_family != 'ipv4' && format('-{0}', matrix.ip_family) || '', + matrix.preview == 'on' && '-preview' || '') }} path: ${{ env.ARTIFACTS }} if-no-files-found: error - name: Dump diagnostics on failure @@ -357,3 +428,13 @@ jobs: kubectl --context kind-kind get pods -A -l ate.dev/worker-pool \ -o 'custom-columns=:.metadata.namespace,:.metadata.name' --no-headers 2>/dev/null \ | while read -r ns name; do dump "$ns" "$name"; done + # The required check, so the branch rules don't list each lane. Passes only + # when every lane passed. + e2e-test: + needs: e2e + if: ${{ !cancelled() }} + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - name: Require every e2e lane to pass + run: test "${{ needs.e2e.result }}" = success diff --git a/.validation-extensions.yaml b/.validation-extensions.yaml new file mode 100644 index 0000000000..70b286a618 --- /dev/null +++ b/.validation-extensions.yaml @@ -0,0 +1,56 @@ +# Copyright 2026 The Agent Substrate 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. + +# Custom validation rules for Agent Substrate. Each new format needs an +# exhaustive test in internal/apivalidationtest/doc.go +formats: + # Names of singleton resources + - name: ate-singleton-name + docs: This field must be "default" + # allow optional/required to cover "" for subfields + pattern: (^$|^default$) + message: must be "default" + + # HTTP probe paths + - name: ate-http-probe-path + docs: This field must be a valid HTTP path with valid escapes and no query or fragment components + # allow optional/required to cover "" for subfields + pattern: (^$|^/([A-Za-z0-9\-._~!$&'\(\)*+,;=:@/]|%[0-9A-Fa-f]{2})*$) + message: must be a valid HTTP path (RFC 3986) + + # Environment variable names + - name: ate-env-var-name + docs: This field must be a valid environment variable name + # allow optional/required to cover "" for subfields + pattern: (^$|^[ -<>-~]+$) + message: may contain any printable ASCII character except '=' + + # External volume storage IDs + - name: ate-volume-storage-id + docs: This field must not contain control characters other than tab, newline and carriage return + pattern: '^[^\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x9F]*$' + message: must not contain control characters + + # HTTP header names + - name: ate-http-header-name + docs: This field must be a valid HTTP header name (RFC 9110 token) + # allow optional/required to cover "" for subfields + pattern: (^$|^[-A-Za-z0-9!#$%&'*+.^_`|~]+$) + message: must be an HTTP header name + + # HTTP header values + - name: ate-http-header-value + docs: This field must be a valid HTTP field value (no control characters other than tab) + pattern: '^[^\x00-\x08\x0A-\x1F\x7F]*$' + message: must be a valid HTTP field value diff --git a/AGENTS.md b/AGENTS.md index 97e3f8aae6..c0b8ede95f 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -28,8 +28,8 @@ - Keep each PR to one change. Send refactors, cleanups and follow-ups as separate PRs. For how to batch small fixes, see "Optimizing PRs for review" in `CONTRIBUTING.md`. - Split a PR into commits that are easy to review in order. PRs are squash-merged, so only the branch `HEAD` needs to build and pass tests. -- Follow "Contribution process" in `CONTRIBUTING.md`: open an issue first for anything beyond a small fix, and search open PRs and issues before you start. -- Start the PR description with why the change is needed, or link the issue. Only write "Fixes #N" if the PR fully fixes it, and keep the description in sync with the final diff. +- Follow "Contribution process" in `CONTRIBUTING.md`: search open issues and PRs before you start, and do not open a PR (including a draft or a small fix) without an issue labeled `ready-for-pr`. +- Link the `ready-for-pr` issue in the PR description (`Fixes #N` only if the PR fully fixes it, otherwise `Part of #N`), explain why the change is needed, and keep the description in sync with the final diff. - Rebase onto upstream `main` before opening a PR, and don't merge main into your branch. This file may have changed there. Follow that version. - When updating a PR, keep rebases and other changes in separate pushes, so reviewers can see what changed: - To address review comments or test failures, push the fix without rebasing. @@ -112,7 +112,7 @@ The dev entry points are the scripts under `hack/` and the `cmd/ate-setup` insta ### Testing and Verification - **Run Unit Tests**: `go test -race ./...` - **Run E2E Tests**: `hack/run-e2e.sh` (Requires a cluster with Agent Substrate installed; `hack/run-e2e-kind.sh` for kind) -- **Run Linters and Verifiers**: `hack/verify-all.sh` (formatting, golangci-lint, boilerplate headers, licenses, go modules, generated code, and the metrics registry) +- **Run Linters and Verifiers**: `hack/verify-all.sh` runs every script in `hack/verify/` ## Code Style Guidelines @@ -155,7 +155,7 @@ See the [metric registry](docs/guides/observability.md#the-metric-registry) sect Agent Substrate is built for zero-trust, multi-tenant execution of untrusted actors. Preserve and extend these invariants when modifying the codebase (see `docs/security/security.md` and `docs/security/threat-model.md` for the full architecture): -- **Workload & Storage Isolation**: Actors run strictly inside `gVisor` (`cmd/ateworker-gvisor`) or `Cloud Hypervisor` microVM (`cmd/ateworker-microvm`) sandboxes; plain Linux containers are not supported. `atelet` scrubs actor directories across lifecycle transitions (`resetActorDirs`), and snapshots are stamped with `ActorSandboxRuntime` metadata and transferred via `cmd/objectstore-plugin`. +- **Workload & Storage Isolation**: Actors run strictly inside `gVisor` (`cmd/ateworker-gvisor`) or `Cloud Hypervisor` microVM (`cmd/ateworker-microvm`) sandboxes; plain Linux containers are not supported. `atelet` scrubs actor directories across lifecycle transitions (`cmd/atelet/internal/actordirs`), and snapshots are stamped with `ActorSandboxRuntime` metadata and transferred via `cmd/objectstore-plugin`. - **Component & Actor Identity (mTLS, JWTs, and JWKs)**: Inter-component communication uses mTLS backed by `cmd/podcertcontroller` (`podid`, `servicedns`, and `postgres` signers). Actor JWT signing (`internal/localjwtauthority`), verification (`internal/oidcjwt`), and key discovery (served via `cmd/ate-idp-server`) are built on the standard library's crypto packages. Extend those packages rather than adding `go-jose` or another JOSE library, so the code that decides whether a token is valid stays small and supports only the algorithms Substrate uses. - **Control-Plane Authentication & Authorization**: `ate-api-server` checks every Control RPC against an embedded OpenFGA model (`cmd/ateapi/internal/authz/model.fga`), always enforced. Every served unary RPC needs an entry in `defaultRPCPermissions` (`registry.go`): an RPC without one is denied, and a test fails the build. Access is granted per global scope and atespace through AccessPolicy (`kubectl ate access-policy`); the install's bootstrap owner is the shared `ate-client` ServiceAccount that `kubectl ate` uses. See `docs/guides/authorization.md` for roles and known gaps. Callers are authenticated via `SPIFFE` mTLS or configured OIDC `JWTProvider`s (`cmd/ateapi/internal/apiauthn`). - **Network Isolation, Ingress, & Egress**: `manifests/ate-install/ate-system-networkpolicies.yaml` enforces default-deny ingress across `ate-system`, and `cmd/atecontroller` reconciles per-`WorkerPool` `NetworkPolicy` objects. Actors run in private `/30` point-to-point veth network namespaces (`internal/ateworker/actornet`) with link-local blocking, policy-enforced DNS filtering (`internal/atunnel/dns`), and zero ambient credentials. Outbound traffic traverses `atunnel` to `atenet-egress`, which enforces per-actor `EgressPolicy` and injects credentials out-of-band via `cmd/credential-provider/kubernetes-secrets` (`k8s-credential-provider`) or actor JWT minting. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 5166b531d4..5c6266752c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -70,6 +70,9 @@ project](https://www.kubernetes.dev/docs/guide/pull-requests/#ai-guidance): > responses. If you do not engage directly with reviewers, the PR will be > closed. +In issues and design discussions, keep comments concise, verify any claims +yourself, and do not post unvetted or automated AI output. + ### Working hours We want to move quickly, but we also want to be respectful of each other's @@ -135,30 +138,51 @@ suspend or resume spends its time on such a cluster, follow ## Contribution process -This project is focused on iterating quickly but responsibly. This has -implications for contributors: - -1) Things move quickly, so PRs may need to be rebased or updated frequently. -Small PRs that are focused on a single issue or feature are easier to review -and update than large PRs that touch many different parts of the codebase. - -2) While we welcome new contributors, we do have priorities and many efforts in -flight. Small fixes and cleanups can go straight to a PR, but before you start anything -larger, please discuss it with us first. If there is an issue open, comment -there (and if not, open one). Before jumping into a task, please search open -PRs, so we are not duplicating work and wasting time. We want to be respectful -of everyone's time, and to make sure that your work is aligned with our goals -for the project. - -3) PRs which are not aligned with our priorities and goals may be closed -without extensive review. We are not trying to be discouraging, but we need to -make sure that we are focused on the most important work. - -4) When in doubt, communicate. We have GitHub, a mailing list, and Slack -channels, and we encourage you to use them. We also have regular community -meetings (via video calls), and you are welcome to attend those, too. If you -are unsure about something, please ask. It can save us all a lot of time and -effort. +Generating code is cheap now, while design and code review time are not. Driving +clear issue investigations and design discussions is also how contributors build +trust toward [Reviewer and Maintainer roles](GOVERNANCE.md), much more than +submitting a high volume of pull requests. + +To keep velocity high and focus on agreed priorities, we **require** issue +consensus before pull requests: + +1) **Discuss on an issue first.** Before starting work, search open issues and +PRs so you do not duplicate effort already in flight. If an issue exists, join +the discussion there, or open a new one. If you want to share prototype code +during discussion, link to a branch or diff on your fork instead of opening a +PR, to avoid unnecessary CI and review costs. + +2) **Wait for `ready-for-pr`.** Every PR must have an associated issue with the +[`ready-for-pr`](https://github.com/agent-substrate/substrate/issues?q=state%3Aopen%20label%3Aready-for-pr) +label, applied by a maintainer. Applying this label indicates consensus on +direction and that maintainers are ready to review a PR. There is no exception +for trivial fixes or cleanups, since unprioritized PRs still consume review +time and merge-queue capacity. Please let maintainers triage issues as bandwidth +allows instead of pinging individual maintainers. + +3) **Link the issue in your PR.** Reference the `ready-for-pr` issue in your PR +description: use `Fixes #NNN` when the PR fully resolves the issue, or `Part of +#NNN` when an agreed issue takes multiple PRs (such as a preparatory refactor, +incremental steps of a larger change, or a partial fix) so merging does not +close the issue early. PRs (both *Draft* and *Ready for review*) not associated +with a `ready-for-pr` issue will be closed without review. + +4) **Check release milestones for priority.** Maintainers add issues to release +[milestones](https://github.com/agent-substrate/substrate/milestones) (for +example, `v1.1`) to communicate prioritization. PRs that are not aligned with +project priorities and goals may be closed without extensive review. + +5) **Keep PRs small and up to date.** Things move quickly, so PRs may need to +be rebased or updated frequently. Small PRs focused on a single issue are +easier to review and update than large PRs touching many parts of the codebase. + +6) **When in doubt, communicate.** We have GitHub, a mailing list, Slack +channels, and regular [community meetings](docs/project/community.md), and we +encourage you to use them. If you are unsure about something, please ask. It +can save us all a lot of time and effort. + +5) API changes MUST have an in-tree implementation. A new RPC, field, or CLI +flag MUST come with code in this repo that uses it, either in the same PR or (very rarely) in an agreed-upon followup. If you are building something that runs *on* Substrate rather than changing Substrate itself, see [Integration @@ -177,8 +201,8 @@ get merged. Please keep that in mind as you work, especially with AI agents. update code and tests together). * **Small and bulk PRs**: if you find a typo, review the whole file and fix everything in one pass rather than sending a single edit. Group - related typo, doc, and single-line cleanup fixes into one PR rather - than opening several small ones for the same topic. Maintainers may ask + related typo, doc, and single-line cleanup fixes into one issue and PR + rather than opening several small ones for the same topic. Maintainers may ask you to consolidate fragmented PRs into one, or close them in favor of a combined submission. diff --git a/README.md b/README.md index 4832f4b930..85e54271ca 100644 --- a/README.md +++ b/README.md @@ -15,8 +15,6 @@ [![govulncheck](https://github.com/agent-substrate/substrate/actions/workflows/govulncheck.yaml/badge.svg)](https://github.com/agent-substrate/substrate/actions/workflows/govulncheck.yaml) [![GitHub stars](https://img.shields.io/github/stars/agent-substrate/substrate?style=flat)](https://github.com/agent-substrate/substrate/stargazers) -agent-substrate/substrate on Trendshift: #1 repository of the day - [Quickstart](#quickstart-development) · [Security](docs/security/security.md) · [Architecture](docs/concepts/architecture.md) · [Contributing](CONTRIBUTING.md) @@ -106,13 +104,14 @@ if you don't have access. - [#substrate-users](https://cloud-native.slack.com/archives/C0B6RCAJULW) to discuss using substrate. - [#substrate-dev](https://cloud-native.slack.com/archives/C0B6M3E2J3D) to discuss developing substrate. -## Developing +## Contributing -Please see [CONTRIBUTING.md](CONTRIBUTING.md) for guidelines on contributing to -the project. We welcome contributions of all kinds, but the project is VERY -young. Our immediate focus is on building out the core system and demos, so we -may not be able to review or merge contributions that don't align with those -goals in the near term. +Before starting work or opening a pull request, read +**[CONTRIBUTING.md](CONTRIBUTING.md)**. Every pull request (including drafts and +small fixes) must link an issue with the +[`ready-for-pr`](https://github.com/agent-substrate/substrate/issues?q=state%3Aopen%20label%3Aready-for-pr) +label, indicating maintainer consensus on the direction. Pull requests without a +linked `ready-for-pr` issue will be closed without review. ## Quickstart (Development) diff --git a/_LICENSES/github.com/emicklei/go-restful/v3/LICENSE b/_LICENSES/github.com/emicklei/go-restful/v3/LICENSE deleted file mode 100644 index ece7ec61ef..0000000000 --- a/_LICENSES/github.com/emicklei/go-restful/v3/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012,2013 Ernest Micklei - -MIT License - -Permission is hereby granted, free of charge, to any person obtaining -a copy of this software and associated documentation files (the -"Software"), to deal in the Software without restriction, including -without limitation the rights to use, copy, modify, merge, publish, -distribute, sublicense, and/or sell copies of the Software, and to -permit persons to whom the Software is furnished to do so, subject to -the following conditions: - -The above copyright notice and this permission notice shall be -included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND -NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE -LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION -OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION -WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/_LICENSES/github.com/go-openapi/swag/netutils/LICENSE b/_LICENSES/github.com/go-openapi/swag/netutils/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/_LICENSES/github.com/go-openapi/swag/netutils/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/_LICENSES/github.com/go-openapi/swag/stringutils/LICENSE b/_LICENSES/github.com/go-openapi/swag/stringutils/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/_LICENSES/github.com/go-openapi/swag/stringutils/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/_LICENSES/github.com/go-openapi/swag/yamlutils/LICENSE b/_LICENSES/github.com/go-openapi/swag/yamlutils/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/_LICENSES/github.com/go-openapi/swag/yamlutils/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/_LICENSES/github.com/json-iterator/go/LICENSE b/_LICENSES/github.com/json-iterator/go/LICENSE deleted file mode 100644 index 2cf4f5ab28..0000000000 --- a/_LICENSES/github.com/json-iterator/go/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2016 json-iterator - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/_LICENSES/github.com/modern-go/concurrent/LICENSE b/_LICENSES/github.com/modern-go/concurrent/LICENSE deleted file mode 100644 index 261eeb9e9f..0000000000 --- a/_LICENSES/github.com/modern-go/concurrent/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/_LICENSES/github.com/modern-go/reflect2/LICENSE b/_LICENSES/github.com/modern-go/reflect2/LICENSE deleted file mode 100644 index 261eeb9e9f..0000000000 --- a/_LICENSES/github.com/modern-go/reflect2/LICENSE +++ /dev/null @@ -1,201 +0,0 @@ - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/_LICENSES/github.com/pandatix/go-abnf/LICENSE b/_LICENSES/github.com/pandatix/go-abnf/LICENSE new file mode 100644 index 0000000000..89527daea5 --- /dev/null +++ b/_LICENSES/github.com/pandatix/go-abnf/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2024 Lucas TESSON - PandatiX + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/_LICENSES/github.com/peterbourgon/diskv/LICENSE b/_LICENSES/github.com/peterbourgon/diskv/v3/LICENSE similarity index 100% rename from _LICENSES/github.com/peterbourgon/diskv/LICENSE rename to _LICENSES/github.com/peterbourgon/diskv/v3/LICENSE diff --git a/_LICENSES/github.com/go-openapi/swag/LICENSE b/_LICENSES/github.com/tink-crypto/tink-go/v2/LICENSE similarity index 100% rename from _LICENSES/github.com/go-openapi/swag/LICENSE rename to _LICENSES/github.com/tink-crypto/tink-go/v2/LICENSE diff --git a/_LICENSES/github.com/go-openapi/swag/cmdutils/LICENSE b/_LICENSES/k8s.io/apiextensions-api/pkg/LICENSE similarity index 100% rename from _LICENSES/github.com/go-openapi/swag/cmdutils/LICENSE rename to _LICENSES/k8s.io/apiextensions-api/pkg/LICENSE diff --git a/_LICENSES/k8s.io/apiextensions-apiserver/pkg/LICENSE b/_LICENSES/k8s.io/apiextensions-apiserver/pkg/LICENSE deleted file mode 100644 index d645695673..0000000000 --- a/_LICENSES/k8s.io/apiextensions-apiserver/pkg/LICENSE +++ /dev/null @@ -1,202 +0,0 @@ - - Apache License - Version 2.0, January 2004 - http://www.apache.org/licenses/ - - TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - - 1. Definitions. - - "License" shall mean the terms and conditions for use, reproduction, - and distribution as defined by Sections 1 through 9 of this document. - - "Licensor" shall mean the copyright owner or entity authorized by - the copyright owner that is granting the License. - - "Legal Entity" shall mean the union of the acting entity and all - other entities that control, are controlled by, or are under common - control with that entity. For the purposes of this definition, - "control" means (i) the power, direct or indirect, to cause the - direction or management of such entity, whether by contract or - otherwise, or (ii) ownership of fifty percent (50%) or more of the - outstanding shares, or (iii) beneficial ownership of such entity. - - "You" (or "Your") shall mean an individual or Legal Entity - exercising permissions granted by this License. - - "Source" form shall mean the preferred form for making modifications, - including but not limited to software source code, documentation - source, and configuration files. - - "Object" form shall mean any form resulting from mechanical - transformation or translation of a Source form, including but - not limited to compiled object code, generated documentation, - and conversions to other media types. - - "Work" shall mean the work of authorship, whether in Source or - Object form, made available under the License, as indicated by a - copyright notice that is included in or attached to the work - (an example is provided in the Appendix below). - - "Derivative Works" shall mean any work, whether in Source or Object - form, that is based on (or derived from) the Work and for which the - editorial revisions, annotations, elaborations, or other modifications - represent, as a whole, an original work of authorship. For the purposes - of this License, Derivative Works shall not include works that remain - separable from, or merely link (or bind by name) to the interfaces of, - the Work and Derivative Works thereof. - - "Contribution" shall mean any work of authorship, including - the original version of the Work and any modifications or additions - to that Work or Derivative Works thereof, that is intentionally - submitted to Licensor for inclusion in the Work by the copyright owner - or by an individual or Legal Entity authorized to submit on behalf of - the copyright owner. For the purposes of this definition, "submitted" - means any form of electronic, verbal, or written communication sent - to the Licensor or its representatives, including but not limited to - communication on electronic mailing lists, source code control systems, - and issue tracking systems that are managed by, or on behalf of, the - Licensor for the purpose of discussing and improving the Work, but - excluding communication that is conspicuously marked or otherwise - designated in writing by the copyright owner as "Not a Contribution." - - "Contributor" shall mean Licensor and any individual or Legal Entity - on behalf of whom a Contribution has been received by Licensor and - subsequently incorporated within the Work. - - 2. Grant of Copyright License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - copyright license to reproduce, prepare Derivative Works of, - publicly display, publicly perform, sublicense, and distribute the - Work and such Derivative Works in Source or Object form. - - 3. Grant of Patent License. Subject to the terms and conditions of - this License, each Contributor hereby grants to You a perpetual, - worldwide, non-exclusive, no-charge, royalty-free, irrevocable - (except as stated in this section) patent license to make, have made, - use, offer to sell, sell, import, and otherwise transfer the Work, - where such license applies only to those patent claims licensable - by such Contributor that are necessarily infringed by their - Contribution(s) alone or by combination of their Contribution(s) - with the Work to which such Contribution(s) was submitted. If You - institute patent litigation against any entity (including a - cross-claim or counterclaim in a lawsuit) alleging that the Work - or a Contribution incorporated within the Work constitutes direct - or contributory patent infringement, then any patent licenses - granted to You under this License for that Work shall terminate - as of the date such litigation is filed. - - 4. Redistribution. You may reproduce and distribute copies of the - Work or Derivative Works thereof in any medium, with or without - modifications, and in Source or Object form, provided that You - meet the following conditions: - - (a) You must give any other recipients of the Work or - Derivative Works a copy of this License; and - - (b) You must cause any modified files to carry prominent notices - stating that You changed the files; and - - (c) You must retain, in the Source form of any Derivative Works - that You distribute, all copyright, patent, trademark, and - attribution notices from the Source form of the Work, - excluding those notices that do not pertain to any part of - the Derivative Works; and - - (d) If the Work includes a "NOTICE" text file as part of its - distribution, then any Derivative Works that You distribute must - include a readable copy of the attribution notices contained - within such NOTICE file, excluding those notices that do not - pertain to any part of the Derivative Works, in at least one - of the following places: within a NOTICE text file distributed - as part of the Derivative Works; within the Source form or - documentation, if provided along with the Derivative Works; or, - within a display generated by the Derivative Works, if and - wherever such third-party notices normally appear. The contents - of the NOTICE file are for informational purposes only and - do not modify the License. You may add Your own attribution - notices within Derivative Works that You distribute, alongside - or as an addendum to the NOTICE text from the Work, provided - that such additional attribution notices cannot be construed - as modifying the License. - - You may add Your own copyright statement to Your modifications and - may provide additional or different license terms and conditions - for use, reproduction, or distribution of Your modifications, or - for any such Derivative Works as a whole, provided Your use, - reproduction, and distribution of the Work otherwise complies with - the conditions stated in this License. - - 5. Submission of Contributions. Unless You explicitly state otherwise, - any Contribution intentionally submitted for inclusion in the Work - by You to the Licensor shall be under the terms and conditions of - this License, without any additional terms or conditions. - Notwithstanding the above, nothing herein shall supersede or modify - the terms of any separate license agreement you may have executed - with Licensor regarding such Contributions. - - 6. Trademarks. This License does not grant permission to use the trade - names, trademarks, service marks, or product names of the Licensor, - except as required for reasonable and customary use in describing the - origin of the Work and reproducing the content of the NOTICE file. - - 7. Disclaimer of Warranty. Unless required by applicable law or - agreed to in writing, Licensor provides the Work (and each - Contributor provides its Contributions) on an "AS IS" BASIS, - WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or - implied, including, without limitation, any warranties or conditions - of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A - PARTICULAR PURPOSE. You are solely responsible for determining the - appropriateness of using or redistributing the Work and assume any - risks associated with Your exercise of permissions under this License. - - 8. Limitation of Liability. In no event and under no legal theory, - whether in tort (including negligence), contract, or otherwise, - unless required by applicable law (such as deliberate and grossly - negligent acts) or agreed to in writing, shall any Contributor be - liable to You for damages, including any direct, indirect, special, - incidental, or consequential damages of any character arising as a - result of this License or out of the use or inability to use the - Work (including but not limited to damages for loss of goodwill, - work stoppage, computer failure or malfunction, or any and all - other commercial damages or losses), even if such Contributor - has been advised of the possibility of such damages. - - 9. Accepting Warranty or Additional Liability. While redistributing - the Work or Derivative Works thereof, You may choose to offer, - and charge a fee for, acceptance of support, warranty, indemnity, - or other liability obligations and/or rights consistent with this - License. However, in accepting such obligations, You may act only - on Your own behalf and on Your sole responsibility, not on behalf - of any other Contributor, and only if You agree to indemnify, - defend, and hold each Contributor harmless for any liability - incurred by, or claims asserted against, such Contributor by reason - of your accepting any such warranty or additional liability. - - END OF TERMS AND CONDITIONS - - APPENDIX: How to apply the Apache License to your work. - - To apply the Apache License to your work, attach the following - boilerplate notice, with the fields enclosed by brackets "[]" - replaced with your own identifying information. (Don't include - the brackets!) The text should be enclosed in the appropriate - comment syntax for the file format. We also recommend that a - file or class name and description of purpose be included on the - same "printed page" as the copyright notice for easier - identification within third-party archives. - - Copyright [yyyy] [name of copyright owner] - - 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. diff --git a/_LICENSES/github.com/go-openapi/swag/fileutils/LICENSE b/_LICENSES/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/LICENSE similarity index 100% rename from _LICENSES/github.com/go-openapi/swag/fileutils/LICENSE rename to _LICENSES/k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/LICENSE diff --git a/_LICENSES/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/LICENSE b/_LICENSES/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/LICENSE deleted file mode 100644 index 2441273007..0000000000 --- a/_LICENSES/k8s.io/kube-openapi/pkg/internal/third_party/go-json-experiment/json/LICENSE +++ /dev/null @@ -1,27 +0,0 @@ -Copyright (c) 2020 The Go Authors. All rights reserved. - -Redistribution and use in source and binary forms, with or without -modification, are permitted provided that the following conditions are -met: - - * Redistributions of source code must retain the above copyright -notice, this list of conditions and the following disclaimer. - * Redistributions in binary form must reproduce the above -copyright notice, this list of conditions and the following disclaimer -in the documentation and/or other materials provided with the -distribution. - * Neither the name of Google Inc. nor the names of its -contributors may be used to endorse or promote products derived from -this software without specific prior written permission. - -THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/_LICENSES/sigs.k8s.io/structured-merge-diff/v6/LICENSE b/_LICENSES/sigs.k8s.io/structured-merge-diff/v7/LICENSE similarity index 100% rename from _LICENSES/sigs.k8s.io/structured-merge-diff/v6/LICENSE rename to _LICENSES/sigs.k8s.io/structured-merge-diff/v7/LICENSE diff --git a/api/ateapi/v1/ateapi.pb.go b/api/ateapi/v1/ateapi.pb.go index d63c010fb1..9e8e106671 100644 --- a/api/ateapi/v1/ateapi.pb.go +++ b/api/ateapi/v1/ateapi.pb.go @@ -931,7 +931,7 @@ type ResourceMetadata struct { // for update operations. // // +k8s:optional - // +k8s:alpha(since: "0.0")=+k8s:monotonic # TODO: get rid of alpha prefix + // +k8s:monotonic // +k8s:minimum=1 // +k8s:update=NoUnset Version int64 `protobuf:"varint,4,opt,name=version,proto3" json:"version,omitempty"` @@ -1051,7 +1051,7 @@ type ExternalVolumes struct { // +k8s:maxItems=32 # matches the template's volumes bound // +k8s:listType=map // +k8s:listMapKey=name - Volumes []*ExternalVolumeStatus `protobuf:"bytes,1,rep,name=volumes,proto3" json:"volumes,omitempty"` + Volumes []*ActorExternalVolumeStatus `protobuf:"bytes,1,rep,name=volumes,proto3" json:"volumes,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1086,15 +1086,18 @@ func (*ExternalVolumes) Descriptor() ([]byte, []int) { return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{5} } -func (x *ExternalVolumes) GetVolumes() []*ExternalVolumeStatus { +func (x *ExternalVolumes) GetVolumes() []*ActorExternalVolumeStatus { if x != nil { return x.Volumes } return nil } -// ExternalVolumeStatus is one actor's view of an external volume it mounts. -type ExternalVolumeStatus struct { +// ActorExternalVolumeStatus is one actor's view of an external volume it mounts. +// +// (-- TODO(#1637): temporary rename to unblock ExternalVolume.status; delete +// once ExternalVolume replaces ActorStatus.external_volumes. --) +type ActorExternalVolumeStatus struct { state protoimpl.MessageState `protogen:"open.v1"` // Name of the volume specified in the actor template. Template volume // names are DNS labels. @@ -1115,22 +1118,24 @@ type ExternalVolumeStatus struct { // +k8s:maxLength=256 // +k8s:update=NoModify // +k8s:update=NoUnset - // +k8s:customValidation # no control characters + // +k8s:format=ate-volume-storage-id StorageVolumeId string `protobuf:"bytes,2,opt,name=storage_volume_id,json=storageVolumeId,proto3" json:"storage_volume_id,omitempty"` - // Internal volume plugin name or CSI driver name, from the StorageClass - // provisioner. Must be a DNS subdomain, optionally prefixed with - // "substrate.io/" (per the CSI spec's driver-name syntax). + // CSI driver name, from the StorageClass provisioner. Must be a DNS + // subdomain of at most 63 characters. + // + // (-- Same rule as `CsiDriver.driver_name`, and the CSI spec's driver name + // limit. --) // // +k8s:required - // +k8s:maxLength=253 + // +k8s:maxLength=63 // +k8s:update=NoModify // +k8s:update=NoUnset # set-once, like name above - // +k8s:customValidation + // +k8s:format=k8s-long-name VolumeType string `protobuf:"bytes,3,opt,name=volume_type,json=volumeType,proto3" json:"volume_type,omitempty"` // volume_context contains metadata returned by the CSI driver during volume - // provisioning, needed by the node plugin for mounting (e.g. attachment - // info). Keys and values are the driver's own, so the map is only bounded, - // not validated. + // provisioning, needed by the node plugin for mounting, such as an NFS + // server and export path. Keys and values are the driver's own, so the map + // is only bounded, not validated. // // +k8s:optional // +k8s:customValidation # at most 40 KiB in total, ten times the CSI limit for map fields @@ -1139,20 +1144,20 @@ type ExternalVolumeStatus struct { sizeCache protoimpl.SizeCache } -func (x *ExternalVolumeStatus) Reset() { - *x = ExternalVolumeStatus{} +func (x *ActorExternalVolumeStatus) Reset() { + *x = ActorExternalVolumeStatus{} mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[6] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *ExternalVolumeStatus) String() string { +func (x *ActorExternalVolumeStatus) String() string { return protoimpl.X.MessageStringOf(x) } -func (*ExternalVolumeStatus) ProtoMessage() {} +func (*ActorExternalVolumeStatus) ProtoMessage() {} -func (x *ExternalVolumeStatus) ProtoReflect() protoreflect.Message { +func (x *ActorExternalVolumeStatus) ProtoReflect() protoreflect.Message { mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[6] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) @@ -1164,33 +1169,33 @@ func (x *ExternalVolumeStatus) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use ExternalVolumeStatus.ProtoReflect.Descriptor instead. -func (*ExternalVolumeStatus) Descriptor() ([]byte, []int) { +// Deprecated: Use ActorExternalVolumeStatus.ProtoReflect.Descriptor instead. +func (*ActorExternalVolumeStatus) Descriptor() ([]byte, []int) { return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{6} } -func (x *ExternalVolumeStatus) GetName() string { +func (x *ActorExternalVolumeStatus) GetName() string { if x != nil { return x.Name } return "" } -func (x *ExternalVolumeStatus) GetStorageVolumeId() string { +func (x *ActorExternalVolumeStatus) GetStorageVolumeId() string { if x != nil { return x.StorageVolumeId } return "" } -func (x *ExternalVolumeStatus) GetVolumeType() string { +func (x *ActorExternalVolumeStatus) GetVolumeType() string { if x != nil { return x.VolumeType } return "" } -func (x *ExternalVolumeStatus) GetVolumeContext() map[string]string { +func (x *ActorExternalVolumeStatus) GetVolumeContext() map[string]string { if x != nil { return x.VolumeContext } @@ -1313,7 +1318,7 @@ type EgressPolicy struct { // // +k8s:required // +k8s:subfield(atespace)=+k8s:required - // +k8s:customValidation # name must be "default" + // +k8s:subfield(name)=+k8s:format=ate-singleton-name Metadata *ResourceMetadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` // Rules are an unordered set of allows. Traffic is denied when no rule // matches. @@ -1949,21 +1954,22 @@ type CredentialHeader struct { // The case-insensitive HTTP request header to replace when present. // // +k8s:required - // +k8s:customValidation # format + // +k8s:format=ate-http-header-name Header string `protobuf:"bytes,1,opt,name=header,proto3" json:"header,omitempty"` // Prepended verbatim to the credential value. Include any desired separator; // for example, use "Bearer " (including the space) for Authorization. // // +k8s:optional - // +k8s:customValidation # format + // +k8s:format=ate-http-header-value Prefix string `protobuf:"bytes,2,opt,name=prefix,proto3" json:"prefix,omitempty"` // Source-agnostic reference interpreted by a registered credential provider: // `ate-secret:////` // - // Exactly one of credential_uri and actor_jwt must be set. + // Exactly one of credential_uri, actor_jwt, and token_exchange must be set. // // +k8s:optional // +k8s:unionMember + // +k8s:maxLength=1024 // +k8s:customValidation # format CredentialUri string `protobuf:"bytes,3,opt,name=credential_uri,json=credentialUri,proto3" json:"credential_uri,omitempty"` // A Substrate-issued JWT asserting the identity of the Actor that sent the @@ -1971,7 +1977,13 @@ type CredentialHeader struct { // // +k8s:optional // +k8s:unionMember - ActorJwt *ActorJwtSource `protobuf:"bytes,4,opt,name=actor_jwt,json=actorJwt,proto3" json:"actor_jwt,omitempty"` + ActorJwt *ActorJwtSource `protobuf:"bytes,4,opt,name=actor_jwt,json=actorJwt,proto3" json:"actor_jwt,omitempty"` + // A token obtained by exchanging an actor JWT at an OAuth 2.0 token + // exchange endpoint (RFC 8693). + // + // +k8s:optional + // +k8s:unionMember + TokenExchange *TokenExchangeSource `protobuf:"bytes,5,opt,name=token_exchange,json=tokenExchange,proto3" json:"token_exchange,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -2034,6 +2046,218 @@ func (x *CredentialHeader) GetActorJwt() *ActorJwtSource { return nil } +func (x *CredentialHeader) GetTokenExchange() *TokenExchangeSource { + if x != nil { + return x.TokenExchange + } + return nil +} + +// TokenExchangeSource has the gateway mint an actor JWT and exchange it at +// token_url (RFC 8693). The returned token becomes the header value. +type TokenExchangeSource struct { + state protoimpl.MessageState `protogen:"open.v1"` + // HTTPS URL of the token endpoint, with a DNS hostname and without userinfo, + // query, or fragment. + // + // +k8s:required + // +k8s:maxLength=2048 + // +k8s:customValidation # format + TokenUrl string `protobuf:"bytes,1,opt,name=token_url,json=tokenUrl,proto3" json:"token_url,omitempty"` + // The actor JWT sent as the RFC 8693 subject_token. + // + // +k8s:required + SubjectActorJwt *ActorJwtSource `protobuf:"bytes,2,opt,name=subject_actor_jwt,json=subjectActorJwt,proto3" json:"subject_actor_jwt,omitempty"` + // RFC 8693 resource parameters, each sent as a separate form entry. Each + // entry must be an absolute URI without a fragment. + // + // +k8s:optional + // +k8s:maxItems=16 + // +k8s:listType=set + // +k8s:eachVal=+k8s:minLength=1 + // +k8s:eachVal=+k8s:maxLength=2048 + // +k8s:customValidation # absolute URI without fragment + Resources []string `protobuf:"bytes,3,rep,name=resources,proto3" json:"resources,omitempty"` + // RFC 8693 audience parameters, each sent as a separate form entry. + // + // +k8s:optional + // +k8s:maxItems=16 + // +k8s:listType=set + // +k8s:eachVal=+k8s:minLength=1 + // +k8s:eachVal=+k8s:maxLength=512 + Audiences []string `protobuf:"bytes,4,rep,name=audiences,proto3" json:"audiences,omitempty"` + // RFC 8693 scope parameter, space-joined. + // + // +k8s:optional + // +k8s:maxItems=16 + // +k8s:listType=set + // +k8s:eachVal=+k8s:minLength=1 + // +k8s:eachVal=+k8s:maxLength=256 + // +k8s:customValidation # RFC 6749 scope-token characters + Scopes []string `protobuf:"bytes,5,rep,name=scopes,proto3" json:"scopes,omitempty"` + // RFC 8693 requested_token_type parameter (for example, + // "urn:ietf:params:oauth:token-type:access_token"). Omitted from the form + // post when empty. + // + // +k8s:optional + // +k8s:maxLength=512 + RequestedTokenType string `protobuf:"bytes,6,opt,name=requested_token_type,json=requestedTokenType,proto3" json:"requested_token_type,omitempty"` + // Additional application/x-www-form-urlencoded parameters sent with the + // exchange request. Keys may repeat; reserved RFC 8693 parameter names + // (grant_type, subject_token, subject_token_type, actor_token, + // actor_token_type, resource, audience, scope, requested_token_type) are + // rejected. Intended for non-secret configuration (not client credentials). + // + // +k8s:optional + // +k8s:maxItems=16 + // +k8s:listType=atomic + // +k8s:customValidation # reject reserved RFC 8693 parameter names + AdditionalParameters []*FormEntry `protobuf:"bytes,7,rep,name=additional_parameters,json=additionalParameters,proto3" json:"additional_parameters,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *TokenExchangeSource) Reset() { + *x = TokenExchangeSource{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[18] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *TokenExchangeSource) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TokenExchangeSource) ProtoMessage() {} + +func (x *TokenExchangeSource) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[18] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TokenExchangeSource.ProtoReflect.Descriptor instead. +func (*TokenExchangeSource) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{18} +} + +func (x *TokenExchangeSource) GetTokenUrl() string { + if x != nil { + return x.TokenUrl + } + return "" +} + +func (x *TokenExchangeSource) GetSubjectActorJwt() *ActorJwtSource { + if x != nil { + return x.SubjectActorJwt + } + return nil +} + +func (x *TokenExchangeSource) GetResources() []string { + if x != nil { + return x.Resources + } + return nil +} + +func (x *TokenExchangeSource) GetAudiences() []string { + if x != nil { + return x.Audiences + } + return nil +} + +func (x *TokenExchangeSource) GetScopes() []string { + if x != nil { + return x.Scopes + } + return nil +} + +func (x *TokenExchangeSource) GetRequestedTokenType() string { + if x != nil { + return x.RequestedTokenType + } + return "" +} + +func (x *TokenExchangeSource) GetAdditionalParameters() []*FormEntry { + if x != nil { + return x.AdditionalParameters + } + return nil +} + +// FormEntry is a single key-value entry in an application/x-www-form-urlencoded +// request body. +type FormEntry struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Parameter name. + // + // +k8s:required + // +k8s:maxLength=128 + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + // Parameter value. + // + // +k8s:required + // +k8s:maxLength=2048 + Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FormEntry) Reset() { + *x = FormEntry{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[19] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FormEntry) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FormEntry) ProtoMessage() {} + +func (x *FormEntry) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[19] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FormEntry.ProtoReflect.Descriptor instead. +func (*FormEntry) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{19} +} + +func (x *FormEntry) GetKey() string { + if x != nil { + return x.Key + } + return "" +} + +func (x *FormEntry) GetValue() string { + if x != nil { + return x.Value + } + return "" +} + // ActorJwtSource has the gateway mint a JWT for the Actor that sent the // request. Relying parties verify it with OpenID Connect Discovery against its // issuer. The gateway reuses a JWT across requests while enough of its @@ -2060,7 +2284,7 @@ type ActorJwtSource struct { func (x *ActorJwtSource) Reset() { *x = ActorJwtSource{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[18] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[20] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2072,7 +2296,7 @@ func (x *ActorJwtSource) String() string { func (*ActorJwtSource) ProtoMessage() {} func (x *ActorJwtSource) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[18] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[20] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2085,7 +2309,7 @@ func (x *ActorJwtSource) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorJwtSource.ProtoReflect.Descriptor instead. func (*ActorJwtSource) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{18} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{20} } func (x *ActorJwtSource) GetAudiences() []string { @@ -2122,7 +2346,6 @@ type ActorStatus struct { // actor. These volumes only live as long as the actor and are deleted with // it. // - // +ate:preview=ExternalVolumes // +k8s:optional ExternalVolumes *ExternalVolumes `protobuf:"bytes,3,opt,name=external_volumes,json=externalVolumes,proto3" json:"external_volumes,omitempty"` // crash records why and when the Actor entered CRASHED. It is set with the @@ -2151,7 +2374,7 @@ type ActorStatus struct { // that have become stale and need to be cleaned up. // // +k8s:optional - // +k8s:alpha(since: "0.0")=+k8s:monotonic # TODO: get rid of alpha prefix + // +k8s:monotonic // +k8s:minimum=0 // +k8s:update=NoUnset LastAssignedGeneration int32 `protobuf:"varint,7,opt,name=last_assigned_generation,json=lastAssignedGeneration,proto3" json:"last_assigned_generation,omitempty"` @@ -2161,7 +2384,7 @@ type ActorStatus struct { func (x *ActorStatus) Reset() { *x = ActorStatus{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[19] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[21] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2173,7 +2396,7 @@ func (x *ActorStatus) String() string { func (*ActorStatus) ProtoMessage() {} func (x *ActorStatus) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[19] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[21] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2186,7 +2409,7 @@ func (x *ActorStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorStatus.ProtoReflect.Descriptor instead. func (*ActorStatus) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{19} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{21} } func (x *ActorStatus) GetState() ActorState { @@ -2256,7 +2479,7 @@ type ActorCrash struct { func (x *ActorCrash) Reset() { *x = ActorCrash{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[20] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[22] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2268,7 +2491,7 @@ func (x *ActorCrash) String() string { func (*ActorCrash) ProtoMessage() {} func (x *ActorCrash) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[20] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[22] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2281,7 +2504,7 @@ func (x *ActorCrash) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorCrash.ProtoReflect.Descriptor instead. func (*ActorCrash) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{20} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{22} } func (x *ActorCrash) GetMessage() string { @@ -2318,7 +2541,7 @@ type WorkerAssignment struct { // // Workers are global-scoped, so this carries no atespace. // - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden // +k8s:required // +k8s:update=NoModify Worker *ObjectRef `protobuf:"bytes,6,opt,name=worker,proto3" json:"worker,omitempty"` @@ -2381,13 +2604,21 @@ type WorkerAssignment struct { // +k8s:customValidation # a SPIFFE ID // +k8s:update=NoModify WorkerSpiffeId string `protobuf:"bytes,10,opt,name=worker_spiffe_id,json=workerSpiffeId,proto3" json:"worker_spiffe_id,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // actor_activation_uid identifies the Actor's current activation on this + // Worker. Each Run or Restore call starts an activation with a new UUID. The + // field is empty until the Actor becomes RUNNING and for activations started + // by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + ActorActivationUid string `protobuf:"bytes,11,opt,name=actor_activation_uid,json=actorActivationUid,proto3" json:"actor_activation_uid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *WorkerAssignment) Reset() { *x = WorkerAssignment{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[21] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[23] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2399,7 +2630,7 @@ func (x *WorkerAssignment) String() string { func (*WorkerAssignment) ProtoMessage() {} func (x *WorkerAssignment) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[21] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[23] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2412,7 +2643,7 @@ func (x *WorkerAssignment) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkerAssignment.ProtoReflect.Descriptor instead. func (*WorkerAssignment) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{21} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{23} } func (x *WorkerAssignment) GetWorker() *ObjectRef { @@ -2485,6 +2716,13 @@ func (x *WorkerAssignment) GetWorkerSpiffeId() string { return "" } +func (x *WorkerAssignment) GetActorActivationUid() string { + if x != nil { + return x.ActorActivationUid + } + return "" +} + // TagStatus is the server-owned state of a Tag. // The tag is fixed to one external snapshot once its creation completes, so // the rest is immutable provenance. @@ -2497,14 +2735,20 @@ type TagStatus struct { // moves between snapshots and is usable only once COMPLETED. Unset until it // is recorded; a tag whose creation failed first never gets one. // + // (-- Custom validation allows an update to record the snapshot once, and then + // only to move its durable_snapshot from PENDING to COMPLETED. --) + // // +k8s:optional + // +k8s:update=NoUnset // +k8s:subfield(durable_snapshot)=+k8s:required + // +k8s:customValidation Snapshot *Snapshot `protobuf:"bytes,1,opt,name=snapshot,proto3" json:"snapshot,omitempty"` // UID of the ActorTemplate the snapshot was taken under. Actors can only be // seeded from a tag under the same template. // // +k8s:required // +k8s:format=k8s-uuid + // +k8s:immutable ActorTemplateUid string `protobuf:"bytes,2,opt,name=actor_template_uid,json=actorTemplateUid,proto3" json:"actor_template_uid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -2512,7 +2756,7 @@ type TagStatus struct { func (x *TagStatus) Reset() { *x = TagStatus{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[22] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[24] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2524,7 +2768,7 @@ func (x *TagStatus) String() string { func (*TagStatus) ProtoMessage() {} func (x *TagStatus) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[22] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[24] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2537,7 +2781,7 @@ func (x *TagStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use TagStatus.ProtoReflect.Descriptor instead. func (*TagStatus) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{22} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{24} } func (x *TagStatus) GetSnapshot() *Snapshot { @@ -2568,6 +2812,7 @@ type Tag struct { // status is set by the control plane; it is ignored on write. // // +k8s:optional + // +k8s:update=NoUnset Status *TagStatus `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` // scope controls who may create an Actor from this tag. // @@ -2589,7 +2834,7 @@ type Tag struct { func (x *Tag) Reset() { *x = Tag{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[23] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[25] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2601,7 +2846,7 @@ func (x *Tag) String() string { func (*Tag) ProtoMessage() {} func (x *Tag) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[23] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[25] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2614,7 +2859,7 @@ func (x *Tag) ProtoReflect() protoreflect.Message { // Deprecated: Use Tag.ProtoReflect.Descriptor instead. func (*Tag) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{23} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{25} } func (x *Tag) GetMetadata() *ResourceMetadata { @@ -2645,34 +2890,45 @@ func (x *Tag) GetSourceActor() *ObjectRef { return nil } -// Atespace is the isolation boundary an Actor is created into. Global-scoped: -// metadata.atespace is always empty; the atespace's identity is metadata.name. -type Atespace struct { +// ExternalVolume is an atespace-scoped record of a storage volume. Identity +// is `metadata.atespace` and `metadata.name`. It is read-only: the server +// creates and deletes it. An atespace cannot be deleted while it holds an +// ExternalVolume. +// +// (-- Nothing creates an ExternalVolume yet. The server-side creation, the +// actor template reference and an import RPC come in later changes. --) +type ExternalVolume struct { state protoimpl.MessageState `protogen:"open.v1"` - // Common resource metadata: name, uid, version, timestamps. + // Common resource metadata: `atespace`, `name`, `uid`, `version`, + // timestamps. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix - Metadata *ResourceMetadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` + // +k8s:subfield(atespace)=+k8s:required + Metadata *ResourceMetadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` + // Server-managed state. + // + // +k8s:optional + // +k8s:update=NoUnset + Status *ExternalVolumeStatus `protobuf:"bytes,2,opt,name=status,proto3" json:"status,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *Atespace) Reset() { - *x = Atespace{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[24] +func (x *ExternalVolume) Reset() { + *x = ExternalVolume{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[26] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *Atespace) String() string { +func (x *ExternalVolume) String() string { return protoimpl.X.MessageStringOf(x) } -func (*Atespace) ProtoMessage() {} +func (*ExternalVolume) ProtoMessage() {} -func (x *Atespace) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[24] +func (x *ExternalVolume) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[26] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2683,23 +2939,230 @@ func (x *Atespace) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use Atespace.ProtoReflect.Descriptor instead. -func (*Atespace) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{24} +// Deprecated: Use ExternalVolume.ProtoReflect.Descriptor instead. +func (*ExternalVolume) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{26} } -func (x *Atespace) GetMetadata() *ResourceMetadata { +func (x *ExternalVolume) GetMetadata() *ResourceMetadata { if x != nil { return x.Metadata } return nil } -// ObjectRef references a Substrate resource by its atespace and name. -type ObjectRef struct { +func (x *ExternalVolume) GetStatus() *ExternalVolumeStatus { + if x != nil { + return x.Status + } + return nil +} + +// ExternalVolumeStatus is the server-managed state of an ExternalVolume. +type ExternalVolumeStatus struct { state protoimpl.MessageState `protogen:"open.v1"` - // The atespace of the referenced resource. This field should be empty if the - // target resource is global-scoped, but references to objects in the same + // `csi` is the CSI volume backing this ExternalVolume. Unset until the + // server has provisioned it, then never changed. + // + // +k8s:optional + // +k8s:update=NoModify + // +k8s:update=NoUnset + Csi *CsiVolumeStatus `protobuf:"bytes,1,opt,name=csi,proto3" json:"csi,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ExternalVolumeStatus) Reset() { + *x = ExternalVolumeStatus{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[27] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ExternalVolumeStatus) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ExternalVolumeStatus) ProtoMessage() {} + +func (x *ExternalVolumeStatus) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[27] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ExternalVolumeStatus.ProtoReflect.Descriptor instead. +func (*ExternalVolumeStatus) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{27} +} + +func (x *ExternalVolumeStatus) GetCsi() *CsiVolumeStatus { + if x != nil { + return x.Csi + } + return nil +} + +// CsiVolumeStatus is the CSI volume backing an ExternalVolume. +type CsiVolumeStatus struct { + state protoimpl.MessageState `protogen:"open.v1"` + // `volume_id` is the volume's ID in the storage system, in the format the + // CSI driver expects. Its format is the storage system's own: at most 256 + // bytes, with no control characters, tabs or line breaks, and no leading or + // trailing whitespace. Together with `driver_name` it is unique across all + // atespaces. + // + // (-- TODO(#2935): "/" stays allowed because CSI IDs such as GCE PD paths + // contain it, so atelet must stop joining the raw ID into its staging path + // before an ExternalVolume can reach a node. --) + // + // +k8s:required + // +k8s:maxBytes=256 + // +k8s:update=NoModify + // +k8s:update=NoUnset + // +k8s:format=ate-volume-storage-id + // +k8s:customValidation # no tabs, line breaks or surrounding whitespace + VolumeId string `protobuf:"bytes,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"` + // `driver_name` is the CSI driver name: a DNS-1123 subdomain of at most 63 + // characters, as the CSI spec requires. + // + // +k8s:required + // +k8s:maxLength=63 + // +k8s:update=NoModify + // +k8s:update=NoUnset + // +k8s:format=k8s-long-name + DriverName string `protobuf:"bytes,2,opt,name=driver_name,json=driverName,proto3" json:"driver_name,omitempty"` + // `volume_context` is the driver metadata the node plugin needs to mount + // the volume, such as an NFS server and export path. It is passed as the + // volume context of the node plugin's stage and publish calls. Keys and + // values are the driver's own, so the map is only bounded: at most 128 + // entries, keys of at most 256 bytes, values of at most 4095 bytes, 4 KiB + // in total, and no NUL bytes. Attachment metadata is per node and not + // recorded here. + // + // +k8s:optional + // +k8s:maxProperties=128 + // +k8s:eachKey=+k8s:minLength=1 + // +k8s:eachKey=+k8s:maxBytes=256 + // +k8s:eachVal=+k8s:maxBytes=4095 + // +k8s:customValidation # at most 4 KiB in total, the CSI limit for map fields; no NUL bytes + VolumeContext map[string]string `protobuf:"bytes,3,rep,name=volume_context,json=volumeContext,proto3" json:"volume_context,omitempty" protobuf_key:"bytes,1,opt,name=key" protobuf_val:"bytes,2,opt,name=value"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CsiVolumeStatus) Reset() { + *x = CsiVolumeStatus{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[28] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CsiVolumeStatus) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CsiVolumeStatus) ProtoMessage() {} + +func (x *CsiVolumeStatus) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[28] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CsiVolumeStatus.ProtoReflect.Descriptor instead. +func (*CsiVolumeStatus) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{28} +} + +func (x *CsiVolumeStatus) GetVolumeId() string { + if x != nil { + return x.VolumeId + } + return "" +} + +func (x *CsiVolumeStatus) GetDriverName() string { + if x != nil { + return x.DriverName + } + return "" +} + +func (x *CsiVolumeStatus) GetVolumeContext() map[string]string { + if x != nil { + return x.VolumeContext + } + return nil +} + +// Atespace is the isolation boundary an Actor is created into. Global-scoped: +// metadata.atespace is always empty; the atespace's identity is metadata.name. +type Atespace struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Common resource metadata: name, uid, version, timestamps. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:forbidden + Metadata *ResourceMetadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *Atespace) Reset() { + *x = Atespace{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[29] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *Atespace) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*Atespace) ProtoMessage() {} + +func (x *Atespace) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[29] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use Atespace.ProtoReflect.Descriptor instead. +func (*Atespace) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{29} +} + +func (x *Atespace) GetMetadata() *ResourceMetadata { + if x != nil { + return x.Metadata + } + return nil +} + +// ObjectRef references a Substrate resource by its atespace and name. +type ObjectRef struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The atespace of the referenced resource. This field should be empty if the + // target resource is global-scoped, but references to objects in the same // atespace as the referrer must still populate this field. // // References to atespaced resources should add `+k8s:subfield(atespace)=+k8s:required` @@ -2718,7 +3181,7 @@ type ObjectRef struct { func (x *ObjectRef) Reset() { *x = ObjectRef{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[25] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[30] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2730,7 +3193,7 @@ func (x *ObjectRef) String() string { func (*ObjectRef) ProtoMessage() {} func (x *ObjectRef) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[25] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[30] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2743,7 +3206,7 @@ func (x *ObjectRef) ProtoReflect() protoreflect.Message { // Deprecated: Use ObjectRef.ProtoReflect.Descriptor instead. func (*ObjectRef) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{25} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{30} } func (x *ObjectRef) GetAtespace() string { @@ -2798,7 +3261,9 @@ type ActorTemplate struct { // micro-VM is booted at that size. // // +k8s:required - // +k8s:customValidation # cpu and memory limits are both set + // +k8s:subfield(limits)=+k8s:required + // +k8s:subfield(limits)=+k8s:subfield(cpu_millicores)=+k8s:required + // +k8s:subfield(limits)=+k8s:subfield(memory_bytes)=+k8s:required Resources *ResourceRequirements `protobuf:"bytes,6,opt,name=resources,proto3" json:"resources,omitempty"` // Egress policy for the golden Actor during initialization. The template // controller creates a policy with these rules through CreateActorEgressPolicy @@ -2807,7 +3272,6 @@ type ActorTemplate struct { // If absent, no policy is created. When set, at least one rule is required. // May not be set when snapshot_config.golden_snapshot_config.mode is DISABLED. // - // +ate:preview=GoldenEgressPolicy // +k8s:ifDisabled(GoldenEgressPolicy)=+k8s:forbidden // +k8s:optional GoldenEgressPolicy *EgressPolicyTemplate `protobuf:"bytes,9,opt,name=golden_egress_policy,json=goldenEgressPolicy,proto3" json:"golden_egress_policy,omitempty"` @@ -2819,7 +3283,7 @@ type ActorTemplate struct { func (x *ActorTemplate) Reset() { *x = ActorTemplate{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[26] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[31] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2831,7 +3295,7 @@ func (x *ActorTemplate) String() string { func (*ActorTemplate) ProtoMessage() {} func (x *ActorTemplate) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[26] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[31] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2844,7 +3308,7 @@ func (x *ActorTemplate) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorTemplate.ProtoReflect.Descriptor instead. func (*ActorTemplate) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{26} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{31} } func (x *ActorTemplate) GetMetadata() *ResourceMetadata { @@ -2916,7 +3380,7 @@ type ResourceRequirements struct { func (x *ResourceRequirements) Reset() { *x = ResourceRequirements{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[27] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[32] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2928,7 +3392,7 @@ func (x *ResourceRequirements) String() string { func (*ResourceRequirements) ProtoMessage() {} func (x *ResourceRequirements) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[27] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[32] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2941,7 +3405,7 @@ func (x *ResourceRequirements) ProtoReflect() protoreflect.Message { // Deprecated: Use ResourceRequirements.ProtoReflect.Descriptor instead. func (*ResourceRequirements) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{27} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{32} } func (x *ResourceRequirements) GetLimits() *Resources { @@ -2971,7 +3435,7 @@ type Resources struct { func (x *Resources) Reset() { *x = Resources{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[28] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[33] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -2983,7 +3447,7 @@ func (x *Resources) String() string { func (*Resources) ProtoMessage() {} func (x *Resources) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[28] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[33] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -2996,7 +3460,7 @@ func (x *Resources) ProtoReflect() protoreflect.Message { // Deprecated: Use Resources.ProtoReflect.Descriptor instead. func (*Resources) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{28} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{33} } func (x *Resources) GetCpuMillicores() int64 { @@ -3037,7 +3501,7 @@ type GoldenSnapshotStatus struct { func (x *GoldenSnapshotStatus) Reset() { *x = GoldenSnapshotStatus{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[29] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[34] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3049,7 +3513,7 @@ func (x *GoldenSnapshotStatus) String() string { func (*GoldenSnapshotStatus) ProtoMessage() {} func (x *GoldenSnapshotStatus) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[29] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[34] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3062,7 +3526,7 @@ func (x *GoldenSnapshotStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use GoldenSnapshotStatus.ProtoReflect.Descriptor instead. func (*GoldenSnapshotStatus) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{29} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{34} } func (x *GoldenSnapshotStatus) GetGoldenTag() *ObjectRef { @@ -3096,7 +3560,7 @@ type ActorTemplateStatus struct { func (x *ActorTemplateStatus) Reset() { *x = ActorTemplateStatus{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[30] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[35] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3108,7 +3572,7 @@ func (x *ActorTemplateStatus) String() string { func (*ActorTemplateStatus) ProtoMessage() {} func (x *ActorTemplateStatus) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[30] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[35] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3121,7 +3585,7 @@ func (x *ActorTemplateStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorTemplateStatus.ProtoReflect.Descriptor instead. func (*ActorTemplateStatus) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{30} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{35} } func (x *ActorTemplateStatus) GetGoldenSnapshotStatus() *GoldenSnapshotStatus { @@ -3141,9 +3605,10 @@ type SnapshotConfig struct { // gate. Each path segment may contain only ASCII letters, digits, '_' and // '-'. Each owner's snapshots are stored under // /atespaces/..., so no segment may be "atespaces" in any - // letter case. + // letter case. For a gs:// location, the bucket name and path together may + // be at most 338 characters, so each actor's prefix fits a locally minted + // snapshot transfer token. // - // +ate:preview=PerTemplateSnapshotLocation // +k8s:ifDisabled(PerTemplateSnapshotLocation)=+k8s:forbidden // +k8s:optional // +k8s:maxLength=1024 @@ -3172,7 +3637,7 @@ type SnapshotConfig struct { func (x *SnapshotConfig) Reset() { *x = SnapshotConfig{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[31] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[36] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3184,7 +3649,7 @@ func (x *SnapshotConfig) String() string { func (*SnapshotConfig) ProtoMessage() {} func (x *SnapshotConfig) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[31] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[36] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3197,7 +3662,7 @@ func (x *SnapshotConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use SnapshotConfig.ProtoReflect.Descriptor instead. func (*SnapshotConfig) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{31} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{36} } func (x *SnapshotConfig) GetStorageLocation() string { @@ -3237,7 +3702,7 @@ type GoldenSnapshotConfig struct { func (x *GoldenSnapshotConfig) Reset() { *x = GoldenSnapshotConfig{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[32] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[37] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3249,7 +3714,7 @@ func (x *GoldenSnapshotConfig) String() string { func (*GoldenSnapshotConfig) ProtoMessage() {} func (x *GoldenSnapshotConfig) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[32] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[37] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3262,7 +3727,7 @@ func (x *GoldenSnapshotConfig) ProtoReflect() protoreflect.Message { // Deprecated: Use GoldenSnapshotConfig.ProtoReflect.Descriptor instead. func (*GoldenSnapshotConfig) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{32} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{37} } func (x *GoldenSnapshotConfig) GetMode() GoldenSnapshotMode { @@ -3342,7 +3807,7 @@ type Container struct { func (x *Container) Reset() { *x = Container{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[33] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[38] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3354,7 +3819,7 @@ func (x *Container) String() string { func (*Container) ProtoMessage() {} func (x *Container) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[33] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[38] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3367,7 +3832,7 @@ func (x *Container) ProtoReflect() protoreflect.Message { // Deprecated: Use Container.ProtoReflect.Descriptor instead. func (*Container) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{33} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{38} } func (x *Container) GetName() string { @@ -3447,7 +3912,7 @@ type SecurityContext struct { func (x *SecurityContext) Reset() { *x = SecurityContext{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[34] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[39] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3459,7 +3924,7 @@ func (x *SecurityContext) String() string { func (*SecurityContext) ProtoMessage() {} func (x *SecurityContext) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[34] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[39] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3472,7 +3937,7 @@ func (x *SecurityContext) ProtoReflect() protoreflect.Message { // Deprecated: Use SecurityContext.ProtoReflect.Descriptor instead. func (*SecurityContext) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{34} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{39} } func (x *SecurityContext) GetCapabilities() *Capabilities { @@ -3511,7 +3976,7 @@ type Capabilities struct { func (x *Capabilities) Reset() { *x = Capabilities{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[35] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[40] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3523,7 +3988,7 @@ func (x *Capabilities) String() string { func (*Capabilities) ProtoMessage() {} func (x *Capabilities) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[35] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[40] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3536,7 +4001,7 @@ func (x *Capabilities) ProtoReflect() protoreflect.Message { // Deprecated: Use Capabilities.ProtoReflect.Descriptor instead. func (*Capabilities) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{35} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{40} } func (x *Capabilities) GetAdd() []string { @@ -3561,7 +4026,7 @@ type EnvVar struct { // // +k8s:required // +k8s:maxLength=256 # guardrail; - // +k8s:customValidation # printable ASCII except '=' + // +k8s:format=ate-env-var-name Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // value is the literal value. // @@ -3574,7 +4039,7 @@ type EnvVar struct { func (x *EnvVar) Reset() { *x = EnvVar{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[36] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[41] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3586,7 +4051,7 @@ func (x *EnvVar) String() string { func (*EnvVar) ProtoMessage() {} func (x *EnvVar) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[36] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[41] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3599,7 +4064,7 @@ func (x *EnvVar) ProtoReflect() protoreflect.Message { // Deprecated: Use EnvVar.ProtoReflect.Descriptor instead. func (*EnvVar) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{36} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{41} } func (x *EnvVar) GetName() string { @@ -3639,7 +4104,7 @@ type WakeupProbe struct { func (x *WakeupProbe) Reset() { *x = WakeupProbe{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[37] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[42] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3651,7 +4116,7 @@ func (x *WakeupProbe) String() string { func (*WakeupProbe) ProtoMessage() {} func (x *WakeupProbe) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[37] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[42] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3664,7 +4129,7 @@ func (x *WakeupProbe) ProtoReflect() protoreflect.Message { // Deprecated: Use WakeupProbe.ProtoReflect.Descriptor instead. func (*WakeupProbe) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{37} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{42} } func (x *WakeupProbe) GetHttpGet() *HttpGetAction { @@ -3690,7 +4155,7 @@ type HttpGetAction struct { // // +k8s:required // +k8s:maxLength=1024 - // +k8s:customValidation # RFC 3986 path shape; no regex/pattern tag exists + // +k8s:format=ate-http-probe-path Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"` // port is the container port to connect to. // @@ -3704,7 +4169,7 @@ type HttpGetAction struct { func (x *HttpGetAction) Reset() { *x = HttpGetAction{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[38] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[43] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3716,7 +4181,7 @@ func (x *HttpGetAction) String() string { func (*HttpGetAction) ProtoMessage() {} func (x *HttpGetAction) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[38] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[43] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3729,7 +4194,7 @@ func (x *HttpGetAction) ProtoReflect() protoreflect.Message { // Deprecated: Use HttpGetAction.ProtoReflect.Descriptor instead. func (*HttpGetAction) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{38} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{43} } func (x *HttpGetAction) GetPath() string { @@ -3761,7 +4226,6 @@ type Volume struct { DurableDir *DurableDirVolumeSource `protobuf:"bytes,2,opt,name=durable_dir,json=durableDir,proto3" json:"durable_dir,omitempty"` // external is a CSI volume: provisioned for this actor from a template. // - // +ate:preview=ExternalVolumes // +k8s:ifDisabled(ExternalVolumes)=+k8s:forbidden // +k8s:optional // +k8s:unionMember @@ -3780,7 +4244,7 @@ type Volume struct { func (x *Volume) Reset() { *x = Volume{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[39] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[44] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3792,7 +4256,7 @@ func (x *Volume) String() string { func (*Volume) ProtoMessage() {} func (x *Volume) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[39] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[44] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3805,7 +4269,7 @@ func (x *Volume) ProtoReflect() protoreflect.Message { // Deprecated: Use Volume.ProtoReflect.Descriptor instead. func (*Volume) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{39} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{44} } func (x *Volume) GetName() string { @@ -3858,7 +4322,7 @@ type ExternalVolumeSource struct { func (x *ExternalVolumeSource) Reset() { *x = ExternalVolumeSource{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[40] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[45] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3870,7 +4334,7 @@ func (x *ExternalVolumeSource) String() string { func (*ExternalVolumeSource) ProtoMessage() {} func (x *ExternalVolumeSource) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[40] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[45] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3883,7 +4347,7 @@ func (x *ExternalVolumeSource) ProtoReflect() protoreflect.Message { // Deprecated: Use ExternalVolumeSource.ProtoReflect.Descriptor instead. func (*ExternalVolumeSource) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{40} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{45} } func (x *ExternalVolumeSource) GetTemplate() *ExternalVolumeTemplate { @@ -3911,7 +4375,7 @@ type ImageVolumeSource struct { func (x *ImageVolumeSource) Reset() { *x = ImageVolumeSource{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[41] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[46] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3923,7 +4387,7 @@ func (x *ImageVolumeSource) String() string { func (*ImageVolumeSource) ProtoMessage() {} func (x *ImageVolumeSource) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[41] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[46] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3936,7 +4400,7 @@ func (x *ImageVolumeSource) ProtoReflect() protoreflect.Message { // Deprecated: Use ImageVolumeSource.ProtoReflect.Descriptor instead. func (*ImageVolumeSource) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{41} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{46} } func (x *ImageVolumeSource) GetReference() string { @@ -3956,7 +4420,7 @@ type DurableDirVolumeSource struct { func (x *DurableDirVolumeSource) Reset() { *x = DurableDirVolumeSource{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[42] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[47] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -3968,7 +4432,7 @@ func (x *DurableDirVolumeSource) String() string { func (*DurableDirVolumeSource) ProtoMessage() {} func (x *DurableDirVolumeSource) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[42] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[47] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -3981,7 +4445,7 @@ func (x *DurableDirVolumeSource) ProtoReflect() protoreflect.Message { // Deprecated: Use DurableDirVolumeSource.ProtoReflect.Descriptor instead. func (*DurableDirVolumeSource) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{42} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{47} } // ExternalVolumeTemplate provisions an external volume per actor; the volume @@ -4005,7 +4469,7 @@ type ExternalVolumeTemplate struct { func (x *ExternalVolumeTemplate) Reset() { *x = ExternalVolumeTemplate{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[43] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[48] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4017,7 +4481,7 @@ func (x *ExternalVolumeTemplate) String() string { func (*ExternalVolumeTemplate) ProtoMessage() {} func (x *ExternalVolumeTemplate) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[43] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[48] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4030,7 +4494,7 @@ func (x *ExternalVolumeTemplate) ProtoReflect() protoreflect.Message { // Deprecated: Use ExternalVolumeTemplate.ProtoReflect.Descriptor instead. func (*ExternalVolumeTemplate) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{43} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{48} } func (x *ExternalVolumeTemplate) GetCapacityBytes() int64 { @@ -4047,6 +4511,213 @@ func (x *ExternalVolumeTemplate) GetStorageClassName() string { return "" } +// CsiDriver configures how the control plane connects to a CSI driver's +// Controller service. Worker nodes connect to the CSI Node service at the +// standard Substrate socket path. Global-scoped: metadata.atespace must be +// empty. +type CsiDriver struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Common resource metadata: name, uid, version, timestamps. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:forbidden + Metadata *ResourceMetadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` + // driver_name is the CSI driver name, e.g. "nfs.csi.k8s.io". It is a DNS + // subdomain of at most 63 characters and is unique across all CsiDrivers. + // + // +k8s:required + // +k8s:maxLength=63 + // +k8s:immutable + // +k8s:format=k8s-long-name + DriverName string `protobuf:"bytes,2,opt,name=driver_name,json=driverName,proto3" json:"driver_name,omitempty"` + // controller_endpoint is the TCP network address of the CSI Controller + // service. + // + // +k8s:required + ControllerEndpoint *CsiDriverEndpoint `protobuf:"bytes,3,opt,name=controller_endpoint,json=controllerEndpoint,proto3" json:"controller_endpoint,omitempty"` + // tls configures pod-identity mTLS for connections to controller_endpoint. + // Omit to connect in plaintext. + // + // +k8s:optional + Tls *CsiDriverTlsConfig `protobuf:"bytes,4,opt,name=tls,proto3" json:"tls,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CsiDriver) Reset() { + *x = CsiDriver{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[49] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CsiDriver) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CsiDriver) ProtoMessage() {} + +func (x *CsiDriver) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[49] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CsiDriver.ProtoReflect.Descriptor instead. +func (*CsiDriver) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{49} +} + +func (x *CsiDriver) GetMetadata() *ResourceMetadata { + if x != nil { + return x.Metadata + } + return nil +} + +func (x *CsiDriver) GetDriverName() string { + if x != nil { + return x.DriverName + } + return "" +} + +func (x *CsiDriver) GetControllerEndpoint() *CsiDriverEndpoint { + if x != nil { + return x.ControllerEndpoint + } + return nil +} + +func (x *CsiDriver) GetTls() *CsiDriverTlsConfig { + if x != nil { + return x.Tls + } + return nil +} + +// CsiDriverEndpoint identifies the network address of a CSI Controller service. +type CsiDriverEndpoint struct { + state protoimpl.MessageState `protogen:"open.v1"` + // host is the DNS name or IP address (IPv4 or IPv6 without a zone ID) of the + // CSI Controller service, e.g. + // "csi-nfs-controller.kube-system.svc.cluster.local" or "127.0.0.1". + // + // +k8s:required + // +k8s:maxLength=253 + // +k8s:customValidation # DNS-1123 subdomain or IPv4/IPv6 address without zone + Host string `protobuf:"bytes,1,opt,name=host,proto3" json:"host,omitempty"` + // port is the TCP port number of the CSI Controller service. + // + // +k8s:required + // +k8s:minimum=1 + // +k8s:maximum=65535 + Port int32 `protobuf:"varint,2,opt,name=port,proto3" json:"port,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CsiDriverEndpoint) Reset() { + *x = CsiDriverEndpoint{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[50] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CsiDriverEndpoint) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CsiDriverEndpoint) ProtoMessage() {} + +func (x *CsiDriverEndpoint) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[50] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CsiDriverEndpoint.ProtoReflect.Descriptor instead. +func (*CsiDriverEndpoint) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{50} +} + +func (x *CsiDriverEndpoint) GetHost() string { + if x != nil { + return x.Host + } + return "" +} + +func (x *CsiDriverEndpoint) GetPort() int32 { + if x != nil { + return x.Port + } + return 0 +} + +// CsiDriverTlsConfig configures pod-identity mTLS for CSI controller gRPC +// connections. Omit CsiDriver.tls for plaintext. +type CsiDriverTlsConfig struct { + state protoimpl.MessageState `protogen:"open.v1"` + // server_name is the expected TLS server name on the controller certificate. + // + // +k8s:required + // +k8s:format=k8s-long-name + // +k8s:maxLength=253 + ServerName string `protobuf:"bytes,1,opt,name=server_name,json=serverName,proto3" json:"server_name,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CsiDriverTlsConfig) Reset() { + *x = CsiDriverTlsConfig{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[51] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CsiDriverTlsConfig) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CsiDriverTlsConfig) ProtoMessage() {} + +func (x *CsiDriverTlsConfig) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[51] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CsiDriverTlsConfig.ProtoReflect.Descriptor instead. +func (*CsiDriverTlsConfig) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{51} +} + +func (x *CsiDriverTlsConfig) GetServerName() string { + if x != nil { + return x.ServerName + } + return "" +} + // SystemInfoVolumeSource is a read-only volume of substrate-generated // per-actor files (identity fields, projected trust bundles), regenerated by // atelet on every Run/Restore. @@ -4067,7 +4738,7 @@ type SystemInfoVolumeSource struct { func (x *SystemInfoVolumeSource) Reset() { *x = SystemInfoVolumeSource{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[44] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[52] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4079,7 +4750,7 @@ func (x *SystemInfoVolumeSource) String() string { func (*SystemInfoVolumeSource) ProtoMessage() {} func (x *SystemInfoVolumeSource) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[44] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[52] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4092,7 +4763,7 @@ func (x *SystemInfoVolumeSource) ProtoReflect() protoreflect.Message { // Deprecated: Use SystemInfoVolumeSource.ProtoReflect.Descriptor instead. func (*SystemInfoVolumeSource) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{44} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{52} } func (x *SystemInfoVolumeSource) GetDataSources() []*SystemInfoDataSource { @@ -4118,7 +4789,7 @@ type SystemInfoDataSource struct { func (x *SystemInfoDataSource) Reset() { *x = SystemInfoDataSource{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[45] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[53] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4130,7 +4801,7 @@ func (x *SystemInfoDataSource) String() string { func (*SystemInfoDataSource) ProtoMessage() {} func (x *SystemInfoDataSource) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[45] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[53] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4143,7 +4814,7 @@ func (x *SystemInfoDataSource) ProtoReflect() protoreflect.Message { // Deprecated: Use SystemInfoDataSource.ProtoReflect.Descriptor instead. func (*SystemInfoDataSource) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{45} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{53} } func (x *SystemInfoDataSource) GetActorMetadata() *ActorMetadataDataSource { @@ -4180,7 +4851,7 @@ type ActorMetadataDataSource struct { func (x *ActorMetadataDataSource) Reset() { *x = ActorMetadataDataSource{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[46] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[54] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4192,7 +4863,7 @@ func (x *ActorMetadataDataSource) String() string { func (*ActorMetadataDataSource) ProtoMessage() {} func (x *ActorMetadataDataSource) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[46] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[54] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4205,7 +4876,7 @@ func (x *ActorMetadataDataSource) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorMetadataDataSource.ProtoReflect.Descriptor instead. func (*ActorMetadataDataSource) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{46} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{54} } func (x *ActorMetadataDataSource) GetItems() []*ActorMetadataItem { @@ -4237,7 +4908,7 @@ type ActorMetadataItem struct { func (x *ActorMetadataItem) Reset() { *x = ActorMetadataItem{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[47] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[55] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4249,7 +4920,7 @@ func (x *ActorMetadataItem) String() string { func (*ActorMetadataItem) ProtoMessage() {} func (x *ActorMetadataItem) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[47] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[55] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4262,7 +4933,7 @@ func (x *ActorMetadataItem) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorMetadataItem.ProtoReflect.Descriptor instead. func (*ActorMetadataItem) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{47} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{55} } func (x *ActorMetadataItem) GetField() ActorMetadataField { @@ -4314,7 +4985,7 @@ type TrustBundleDataSource struct { func (x *TrustBundleDataSource) Reset() { *x = TrustBundleDataSource{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[48] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[56] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4326,7 +4997,7 @@ func (x *TrustBundleDataSource) String() string { func (*TrustBundleDataSource) ProtoMessage() {} func (x *TrustBundleDataSource) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[48] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[56] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4339,7 +5010,7 @@ func (x *TrustBundleDataSource) ProtoReflect() protoreflect.Message { // Deprecated: Use TrustBundleDataSource.ProtoReflect.Descriptor instead. func (*TrustBundleDataSource) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{48} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{56} } func (x *TrustBundleDataSource) GetNames() []string { @@ -4379,7 +5050,7 @@ type VolumeMount struct { func (x *VolumeMount) Reset() { *x = VolumeMount{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[49] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[57] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4391,7 +5062,7 @@ func (x *VolumeMount) String() string { func (*VolumeMount) ProtoMessage() {} func (x *VolumeMount) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[49] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[57] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4404,7 +5075,7 @@ func (x *VolumeMount) ProtoReflect() protoreflect.Message { // Deprecated: Use VolumeMount.ProtoReflect.Descriptor instead. func (*VolumeMount) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{49} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{57} } func (x *VolumeMount) GetName() string { @@ -4433,7 +5104,7 @@ type CreateAtespaceRequest struct { func (x *CreateAtespaceRequest) Reset() { *x = CreateAtespaceRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[50] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[58] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4445,7 +5116,7 @@ func (x *CreateAtespaceRequest) String() string { func (*CreateAtespaceRequest) ProtoMessage() {} func (x *CreateAtespaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[50] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[58] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4458,7 +5129,7 @@ func (x *CreateAtespaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateAtespaceRequest.ProtoReflect.Descriptor instead. func (*CreateAtespaceRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{50} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{58} } func (x *CreateAtespaceRequest) GetAtespace() *Atespace { @@ -4471,7 +5142,7 @@ func (x *CreateAtespaceRequest) GetAtespace() *Atespace { type GetAtespaceRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Atespace *ObjectRef `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -4479,7 +5150,7 @@ type GetAtespaceRequest struct { func (x *GetAtespaceRequest) Reset() { *x = GetAtespaceRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[51] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[59] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4491,7 +5162,7 @@ func (x *GetAtespaceRequest) String() string { func (*GetAtespaceRequest) ProtoMessage() {} func (x *GetAtespaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[51] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[59] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4504,7 +5175,7 @@ func (x *GetAtespaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetAtespaceRequest.ProtoReflect.Descriptor instead. func (*GetAtespaceRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{51} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{59} } func (x *GetAtespaceRequest) GetAtespace() *ObjectRef { @@ -4526,7 +5197,7 @@ type ListAtespacesRequest struct { func (x *ListAtespacesRequest) Reset() { *x = ListAtespacesRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[52] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[60] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4538,7 +5209,7 @@ func (x *ListAtespacesRequest) String() string { func (*ListAtespacesRequest) ProtoMessage() {} func (x *ListAtespacesRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[52] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[60] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4551,7 +5222,7 @@ func (x *ListAtespacesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAtespacesRequest.ProtoReflect.Descriptor instead. func (*ListAtespacesRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{52} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{60} } func (x *ListAtespacesRequest) GetOptions() *ListOptions { @@ -4573,7 +5244,7 @@ type ListAtespacesResponse struct { func (x *ListAtespacesResponse) Reset() { *x = ListAtespacesResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[53] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[61] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4585,7 +5256,7 @@ func (x *ListAtespacesResponse) String() string { func (*ListAtespacesResponse) ProtoMessage() {} func (x *ListAtespacesResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[53] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[61] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4598,7 +5269,7 @@ func (x *ListAtespacesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListAtespacesResponse.ProtoReflect.Descriptor instead. func (*ListAtespacesResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{53} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{61} } func (x *ListAtespacesResponse) GetAtespaces() []*Atespace { @@ -4618,7 +5289,7 @@ func (x *ListAtespacesResponse) GetNextPageToken() string { type DeleteAtespaceRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Atespace *ObjectRef `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"` // Optional per-delete preconditions. // @@ -4630,7 +5301,7 @@ type DeleteAtespaceRequest struct { func (x *DeleteAtespaceRequest) Reset() { *x = DeleteAtespaceRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[54] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[62] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4642,7 +5313,7 @@ func (x *DeleteAtespaceRequest) String() string { func (*DeleteAtespaceRequest) ProtoMessage() {} func (x *DeleteAtespaceRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[54] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[62] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4655,7 +5326,7 @@ func (x *DeleteAtespaceRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteAtespaceRequest.ProtoReflect.Descriptor instead. func (*DeleteAtespaceRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{54} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{62} } func (x *DeleteAtespaceRequest) GetAtespace() *ObjectRef { @@ -4672,33 +5343,33 @@ func (x *DeleteAtespaceRequest) GetOptions() *DeleteOptions { return nil } -type CreateActorTemplateRequest struct { +// CreateCsiDriverRequest creates a CsiDriver. +type CreateCsiDriverRequest struct { state protoimpl.MessageState `protogen:"open.v1"` - // The actor template version to create. Server-assigned metadata (uid, - // version, timestamps) is ignored, as are the status fields. + // The driver to create. metadata.name is required and metadata.atespace + // must be empty. // // +k8s:required - // +k8s:customValidation # volume_mounts must reference declared volumes; golden policy requires golden snapshots - ActorTemplate *ActorTemplate `protobuf:"bytes,1,opt,name=actor_template,json=actorTemplate,proto3" json:"actor_template,omitempty"` + CsiDriver *CsiDriver `protobuf:"bytes,1,opt,name=csi_driver,json=csiDriver,proto3" json:"csi_driver,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *CreateActorTemplateRequest) Reset() { - *x = CreateActorTemplateRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[55] +func (x *CreateCsiDriverRequest) Reset() { + *x = CreateCsiDriverRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[63] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *CreateActorTemplateRequest) String() string { +func (x *CreateCsiDriverRequest) String() string { return protoimpl.X.MessageStringOf(x) } -func (*CreateActorTemplateRequest) ProtoMessage() {} +func (*CreateCsiDriverRequest) ProtoMessage() {} -func (x *CreateActorTemplateRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[55] +func (x *CreateCsiDriverRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[63] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4709,42 +5380,361 @@ func (x *CreateActorTemplateRequest) ProtoReflect() protoreflect.Message { return mi.MessageOf(x) } -// Deprecated: Use CreateActorTemplateRequest.ProtoReflect.Descriptor instead. -func (*CreateActorTemplateRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{55} +// Deprecated: Use CreateCsiDriverRequest.ProtoReflect.Descriptor instead. +func (*CreateCsiDriverRequest) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{63} } -func (x *CreateActorTemplateRequest) GetActorTemplate() *ActorTemplate { +func (x *CreateCsiDriverRequest) GetCsiDriver() *CsiDriver { if x != nil { - return x.ActorTemplate + return x.CsiDriver } return nil } -type GetActorTemplateRequest struct { +// GetCsiDriverRequest identifies the CsiDriver to get. +type GetCsiDriverRequest struct { state protoimpl.MessageState `protogen:"open.v1"` + // The driver to get. atespace must be empty. + // // +k8s:required - // +k8s:subfield(atespace)=+k8s:required - ActorTemplate *ObjectRef `protobuf:"bytes,1,opt,name=actor_template,json=actorTemplate,proto3" json:"actor_template,omitempty"` + // +k8s:subfield(atespace)=+k8s:forbidden + CsiDriver *ObjectRef `protobuf:"bytes,1,opt,name=csi_driver,json=csiDriver,proto3" json:"csi_driver,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } -func (x *GetActorTemplateRequest) Reset() { - *x = GetActorTemplateRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[56] +func (x *GetCsiDriverRequest) Reset() { + *x = GetCsiDriverRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[64] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } -func (x *GetActorTemplateRequest) String() string { +func (x *GetCsiDriverRequest) String() string { return protoimpl.X.MessageStringOf(x) } -func (*GetActorTemplateRequest) ProtoMessage() {} +func (*GetCsiDriverRequest) ProtoMessage() {} -func (x *GetActorTemplateRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[56] +func (x *GetCsiDriverRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[64] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetCsiDriverRequest.ProtoReflect.Descriptor instead. +func (*GetCsiDriverRequest) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{64} +} + +func (x *GetCsiDriverRequest) GetCsiDriver() *ObjectRef { + if x != nil { + return x.CsiDriver + } + return nil +} + +// ListCsiDriversRequest asks for a page of CsiDrivers. +type ListCsiDriversRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Pagination controls. + // + // +k8s:optional + Options *ListOptions `protobuf:"bytes,1,opt,name=options,proto3" json:"options,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListCsiDriversRequest) Reset() { + *x = ListCsiDriversRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[65] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListCsiDriversRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListCsiDriversRequest) ProtoMessage() {} + +func (x *ListCsiDriversRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[65] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListCsiDriversRequest.ProtoReflect.Descriptor instead. +func (*ListCsiDriversRequest) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{65} +} + +func (x *ListCsiDriversRequest) GetOptions() *ListOptions { + if x != nil { + return x.Options + } + return nil +} + +// ListCsiDriversResponse is one page of CsiDrivers. +type ListCsiDriversResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The page of drivers. This list may be empty even if there are more results. + CsiDrivers []*CsiDriver `protobuf:"bytes,1,rep,name=csi_drivers,json=csiDrivers,proto3" json:"csi_drivers,omitempty"` + // Pagination token for the next page. Empty if this is the last page. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListCsiDriversResponse) Reset() { + *x = ListCsiDriversResponse{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[66] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListCsiDriversResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListCsiDriversResponse) ProtoMessage() {} + +func (x *ListCsiDriversResponse) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[66] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListCsiDriversResponse.ProtoReflect.Descriptor instead. +func (*ListCsiDriversResponse) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{66} +} + +func (x *ListCsiDriversResponse) GetCsiDrivers() []*CsiDriver { + if x != nil { + return x.CsiDrivers + } + return nil +} + +func (x *ListCsiDriversResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + +// UpdateCsiDriverRequest updates a CsiDriver. +type UpdateCsiDriverRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The driver to update. csi_driver.metadata.name identifies which + // resource to update, and metadata.atespace must be empty. + // csi_driver.metadata.uid and csi_driver.metadata.version are + // required preconditions. + // + // controller_endpoint and tls are replaced with what the request carries, + // and any omitted optional field is cleared. driver_name is immutable. + // + // +k8s:required + // +k8s:opaqueType # updates are handled in 2 steps, do not descend + // +k8s:customValidation # descend into metadata + // +k8s:subfield(metadata)=+k8s:required + // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:forbidden + CsiDriver *CsiDriver `protobuf:"bytes,1,opt,name=csi_driver,json=csiDriver,proto3" json:"csi_driver,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *UpdateCsiDriverRequest) Reset() { + *x = UpdateCsiDriverRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[67] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *UpdateCsiDriverRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*UpdateCsiDriverRequest) ProtoMessage() {} + +func (x *UpdateCsiDriverRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[67] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use UpdateCsiDriverRequest.ProtoReflect.Descriptor instead. +func (*UpdateCsiDriverRequest) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{67} +} + +func (x *UpdateCsiDriverRequest) GetCsiDriver() *CsiDriver { + if x != nil { + return x.CsiDriver + } + return nil +} + +// DeleteCsiDriverRequest identifies the CsiDriver to delete. +type DeleteCsiDriverRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The driver to delete. atespace must be empty. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:forbidden + CsiDriver *ObjectRef `protobuf:"bytes,1,opt,name=csi_driver,json=csiDriver,proto3" json:"csi_driver,omitempty"` + // Optional per-delete preconditions. + // + // +k8s:optional + Options *DeleteOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *DeleteCsiDriverRequest) Reset() { + *x = DeleteCsiDriverRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[68] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *DeleteCsiDriverRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*DeleteCsiDriverRequest) ProtoMessage() {} + +func (x *DeleteCsiDriverRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[68] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use DeleteCsiDriverRequest.ProtoReflect.Descriptor instead. +func (*DeleteCsiDriverRequest) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{68} +} + +func (x *DeleteCsiDriverRequest) GetCsiDriver() *ObjectRef { + if x != nil { + return x.CsiDriver + } + return nil +} + +func (x *DeleteCsiDriverRequest) GetOptions() *DeleteOptions { + if x != nil { + return x.Options + } + return nil +} + +type CreateActorTemplateRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The actor template version to create. Server-assigned metadata (uid, + // version, timestamps) is ignored, as are the status fields. + // + // +k8s:required + // +k8s:customValidation # volume_mounts must reference declared volumes; golden policy requires golden snapshots + ActorTemplate *ActorTemplate `protobuf:"bytes,1,opt,name=actor_template,json=actorTemplate,proto3" json:"actor_template,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *CreateActorTemplateRequest) Reset() { + *x = CreateActorTemplateRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[69] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *CreateActorTemplateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*CreateActorTemplateRequest) ProtoMessage() {} + +func (x *CreateActorTemplateRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[69] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use CreateActorTemplateRequest.ProtoReflect.Descriptor instead. +func (*CreateActorTemplateRequest) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{69} +} + +func (x *CreateActorTemplateRequest) GetActorTemplate() *ActorTemplate { + if x != nil { + return x.ActorTemplate + } + return nil +} + +type GetActorTemplateRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // +k8s:required + // +k8s:subfield(atespace)=+k8s:required + ActorTemplate *ObjectRef `protobuf:"bytes,1,opt,name=actor_template,json=actorTemplate,proto3" json:"actor_template,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetActorTemplateRequest) Reset() { + *x = GetActorTemplateRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[70] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetActorTemplateRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetActorTemplateRequest) ProtoMessage() {} + +func (x *GetActorTemplateRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[70] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4757,7 +5747,7 @@ func (x *GetActorTemplateRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetActorTemplateRequest.ProtoReflect.Descriptor instead. func (*GetActorTemplateRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{56} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{70} } func (x *GetActorTemplateRequest) GetActorTemplate() *ObjectRef { @@ -4785,7 +5775,7 @@ type ListActorTemplatesRequest struct { func (x *ListActorTemplatesRequest) Reset() { *x = ListActorTemplatesRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[57] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[71] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4797,7 +5787,7 @@ func (x *ListActorTemplatesRequest) String() string { func (*ListActorTemplatesRequest) ProtoMessage() {} func (x *ListActorTemplatesRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[57] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[71] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4810,7 +5800,7 @@ func (x *ListActorTemplatesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListActorTemplatesRequest.ProtoReflect.Descriptor instead. func (*ListActorTemplatesRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{57} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{71} } func (x *ListActorTemplatesRequest) GetAtespace() string { @@ -4840,7 +5830,7 @@ type ListActorTemplatesResponse struct { func (x *ListActorTemplatesResponse) Reset() { *x = ListActorTemplatesResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[58] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[72] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4852,7 +5842,7 @@ func (x *ListActorTemplatesResponse) String() string { func (*ListActorTemplatesResponse) ProtoMessage() {} func (x *ListActorTemplatesResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[58] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[72] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4865,7 +5855,7 @@ func (x *ListActorTemplatesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListActorTemplatesResponse.ProtoReflect.Descriptor instead. func (*ListActorTemplatesResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{58} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{72} } func (x *ListActorTemplatesResponse) GetActorTemplates() []*ActorTemplate { @@ -4897,7 +5887,7 @@ type DeleteActorTemplateRequest struct { func (x *DeleteActorTemplateRequest) Reset() { *x = DeleteActorTemplateRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[59] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[73] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4909,7 +5899,7 @@ func (x *DeleteActorTemplateRequest) String() string { func (*DeleteActorTemplateRequest) ProtoMessage() {} func (x *DeleteActorTemplateRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[59] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[73] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4922,7 +5912,7 @@ func (x *DeleteActorTemplateRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteActorTemplateRequest.ProtoReflect.Descriptor instead. func (*DeleteActorTemplateRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{59} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{73} } func (x *DeleteActorTemplateRequest) GetActorTemplate() *ObjectRef { @@ -4950,7 +5940,7 @@ type GetActorRequest struct { func (x *GetActorRequest) Reset() { *x = GetActorRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[60] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[74] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -4962,7 +5952,7 @@ func (x *GetActorRequest) String() string { func (*GetActorRequest) ProtoMessage() {} func (x *GetActorRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[60] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[74] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -4975,7 +5965,7 @@ func (x *GetActorRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetActorRequest.ProtoReflect.Descriptor instead. func (*GetActorRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{60} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{74} } func (x *GetActorRequest) GetActor() *ObjectRef { @@ -4998,7 +5988,7 @@ type CreateActorRequest struct { func (x *CreateActorRequest) Reset() { *x = CreateActorRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[61] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[75] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5010,7 +6000,7 @@ func (x *CreateActorRequest) String() string { func (*CreateActorRequest) ProtoMessage() {} func (x *CreateActorRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[61] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[75] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5023,7 +6013,7 @@ func (x *CreateActorRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateActorRequest.ProtoReflect.Descriptor instead. func (*CreateActorRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{61} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{75} } func (x *CreateActorRequest) GetActor() *Actor { @@ -5045,8 +6035,9 @@ type UpdateActorRequest struct { // // +k8s:required // +k8s:opaqueType # updates are handled in 2 steps, do not descend + // +k8s:customValidation # descend into metadata // +k8s:subfield(metadata)=+k8s:required - // +k8s:customValidation # TODO: when we get nested subfields, require metadata.atespace + // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:required Actor *Actor `protobuf:"bytes,1,opt,name=actor,proto3" json:"actor,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -5054,7 +6045,7 @@ type UpdateActorRequest struct { func (x *UpdateActorRequest) Reset() { *x = UpdateActorRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[62] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[76] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5066,7 +6057,7 @@ func (x *UpdateActorRequest) String() string { func (*UpdateActorRequest) ProtoMessage() {} func (x *UpdateActorRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[62] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[76] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5079,7 +6070,7 @@ func (x *UpdateActorRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateActorRequest.ProtoReflect.Descriptor instead. func (*UpdateActorRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{62} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{76} } func (x *UpdateActorRequest) GetActor() *Actor { @@ -5094,7 +6085,7 @@ type SuspendActorRequest struct { // +k8s:required // +k8s:subfield(atespace)=+k8s:required Actor *ObjectRef `protobuf:"bytes,1,opt,name=actor,proto3" json:"actor,omitempty"` - // options controls how SuspendActor persists the actor's snapshot. + // Optional per-suspend controls and precondition guards. // // +k8s:optional Options *SuspendOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` @@ -5104,7 +6095,7 @@ type SuspendActorRequest struct { func (x *SuspendActorRequest) Reset() { *x = SuspendActorRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[63] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[77] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5116,7 +6107,7 @@ func (x *SuspendActorRequest) String() string { func (*SuspendActorRequest) ProtoMessage() {} func (x *SuspendActorRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[63] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[77] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5129,7 +6120,7 @@ func (x *SuspendActorRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SuspendActorRequest.ProtoReflect.Descriptor instead. func (*SuspendActorRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{63} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{77} } func (x *SuspendActorRequest) GetActor() *ObjectRef { @@ -5155,7 +6146,7 @@ type SuspendActorResponse struct { func (x *SuspendActorResponse) Reset() { *x = SuspendActorResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[64] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[78] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5167,7 +6158,7 @@ func (x *SuspendActorResponse) String() string { func (*SuspendActorResponse) ProtoMessage() {} func (x *SuspendActorResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[64] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[78] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5180,7 +6171,7 @@ func (x *SuspendActorResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SuspendActorResponse.ProtoReflect.Descriptor instead. func (*SuspendActorResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{64} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{78} } func (x *SuspendActorResponse) GetActor() *Actor { @@ -5190,7 +6181,8 @@ func (x *SuspendActorResponse) GetActor() *Actor { return nil } -// SuspendOptions tunes how SuspendActor persists the actor's snapshot. +// SuspendOptions are the optional controls a SuspendActor request may carry. +// A guard that does not match the actor fails the request with `ABORTED`. type SuspendOptions struct { state protoimpl.MessageState `protogen:"open.v1"` // mode selects when SuspendActor returns relative to the snapshot reaching @@ -5199,14 +6191,26 @@ type SuspendOptions struct { // +k8s:optional // +k8s:minimum=1 // +k8s:maximum=2 # keep this in sync with the DurabilityMode enum - Mode DurabilityMode `protobuf:"varint,1,opt,name=mode,proto3,enum=substrate.ateapi.v1.DurabilityMode" json:"mode,omitempty"` + Mode DurabilityMode `protobuf:"varint,1,opt,name=mode,proto3,enum=substrate.ateapi.v1.DurabilityMode" json:"mode,omitempty"` + // Suspend only if the actor is still at this version. Zero skips the check. + // A call can change `version` before it fails, so read the actor again before + // a retry. + // + // +k8s:optional + // +k8s:minimum=1 + Version int64 `protobuf:"varint,2,opt,name=version,proto3" json:"version,omitempty"` + // Suspend only if the actor still has this uid. Empty skips the check. + // + // +k8s:optional + // +k8s:format=k8s-uuid + Uid string `protobuf:"bytes,3,opt,name=uid,proto3" json:"uid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *SuspendOptions) Reset() { *x = SuspendOptions{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[65] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[79] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5218,7 +6222,7 @@ func (x *SuspendOptions) String() string { func (*SuspendOptions) ProtoMessage() {} func (x *SuspendOptions) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[65] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[79] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5231,28 +6235,46 @@ func (x *SuspendOptions) ProtoReflect() protoreflect.Message { // Deprecated: Use SuspendOptions.ProtoReflect.Descriptor instead. func (*SuspendOptions) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{65} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{79} +} + +func (x *SuspendOptions) GetMode() DurabilityMode { + if x != nil { + return x.Mode + } + return DurabilityMode_DURABILITY_MODE_UNSPECIFIED +} + +func (x *SuspendOptions) GetVersion() int64 { + if x != nil { + return x.Version + } + return 0 } -func (x *SuspendOptions) GetMode() DurabilityMode { +func (x *SuspendOptions) GetUid() string { if x != nil { - return x.Mode + return x.Uid } - return DurabilityMode_DURABILITY_MODE_UNSPECIFIED + return "" } type ResumeActorRequest struct { state protoimpl.MessageState `protogen:"open.v1"` // +k8s:required // +k8s:subfield(atespace)=+k8s:required - Actor *ObjectRef `protobuf:"bytes,1,opt,name=actor,proto3" json:"actor,omitempty"` + Actor *ObjectRef `protobuf:"bytes,1,opt,name=actor,proto3" json:"actor,omitempty"` + // Optional per-resume controls and precondition guards. + // + // +k8s:optional + Options *ResumeActorRequest_Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ResumeActorRequest) Reset() { *x = ResumeActorRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[66] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[80] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5264,7 +6286,7 @@ func (x *ResumeActorRequest) String() string { func (*ResumeActorRequest) ProtoMessage() {} func (x *ResumeActorRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[66] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[80] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5277,7 +6299,7 @@ func (x *ResumeActorRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ResumeActorRequest.ProtoReflect.Descriptor instead. func (*ResumeActorRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{66} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{80} } func (x *ResumeActorRequest) GetActor() *ObjectRef { @@ -5287,6 +6309,13 @@ func (x *ResumeActorRequest) GetActor() *ObjectRef { return nil } +func (x *ResumeActorRequest) GetOptions() *ResumeActorRequest_Options { + if x != nil { + return x.Options + } + return nil +} + type ResumeActorResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Actor *Actor `protobuf:"bytes,1,opt,name=actor,proto3" json:"actor,omitempty"` @@ -5299,7 +6328,7 @@ type ResumeActorResponse struct { func (x *ResumeActorResponse) Reset() { *x = ResumeActorResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[67] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[81] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5311,7 +6340,7 @@ func (x *ResumeActorResponse) String() string { func (*ResumeActorResponse) ProtoMessage() {} func (x *ResumeActorResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[67] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[81] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5324,7 +6353,7 @@ func (x *ResumeActorResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ResumeActorResponse.ProtoReflect.Descriptor instead. func (*ResumeActorResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{67} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{81} } func (x *ResumeActorResponse) GetActor() *Actor { @@ -5347,14 +6376,18 @@ type RevertActorRequest struct { // actor to revert. // +k8s:required // +k8s:subfield(atespace)=+k8s:required - Actor *ObjectRef `protobuf:"bytes,1,opt,name=actor,proto3" json:"actor,omitempty"` + Actor *ObjectRef `protobuf:"bytes,1,opt,name=actor,proto3" json:"actor,omitempty"` + // Optional per-revert controls and precondition guards. + // + // +k8s:optional + Options *RevertActorRequest_Options `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *RevertActorRequest) Reset() { *x = RevertActorRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[68] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[82] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5366,7 +6399,7 @@ func (x *RevertActorRequest) String() string { func (*RevertActorRequest) ProtoMessage() {} func (x *RevertActorRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[68] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[82] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5379,7 +6412,7 @@ func (x *RevertActorRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RevertActorRequest.ProtoReflect.Descriptor instead. func (*RevertActorRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{68} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{82} } func (x *RevertActorRequest) GetActor() *ObjectRef { @@ -5389,6 +6422,13 @@ func (x *RevertActorRequest) GetActor() *ObjectRef { return nil } +func (x *RevertActorRequest) GetOptions() *RevertActorRequest_Options { + if x != nil { + return x.Options + } + return nil +} + // RevertActorResponse holds the reverted Actor. type RevertActorResponse struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -5401,7 +6441,7 @@ type RevertActorResponse struct { func (x *RevertActorResponse) Reset() { *x = RevertActorResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[69] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[83] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5413,7 +6453,7 @@ func (x *RevertActorResponse) String() string { func (*RevertActorResponse) ProtoMessage() {} func (x *RevertActorResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[69] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[83] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5426,7 +6466,7 @@ func (x *RevertActorResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RevertActorResponse.ProtoReflect.Descriptor instead. func (*RevertActorResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{69} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{83} } func (x *RevertActorResponse) GetActor() *Actor { @@ -5451,7 +6491,7 @@ type DeleteActorRequest struct { func (x *DeleteActorRequest) Reset() { *x = DeleteActorRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[70] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[84] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5463,7 +6503,7 @@ func (x *DeleteActorRequest) String() string { func (*DeleteActorRequest) ProtoMessage() {} func (x *DeleteActorRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[70] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[84] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5476,7 +6516,7 @@ func (x *DeleteActorRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteActorRequest.ProtoReflect.Descriptor instead. func (*DeleteActorRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{70} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{84} } func (x *DeleteActorRequest) GetActor() *ObjectRef { @@ -5504,8 +6544,7 @@ type GetActorEgressPolicyRequest struct { // Name of the singleton egress policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -5513,7 +6552,7 @@ type GetActorEgressPolicyRequest struct { func (x *GetActorEgressPolicyRequest) Reset() { *x = GetActorEgressPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[71] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[85] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5525,7 +6564,7 @@ func (x *GetActorEgressPolicyRequest) String() string { func (*GetActorEgressPolicyRequest) ProtoMessage() {} func (x *GetActorEgressPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[71] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[85] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5538,7 +6577,7 @@ func (x *GetActorEgressPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetActorEgressPolicyRequest.ProtoReflect.Descriptor instead. func (*GetActorEgressPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{71} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{85} } func (x *GetActorEgressPolicyRequest) GetActor() *ObjectRef { @@ -5576,7 +6615,7 @@ type CreateActorEgressPolicyRequest struct { func (x *CreateActorEgressPolicyRequest) Reset() { *x = CreateActorEgressPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[72] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[86] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5588,7 +6627,7 @@ func (x *CreateActorEgressPolicyRequest) String() string { func (*CreateActorEgressPolicyRequest) ProtoMessage() {} func (x *CreateActorEgressPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[72] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[86] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5601,7 +6640,7 @@ func (x *CreateActorEgressPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateActorEgressPolicyRequest.ProtoReflect.Descriptor instead. func (*CreateActorEgressPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{72} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{86} } func (x *CreateActorEgressPolicyRequest) GetActor() *ObjectRef { @@ -5639,7 +6678,7 @@ type UpdateActorEgressPolicyRequest struct { func (x *UpdateActorEgressPolicyRequest) Reset() { *x = UpdateActorEgressPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[73] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[87] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5651,7 +6690,7 @@ func (x *UpdateActorEgressPolicyRequest) String() string { func (*UpdateActorEgressPolicyRequest) ProtoMessage() {} func (x *UpdateActorEgressPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[73] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[87] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5664,7 +6703,7 @@ func (x *UpdateActorEgressPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateActorEgressPolicyRequest.ProtoReflect.Descriptor instead. func (*UpdateActorEgressPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{73} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{87} } func (x *UpdateActorEgressPolicyRequest) GetActor() *ObjectRef { @@ -5692,8 +6731,7 @@ type DeleteActorEgressPolicyRequest struct { // Name of the singleton egress policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` // Optional per-delete preconditions. // @@ -5705,7 +6743,7 @@ type DeleteActorEgressPolicyRequest struct { func (x *DeleteActorEgressPolicyRequest) Reset() { *x = DeleteActorEgressPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[74] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[88] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5717,7 +6755,7 @@ func (x *DeleteActorEgressPolicyRequest) String() string { func (*DeleteActorEgressPolicyRequest) ProtoMessage() {} func (x *DeleteActorEgressPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[74] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[88] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5730,7 +6768,7 @@ func (x *DeleteActorEgressPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteActorEgressPolicyRequest.ProtoReflect.Descriptor instead. func (*DeleteActorEgressPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{74} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{88} } func (x *DeleteActorEgressPolicyRequest) GetActor() *ObjectRef { @@ -5765,7 +6803,7 @@ type GetTagRequest struct { func (x *GetTagRequest) Reset() { *x = GetTagRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[75] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[89] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5777,7 +6815,7 @@ func (x *GetTagRequest) String() string { func (*GetTagRequest) ProtoMessage() {} func (x *GetTagRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[75] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[89] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5790,7 +6828,7 @@ func (x *GetTagRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetTagRequest.ProtoReflect.Descriptor instead. func (*GetTagRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{75} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{89} } func (x *GetTagRequest) GetTag() *ObjectRef { @@ -5829,7 +6867,7 @@ type MintActorJwtRequest struct { func (x *MintActorJwtRequest) Reset() { *x = MintActorJwtRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[76] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[90] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5841,7 +6879,7 @@ func (x *MintActorJwtRequest) String() string { func (*MintActorJwtRequest) ProtoMessage() {} func (x *MintActorJwtRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[76] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[90] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5854,7 +6892,7 @@ func (x *MintActorJwtRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use MintActorJwtRequest.ProtoReflect.Descriptor instead. func (*MintActorJwtRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{76} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{90} } func (x *MintActorJwtRequest) GetActor() *ObjectRef { @@ -5909,7 +6947,7 @@ type MintActorJwtResponse struct { func (x *MintActorJwtResponse) Reset() { *x = MintActorJwtResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[77] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[91] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5921,7 +6959,7 @@ func (x *MintActorJwtResponse) String() string { func (*MintActorJwtResponse) ProtoMessage() {} func (x *MintActorJwtResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[77] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[91] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5934,7 +6972,7 @@ func (x *MintActorJwtResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use MintActorJwtResponse.ProtoReflect.Descriptor instead. func (*MintActorJwtResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{77} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{91} } func (x *MintActorJwtResponse) GetActorJwt() string { @@ -5968,7 +7006,7 @@ type ListTagsRequest struct { func (x *ListTagsRequest) Reset() { *x = ListTagsRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[78] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[92] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -5980,7 +7018,7 @@ func (x *ListTagsRequest) String() string { func (*ListTagsRequest) ProtoMessage() {} func (x *ListTagsRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[78] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[92] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -5993,7 +7031,7 @@ func (x *ListTagsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListTagsRequest.ProtoReflect.Descriptor instead. func (*ListTagsRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{78} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{92} } func (x *ListTagsRequest) GetAtespace() string { @@ -6020,7 +7058,7 @@ type ListTagsResponse struct { func (x *ListTagsResponse) Reset() { *x = ListTagsResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[79] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[93] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6032,7 +7070,7 @@ func (x *ListTagsResponse) String() string { func (*ListTagsResponse) ProtoMessage() {} func (x *ListTagsResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[79] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[93] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6045,7 +7083,7 @@ func (x *ListTagsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListTagsResponse.ProtoReflect.Descriptor instead. func (*ListTagsResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{79} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{93} } func (x *ListTagsResponse) GetTags() []*Tag { @@ -6090,7 +7128,7 @@ type CreateTagRequest struct { func (x *CreateTagRequest) Reset() { *x = CreateTagRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[80] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[94] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6102,7 +7140,7 @@ func (x *CreateTagRequest) String() string { func (*CreateTagRequest) ProtoMessage() {} func (x *CreateTagRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[80] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[94] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6115,7 +7153,7 @@ func (x *CreateTagRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateTagRequest.ProtoReflect.Descriptor instead. func (*CreateTagRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{80} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{94} } func (x *CreateTagRequest) GetTag() *Tag { @@ -6136,8 +7174,9 @@ type UpdateTagRequest struct { // // +k8s:required // +k8s:opaqueType # updates are handled in 2 steps, do not descend + // +k8s:customValidation # descend into metadata // +k8s:subfield(metadata)=+k8s:required - // +k8s:customValidation # TODO: when we get nested subfields, require metadata.atespace + // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:required Tag *Tag `protobuf:"bytes,1,opt,name=tag,proto3" json:"tag,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -6145,7 +7184,7 @@ type UpdateTagRequest struct { func (x *UpdateTagRequest) Reset() { *x = UpdateTagRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[81] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[95] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6157,7 +7196,7 @@ func (x *UpdateTagRequest) String() string { func (*UpdateTagRequest) ProtoMessage() {} func (x *UpdateTagRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[81] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[95] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6170,7 +7209,7 @@ func (x *UpdateTagRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateTagRequest.ProtoReflect.Descriptor instead. func (*UpdateTagRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{81} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{95} } func (x *UpdateTagRequest) GetTag() *Tag { @@ -6195,7 +7234,7 @@ type DeleteTagRequest struct { func (x *DeleteTagRequest) Reset() { *x = DeleteTagRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[82] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[96] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6207,7 +7246,7 @@ func (x *DeleteTagRequest) String() string { func (*DeleteTagRequest) ProtoMessage() {} func (x *DeleteTagRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[82] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[96] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6220,7 +7259,7 @@ func (x *DeleteTagRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteTagRequest.ProtoReflect.Descriptor instead. func (*DeleteTagRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{82} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{96} } func (x *DeleteTagRequest) GetTag() *ObjectRef { @@ -6237,6 +7276,170 @@ func (x *DeleteTagRequest) GetOptions() *DeleteOptions { return nil } +// GetExternalVolumeRequest identifies one ExternalVolume. +type GetExternalVolumeRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The volume to get. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:required + ExternalVolume *ObjectRef `protobuf:"bytes,1,opt,name=external_volume,json=externalVolume,proto3" json:"external_volume,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *GetExternalVolumeRequest) Reset() { + *x = GetExternalVolumeRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[97] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *GetExternalVolumeRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*GetExternalVolumeRequest) ProtoMessage() {} + +func (x *GetExternalVolumeRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[97] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use GetExternalVolumeRequest.ProtoReflect.Descriptor instead. +func (*GetExternalVolumeRequest) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{97} +} + +func (x *GetExternalVolumeRequest) GetExternalVolume() *ObjectRef { + if x != nil { + return x.ExternalVolume + } + return nil +} + +// ListExternalVolumesRequest selects a page of ExternalVolumes. +type ListExternalVolumesRequest struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The atespace to list from. Empty lists across all atespaces. + // + // +k8s:optional + // +k8s:format=k8s-short-name + Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"` + // Pagination controls. + // + // +k8s:optional + Options *ListOptions `protobuf:"bytes,2,opt,name=options,proto3" json:"options,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListExternalVolumesRequest) Reset() { + *x = ListExternalVolumesRequest{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[98] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListExternalVolumesRequest) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListExternalVolumesRequest) ProtoMessage() {} + +func (x *ListExternalVolumesRequest) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[98] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListExternalVolumesRequest.ProtoReflect.Descriptor instead. +func (*ListExternalVolumesRequest) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{98} +} + +func (x *ListExternalVolumesRequest) GetAtespace() string { + if x != nil { + return x.Atespace + } + return "" +} + +func (x *ListExternalVolumesRequest) GetOptions() *ListOptions { + if x != nil { + return x.Options + } + return nil +} + +// ListExternalVolumesResponse is one page of ExternalVolumes. +type ListExternalVolumesResponse struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The volumes in this page. + ExternalVolumes []*ExternalVolume `protobuf:"bytes,1,rep,name=external_volumes,json=externalVolumes,proto3" json:"external_volumes,omitempty"` + // Pagination token for the next page. Empty on the last page. + NextPageToken string `protobuf:"bytes,2,opt,name=next_page_token,json=nextPageToken,proto3" json:"next_page_token,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ListExternalVolumesResponse) Reset() { + *x = ListExternalVolumesResponse{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[99] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ListExternalVolumesResponse) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ListExternalVolumesResponse) ProtoMessage() {} + +func (x *ListExternalVolumesResponse) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[99] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ListExternalVolumesResponse.ProtoReflect.Descriptor instead. +func (*ListExternalVolumesResponse) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{99} +} + +func (x *ListExternalVolumesResponse) GetExternalVolumes() []*ExternalVolume { + if x != nil { + return x.ExternalVolumes + } + return nil +} + +func (x *ListExternalVolumesResponse) GetNextPageToken() string { + if x != nil { + return x.NextPageToken + } + return "" +} + // DeleteOptions are the optional guards a Delete request may carry. type DeleteOptions struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -6259,7 +7462,7 @@ type DeleteOptions struct { func (x *DeleteOptions) Reset() { *x = DeleteOptions{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[83] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[100] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6271,7 +7474,7 @@ func (x *DeleteOptions) String() string { func (*DeleteOptions) ProtoMessage() {} func (x *DeleteOptions) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[83] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[100] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6284,7 +7487,7 @@ func (x *DeleteOptions) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteOptions.ProtoReflect.Descriptor instead. func (*DeleteOptions) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{83} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{100} } func (x *DeleteOptions) GetVersion() int64 { @@ -6323,7 +7526,7 @@ type ListOptions struct { func (x *ListOptions) Reset() { *x = ListOptions{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[84] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[101] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6335,7 +7538,7 @@ func (x *ListOptions) String() string { func (*ListOptions) ProtoMessage() {} func (x *ListOptions) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[84] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[101] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6348,7 +7551,7 @@ func (x *ListOptions) ProtoReflect() protoreflect.Message { // Deprecated: Use ListOptions.ProtoReflect.Descriptor instead. func (*ListOptions) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{84} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{101} } func (x *ListOptions) GetPageSize() int32 { @@ -6372,7 +7575,7 @@ type ListWorkerActorAssignmentsRequest struct { // The Worker under which to list Actors. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` // Pagination controls. // @@ -6384,7 +7587,7 @@ type ListWorkerActorAssignmentsRequest struct { func (x *ListWorkerActorAssignmentsRequest) Reset() { *x = ListWorkerActorAssignmentsRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[85] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[102] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6396,7 +7599,7 @@ func (x *ListWorkerActorAssignmentsRequest) String() string { func (*ListWorkerActorAssignmentsRequest) ProtoMessage() {} func (x *ListWorkerActorAssignmentsRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[85] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[102] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6409,7 +7612,7 @@ func (x *ListWorkerActorAssignmentsRequest) ProtoReflect() protoreflect.Message // Deprecated: Use ListWorkerActorAssignmentsRequest.ProtoReflect.Descriptor instead. func (*ListWorkerActorAssignmentsRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{85} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{102} } func (x *ListWorkerActorAssignmentsRequest) GetWorker() *ObjectRef { @@ -6439,7 +7642,7 @@ type ListWorkerActorAssignmentsResponse struct { func (x *ListWorkerActorAssignmentsResponse) Reset() { *x = ListWorkerActorAssignmentsResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[86] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[103] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6451,7 +7654,7 @@ func (x *ListWorkerActorAssignmentsResponse) String() string { func (*ListWorkerActorAssignmentsResponse) ProtoMessage() {} func (x *ListWorkerActorAssignmentsResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[86] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[103] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6464,7 +7667,7 @@ func (x *ListWorkerActorAssignmentsResponse) ProtoReflect() protoreflect.Message // Deprecated: Use ListWorkerActorAssignmentsResponse.ProtoReflect.Descriptor instead. func (*ListWorkerActorAssignmentsResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{86} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{103} } func (x *ListWorkerActorAssignmentsResponse) GetActorAssignments() []*ActorAssignment { @@ -6493,7 +7696,7 @@ type ListWorkersRequest struct { func (x *ListWorkersRequest) Reset() { *x = ListWorkersRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[87] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[104] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6505,7 +7708,7 @@ func (x *ListWorkersRequest) String() string { func (*ListWorkersRequest) ProtoMessage() {} func (x *ListWorkersRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[87] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[104] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6518,7 +7721,7 @@ func (x *ListWorkersRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkersRequest.ProtoReflect.Descriptor instead. func (*ListWorkersRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{87} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{104} } func (x *ListWorkersRequest) GetOptions() *ListOptions { @@ -6540,7 +7743,7 @@ type ListWorkersResponse struct { func (x *ListWorkersResponse) Reset() { *x = ListWorkersResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[88] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[105] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6552,7 +7755,7 @@ func (x *ListWorkersResponse) String() string { func (*ListWorkersResponse) ProtoMessage() {} func (x *ListWorkersResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[88] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[105] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6565,7 +7768,7 @@ func (x *ListWorkersResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListWorkersResponse.ProtoReflect.Descriptor instead. func (*ListWorkersResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{88} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{105} } func (x *ListWorkersResponse) GetWorkers() []*Worker { @@ -6587,7 +7790,7 @@ type GetWorkerRequest struct { // The Worker to fetch. atespace is always empty; Workers are global-scoped. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -6595,7 +7798,7 @@ type GetWorkerRequest struct { func (x *GetWorkerRequest) Reset() { *x = GetWorkerRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[89] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[106] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6607,7 +7810,7 @@ func (x *GetWorkerRequest) String() string { func (*GetWorkerRequest) ProtoMessage() {} func (x *GetWorkerRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[89] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[106] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6620,7 +7823,7 @@ func (x *GetWorkerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetWorkerRequest.ProtoReflect.Descriptor instead. func (*GetWorkerRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{89} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{106} } func (x *GetWorkerRequest) GetWorker() *ObjectRef { @@ -6642,7 +7845,7 @@ type CreateWorkerRequest struct { func (x *CreateWorkerRequest) Reset() { *x = CreateWorkerRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[90] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[107] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6654,7 +7857,7 @@ func (x *CreateWorkerRequest) String() string { func (*CreateWorkerRequest) ProtoMessage() {} func (x *CreateWorkerRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[90] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[107] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6667,7 +7870,7 @@ func (x *CreateWorkerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateWorkerRequest.ProtoReflect.Descriptor instead. func (*CreateWorkerRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{90} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{107} } func (x *CreateWorkerRequest) GetWorker() *Worker { @@ -6693,8 +7896,9 @@ type UpdateWorkerRequest struct { // // +k8s:required // +k8s:opaqueType # updates are handled in 2 steps, do not descend + // +k8s:customValidation # descend into metadata // +k8s:subfield(metadata)=+k8s:required - // +k8s:customValidation # TODO: when we get nested subfields, forbid metadata.atespace + // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:forbidden Worker *Worker `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -6702,7 +7906,7 @@ type UpdateWorkerRequest struct { func (x *UpdateWorkerRequest) Reset() { *x = UpdateWorkerRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[91] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[108] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6714,7 +7918,7 @@ func (x *UpdateWorkerRequest) String() string { func (*UpdateWorkerRequest) ProtoMessage() {} func (x *UpdateWorkerRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[91] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[108] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6727,7 +7931,7 @@ func (x *UpdateWorkerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateWorkerRequest.ProtoReflect.Descriptor instead. func (*UpdateWorkerRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{91} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{108} } func (x *UpdateWorkerRequest) GetWorker() *Worker { @@ -6742,7 +7946,7 @@ type DeleteWorkerRequest struct { // The Worker to deregister. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` // Optional per-delete preconditions. // @@ -6754,7 +7958,7 @@ type DeleteWorkerRequest struct { func (x *DeleteWorkerRequest) Reset() { *x = DeleteWorkerRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[92] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[109] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6766,7 +7970,7 @@ func (x *DeleteWorkerRequest) String() string { func (*DeleteWorkerRequest) ProtoMessage() {} func (x *DeleteWorkerRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[92] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[109] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6779,7 +7983,7 @@ func (x *DeleteWorkerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DeleteWorkerRequest.ProtoReflect.Descriptor instead. func (*DeleteWorkerRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{92} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{109} } func (x *DeleteWorkerRequest) GetWorker() *ObjectRef { @@ -6801,7 +8005,7 @@ type DrainWorkerRequest struct { // The Worker to mark as terminating. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -6809,7 +8013,7 @@ type DrainWorkerRequest struct { func (x *DrainWorkerRequest) Reset() { *x = DrainWorkerRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[93] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[110] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6821,7 +8025,7 @@ func (x *DrainWorkerRequest) String() string { func (*DrainWorkerRequest) ProtoMessage() {} func (x *DrainWorkerRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[93] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[110] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6834,7 +8038,7 @@ func (x *DrainWorkerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use DrainWorkerRequest.ProtoReflect.Descriptor instead. func (*DrainWorkerRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{93} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{110} } func (x *DrainWorkerRequest) GetWorker() *ObjectRef { @@ -6855,7 +8059,7 @@ type DrainWorkerResponse struct { func (x *DrainWorkerResponse) Reset() { *x = DrainWorkerResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[94] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[111] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6867,7 +8071,7 @@ func (x *DrainWorkerResponse) String() string { func (*DrainWorkerResponse) ProtoMessage() {} func (x *DrainWorkerResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[94] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[111] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6880,7 +8084,7 @@ func (x *DrainWorkerResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use DrainWorkerResponse.ProtoReflect.Descriptor instead. func (*DrainWorkerResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{94} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{111} } func (x *DrainWorkerResponse) GetWorker() *Worker { @@ -6896,7 +8100,7 @@ type MarkWorkerAvailableRequest struct { // The Worker to mark ACTIVE. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -6904,7 +8108,7 @@ type MarkWorkerAvailableRequest struct { func (x *MarkWorkerAvailableRequest) Reset() { *x = MarkWorkerAvailableRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[95] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[112] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6916,7 +8120,7 @@ func (x *MarkWorkerAvailableRequest) String() string { func (*MarkWorkerAvailableRequest) ProtoMessage() {} func (x *MarkWorkerAvailableRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[95] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[112] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6929,7 +8133,7 @@ func (x *MarkWorkerAvailableRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use MarkWorkerAvailableRequest.ProtoReflect.Descriptor instead. func (*MarkWorkerAvailableRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{95} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{112} } func (x *MarkWorkerAvailableRequest) GetWorker() *ObjectRef { @@ -6950,7 +8154,7 @@ type MarkWorkerAvailableResponse struct { func (x *MarkWorkerAvailableResponse) Reset() { *x = MarkWorkerAvailableResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[96] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[113] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -6962,7 +8166,7 @@ func (x *MarkWorkerAvailableResponse) String() string { func (*MarkWorkerAvailableResponse) ProtoMessage() {} func (x *MarkWorkerAvailableResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[96] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[113] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -6975,7 +8179,7 @@ func (x *MarkWorkerAvailableResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use MarkWorkerAvailableResponse.ProtoReflect.Descriptor instead. func (*MarkWorkerAvailableResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{96} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{113} } func (x *MarkWorkerAvailableResponse) GetWorker() *Worker { @@ -6991,7 +8195,7 @@ type MarkWorkerUnavailableRequest struct { // The Worker to mark UNAVAILABLE. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -6999,7 +8203,7 @@ type MarkWorkerUnavailableRequest struct { func (x *MarkWorkerUnavailableRequest) Reset() { *x = MarkWorkerUnavailableRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[97] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[114] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7011,7 +8215,7 @@ func (x *MarkWorkerUnavailableRequest) String() string { func (*MarkWorkerUnavailableRequest) ProtoMessage() {} func (x *MarkWorkerUnavailableRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[97] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[114] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7024,7 +8228,7 @@ func (x *MarkWorkerUnavailableRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use MarkWorkerUnavailableRequest.ProtoReflect.Descriptor instead. func (*MarkWorkerUnavailableRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{97} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{114} } func (x *MarkWorkerUnavailableRequest) GetWorker() *ObjectRef { @@ -7045,7 +8249,7 @@ type MarkWorkerUnavailableResponse struct { func (x *MarkWorkerUnavailableResponse) Reset() { *x = MarkWorkerUnavailableResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[98] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[115] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7057,7 +8261,7 @@ func (x *MarkWorkerUnavailableResponse) String() string { func (*MarkWorkerUnavailableResponse) ProtoMessage() {} func (x *MarkWorkerUnavailableResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[98] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[115] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7070,7 +8274,7 @@ func (x *MarkWorkerUnavailableResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use MarkWorkerUnavailableResponse.ProtoReflect.Descriptor instead. func (*MarkWorkerUnavailableResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{98} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{115} } func (x *MarkWorkerUnavailableResponse) GetWorker() *Worker { @@ -7099,7 +8303,7 @@ type ListActorsRequest struct { func (x *ListActorsRequest) Reset() { *x = ListActorsRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[99] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[116] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7111,7 +8315,7 @@ func (x *ListActorsRequest) String() string { func (*ListActorsRequest) ProtoMessage() {} func (x *ListActorsRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[99] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[116] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7124,7 +8328,7 @@ func (x *ListActorsRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ListActorsRequest.ProtoReflect.Descriptor instead. func (*ListActorsRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{99} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{116} } func (x *ListActorsRequest) GetAtespace() string { @@ -7153,7 +8357,7 @@ type ListActorsResponse struct { func (x *ListActorsResponse) Reset() { *x = ListActorsResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[100] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[117] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7165,7 +8369,7 @@ func (x *ListActorsResponse) String() string { func (*ListActorsResponse) ProtoMessage() {} func (x *ListActorsResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[100] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[117] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7178,7 +8382,7 @@ func (x *ListActorsResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ListActorsResponse.ProtoReflect.Descriptor instead. func (*ListActorsResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{100} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{117} } func (x *ListActorsResponse) GetActors() []*Actor { @@ -7211,7 +8415,7 @@ type Worker struct { // uid and version are echoed back on UpdateWorker as preconditions. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Metadata *ResourceMetadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` // Kubernetes coordinates. Immutable, set at creation. // @@ -7266,7 +8470,7 @@ type Worker struct { func (x *Worker) Reset() { *x = Worker{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[101] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[118] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7278,7 +8482,7 @@ func (x *Worker) String() string { func (*Worker) ProtoMessage() {} func (x *Worker) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[101] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[118] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7291,7 +8495,7 @@ func (x *Worker) ProtoReflect() protoreflect.Message { // Deprecated: Use Worker.ProtoReflect.Descriptor instead. func (*Worker) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{101} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{118} } func (x *Worker) GetMetadata() *ResourceMetadata { @@ -7433,7 +8637,7 @@ type WorkerStatus struct { func (x *WorkerStatus) Reset() { *x = WorkerStatus{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[102] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[119] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7445,7 +8649,7 @@ func (x *WorkerStatus) String() string { func (*WorkerStatus) ProtoMessage() {} func (x *WorkerStatus) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[102] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[119] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7458,7 +8662,7 @@ func (x *WorkerStatus) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkerStatus.ProtoReflect.Descriptor instead. func (*WorkerStatus) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{102} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{119} } func (x *WorkerStatus) GetState() WorkerState { @@ -7546,7 +8750,7 @@ type WorkerSandboxClass struct { func (x *WorkerSandboxClass) Reset() { *x = WorkerSandboxClass{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[103] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[120] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7558,7 +8762,7 @@ func (x *WorkerSandboxClass) String() string { func (*WorkerSandboxClass) ProtoMessage() {} func (x *WorkerSandboxClass) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[103] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[120] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7571,7 +8775,7 @@ func (x *WorkerSandboxClass) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkerSandboxClass.ProtoReflect.Descriptor instead. func (*WorkerSandboxClass) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{103} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{120} } func (x *WorkerSandboxClass) GetSandboxClass() string { @@ -7623,7 +8827,7 @@ type WorkerSandboxRuntime struct { func (x *WorkerSandboxRuntime) Reset() { *x = WorkerSandboxRuntime{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[104] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[121] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7635,7 +8839,7 @@ func (x *WorkerSandboxRuntime) String() string { func (*WorkerSandboxRuntime) ProtoMessage() {} func (x *WorkerSandboxRuntime) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[104] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[121] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7648,7 +8852,7 @@ func (x *WorkerSandboxRuntime) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkerSandboxRuntime.ProtoReflect.Descriptor instead. func (*WorkerSandboxRuntime) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{104} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{121} } func (x *WorkerSandboxRuntime) GetVersion() *VersionedSandboxCompat { @@ -7689,7 +8893,7 @@ type RuntimeOverhead struct { func (x *RuntimeOverhead) Reset() { *x = RuntimeOverhead{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[105] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[122] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7701,7 +8905,7 @@ func (x *RuntimeOverhead) String() string { func (*RuntimeOverhead) ProtoMessage() {} func (x *RuntimeOverhead) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[105] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[122] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7714,7 +8918,7 @@ func (x *RuntimeOverhead) ProtoReflect() protoreflect.Message { // Deprecated: Use RuntimeOverhead.ProtoReflect.Descriptor instead. func (*RuntimeOverhead) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{105} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{122} } func (x *RuntimeOverhead) GetMemoryBytes() int64 { @@ -7753,7 +8957,7 @@ type ActorSandboxRuntime struct { func (x *ActorSandboxRuntime) Reset() { *x = ActorSandboxRuntime{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[106] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[123] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7765,7 +8969,7 @@ func (x *ActorSandboxRuntime) String() string { func (*ActorSandboxRuntime) ProtoMessage() {} func (x *ActorSandboxRuntime) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[106] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[123] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7778,7 +8982,7 @@ func (x *ActorSandboxRuntime) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorSandboxRuntime.ProtoReflect.Descriptor instead. func (*ActorSandboxRuntime) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{106} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{123} } func (x *ActorSandboxRuntime) GetSandboxClass() string { @@ -7829,7 +9033,7 @@ type VersionedSandboxCompat struct { func (x *VersionedSandboxCompat) Reset() { *x = VersionedSandboxCompat{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[107] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[124] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7841,7 +9045,7 @@ func (x *VersionedSandboxCompat) String() string { func (*VersionedSandboxCompat) ProtoMessage() {} func (x *VersionedSandboxCompat) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[107] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[124] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7854,7 +9058,7 @@ func (x *VersionedSandboxCompat) ProtoReflect() protoreflect.Message { // Deprecated: Use VersionedSandboxCompat.ProtoReflect.Descriptor instead. func (*VersionedSandboxCompat) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{107} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{124} } func (x *VersionedSandboxCompat) GetSchemaVersion() string { @@ -7890,7 +9094,7 @@ type AttributeEntry struct { func (x *AttributeEntry) Reset() { *x = AttributeEntry{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[108] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[125] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7902,7 +9106,7 @@ func (x *AttributeEntry) String() string { func (*AttributeEntry) ProtoMessage() {} func (x *AttributeEntry) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[108] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[125] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7915,7 +9119,7 @@ func (x *AttributeEntry) ProtoReflect() protoreflect.Message { // Deprecated: Use AttributeEntry.ProtoReflect.Descriptor instead. func (*AttributeEntry) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{108} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{125} } func (x *AttributeEntry) GetKey() string { @@ -7962,7 +9166,7 @@ type WorkerResources struct { func (x *WorkerResources) Reset() { *x = WorkerResources{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[109] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[126] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -7974,7 +9178,7 @@ func (x *WorkerResources) String() string { func (*WorkerResources) ProtoMessage() {} func (x *WorkerResources) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[109] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[126] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -7987,7 +9191,7 @@ func (x *WorkerResources) ProtoReflect() protoreflect.Message { // Deprecated: Use WorkerResources.ProtoReflect.Descriptor instead. func (*WorkerResources) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{109} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{126} } func (x *WorkerResources) GetCpuMillicores() int64 { @@ -8022,7 +9226,7 @@ type ActorAssignment struct { // that caused an assignment is what addresses it. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Metadata *ResourceMetadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` // actor is the Actor that is assigned to the Worker. // @@ -8043,7 +9247,7 @@ type ActorAssignment struct { func (x *ActorAssignment) Reset() { *x = ActorAssignment{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[110] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[127] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8055,7 +9259,7 @@ func (x *ActorAssignment) String() string { func (*ActorAssignment) ProtoMessage() {} func (x *ActorAssignment) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[110] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[127] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8068,7 +9272,7 @@ func (x *ActorAssignment) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorAssignment.ProtoReflect.Descriptor instead. func (*ActorAssignment) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{110} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{127} } func (x *ActorAssignment) GetMetadata() *ResourceMetadata { @@ -8105,7 +9309,7 @@ type AcquireWorkerEpochRequest struct { // Workers are global-scoped. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -8113,7 +9317,7 @@ type AcquireWorkerEpochRequest struct { func (x *AcquireWorkerEpochRequest) Reset() { *x = AcquireWorkerEpochRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[111] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[128] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8125,7 +9329,7 @@ func (x *AcquireWorkerEpochRequest) String() string { func (*AcquireWorkerEpochRequest) ProtoMessage() {} func (x *AcquireWorkerEpochRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[111] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[128] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8138,7 +9342,7 @@ func (x *AcquireWorkerEpochRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use AcquireWorkerEpochRequest.ProtoReflect.Descriptor instead. func (*AcquireWorkerEpochRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{111} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{128} } func (x *AcquireWorkerEpochRequest) GetWorker() *ObjectRef { @@ -8158,7 +9362,7 @@ type AcquireWorkerEpochResponse struct { func (x *AcquireWorkerEpochResponse) Reset() { *x = AcquireWorkerEpochResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[112] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[129] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8170,7 +9374,7 @@ func (x *AcquireWorkerEpochResponse) String() string { func (*AcquireWorkerEpochResponse) ProtoMessage() {} func (x *AcquireWorkerEpochResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[112] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[129] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8183,7 +9387,7 @@ func (x *AcquireWorkerEpochResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use AcquireWorkerEpochResponse.ProtoReflect.Descriptor instead. func (*AcquireWorkerEpochResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{112} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{129} } func (x *AcquireWorkerEpochResponse) GetEpoch() int64 { @@ -8199,7 +9403,7 @@ type RegisterWorkerRequest struct { // global-scoped. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` // The epoch the worker process acquired through AcquireWorkerEpoch. // @@ -8226,7 +9430,7 @@ type RegisterWorkerRequest struct { func (x *RegisterWorkerRequest) Reset() { *x = RegisterWorkerRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[113] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[130] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8238,7 +9442,7 @@ func (x *RegisterWorkerRequest) String() string { func (*RegisterWorkerRequest) ProtoMessage() {} func (x *RegisterWorkerRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[113] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[130] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8251,7 +9455,7 @@ func (x *RegisterWorkerRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RegisterWorkerRequest.ProtoReflect.Descriptor instead. func (*RegisterWorkerRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{113} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{130} } func (x *RegisterWorkerRequest) GetWorker() *ObjectRef { @@ -8292,7 +9496,7 @@ type RegisterWorkerResponse struct { func (x *RegisterWorkerResponse) Reset() { *x = RegisterWorkerResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[114] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[131] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8304,7 +9508,7 @@ func (x *RegisterWorkerResponse) String() string { func (*RegisterWorkerResponse) ProtoMessage() {} func (x *RegisterWorkerResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[114] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[131] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8317,7 +9521,7 @@ func (x *RegisterWorkerResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RegisterWorkerResponse.ProtoReflect.Descriptor instead. func (*RegisterWorkerResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{114} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{131} } func (x *RegisterWorkerResponse) GetWorker() *Worker { @@ -8333,7 +9537,7 @@ type SetWorkerSandboxRuntimesRequest struct { // global-scoped. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` // The epoch the worker process registered with. // @@ -8357,7 +9561,7 @@ type SetWorkerSandboxRuntimesRequest struct { func (x *SetWorkerSandboxRuntimesRequest) Reset() { *x = SetWorkerSandboxRuntimesRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[115] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[132] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8369,7 +9573,7 @@ func (x *SetWorkerSandboxRuntimesRequest) String() string { func (*SetWorkerSandboxRuntimesRequest) ProtoMessage() {} func (x *SetWorkerSandboxRuntimesRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[115] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[132] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8382,7 +9586,7 @@ func (x *SetWorkerSandboxRuntimesRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use SetWorkerSandboxRuntimesRequest.ProtoReflect.Descriptor instead. func (*SetWorkerSandboxRuntimesRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{115} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{132} } func (x *SetWorkerSandboxRuntimesRequest) GetWorker() *ObjectRef { @@ -8416,7 +9620,7 @@ type SetWorkerSandboxRuntimesResponse struct { func (x *SetWorkerSandboxRuntimesResponse) Reset() { *x = SetWorkerSandboxRuntimesResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[116] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[133] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8428,7 +9632,7 @@ func (x *SetWorkerSandboxRuntimesResponse) String() string { func (*SetWorkerSandboxRuntimesResponse) ProtoMessage() {} func (x *SetWorkerSandboxRuntimesResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[116] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[133] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8441,7 +9645,7 @@ func (x *SetWorkerSandboxRuntimesResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use SetWorkerSandboxRuntimesResponse.ProtoReflect.Descriptor instead. func (*SetWorkerSandboxRuntimesResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{116} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{133} } func (x *SetWorkerSandboxRuntimesResponse) GetWorker() *Worker { @@ -8480,7 +9684,7 @@ type MintWorkerActorCertificateRequest struct { // must be the Worker that the actor is assigned to. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,4,opt,name=worker,proto3" json:"worker,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -8488,7 +9692,7 @@ type MintWorkerActorCertificateRequest struct { func (x *MintWorkerActorCertificateRequest) Reset() { *x = MintWorkerActorCertificateRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[117] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[134] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8500,7 +9704,7 @@ func (x *MintWorkerActorCertificateRequest) String() string { func (*MintWorkerActorCertificateRequest) ProtoMessage() {} func (x *MintWorkerActorCertificateRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[117] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[134] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8513,7 +9717,7 @@ func (x *MintWorkerActorCertificateRequest) ProtoReflect() protoreflect.Message // Deprecated: Use MintWorkerActorCertificateRequest.ProtoReflect.Descriptor instead. func (*MintWorkerActorCertificateRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{117} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{134} } func (x *MintWorkerActorCertificateRequest) GetActor() *ObjectRef { @@ -8557,7 +9761,7 @@ type MintWorkerActorCertificateResponse struct { func (x *MintWorkerActorCertificateResponse) Reset() { *x = MintWorkerActorCertificateResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[118] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[135] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8569,7 +9773,7 @@ func (x *MintWorkerActorCertificateResponse) String() string { func (*MintWorkerActorCertificateResponse) ProtoMessage() {} func (x *MintWorkerActorCertificateResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[118] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[135] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8582,7 +9786,7 @@ func (x *MintWorkerActorCertificateResponse) ProtoReflect() protoreflect.Message // Deprecated: Use MintWorkerActorCertificateResponse.ProtoReflect.Descriptor instead. func (*MintWorkerActorCertificateResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{118} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{135} } func (x *MintWorkerActorCertificateResponse) GetActorCertificates() [][]byte { @@ -8623,7 +9827,7 @@ type MintWorkerActorJwtRequest struct { func (x *MintWorkerActorJwtRequest) Reset() { *x = MintWorkerActorJwtRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[119] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[136] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8635,7 +9839,7 @@ func (x *MintWorkerActorJwtRequest) String() string { func (*MintWorkerActorJwtRequest) ProtoMessage() {} func (x *MintWorkerActorJwtRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[119] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[136] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8648,7 +9852,7 @@ func (x *MintWorkerActorJwtRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use MintWorkerActorJwtRequest.ProtoReflect.Descriptor instead. func (*MintWorkerActorJwtRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{119} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{136} } func (x *MintWorkerActorJwtRequest) GetActor() *ObjectRef { @@ -8696,7 +9900,7 @@ type MintWorkerActorJwtResponse struct { func (x *MintWorkerActorJwtResponse) Reset() { *x = MintWorkerActorJwtResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[120] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[137] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8708,7 +9912,7 @@ func (x *MintWorkerActorJwtResponse) String() string { func (*MintWorkerActorJwtResponse) ProtoMessage() {} func (x *MintWorkerActorJwtResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[120] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[137] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8721,7 +9925,7 @@ func (x *MintWorkerActorJwtResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use MintWorkerActorJwtResponse.ProtoReflect.Descriptor instead. func (*MintWorkerActorJwtResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{120} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{137} } func (x *MintWorkerActorJwtResponse) GetActorJwt() string { @@ -8751,7 +9955,7 @@ type RequestActorSuspendRequest struct { // names the Worker that certificate proves the request came from. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` // The Actor to suspend. It must be assigned to worker; a Worker may speak // only for what it hosts. @@ -8772,7 +9976,7 @@ type RequestActorSuspendRequest struct { func (x *RequestActorSuspendRequest) Reset() { *x = RequestActorSuspendRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[121] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[138] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8784,7 +9988,7 @@ func (x *RequestActorSuspendRequest) String() string { func (*RequestActorSuspendRequest) ProtoMessage() {} func (x *RequestActorSuspendRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[121] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[138] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8797,7 +10001,7 @@ func (x *RequestActorSuspendRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use RequestActorSuspendRequest.ProtoReflect.Descriptor instead. func (*RequestActorSuspendRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{121} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{138} } func (x *RequestActorSuspendRequest) GetWorker() *ObjectRef { @@ -8831,7 +10035,7 @@ type RequestActorSuspendResponse struct { func (x *RequestActorSuspendResponse) Reset() { *x = RequestActorSuspendResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[122] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[139] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8843,7 +10047,7 @@ func (x *RequestActorSuspendResponse) String() string { func (*RequestActorSuspendResponse) ProtoMessage() {} func (x *RequestActorSuspendResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[122] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[139] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8856,7 +10060,7 @@ func (x *RequestActorSuspendResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use RequestActorSuspendResponse.ProtoReflect.Descriptor instead. func (*RequestActorSuspendResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{122} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{139} } func (x *RequestActorSuspendResponse) GetActor() *Actor { @@ -8872,7 +10076,7 @@ type ReportActorCrashedRequest struct { // global-scoped. atelet fills this in from its caller's certificate. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Worker *ObjectRef `protobuf:"bytes,1,opt,name=worker,proto3" json:"worker,omitempty"` // The Actor whose sandbox died. It must be assigned to worker. // @@ -8889,14 +10093,21 @@ type ReportActorCrashedRequest struct { // // +k8s:required // +k8s:maxLength=4096 - Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"` + Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"` + // activation_uid identifies the runtime that exited. + // Accepted for protocol compatibility; crash handling uses the Actor and + // Worker identities. + // + // +k8s:optional + // +k8s:format=k8s-uuid + ActivationUid string `protobuf:"bytes,5,opt,name=activation_uid,json=activationUid,proto3" json:"activation_uid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *ReportActorCrashedRequest) Reset() { *x = ReportActorCrashedRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[123] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[140] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8908,7 +10119,7 @@ func (x *ReportActorCrashedRequest) String() string { func (*ReportActorCrashedRequest) ProtoMessage() {} func (x *ReportActorCrashedRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[123] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[140] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8921,7 +10132,7 @@ func (x *ReportActorCrashedRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportActorCrashedRequest.ProtoReflect.Descriptor instead. func (*ReportActorCrashedRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{123} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{140} } func (x *ReportActorCrashedRequest) GetWorker() *ObjectRef { @@ -8952,6 +10163,13 @@ func (x *ReportActorCrashedRequest) GetMessage() string { return "" } +func (x *ReportActorCrashedRequest) GetActivationUid() string { + if x != nil { + return x.ActivationUid + } + return "" +} + type ReportActorCrashedResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The Actor as the report left it. @@ -8962,7 +10180,7 @@ type ReportActorCrashedResponse struct { func (x *ReportActorCrashedResponse) Reset() { *x = ReportActorCrashedResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[124] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[141] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -8974,7 +10192,7 @@ func (x *ReportActorCrashedResponse) String() string { func (*ReportActorCrashedResponse) ProtoMessage() {} func (x *ReportActorCrashedResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[124] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[141] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -8987,7 +10205,7 @@ func (x *ReportActorCrashedResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportActorCrashedResponse.ProtoReflect.Descriptor instead. func (*ReportActorCrashedResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{124} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{141} } func (x *ReportActorCrashedResponse) GetActor() *Actor { @@ -9018,7 +10236,7 @@ type ReportActorSnapshotStateRequest struct { func (x *ReportActorSnapshotStateRequest) Reset() { *x = ReportActorSnapshotStateRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[125] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[142] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9030,7 +10248,7 @@ func (x *ReportActorSnapshotStateRequest) String() string { func (*ReportActorSnapshotStateRequest) ProtoMessage() {} func (x *ReportActorSnapshotStateRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[125] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[142] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9043,7 +10261,7 @@ func (x *ReportActorSnapshotStateRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportActorSnapshotStateRequest.ProtoReflect.Descriptor instead. func (*ReportActorSnapshotStateRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{125} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{142} } func (x *ReportActorSnapshotStateRequest) GetActor() *ObjectRef { @@ -9075,7 +10293,7 @@ type ReportActorSnapshotStateResponse struct { func (x *ReportActorSnapshotStateResponse) Reset() { *x = ReportActorSnapshotStateResponse{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[126] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[143] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9087,7 +10305,7 @@ func (x *ReportActorSnapshotStateResponse) String() string { func (*ReportActorSnapshotStateResponse) ProtoMessage() {} func (x *ReportActorSnapshotStateResponse) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[126] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[143] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9100,7 +10318,7 @@ func (x *ReportActorSnapshotStateResponse) ProtoReflect() protoreflect.Message { // Deprecated: Use ReportActorSnapshotStateResponse.ProtoReflect.Descriptor instead. func (*ReportActorSnapshotStateResponse) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{126} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{143} } // ActorSnapshotState is what atelet holds for one Actor on its node. It @@ -9134,7 +10352,7 @@ type ActorSnapshotState struct { func (x *ActorSnapshotState) Reset() { *x = ActorSnapshotState{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[127] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[144] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9146,7 +10364,7 @@ func (x *ActorSnapshotState) String() string { func (*ActorSnapshotState) ProtoMessage() {} func (x *ActorSnapshotState) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[127] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[144] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9159,7 +10377,7 @@ func (x *ActorSnapshotState) ProtoReflect() protoreflect.Message { // Deprecated: Use ActorSnapshotState.ProtoReflect.Descriptor instead. func (*ActorSnapshotState) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{127} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{144} } func (x *ActorSnapshotState) GetLatestLocal() *SnapshotReport { @@ -9231,7 +10449,7 @@ type SnapshotReport struct { func (x *SnapshotReport) Reset() { *x = SnapshotReport{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[128] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[145] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9243,7 +10461,7 @@ func (x *SnapshotReport) String() string { func (*SnapshotReport) ProtoMessage() {} func (x *SnapshotReport) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[128] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[145] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9256,7 +10474,7 @@ func (x *SnapshotReport) ProtoReflect() protoreflect.Message { // Deprecated: Use SnapshotReport.ProtoReflect.Descriptor instead. func (*SnapshotReport) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{128} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{145} } func (x *SnapshotReport) GetUuid() string { @@ -9312,7 +10530,8 @@ type AccessPolicy struct { // create_time, and update_time are server-managed. // // +k8s:required - // +k8s:customValidation # name must be "default" + // +k8s:subfield(atespace)=+k8s:forbidden + // +k8s:subfield(name)=+k8s:format=ate-singleton-name Metadata *ResourceMetadata `protobuf:"bytes,1,opt,name=metadata,proto3" json:"metadata,omitempty"` // Role bindings granting permissions on the parent resource. // @@ -9326,7 +10545,7 @@ type AccessPolicy struct { func (x *AccessPolicy) Reset() { *x = AccessPolicy{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[129] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[146] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9338,7 +10557,7 @@ func (x *AccessPolicy) String() string { func (*AccessPolicy) ProtoMessage() {} func (x *AccessPolicy) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[129] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[146] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9351,7 +10570,7 @@ func (x *AccessPolicy) ProtoReflect() protoreflect.Message { // Deprecated: Use AccessPolicy.ProtoReflect.Descriptor instead. func (*AccessPolicy) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{129} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{146} } func (x *AccessPolicy) GetMetadata() *ResourceMetadata { @@ -9393,7 +10612,7 @@ type Binding struct { func (x *Binding) Reset() { *x = Binding{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[130] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[147] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9405,7 +10624,7 @@ func (x *Binding) String() string { func (*Binding) ProtoMessage() {} func (x *Binding) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[130] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[147] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9418,7 +10637,7 @@ func (x *Binding) ProtoReflect() protoreflect.Message { // Deprecated: Use Binding.ProtoReflect.Descriptor instead. func (*Binding) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{130} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{147} } func (x *Binding) GetRole() string { @@ -9441,8 +10660,7 @@ type GetGlobalAccessPolicyRequest struct { // Name of the singleton access policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -9450,7 +10668,7 @@ type GetGlobalAccessPolicyRequest struct { func (x *GetGlobalAccessPolicyRequest) Reset() { *x = GetGlobalAccessPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[131] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[148] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9462,7 +10680,7 @@ func (x *GetGlobalAccessPolicyRequest) String() string { func (*GetGlobalAccessPolicyRequest) ProtoMessage() {} func (x *GetGlobalAccessPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[131] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[148] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9475,7 +10693,7 @@ func (x *GetGlobalAccessPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetGlobalAccessPolicyRequest.ProtoReflect.Descriptor instead. func (*GetGlobalAccessPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{131} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{148} } func (x *GetGlobalAccessPolicyRequest) GetName() string { @@ -9499,7 +10717,7 @@ type CreateGlobalAccessPolicyRequest struct { func (x *CreateGlobalAccessPolicyRequest) Reset() { *x = CreateGlobalAccessPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[132] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[149] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9511,7 +10729,7 @@ func (x *CreateGlobalAccessPolicyRequest) String() string { func (*CreateGlobalAccessPolicyRequest) ProtoMessage() {} func (x *CreateGlobalAccessPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[132] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[149] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9524,7 +10742,7 @@ func (x *CreateGlobalAccessPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use CreateGlobalAccessPolicyRequest.ProtoReflect.Descriptor instead. func (*CreateGlobalAccessPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{132} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{149} } func (x *CreateGlobalAccessPolicyRequest) GetAccessPolicy() *AccessPolicy { @@ -9548,7 +10766,7 @@ type UpdateGlobalAccessPolicyRequest struct { func (x *UpdateGlobalAccessPolicyRequest) Reset() { *x = UpdateGlobalAccessPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[133] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[150] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9560,7 +10778,7 @@ func (x *UpdateGlobalAccessPolicyRequest) String() string { func (*UpdateGlobalAccessPolicyRequest) ProtoMessage() {} func (x *UpdateGlobalAccessPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[133] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[150] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9573,7 +10791,7 @@ func (x *UpdateGlobalAccessPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use UpdateGlobalAccessPolicyRequest.ProtoReflect.Descriptor instead. func (*UpdateGlobalAccessPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{133} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{150} } func (x *UpdateGlobalAccessPolicyRequest) GetAccessPolicy() *AccessPolicy { @@ -9589,13 +10807,12 @@ type GetAtespaceAccessPolicyRequest struct { // The parent Atespace of the access policy resource to retrieve. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Atespace *ObjectRef `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"` // Name of the singleton access policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache @@ -9603,7 +10820,7 @@ type GetAtespaceAccessPolicyRequest struct { func (x *GetAtespaceAccessPolicyRequest) Reset() { *x = GetAtespaceAccessPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[134] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[151] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9615,7 +10832,7 @@ func (x *GetAtespaceAccessPolicyRequest) String() string { func (*GetAtespaceAccessPolicyRequest) ProtoMessage() {} func (x *GetAtespaceAccessPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[134] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[151] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9628,7 +10845,7 @@ func (x *GetAtespaceAccessPolicyRequest) ProtoReflect() protoreflect.Message { // Deprecated: Use GetAtespaceAccessPolicyRequest.ProtoReflect.Descriptor instead. func (*GetAtespaceAccessPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{134} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{151} } func (x *GetAtespaceAccessPolicyRequest) GetAtespace() *ObjectRef { @@ -9651,7 +10868,7 @@ type CreateAtespaceAccessPolicyRequest struct { // Parent Atespace under which to create the policy resource. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Atespace *ObjectRef `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"` // The policy to create. metadata.name must be "default" and // metadata.atespace must be empty. @@ -9664,7 +10881,7 @@ type CreateAtespaceAccessPolicyRequest struct { func (x *CreateAtespaceAccessPolicyRequest) Reset() { *x = CreateAtespaceAccessPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[135] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[152] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9676,7 +10893,7 @@ func (x *CreateAtespaceAccessPolicyRequest) String() string { func (*CreateAtespaceAccessPolicyRequest) ProtoMessage() {} func (x *CreateAtespaceAccessPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[135] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[152] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9689,7 +10906,7 @@ func (x *CreateAtespaceAccessPolicyRequest) ProtoReflect() protoreflect.Message // Deprecated: Use CreateAtespaceAccessPolicyRequest.ProtoReflect.Descriptor instead. func (*CreateAtespaceAccessPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{135} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{152} } func (x *CreateAtespaceAccessPolicyRequest) GetAtespace() *ObjectRef { @@ -9712,7 +10929,7 @@ type UpdateAtespaceAccessPolicyRequest struct { // Parent Atespace under which to update the policy resource. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Atespace *ObjectRef `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"` // Full replacement. Metadata UID and version are required preconditions; // metadata.name must be "default" and metadata.atespace must be empty. @@ -9725,7 +10942,7 @@ type UpdateAtespaceAccessPolicyRequest struct { func (x *UpdateAtespaceAccessPolicyRequest) Reset() { *x = UpdateAtespaceAccessPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[136] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[153] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9737,7 +10954,7 @@ func (x *UpdateAtespaceAccessPolicyRequest) String() string { func (*UpdateAtespaceAccessPolicyRequest) ProtoMessage() {} func (x *UpdateAtespaceAccessPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[136] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[153] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9750,7 +10967,7 @@ func (x *UpdateAtespaceAccessPolicyRequest) ProtoReflect() protoreflect.Message // Deprecated: Use UpdateAtespaceAccessPolicyRequest.ProtoReflect.Descriptor instead. func (*UpdateAtespaceAccessPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{136} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{153} } func (x *UpdateAtespaceAccessPolicyRequest) GetAtespace() *ObjectRef { @@ -9773,13 +10990,12 @@ type DeleteAtespaceAccessPolicyRequest struct { // The parent Atespace of the access policy resource to delete. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden Atespace *ObjectRef `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"` // Name of the singleton access policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name Name string `protobuf:"bytes,2,opt,name=name,proto3" json:"name,omitempty"` // Optional per-delete preconditions. // @@ -9791,7 +11007,7 @@ type DeleteAtespaceAccessPolicyRequest struct { func (x *DeleteAtespaceAccessPolicyRequest) Reset() { *x = DeleteAtespaceAccessPolicyRequest{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[137] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[154] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9803,7 +11019,7 @@ func (x *DeleteAtespaceAccessPolicyRequest) String() string { func (*DeleteAtespaceAccessPolicyRequest) ProtoMessage() {} func (x *DeleteAtespaceAccessPolicyRequest) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[137] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[154] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9816,7 +11032,7 @@ func (x *DeleteAtespaceAccessPolicyRequest) ProtoReflect() protoreflect.Message // Deprecated: Use DeleteAtespaceAccessPolicyRequest.ProtoReflect.Descriptor instead. func (*DeleteAtespaceAccessPolicyRequest) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{137} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{154} } func (x *DeleteAtespaceAccessPolicyRequest) GetAtespace() *ObjectRef { @@ -9862,7 +11078,7 @@ type ResourceAnnotation struct { func (x *ResourceAnnotation) Reset() { *x = ResourceAnnotation{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[138] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[155] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9874,7 +11090,7 @@ func (x *ResourceAnnotation) String() string { func (*ResourceAnnotation) ProtoMessage() {} func (x *ResourceAnnotation) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[138] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[155] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9887,7 +11103,7 @@ func (x *ResourceAnnotation) ProtoReflect() protoreflect.Message { // Deprecated: Use ResourceAnnotation.ProtoReflect.Descriptor instead. func (*ResourceAnnotation) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{138} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{155} } func (x *ResourceAnnotation) GetParents() []string { @@ -9923,14 +11139,17 @@ type MethodAnnotation struct { state protoimpl.MessageState `protogen:"open.v1"` // The message name of the resource the method operates on. For example, // "Actor" for SuspendActor, or "EgressPolicy" for GetActorEgressPolicy. - Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` + Resource string `protobuf:"bytes,1,opt,name=resource,proto3" json:"resource,omitempty"` + // The preview gate that must be enabled to call the method. Unset if the + // method is generally available. + PreviewGate *MethodPreviewGate `protobuf:"bytes,2,opt,name=preview_gate,json=previewGate,proto3" json:"preview_gate,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } func (x *MethodAnnotation) Reset() { *x = MethodAnnotation{} - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[139] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[156] ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) ms.StoreMessageInfo(mi) } @@ -9942,7 +11161,7 @@ func (x *MethodAnnotation) String() string { func (*MethodAnnotation) ProtoMessage() {} func (x *MethodAnnotation) ProtoReflect() protoreflect.Message { - mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[139] + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[156] if x != nil { ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) if ms.LoadMessageInfo() == nil { @@ -9955,7 +11174,7 @@ func (x *MethodAnnotation) ProtoReflect() protoreflect.Message { // Deprecated: Use MethodAnnotation.ProtoReflect.Descriptor instead. func (*MethodAnnotation) Descriptor() ([]byte, []int) { - return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{139} + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{156} } func (x *MethodAnnotation) GetResource() string { @@ -9965,6 +11184,289 @@ func (x *MethodAnnotation) GetResource() string { return "" } +func (x *MethodAnnotation) GetPreviewGate() *MethodPreviewGate { + if x != nil { + return x.PreviewGate + } + return nil +} + +// MethodPreviewGate names the preview feature a method is part of. +type MethodPreviewGate struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The gate name. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *MethodPreviewGate) Reset() { + *x = MethodPreviewGate{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[157] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *MethodPreviewGate) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*MethodPreviewGate) ProtoMessage() {} + +func (x *MethodPreviewGate) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[157] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use MethodPreviewGate.ProtoReflect.Descriptor instead. +func (*MethodPreviewGate) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{157} +} + +func (x *MethodPreviewGate) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +// FieldAnnotation describes a field of the API. +type FieldAnnotation struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The preview feature the field is part of. Unset if the field is + // generally available. + PreviewGate *FieldPreviewGate `protobuf:"bytes,1,opt,name=preview_gate,json=previewGate,proto3" json:"preview_gate,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FieldAnnotation) Reset() { + *x = FieldAnnotation{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[158] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FieldAnnotation) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FieldAnnotation) ProtoMessage() {} + +func (x *FieldAnnotation) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[158] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FieldAnnotation.ProtoReflect.Descriptor instead. +func (*FieldAnnotation) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{158} +} + +func (x *FieldAnnotation) GetPreviewGate() *FieldPreviewGate { + if x != nil { + return x.PreviewGate + } + return nil +} + +// FieldPreviewGate names the preview feature a field is part of. +type FieldPreviewGate struct { + state protoimpl.MessageState `protogen:"open.v1"` + // The gate name. + Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` + // allow_when_disabled allows setting the field while the gate is disabled. + AllowWhenDisabled bool `protobuf:"varint,2,opt,name=allow_when_disabled,json=allowWhenDisabled,proto3" json:"allow_when_disabled,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *FieldPreviewGate) Reset() { + *x = FieldPreviewGate{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[159] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *FieldPreviewGate) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*FieldPreviewGate) ProtoMessage() {} + +func (x *FieldPreviewGate) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[159] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use FieldPreviewGate.ProtoReflect.Descriptor instead. +func (*FieldPreviewGate) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{159} +} + +func (x *FieldPreviewGate) GetName() string { + if x != nil { + return x.Name + } + return "" +} + +func (x *FieldPreviewGate) GetAllowWhenDisabled() bool { + if x != nil { + return x.AllowWhenDisabled + } + return false +} + +// Options are the optional controls a ResumeActor request may carry. +// A guard that does not match the actor fails the request with `ABORTED`. +type ResumeActorRequest_Options struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Resume only if the actor is still at this version. Zero skips the check. + // A call can change `version` before it fails, so read the actor again + // before a retry. + // + // +k8s:optional + // +k8s:minimum=1 + Version int64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` + // Resume only if the actor still has this uid. Empty skips the check. + // + // +k8s:optional + // +k8s:format=k8s-uuid + Uid string `protobuf:"bytes,2,opt,name=uid,proto3" json:"uid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ResumeActorRequest_Options) Reset() { + *x = ResumeActorRequest_Options{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[163] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ResumeActorRequest_Options) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ResumeActorRequest_Options) ProtoMessage() {} + +func (x *ResumeActorRequest_Options) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[163] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ResumeActorRequest_Options.ProtoReflect.Descriptor instead. +func (*ResumeActorRequest_Options) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{80, 0} +} + +func (x *ResumeActorRequest_Options) GetVersion() int64 { + if x != nil { + return x.Version + } + return 0 +} + +func (x *ResumeActorRequest_Options) GetUid() string { + if x != nil { + return x.Uid + } + return "" +} + +// Options are the optional controls a RevertActor request may carry. +// A guard that does not match the actor fails the request with `ABORTED`. +type RevertActorRequest_Options struct { + state protoimpl.MessageState `protogen:"open.v1"` + // Revert only if the actor is still at this version. Zero skips the check. + // A call can change `version` before it fails, so read the actor again + // before a retry. + // + // +k8s:optional + // +k8s:minimum=1 + Version int64 `protobuf:"varint,1,opt,name=version,proto3" json:"version,omitempty"` + // Revert only if the actor still has this uid. Empty skips the check. + // + // +k8s:optional + // +k8s:format=k8s-uuid + Uid string `protobuf:"bytes,2,opt,name=uid,proto3" json:"uid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *RevertActorRequest_Options) Reset() { + *x = RevertActorRequest_Options{} + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[164] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *RevertActorRequest_Options) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*RevertActorRequest_Options) ProtoMessage() {} + +func (x *RevertActorRequest_Options) ProtoReflect() protoreflect.Message { + mi := &file_api_ateapi_v1_ateapi_proto_msgTypes[164] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use RevertActorRequest_Options.ProtoReflect.Descriptor instead. +func (*RevertActorRequest_Options) Descriptor() ([]byte, []int) { + return file_api_ateapi_v1_ateapi_proto_rawDescGZIP(), []int{82, 0} +} + +func (x *RevertActorRequest_Options) GetVersion() int64 { + if x != nil { + return x.Version + } + return 0 +} + +func (x *RevertActorRequest_Options) GetUid() string { + if x != nil { + return x.Uid + } + return "" +} + var file_api_ateapi_v1_ateapi_proto_extTypes = []protoimpl.ExtensionInfo{ { ExtendedType: (*descriptorpb.MessageOptions)(nil), @@ -9982,6 +11484,14 @@ var file_api_ateapi_v1_ateapi_proto_extTypes = []protoimpl.ExtensionInfo{ Tag: "bytes,50000,opt,name=method", Filename: "api/ateapi/v1/ateapi.proto", }, + { + ExtendedType: (*descriptorpb.FieldOptions)(nil), + ExtensionType: (*FieldAnnotation)(nil), + Field: 50000, + Name: "substrate.ateapi.v1.field", + Tag: "bytes,50000,opt,name=field", + Filename: "api/ateapi/v1/ateapi.proto", + }, } // Extension fields to descriptorpb.MessageOptions. @@ -9996,6 +11506,12 @@ var ( E_Method = &file_api_ateapi_v1_ateapi_proto_extTypes[1] ) +// Extension fields to descriptorpb.FieldOptions. +var ( + // optional substrate.ateapi.v1.FieldAnnotation field = 50000; + E_Field = &file_api_ateapi_v1_ateapi_proto_extTypes[2] +) + var File_api_ateapi_v1_ateapi_proto protoreflect.FileDescriptor const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + @@ -10032,15 +11548,15 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\vupdate_time\x18\x06 \x01(\v2\x1a.google.protobuf.TimestampR\n" + "updateTime\x12;\n" + "\vdelete_time\x18\a \x01(\v2\x1a.google.protobuf.TimestampR\n" + - "deleteTime\"V\n" + - "\x0fExternalVolumes\x12C\n" + - "\avolumes\x18\x01 \x03(\v2).substrate.ateapi.v1.ExternalVolumeStatusR\avolumes\"\x9e\x02\n" + - "\x14ExternalVolumeStatus\x12\x12\n" + + "deleteTime\"[\n" + + "\x0fExternalVolumes\x12H\n" + + "\avolumes\x18\x01 \x03(\v2..substrate.ateapi.v1.ActorExternalVolumeStatusR\avolumes\"\xa8\x02\n" + + "\x19ActorExternalVolumeStatus\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12*\n" + "\x11storage_volume_id\x18\x02 \x01(\tR\x0fstorageVolumeId\x12\x1f\n" + "\vvolume_type\x18\x03 \x01(\tR\n" + - "volumeType\x12c\n" + - "\x0evolume_context\x18\x04 \x03(\v2<.substrate.ateapi.v1.ExternalVolumeStatus.VolumeContextEntryR\rvolumeContext\x1a@\n" + + "volumeType\x12h\n" + + "\x0evolume_context\x18\x04 \x03(\v2A.substrate.ateapi.v1.ActorExternalVolumeStatus.VolumeContextEntryR\rvolumeContext\x1a@\n" + "\x12VolumeContextEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"\xe2\x02\n" + @@ -10080,19 +11596,33 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\n" + "\bAllPorts\"a\n" + "\x0fHttpRuleEffects\x12N\n" + - "\x0freplace_headers\x18\x01 \x03(\v2%.substrate.ateapi.v1.CredentialHeaderR\x0ereplaceHeaders\"\xab\x01\n" + + "\x0freplace_headers\x18\x01 \x03(\v2%.substrate.ateapi.v1.CredentialHeaderR\x0ereplaceHeaders\"\xfc\x01\n" + "\x10CredentialHeader\x12\x16\n" + "\x06header\x18\x01 \x01(\tR\x06header\x12\x16\n" + "\x06prefix\x18\x02 \x01(\tR\x06prefix\x12%\n" + "\x0ecredential_uri\x18\x03 \x01(\tR\rcredentialUri\x12@\n" + - "\tactor_jwt\x18\x04 \x01(\v2#.substrate.ateapi.v1.ActorJwtSourceR\bactorJwt\"]\n" + + "\tactor_jwt\x18\x04 \x01(\v2#.substrate.ateapi.v1.ActorJwtSourceR\bactorJwt\x12O\n" + + "\x0etoken_exchange\x18\x05 \x01(\v2(.substrate.ateapi.v1.TokenExchangeSourceR\rtokenExchange\"\xde\x02\n" + + "\x13TokenExchangeSource\x12\x1b\n" + + "\ttoken_url\x18\x01 \x01(\tR\btokenUrl\x12O\n" + + "\x11subject_actor_jwt\x18\x02 \x01(\v2#.substrate.ateapi.v1.ActorJwtSourceR\x0fsubjectActorJwt\x12\x1c\n" + + "\tresources\x18\x03 \x03(\tR\tresources\x12\x1c\n" + + "\taudiences\x18\x04 \x03(\tR\taudiences\x12\x16\n" + + "\x06scopes\x18\x05 \x03(\tR\x06scopes\x120\n" + + "\x14requested_token_type\x18\x06 \x01(\tR\x12requestedTokenType\x12S\n" + + "\x15additional_parameters\x18\a \x03(\v2\x1e.substrate.ateapi.v1.FormEntryR\x14additionalParameters\"3\n" + + "\tFormEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value\"]\n" + "\x0eActorJwtSource\x12\x1c\n" + "\taudiences\x18\x01 \x03(\tR\taudiences\x12-\n" + - "\x12expiration_seconds\x18\x02 \x01(\x03R\x11expirationSeconds\"\xbc\x03\n" + + "\x12expiration_seconds\x18\x02 \x01(\x03R\x11expirationSeconds\"\xd7\x03\n" + "\vActorStatus\x125\n" + "\x05state\x18\x01 \x01(\x0e2\x1f.substrate.ateapi.v1.ActorStateR\x05state\x12R\n" + - "\x11worker_assignment\x18\x02 \x01(\v2%.substrate.ateapi.v1.WorkerAssignmentR\x10workerAssignment\x12O\n" + - "\x10external_volumes\x18\x03 \x01(\v2$.substrate.ateapi.v1.ExternalVolumesR\x0fexternalVolumes\x125\n" + + "\x11worker_assignment\x18\x02 \x01(\v2%.substrate.ateapi.v1.WorkerAssignmentR\x10workerAssignment\x12j\n" + + "\x10external_volumes\x18\x03 \x01(\v2$.substrate.ateapi.v1.ExternalVolumesB\x19\x82\xb5\x18\x15\n" + + "\x13\n" + + "\x0fExternalVolumes\x10\x01R\x0fexternalVolumes\x125\n" + "\x05crash\x18\x04 \x01(\v2\x1f.substrate.ateapi.v1.ActorCrashR\x05crash\x12#\n" + "\rassigned_node\x18\x05 \x01(\tR\fassignedNode\x12;\n" + "\tsnapshots\x18\x06 \x03(\v2\x1d.substrate.ateapi.v1.SnapshotR\tsnapshots\x128\n" + @@ -10101,7 +11631,7 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "ActorCrash\x12\x18\n" + "\amessage\x18\x01 \x01(\tR\amessage\x129\n" + "\n" + - "crash_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\tcrashTime\"\xbe\x03\n" + + "crash_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\tcrashTime\"\xf0\x03\n" + "\x10WorkerAssignment\x126\n" + "\x06worker\x18\x06 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x06worker\x12)\n" + "\x10worker_namespace\x18\x01 \x01(\tR\x0fworkerNamespace\x12\x1f\n" + @@ -10115,7 +11645,8 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\fworker_epoch\x18\b \x01(\x03R\vworkerEpoch\x12Q\n" + "\x0fsandbox_runtime\x18\t \x01(\v2(.substrate.ateapi.v1.ActorSandboxRuntimeR\x0esandboxRuntime\x12(\n" + "\x10worker_spiffe_id\x18\n" + - " \x01(\tR\x0eworkerSpiffeId\"t\n" + + " \x01(\tR\x0eworkerSpiffeId\x120\n" + + "\x14actor_activation_uid\x18\v \x01(\tR\x12actorActivationUid\"t\n" + "\tTagStatus\x129\n" + "\bsnapshot\x18\x01 \x01(\v2\x1d.substrate.ateapi.v1.SnapshotR\bsnapshot\x12,\n" + "\x12actor_template_uid\x18\x02 \x01(\tR\x10actorTemplateUid\"\x86\x02\n" + @@ -10123,12 +11654,25 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\bmetadata\x18\x01 \x01(\v2%.substrate.ateapi.v1.ResourceMetadataR\bmetadata\x126\n" + "\x06status\x18\x02 \x01(\v2\x1e.substrate.ateapi.v1.TagStatusR\x06status\x123\n" + "\x05scope\x18\x03 \x01(\x0e2\x1d.substrate.ateapi.v1.TagScopeR\x05scope\x12A\n" + - "\fsource_actor\x18\x04 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\vsourceActor:\f\x82\xb5\x18\b\x18\x01\"\x04Tags\"`\n" + + "\fsource_actor\x18\x04 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\vsourceActor:\f\x82\xb5\x18\b\x18\x01\"\x04Tags\"\xaf\x01\n" + + "\x0eExternalVolume\x12A\n" + + "\bmetadata\x18\x01 \x01(\v2%.substrate.ateapi.v1.ResourceMetadataR\bmetadata\x12A\n" + + "\x06status\x18\x02 \x01(\v2).substrate.ateapi.v1.ExternalVolumeStatusR\x06status:\x17\x82\xb5\x18\x13\x18\x01\"\x0fExternalVolumes\"N\n" + + "\x14ExternalVolumeStatus\x126\n" + + "\x03csi\x18\x01 \x01(\v2$.substrate.ateapi.v1.CsiVolumeStatusR\x03csi\"\xf1\x01\n" + + "\x0fCsiVolumeStatus\x12\x1b\n" + + "\tvolume_id\x18\x01 \x01(\tR\bvolumeId\x12\x1f\n" + + "\vdriver_name\x18\x02 \x01(\tR\n" + + "driverName\x12^\n" + + "\x0evolume_context\x18\x03 \x03(\v27.substrate.ateapi.v1.CsiVolumeStatus.VolumeContextEntryR\rvolumeContext\x1a@\n" + + "\x12VolumeContextEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01\"`\n" + "\bAtespace\x12A\n" + "\bmetadata\x18\x01 \x01(\v2%.substrate.ateapi.v1.ResourceMetadataR\bmetadata:\x11\x82\xb5\x18\r\x18\x02\"\tAtespaces\";\n" + "\tObjectRef\x12\x1a\n" + "\batespace\x18\x01 \x01(\tR\batespace\x12\x12\n" + - "\x04name\x18\x02 \x01(\tR\x04name\"\xdf\x04\n" + + "\x04name\x18\x02 \x01(\tR\x04name\"\xfb\x04\n" + "\rActorTemplate\x12A\n" + "\bmetadata\x18\x01 \x01(\v2%.substrate.ateapi.v1.ResourceMetadataR\bmetadata\x12F\n" + "\x0fworker_selector\x18\x02 \x01(\v2\x1d.substrate.ateapi.v1.SelectorR\x0eworkerSelector\x12>\n" + @@ -10137,8 +11681,10 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "containers\x125\n" + "\avolumes\x18\x04 \x03(\v2\x1b.substrate.ateapi.v1.VolumeR\avolumes\x12L\n" + "\x0fsnapshot_config\x18\x05 \x01(\v2#.substrate.ateapi.v1.SnapshotConfigR\x0esnapshotConfig\x12G\n" + - "\tresources\x18\x06 \x01(\v2).substrate.ateapi.v1.ResourceRequirementsR\tresources\x12[\n" + - "\x14golden_egress_policy\x18\t \x01(\v2).substrate.ateapi.v1.EgressPolicyTemplateR\x12goldenEgressPolicy\x12@\n" + + "\tresources\x18\x06 \x01(\v2).substrate.ateapi.v1.ResourceRequirementsR\tresources\x12w\n" + + "\x14golden_egress_policy\x18\t \x01(\v2).substrate.ateapi.v1.EgressPolicyTemplateB\x1a\x82\xb5\x18\x16\n" + + "\x14\n" + + "\x12GoldenEgressPolicyR\x12goldenEgressPolicy\x12@\n" + "\x06status\x18\a \x01(\v2(.substrate.ateapi.v1.ActorTemplateStatusR\x06status:\x16\x82\xb5\x18\x12\x18\x01\"\x0eActorTemplates\"N\n" + "\x14ResourceRequirements\x126\n" + "\x06limits\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ResourcesR\x06limits\"U\n" + @@ -10151,9 +11697,11 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\rsnapshot_time\x18\x02 \x01(\v2\x1a.google.protobuf.TimestampR\fsnapshotTime\x12#\n" + "\rerror_message\x18\x03 \x01(\tR\ferrorMessage\"v\n" + "\x13ActorTemplateStatus\x12_\n" + - "\x16golden_snapshot_status\x18\x01 \x01(\v2).substrate.ateapi.v1.GoldenSnapshotStatusR\x14goldenSnapshotStatus\"\xf2\x01\n" + - "\x0eSnapshotConfig\x12)\n" + - "\x10storage_location\x18\x01 \x01(\tR\x0fstorageLocation\x12T\n" + + "\x16golden_snapshot_status\x18\x01 \x01(\v2).substrate.ateapi.v1.GoldenSnapshotStatusR\x14goldenSnapshotStatus\"\x97\x02\n" + + "\x0eSnapshotConfig\x12N\n" + + "\x10storage_location\x18\x01 \x01(\tB#\x82\xb5\x18\x1f\n" + + "\x1d\n" + + "\x1bPerTemplateSnapshotLocationR\x0fstorageLocation\x12T\n" + "\x12preferred_fidelity\x18\x02 \x01(\x0e2%.substrate.ateapi.v1.SnapshotFidelityR\x11preferredFidelity\x12_\n" + "\x16golden_snapshot_config\x18\x03 \x01(\v2).substrate.ateapi.v1.GoldenSnapshotConfigR\x14goldenSnapshotConfig\"S\n" + "\x14GoldenSnapshotConfig\x12;\n" + @@ -10181,12 +11729,14 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\x0ftimeout_seconds\x18\x02 \x01(\x05R\x0etimeoutSeconds\"7\n" + "\rHttpGetAction\x12\x12\n" + "\x04path\x18\x01 \x01(\tR\x04path\x12\x12\n" + - "\x04port\x18\x02 \x01(\x05R\x04port\"\xbd\x02\n" + + "\x04port\x18\x02 \x01(\x05R\x04port\"\xd6\x02\n" + "\x06Volume\x12\x12\n" + "\x04name\x18\x01 \x01(\tR\x04name\x12L\n" + "\vdurable_dir\x18\x02 \x01(\v2+.substrate.ateapi.v1.DurableDirVolumeSourceR\n" + - "durableDir\x12E\n" + - "\bexternal\x18\x03 \x01(\v2).substrate.ateapi.v1.ExternalVolumeSourceR\bexternal\x12L\n" + + "durableDir\x12^\n" + + "\bexternal\x18\x03 \x01(\v2).substrate.ateapi.v1.ExternalVolumeSourceB\x17\x82\xb5\x18\x13\n" + + "\x11\n" + + "\x0fExternalVolumesR\bexternal\x12L\n" + "\vsystem_info\x18\x04 \x01(\v2+.substrate.ateapi.v1.SystemInfoVolumeSourceR\n" + "systemInfo\x12<\n" + "\x05image\x18\x05 \x01(\v2&.substrate.ateapi.v1.ImageVolumeSourceR\x05image\"_\n" + @@ -10197,7 +11747,20 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\x16DurableDirVolumeSource\"m\n" + "\x16ExternalVolumeTemplate\x12%\n" + "\x0ecapacity_bytes\x18\x01 \x01(\x03R\rcapacityBytes\x12,\n" + - "\x12storage_class_name\x18\x02 \x01(\tR\x10storageClassName\"f\n" + + "\x12storage_class_name\x18\x02 \x01(\tR\x10storageClassName\"\x97\x02\n" + + "\tCsiDriver\x12A\n" + + "\bmetadata\x18\x01 \x01(\v2%.substrate.ateapi.v1.ResourceMetadataR\bmetadata\x12\x1f\n" + + "\vdriver_name\x18\x02 \x01(\tR\n" + + "driverName\x12W\n" + + "\x13controller_endpoint\x18\x03 \x01(\v2&.substrate.ateapi.v1.CsiDriverEndpointR\x12controllerEndpoint\x129\n" + + "\x03tls\x18\x04 \x01(\v2'.substrate.ateapi.v1.CsiDriverTlsConfigR\x03tls:\x12\x82\xb5\x18\x0e\x18\x02\"\n" + + "CsiDrivers\";\n" + + "\x11CsiDriverEndpoint\x12\x12\n" + + "\x04host\x18\x01 \x01(\tR\x04host\x12\x12\n" + + "\x04port\x18\x02 \x01(\x05R\x04port\"5\n" + + "\x12CsiDriverTlsConfig\x12\x1f\n" + + "\vserver_name\x18\x01 \x01(\tR\n" + + "serverName\"f\n" + "\x16SystemInfoVolumeSource\x12L\n" + "\fdata_sources\x18\x01 \x03(\v2).substrate.ateapi.v1.SystemInfoDataSourceR\vdataSources\"\xba\x01\n" + "\x14SystemInfoDataSource\x12S\n" + @@ -10226,6 +11789,25 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"\x91\x01\n" + "\x15DeleteAtespaceRequest\x12:\n" + "\batespace\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\batespace\x12<\n" + + "\aoptions\x18\x02 \x01(\v2\".substrate.ateapi.v1.DeleteOptionsR\aoptions\"W\n" + + "\x16CreateCsiDriverRequest\x12=\n" + + "\n" + + "csi_driver\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.CsiDriverR\tcsiDriver\"T\n" + + "\x13GetCsiDriverRequest\x12=\n" + + "\n" + + "csi_driver\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\tcsiDriver\"S\n" + + "\x15ListCsiDriversRequest\x12:\n" + + "\aoptions\x18\x01 \x01(\v2 .substrate.ateapi.v1.ListOptionsR\aoptions\"\x81\x01\n" + + "\x16ListCsiDriversResponse\x12?\n" + + "\vcsi_drivers\x18\x01 \x03(\v2\x1e.substrate.ateapi.v1.CsiDriverR\n" + + "csiDrivers\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\"W\n" + + "\x16UpdateCsiDriverRequest\x12=\n" + + "\n" + + "csi_driver\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.CsiDriverR\tcsiDriver\"\x95\x01\n" + + "\x16DeleteCsiDriverRequest\x12=\n" + + "\n" + + "csi_driver\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\tcsiDriver\x12<\n" + "\aoptions\x18\x02 \x01(\v2\".substrate.ateapi.v1.DeleteOptionsR\aoptions\"g\n" + "\x1aCreateActorTemplateRequest\x12I\n" + "\x0eactor_template\x18\x01 \x01(\v2\".substrate.ateapi.v1.ActorTemplateR\ractorTemplate\"`\n" + @@ -10250,16 +11832,26 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\x05actor\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x05actor\x12=\n" + "\aoptions\x18\x02 \x01(\v2#.substrate.ateapi.v1.SuspendOptionsR\aoptions\"H\n" + "\x14SuspendActorResponse\x120\n" + - "\x05actor\x18\x01 \x01(\v2\x1a.substrate.ateapi.v1.ActorR\x05actor\"I\n" + + "\x05actor\x18\x01 \x01(\v2\x1a.substrate.ateapi.v1.ActorR\x05actor\"u\n" + "\x0eSuspendOptions\x127\n" + - "\x04mode\x18\x01 \x01(\x0e2#.substrate.ateapi.v1.DurabilityModeR\x04mode\"J\n" + + "\x04mode\x18\x01 \x01(\x0e2#.substrate.ateapi.v1.DurabilityModeR\x04mode\x12\x18\n" + + "\aversion\x18\x02 \x01(\x03R\aversion\x12\x10\n" + + "\x03uid\x18\x03 \x01(\tR\x03uid\"\xcc\x01\n" + "\x12ResumeActorRequest\x124\n" + - "\x05actor\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x05actor\"a\n" + + "\x05actor\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x05actor\x12I\n" + + "\aoptions\x18\x02 \x01(\v2/.substrate.ateapi.v1.ResumeActorRequest.OptionsR\aoptions\x1a5\n" + + "\aOptions\x12\x18\n" + + "\aversion\x18\x01 \x01(\x03R\aversion\x12\x10\n" + + "\x03uid\x18\x02 \x01(\tR\x03uid\"a\n" + "\x13ResumeActorResponse\x120\n" + "\x05actor\x18\x01 \x01(\v2\x1a.substrate.ateapi.v1.ActorR\x05actor\x12\x18\n" + - "\aresumed\x18\x02 \x01(\bR\aresumed\"J\n" + + "\aresumed\x18\x02 \x01(\bR\aresumed\"\xcc\x01\n" + "\x12RevertActorRequest\x124\n" + - "\x05actor\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x05actor\"G\n" + + "\x05actor\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x05actor\x12I\n" + + "\aoptions\x18\x02 \x01(\v2/.substrate.ateapi.v1.RevertActorRequest.OptionsR\aoptions\x1a5\n" + + "\aOptions\x12\x18\n" + + "\aversion\x18\x01 \x01(\x03R\aversion\x12\x10\n" + + "\x03uid\x18\x02 \x01(\tR\x03uid\"G\n" + "\x13RevertActorResponse\x120\n" + "\x05actor\x18\x01 \x01(\v2\x1a.substrate.ateapi.v1.ActorR\x05actor\"\x88\x01\n" + "\x12DeleteActorRequest\x124\n" + @@ -10300,7 +11892,15 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\x03tag\x18\x01 \x01(\v2\x18.substrate.ateapi.v1.TagR\x03tag\"\x82\x01\n" + "\x10DeleteTagRequest\x120\n" + "\x03tag\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x03tag\x12<\n" + - "\aoptions\x18\x02 \x01(\v2\".substrate.ateapi.v1.DeleteOptionsR\aoptions\";\n" + + "\aoptions\x18\x02 \x01(\v2\".substrate.ateapi.v1.DeleteOptionsR\aoptions\"c\n" + + "\x18GetExternalVolumeRequest\x12G\n" + + "\x0fexternal_volume\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x0eexternalVolume\"t\n" + + "\x1aListExternalVolumesRequest\x12\x1a\n" + + "\batespace\x18\x01 \x01(\tR\batespace\x12:\n" + + "\aoptions\x18\x02 \x01(\v2 .substrate.ateapi.v1.ListOptionsR\aoptions\"\x95\x01\n" + + "\x1bListExternalVolumesResponse\x12N\n" + + "\x10external_volumes\x18\x01 \x03(\v2#.substrate.ateapi.v1.ExternalVolumeR\x0fexternalVolumes\x12&\n" + + "\x0fnext_page_token\x18\x02 \x01(\tR\rnextPageToken\";\n" + "\rDeleteOptions\x12\x18\n" + "\aversion\x18\x01 \x01(\x03R\aversion\x12\x10\n" + "\x03uid\x18\x02 \x01(\tR\x03uid\"I\n" + @@ -10438,12 +12038,13 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\x05actor\x18\x02 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x05actor\x12\x1b\n" + "\tactor_uid\x18\x03 \x01(\tR\bactorUid\"O\n" + "\x1bRequestActorSuspendResponse\x120\n" + - "\x05actor\x18\x01 \x01(\v2\x1a.substrate.ateapi.v1.ActorR\x05actor\"\xc0\x01\n" + + "\x05actor\x18\x01 \x01(\v2\x1a.substrate.ateapi.v1.ActorR\x05actor\"\xe7\x01\n" + "\x19ReportActorCrashedRequest\x126\n" + "\x06worker\x18\x01 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x06worker\x124\n" + "\x05actor\x18\x02 \x01(\v2\x1e.substrate.ateapi.v1.ObjectRefR\x05actor\x12\x1b\n" + "\tactor_uid\x18\x03 \x01(\tR\bactorUid\x12\x18\n" + - "\amessage\x18\x04 \x01(\tR\amessage\"N\n" + + "\amessage\x18\x04 \x01(\tR\amessage\x12%\n" + + "\x0eactivation_uid\x18\x05 \x01(\tR\ractivationUid\"N\n" + "\x1aReportActorCrashedResponse\x120\n" + "\x05actor\x18\x01 \x01(\v2\x1a.substrate.ateapi.v1.ActorR\x05actor\"\xb3\x01\n" + "\x1fReportActorSnapshotStateRequest\x124\n" + @@ -10496,9 +12097,17 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\aparents\x18\x01 \x03(\tR\aparents\x12\x1c\n" + "\tsingleton\x18\x02 \x01(\bR\tsingleton\x120\n" + "\x05scope\x18\x03 \x01(\x0e2\x1a.substrate.ateapi.v1.ScopeR\x05scope\x12\x16\n" + - "\x06plural\x18\x04 \x01(\tR\x06plural\".\n" + + "\x06plural\x18\x04 \x01(\tR\x06plural\"y\n" + "\x10MethodAnnotation\x12\x1a\n" + - "\bresource\x18\x01 \x01(\tR\bresource*a\n" + + "\bresource\x18\x01 \x01(\tR\bresource\x12I\n" + + "\fpreview_gate\x18\x02 \x01(\v2&.substrate.ateapi.v1.MethodPreviewGateR\vpreviewGate\"'\n" + + "\x11MethodPreviewGate\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\"[\n" + + "\x0fFieldAnnotation\x12H\n" + + "\fpreview_gate\x18\x01 \x01(\v2%.substrate.ateapi.v1.FieldPreviewGateR\vpreviewGate\"V\n" + + "\x10FieldPreviewGate\x12\x12\n" + + "\x04name\x18\x01 \x01(\tR\x04name\x12.\n" + + "\x13allow_when_disabled\x18\x02 \x01(\bR\x11allowWhenDisabled*a\n" + "\rSnapshotOwner\x12\x1e\n" + "\x1aSNAPSHOT_OWNER_UNSPECIFIED\x10\x00\x12\x18\n" + "\x14SNAPSHOT_OWNER_ACTOR\x10\x01\x12\x16\n" + @@ -10547,7 +12156,7 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\x05Scope\x12\x15\n" + "\x11SCOPE_UNSPECIFIED\x10\x00\x12\x12\n" + "\x0eSCOPE_ATESPACE\x10\x01\x12\x10\n" + - "\fSCOPE_GLOBAL\x10\x022\xca&\n" + + "\fSCOPE_GLOBAL\x10\x022\xbc-\n" + "\aControl\x12Y\n" + "\bGetActor\x12$.substrate.ateapi.v1.GetActorRequest\x1a\x1a.substrate.ateapi.v1.Actor\"\v\x82\xb5\x18\a\n" + "\x05Actor\x12_\n" + @@ -10582,7 +12191,11 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\tUpdateTag\x12%.substrate.ateapi.v1.UpdateTagRequest\x1a\x18.substrate.ateapi.v1.Tag\"\t\x82\xb5\x18\x05\n" + "\x03Tag\x12W\n" + "\tDeleteTag\x12%.substrate.ateapi.v1.DeleteTagRequest\x1a\x18.substrate.ateapi.v1.Tag\"\t\x82\xb5\x18\x05\n" + - "\x03Tag\x12n\n" + + "\x03Tag\x12}\n" + + "\x11GetExternalVolume\x12-.substrate.ateapi.v1.GetExternalVolumeRequest\x1a#.substrate.ateapi.v1.ExternalVolume\"\x14\x82\xb5\x18\x10\n" + + "\x0eExternalVolume\x12\x8e\x01\n" + + "\x13ListExternalVolumes\x12/.substrate.ateapi.v1.ListExternalVolumesRequest\x1a0.substrate.ateapi.v1.ListExternalVolumesResponse\"\x14\x82\xb5\x18\x10\n" + + "\x0eExternalVolume\x12n\n" + "\vListWorkers\x12'.substrate.ateapi.v1.ListWorkersRequest\x1a(.substrate.ateapi.v1.ListWorkersResponse\"\f\x82\xb5\x18\b\n" + "\x06Worker\x12]\n" + "\tGetWorker\x12%.substrate.ateapi.v1.GetWorkerRequest\x1a\x1b.substrate.ateapi.v1.Worker\"\f\x82\xb5\x18\b\n" + @@ -10615,7 +12228,19 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\bAtespace\x12k\n" + "\x0eDeleteAtespace\x12*.substrate.ateapi.v1.DeleteAtespaceRequest\x1a\x1d.substrate.ateapi.v1.Atespace\"\x0e\x82\xb5\x18\n" + "\n" + - "\bAtespace\x12\x7f\n" + + "\bAtespace\x12\x82\x01\n" + + "\x0fCreateCsiDriver\x12+.substrate.ateapi.v1.CreateCsiDriverRequest\x1a\x1e.substrate.ateapi.v1.CsiDriver\"\"\x82\xb5\x18\x1e\n" + + "\tCsiDriver\x12\x11\n" + + "\x0fExternalVolumes\x12i\n" + + "\fGetCsiDriver\x12(.substrate.ateapi.v1.GetCsiDriverRequest\x1a\x1e.substrate.ateapi.v1.CsiDriver\"\x0f\x82\xb5\x18\v\n" + + "\tCsiDriver\x12z\n" + + "\x0eListCsiDrivers\x12*.substrate.ateapi.v1.ListCsiDriversRequest\x1a+.substrate.ateapi.v1.ListCsiDriversResponse\"\x0f\x82\xb5\x18\v\n" + + "\tCsiDriver\x12\x82\x01\n" + + "\x0fUpdateCsiDriver\x12+.substrate.ateapi.v1.UpdateCsiDriverRequest\x1a\x1e.substrate.ateapi.v1.CsiDriver\"\"\x82\xb5\x18\x1e\n" + + "\tCsiDriver\x12\x11\n" + + "\x0fExternalVolumes\x12o\n" + + "\x0fDeleteCsiDriver\x12+.substrate.ateapi.v1.DeleteCsiDriverRequest\x1a\x1e.substrate.ateapi.v1.CsiDriver\"\x0f\x82\xb5\x18\v\n" + + "\tCsiDriver\x12\x7f\n" + "\x13CreateActorTemplate\x12/.substrate.ateapi.v1.CreateActorTemplateRequest\x1a\".substrate.ateapi.v1.ActorTemplate\"\x13\x82\xb5\x18\x0f\n" + "\rActorTemplate\x12y\n" + "\x10GetActorTemplate\x12,.substrate.ateapi.v1.GetActorTemplateRequest\x1a\".substrate.ateapi.v1.ActorTemplate\"\x13\x82\xb5\x18\x0f\n" + @@ -10648,7 +12273,8 @@ const file_api_ateapi_v1_ateapi_proto_rawDesc = "" + "\x18ReportActorSnapshotState\x124.substrate.ateapi.v1.ReportActorSnapshotStateRequest\x1a5.substrate.ateapi.v1.ReportActorSnapshotStateResponse\x12u\n" + "\x12ReportActorCrashed\x12..substrate.ateapi.v1.ReportActorCrashedRequest\x1a/.substrate.ateapi.v1.ReportActorCrashedResponse:f\n" + "\bresource\x12\x1f.google.protobuf.MessageOptions\x18І\x03 \x01(\v2'.substrate.ateapi.v1.ResourceAnnotationR\bresource:_\n" + - "\x06method\x12\x1e.google.protobuf.MethodOptions\x18І\x03 \x01(\v2%.substrate.ateapi.v1.MethodAnnotationR\x06methodB+Z)go.ate.dev/substrate/api/ateapi/v1;ateapib\x06proto3" + "\x06method\x12\x1e.google.protobuf.MethodOptions\x18І\x03 \x01(\v2%.substrate.ateapi.v1.MethodAnnotationR\x06method:[\n" + + "\x05field\x12\x1d.google.protobuf.FieldOptions\x18І\x03 \x01(\v2$.substrate.ateapi.v1.FieldAnnotationR\x05fieldB+Z)go.ate.dev/substrate/api/ateapi/v1;ateapib\x06proto3" var ( file_api_ateapi_v1_ateapi_proto_rawDescOnce sync.Once @@ -10663,7 +12289,7 @@ func file_api_ateapi_v1_ateapi_proto_rawDescGZIP() []byte { } var file_api_ateapi_v1_ateapi_proto_enumTypes = make([]protoimpl.EnumInfo, 10) -var file_api_ateapi_v1_ateapi_proto_msgTypes = make([]protoimpl.MessageInfo, 143) +var file_api_ateapi_v1_ateapi_proto_msgTypes = make([]protoimpl.MessageInfo, 166) var file_api_ateapi_v1_ateapi_proto_goTypes = []any{ (SnapshotOwner)(0), // 0: substrate.ateapi.v1.SnapshotOwner (SnapshotStorageState)(0), // 1: substrate.ateapi.v1.SnapshotStorageState @@ -10681,7 +12307,7 @@ var file_api_ateapi_v1_ateapi_proto_goTypes = []any{ (*Selector)(nil), // 13: substrate.ateapi.v1.Selector (*ResourceMetadata)(nil), // 14: substrate.ateapi.v1.ResourceMetadata (*ExternalVolumes)(nil), // 15: substrate.ateapi.v1.ExternalVolumes - (*ExternalVolumeStatus)(nil), // 16: substrate.ateapi.v1.ExternalVolumeStatus + (*ActorExternalVolumeStatus)(nil), // 16: substrate.ateapi.v1.ActorExternalVolumeStatus (*Actor)(nil), // 17: substrate.ateapi.v1.Actor (*EgressPolicy)(nil), // 18: substrate.ateapi.v1.EgressPolicy (*EgressPolicyTemplate)(nil), // 19: substrate.ateapi.v1.EgressPolicyTemplate @@ -10693,134 +12319,158 @@ var file_api_ateapi_v1_ateapi_proto_goTypes = []any{ (*AllPorts)(nil), // 25: substrate.ateapi.v1.AllPorts (*HttpRuleEffects)(nil), // 26: substrate.ateapi.v1.HttpRuleEffects (*CredentialHeader)(nil), // 27: substrate.ateapi.v1.CredentialHeader - (*ActorJwtSource)(nil), // 28: substrate.ateapi.v1.ActorJwtSource - (*ActorStatus)(nil), // 29: substrate.ateapi.v1.ActorStatus - (*ActorCrash)(nil), // 30: substrate.ateapi.v1.ActorCrash - (*WorkerAssignment)(nil), // 31: substrate.ateapi.v1.WorkerAssignment - (*TagStatus)(nil), // 32: substrate.ateapi.v1.TagStatus - (*Tag)(nil), // 33: substrate.ateapi.v1.Tag - (*Atespace)(nil), // 34: substrate.ateapi.v1.Atespace - (*ObjectRef)(nil), // 35: substrate.ateapi.v1.ObjectRef - (*ActorTemplate)(nil), // 36: substrate.ateapi.v1.ActorTemplate - (*ResourceRequirements)(nil), // 37: substrate.ateapi.v1.ResourceRequirements - (*Resources)(nil), // 38: substrate.ateapi.v1.Resources - (*GoldenSnapshotStatus)(nil), // 39: substrate.ateapi.v1.GoldenSnapshotStatus - (*ActorTemplateStatus)(nil), // 40: substrate.ateapi.v1.ActorTemplateStatus - (*SnapshotConfig)(nil), // 41: substrate.ateapi.v1.SnapshotConfig - (*GoldenSnapshotConfig)(nil), // 42: substrate.ateapi.v1.GoldenSnapshotConfig - (*Container)(nil), // 43: substrate.ateapi.v1.Container - (*SecurityContext)(nil), // 44: substrate.ateapi.v1.SecurityContext - (*Capabilities)(nil), // 45: substrate.ateapi.v1.Capabilities - (*EnvVar)(nil), // 46: substrate.ateapi.v1.EnvVar - (*WakeupProbe)(nil), // 47: substrate.ateapi.v1.WakeupProbe - (*HttpGetAction)(nil), // 48: substrate.ateapi.v1.HttpGetAction - (*Volume)(nil), // 49: substrate.ateapi.v1.Volume - (*ExternalVolumeSource)(nil), // 50: substrate.ateapi.v1.ExternalVolumeSource - (*ImageVolumeSource)(nil), // 51: substrate.ateapi.v1.ImageVolumeSource - (*DurableDirVolumeSource)(nil), // 52: substrate.ateapi.v1.DurableDirVolumeSource - (*ExternalVolumeTemplate)(nil), // 53: substrate.ateapi.v1.ExternalVolumeTemplate - (*SystemInfoVolumeSource)(nil), // 54: substrate.ateapi.v1.SystemInfoVolumeSource - (*SystemInfoDataSource)(nil), // 55: substrate.ateapi.v1.SystemInfoDataSource - (*ActorMetadataDataSource)(nil), // 56: substrate.ateapi.v1.ActorMetadataDataSource - (*ActorMetadataItem)(nil), // 57: substrate.ateapi.v1.ActorMetadataItem - (*TrustBundleDataSource)(nil), // 58: substrate.ateapi.v1.TrustBundleDataSource - (*VolumeMount)(nil), // 59: substrate.ateapi.v1.VolumeMount - (*CreateAtespaceRequest)(nil), // 60: substrate.ateapi.v1.CreateAtespaceRequest - (*GetAtespaceRequest)(nil), // 61: substrate.ateapi.v1.GetAtespaceRequest - (*ListAtespacesRequest)(nil), // 62: substrate.ateapi.v1.ListAtespacesRequest - (*ListAtespacesResponse)(nil), // 63: substrate.ateapi.v1.ListAtespacesResponse - (*DeleteAtespaceRequest)(nil), // 64: substrate.ateapi.v1.DeleteAtespaceRequest - (*CreateActorTemplateRequest)(nil), // 65: substrate.ateapi.v1.CreateActorTemplateRequest - (*GetActorTemplateRequest)(nil), // 66: substrate.ateapi.v1.GetActorTemplateRequest - (*ListActorTemplatesRequest)(nil), // 67: substrate.ateapi.v1.ListActorTemplatesRequest - (*ListActorTemplatesResponse)(nil), // 68: substrate.ateapi.v1.ListActorTemplatesResponse - (*DeleteActorTemplateRequest)(nil), // 69: substrate.ateapi.v1.DeleteActorTemplateRequest - (*GetActorRequest)(nil), // 70: substrate.ateapi.v1.GetActorRequest - (*CreateActorRequest)(nil), // 71: substrate.ateapi.v1.CreateActorRequest - (*UpdateActorRequest)(nil), // 72: substrate.ateapi.v1.UpdateActorRequest - (*SuspendActorRequest)(nil), // 73: substrate.ateapi.v1.SuspendActorRequest - (*SuspendActorResponse)(nil), // 74: substrate.ateapi.v1.SuspendActorResponse - (*SuspendOptions)(nil), // 75: substrate.ateapi.v1.SuspendOptions - (*ResumeActorRequest)(nil), // 76: substrate.ateapi.v1.ResumeActorRequest - (*ResumeActorResponse)(nil), // 77: substrate.ateapi.v1.ResumeActorResponse - (*RevertActorRequest)(nil), // 78: substrate.ateapi.v1.RevertActorRequest - (*RevertActorResponse)(nil), // 79: substrate.ateapi.v1.RevertActorResponse - (*DeleteActorRequest)(nil), // 80: substrate.ateapi.v1.DeleteActorRequest - (*GetActorEgressPolicyRequest)(nil), // 81: substrate.ateapi.v1.GetActorEgressPolicyRequest - (*CreateActorEgressPolicyRequest)(nil), // 82: substrate.ateapi.v1.CreateActorEgressPolicyRequest - (*UpdateActorEgressPolicyRequest)(nil), // 83: substrate.ateapi.v1.UpdateActorEgressPolicyRequest - (*DeleteActorEgressPolicyRequest)(nil), // 84: substrate.ateapi.v1.DeleteActorEgressPolicyRequest - (*GetTagRequest)(nil), // 85: substrate.ateapi.v1.GetTagRequest - (*MintActorJwtRequest)(nil), // 86: substrate.ateapi.v1.MintActorJwtRequest - (*MintActorJwtResponse)(nil), // 87: substrate.ateapi.v1.MintActorJwtResponse - (*ListTagsRequest)(nil), // 88: substrate.ateapi.v1.ListTagsRequest - (*ListTagsResponse)(nil), // 89: substrate.ateapi.v1.ListTagsResponse - (*CreateTagRequest)(nil), // 90: substrate.ateapi.v1.CreateTagRequest - (*UpdateTagRequest)(nil), // 91: substrate.ateapi.v1.UpdateTagRequest - (*DeleteTagRequest)(nil), // 92: substrate.ateapi.v1.DeleteTagRequest - (*DeleteOptions)(nil), // 93: substrate.ateapi.v1.DeleteOptions - (*ListOptions)(nil), // 94: substrate.ateapi.v1.ListOptions - (*ListWorkerActorAssignmentsRequest)(nil), // 95: substrate.ateapi.v1.ListWorkerActorAssignmentsRequest - (*ListWorkerActorAssignmentsResponse)(nil), // 96: substrate.ateapi.v1.ListWorkerActorAssignmentsResponse - (*ListWorkersRequest)(nil), // 97: substrate.ateapi.v1.ListWorkersRequest - (*ListWorkersResponse)(nil), // 98: substrate.ateapi.v1.ListWorkersResponse - (*GetWorkerRequest)(nil), // 99: substrate.ateapi.v1.GetWorkerRequest - (*CreateWorkerRequest)(nil), // 100: substrate.ateapi.v1.CreateWorkerRequest - (*UpdateWorkerRequest)(nil), // 101: substrate.ateapi.v1.UpdateWorkerRequest - (*DeleteWorkerRequest)(nil), // 102: substrate.ateapi.v1.DeleteWorkerRequest - (*DrainWorkerRequest)(nil), // 103: substrate.ateapi.v1.DrainWorkerRequest - (*DrainWorkerResponse)(nil), // 104: substrate.ateapi.v1.DrainWorkerResponse - (*MarkWorkerAvailableRequest)(nil), // 105: substrate.ateapi.v1.MarkWorkerAvailableRequest - (*MarkWorkerAvailableResponse)(nil), // 106: substrate.ateapi.v1.MarkWorkerAvailableResponse - (*MarkWorkerUnavailableRequest)(nil), // 107: substrate.ateapi.v1.MarkWorkerUnavailableRequest - (*MarkWorkerUnavailableResponse)(nil), // 108: substrate.ateapi.v1.MarkWorkerUnavailableResponse - (*ListActorsRequest)(nil), // 109: substrate.ateapi.v1.ListActorsRequest - (*ListActorsResponse)(nil), // 110: substrate.ateapi.v1.ListActorsResponse - (*Worker)(nil), // 111: substrate.ateapi.v1.Worker - (*WorkerStatus)(nil), // 112: substrate.ateapi.v1.WorkerStatus - (*WorkerSandboxClass)(nil), // 113: substrate.ateapi.v1.WorkerSandboxClass - (*WorkerSandboxRuntime)(nil), // 114: substrate.ateapi.v1.WorkerSandboxRuntime - (*RuntimeOverhead)(nil), // 115: substrate.ateapi.v1.RuntimeOverhead - (*ActorSandboxRuntime)(nil), // 116: substrate.ateapi.v1.ActorSandboxRuntime - (*VersionedSandboxCompat)(nil), // 117: substrate.ateapi.v1.VersionedSandboxCompat - (*AttributeEntry)(nil), // 118: substrate.ateapi.v1.AttributeEntry - (*WorkerResources)(nil), // 119: substrate.ateapi.v1.WorkerResources - (*ActorAssignment)(nil), // 120: substrate.ateapi.v1.ActorAssignment - (*AcquireWorkerEpochRequest)(nil), // 121: substrate.ateapi.v1.AcquireWorkerEpochRequest - (*AcquireWorkerEpochResponse)(nil), // 122: substrate.ateapi.v1.AcquireWorkerEpochResponse - (*RegisterWorkerRequest)(nil), // 123: substrate.ateapi.v1.RegisterWorkerRequest - (*RegisterWorkerResponse)(nil), // 124: substrate.ateapi.v1.RegisterWorkerResponse - (*SetWorkerSandboxRuntimesRequest)(nil), // 125: substrate.ateapi.v1.SetWorkerSandboxRuntimesRequest - (*SetWorkerSandboxRuntimesResponse)(nil), // 126: substrate.ateapi.v1.SetWorkerSandboxRuntimesResponse - (*MintWorkerActorCertificateRequest)(nil), // 127: substrate.ateapi.v1.MintWorkerActorCertificateRequest - (*MintWorkerActorCertificateResponse)(nil), // 128: substrate.ateapi.v1.MintWorkerActorCertificateResponse - (*MintWorkerActorJwtRequest)(nil), // 129: substrate.ateapi.v1.MintWorkerActorJwtRequest - (*MintWorkerActorJwtResponse)(nil), // 130: substrate.ateapi.v1.MintWorkerActorJwtResponse - (*RequestActorSuspendRequest)(nil), // 131: substrate.ateapi.v1.RequestActorSuspendRequest - (*RequestActorSuspendResponse)(nil), // 132: substrate.ateapi.v1.RequestActorSuspendResponse - (*ReportActorCrashedRequest)(nil), // 133: substrate.ateapi.v1.ReportActorCrashedRequest - (*ReportActorCrashedResponse)(nil), // 134: substrate.ateapi.v1.ReportActorCrashedResponse - (*ReportActorSnapshotStateRequest)(nil), // 135: substrate.ateapi.v1.ReportActorSnapshotStateRequest - (*ReportActorSnapshotStateResponse)(nil), // 136: substrate.ateapi.v1.ReportActorSnapshotStateResponse - (*ActorSnapshotState)(nil), // 137: substrate.ateapi.v1.ActorSnapshotState - (*SnapshotReport)(nil), // 138: substrate.ateapi.v1.SnapshotReport - (*AccessPolicy)(nil), // 139: substrate.ateapi.v1.AccessPolicy - (*Binding)(nil), // 140: substrate.ateapi.v1.Binding - (*GetGlobalAccessPolicyRequest)(nil), // 141: substrate.ateapi.v1.GetGlobalAccessPolicyRequest - (*CreateGlobalAccessPolicyRequest)(nil), // 142: substrate.ateapi.v1.CreateGlobalAccessPolicyRequest - (*UpdateGlobalAccessPolicyRequest)(nil), // 143: substrate.ateapi.v1.UpdateGlobalAccessPolicyRequest - (*GetAtespaceAccessPolicyRequest)(nil), // 144: substrate.ateapi.v1.GetAtespaceAccessPolicyRequest - (*CreateAtespaceAccessPolicyRequest)(nil), // 145: substrate.ateapi.v1.CreateAtespaceAccessPolicyRequest - (*UpdateAtespaceAccessPolicyRequest)(nil), // 146: substrate.ateapi.v1.UpdateAtespaceAccessPolicyRequest - (*DeleteAtespaceAccessPolicyRequest)(nil), // 147: substrate.ateapi.v1.DeleteAtespaceAccessPolicyRequest - (*ResourceAnnotation)(nil), // 148: substrate.ateapi.v1.ResourceAnnotation - (*MethodAnnotation)(nil), // 149: substrate.ateapi.v1.MethodAnnotation - nil, // 150: substrate.ateapi.v1.Selector.MatchLabelsEntry - nil, // 151: substrate.ateapi.v1.ExternalVolumeStatus.VolumeContextEntry - nil, // 152: substrate.ateapi.v1.Worker.LabelsEntry - (*timestamppb.Timestamp)(nil), // 153: google.protobuf.Timestamp - (*descriptorpb.MessageOptions)(nil), // 154: google.protobuf.MessageOptions - (*descriptorpb.MethodOptions)(nil), // 155: google.protobuf.MethodOptions + (*TokenExchangeSource)(nil), // 28: substrate.ateapi.v1.TokenExchangeSource + (*FormEntry)(nil), // 29: substrate.ateapi.v1.FormEntry + (*ActorJwtSource)(nil), // 30: substrate.ateapi.v1.ActorJwtSource + (*ActorStatus)(nil), // 31: substrate.ateapi.v1.ActorStatus + (*ActorCrash)(nil), // 32: substrate.ateapi.v1.ActorCrash + (*WorkerAssignment)(nil), // 33: substrate.ateapi.v1.WorkerAssignment + (*TagStatus)(nil), // 34: substrate.ateapi.v1.TagStatus + (*Tag)(nil), // 35: substrate.ateapi.v1.Tag + (*ExternalVolume)(nil), // 36: substrate.ateapi.v1.ExternalVolume + (*ExternalVolumeStatus)(nil), // 37: substrate.ateapi.v1.ExternalVolumeStatus + (*CsiVolumeStatus)(nil), // 38: substrate.ateapi.v1.CsiVolumeStatus + (*Atespace)(nil), // 39: substrate.ateapi.v1.Atespace + (*ObjectRef)(nil), // 40: substrate.ateapi.v1.ObjectRef + (*ActorTemplate)(nil), // 41: substrate.ateapi.v1.ActorTemplate + (*ResourceRequirements)(nil), // 42: substrate.ateapi.v1.ResourceRequirements + (*Resources)(nil), // 43: substrate.ateapi.v1.Resources + (*GoldenSnapshotStatus)(nil), // 44: substrate.ateapi.v1.GoldenSnapshotStatus + (*ActorTemplateStatus)(nil), // 45: substrate.ateapi.v1.ActorTemplateStatus + (*SnapshotConfig)(nil), // 46: substrate.ateapi.v1.SnapshotConfig + (*GoldenSnapshotConfig)(nil), // 47: substrate.ateapi.v1.GoldenSnapshotConfig + (*Container)(nil), // 48: substrate.ateapi.v1.Container + (*SecurityContext)(nil), // 49: substrate.ateapi.v1.SecurityContext + (*Capabilities)(nil), // 50: substrate.ateapi.v1.Capabilities + (*EnvVar)(nil), // 51: substrate.ateapi.v1.EnvVar + (*WakeupProbe)(nil), // 52: substrate.ateapi.v1.WakeupProbe + (*HttpGetAction)(nil), // 53: substrate.ateapi.v1.HttpGetAction + (*Volume)(nil), // 54: substrate.ateapi.v1.Volume + (*ExternalVolumeSource)(nil), // 55: substrate.ateapi.v1.ExternalVolumeSource + (*ImageVolumeSource)(nil), // 56: substrate.ateapi.v1.ImageVolumeSource + (*DurableDirVolumeSource)(nil), // 57: substrate.ateapi.v1.DurableDirVolumeSource + (*ExternalVolumeTemplate)(nil), // 58: substrate.ateapi.v1.ExternalVolumeTemplate + (*CsiDriver)(nil), // 59: substrate.ateapi.v1.CsiDriver + (*CsiDriverEndpoint)(nil), // 60: substrate.ateapi.v1.CsiDriverEndpoint + (*CsiDriverTlsConfig)(nil), // 61: substrate.ateapi.v1.CsiDriverTlsConfig + (*SystemInfoVolumeSource)(nil), // 62: substrate.ateapi.v1.SystemInfoVolumeSource + (*SystemInfoDataSource)(nil), // 63: substrate.ateapi.v1.SystemInfoDataSource + (*ActorMetadataDataSource)(nil), // 64: substrate.ateapi.v1.ActorMetadataDataSource + (*ActorMetadataItem)(nil), // 65: substrate.ateapi.v1.ActorMetadataItem + (*TrustBundleDataSource)(nil), // 66: substrate.ateapi.v1.TrustBundleDataSource + (*VolumeMount)(nil), // 67: substrate.ateapi.v1.VolumeMount + (*CreateAtespaceRequest)(nil), // 68: substrate.ateapi.v1.CreateAtespaceRequest + (*GetAtespaceRequest)(nil), // 69: substrate.ateapi.v1.GetAtespaceRequest + (*ListAtespacesRequest)(nil), // 70: substrate.ateapi.v1.ListAtespacesRequest + (*ListAtespacesResponse)(nil), // 71: substrate.ateapi.v1.ListAtespacesResponse + (*DeleteAtespaceRequest)(nil), // 72: substrate.ateapi.v1.DeleteAtespaceRequest + (*CreateCsiDriverRequest)(nil), // 73: substrate.ateapi.v1.CreateCsiDriverRequest + (*GetCsiDriverRequest)(nil), // 74: substrate.ateapi.v1.GetCsiDriverRequest + (*ListCsiDriversRequest)(nil), // 75: substrate.ateapi.v1.ListCsiDriversRequest + (*ListCsiDriversResponse)(nil), // 76: substrate.ateapi.v1.ListCsiDriversResponse + (*UpdateCsiDriverRequest)(nil), // 77: substrate.ateapi.v1.UpdateCsiDriverRequest + (*DeleteCsiDriverRequest)(nil), // 78: substrate.ateapi.v1.DeleteCsiDriverRequest + (*CreateActorTemplateRequest)(nil), // 79: substrate.ateapi.v1.CreateActorTemplateRequest + (*GetActorTemplateRequest)(nil), // 80: substrate.ateapi.v1.GetActorTemplateRequest + (*ListActorTemplatesRequest)(nil), // 81: substrate.ateapi.v1.ListActorTemplatesRequest + (*ListActorTemplatesResponse)(nil), // 82: substrate.ateapi.v1.ListActorTemplatesResponse + (*DeleteActorTemplateRequest)(nil), // 83: substrate.ateapi.v1.DeleteActorTemplateRequest + (*GetActorRequest)(nil), // 84: substrate.ateapi.v1.GetActorRequest + (*CreateActorRequest)(nil), // 85: substrate.ateapi.v1.CreateActorRequest + (*UpdateActorRequest)(nil), // 86: substrate.ateapi.v1.UpdateActorRequest + (*SuspendActorRequest)(nil), // 87: substrate.ateapi.v1.SuspendActorRequest + (*SuspendActorResponse)(nil), // 88: substrate.ateapi.v1.SuspendActorResponse + (*SuspendOptions)(nil), // 89: substrate.ateapi.v1.SuspendOptions + (*ResumeActorRequest)(nil), // 90: substrate.ateapi.v1.ResumeActorRequest + (*ResumeActorResponse)(nil), // 91: substrate.ateapi.v1.ResumeActorResponse + (*RevertActorRequest)(nil), // 92: substrate.ateapi.v1.RevertActorRequest + (*RevertActorResponse)(nil), // 93: substrate.ateapi.v1.RevertActorResponse + (*DeleteActorRequest)(nil), // 94: substrate.ateapi.v1.DeleteActorRequest + (*GetActorEgressPolicyRequest)(nil), // 95: substrate.ateapi.v1.GetActorEgressPolicyRequest + (*CreateActorEgressPolicyRequest)(nil), // 96: substrate.ateapi.v1.CreateActorEgressPolicyRequest + (*UpdateActorEgressPolicyRequest)(nil), // 97: substrate.ateapi.v1.UpdateActorEgressPolicyRequest + (*DeleteActorEgressPolicyRequest)(nil), // 98: substrate.ateapi.v1.DeleteActorEgressPolicyRequest + (*GetTagRequest)(nil), // 99: substrate.ateapi.v1.GetTagRequest + (*MintActorJwtRequest)(nil), // 100: substrate.ateapi.v1.MintActorJwtRequest + (*MintActorJwtResponse)(nil), // 101: substrate.ateapi.v1.MintActorJwtResponse + (*ListTagsRequest)(nil), // 102: substrate.ateapi.v1.ListTagsRequest + (*ListTagsResponse)(nil), // 103: substrate.ateapi.v1.ListTagsResponse + (*CreateTagRequest)(nil), // 104: substrate.ateapi.v1.CreateTagRequest + (*UpdateTagRequest)(nil), // 105: substrate.ateapi.v1.UpdateTagRequest + (*DeleteTagRequest)(nil), // 106: substrate.ateapi.v1.DeleteTagRequest + (*GetExternalVolumeRequest)(nil), // 107: substrate.ateapi.v1.GetExternalVolumeRequest + (*ListExternalVolumesRequest)(nil), // 108: substrate.ateapi.v1.ListExternalVolumesRequest + (*ListExternalVolumesResponse)(nil), // 109: substrate.ateapi.v1.ListExternalVolumesResponse + (*DeleteOptions)(nil), // 110: substrate.ateapi.v1.DeleteOptions + (*ListOptions)(nil), // 111: substrate.ateapi.v1.ListOptions + (*ListWorkerActorAssignmentsRequest)(nil), // 112: substrate.ateapi.v1.ListWorkerActorAssignmentsRequest + (*ListWorkerActorAssignmentsResponse)(nil), // 113: substrate.ateapi.v1.ListWorkerActorAssignmentsResponse + (*ListWorkersRequest)(nil), // 114: substrate.ateapi.v1.ListWorkersRequest + (*ListWorkersResponse)(nil), // 115: substrate.ateapi.v1.ListWorkersResponse + (*GetWorkerRequest)(nil), // 116: substrate.ateapi.v1.GetWorkerRequest + (*CreateWorkerRequest)(nil), // 117: substrate.ateapi.v1.CreateWorkerRequest + (*UpdateWorkerRequest)(nil), // 118: substrate.ateapi.v1.UpdateWorkerRequest + (*DeleteWorkerRequest)(nil), // 119: substrate.ateapi.v1.DeleteWorkerRequest + (*DrainWorkerRequest)(nil), // 120: substrate.ateapi.v1.DrainWorkerRequest + (*DrainWorkerResponse)(nil), // 121: substrate.ateapi.v1.DrainWorkerResponse + (*MarkWorkerAvailableRequest)(nil), // 122: substrate.ateapi.v1.MarkWorkerAvailableRequest + (*MarkWorkerAvailableResponse)(nil), // 123: substrate.ateapi.v1.MarkWorkerAvailableResponse + (*MarkWorkerUnavailableRequest)(nil), // 124: substrate.ateapi.v1.MarkWorkerUnavailableRequest + (*MarkWorkerUnavailableResponse)(nil), // 125: substrate.ateapi.v1.MarkWorkerUnavailableResponse + (*ListActorsRequest)(nil), // 126: substrate.ateapi.v1.ListActorsRequest + (*ListActorsResponse)(nil), // 127: substrate.ateapi.v1.ListActorsResponse + (*Worker)(nil), // 128: substrate.ateapi.v1.Worker + (*WorkerStatus)(nil), // 129: substrate.ateapi.v1.WorkerStatus + (*WorkerSandboxClass)(nil), // 130: substrate.ateapi.v1.WorkerSandboxClass + (*WorkerSandboxRuntime)(nil), // 131: substrate.ateapi.v1.WorkerSandboxRuntime + (*RuntimeOverhead)(nil), // 132: substrate.ateapi.v1.RuntimeOverhead + (*ActorSandboxRuntime)(nil), // 133: substrate.ateapi.v1.ActorSandboxRuntime + (*VersionedSandboxCompat)(nil), // 134: substrate.ateapi.v1.VersionedSandboxCompat + (*AttributeEntry)(nil), // 135: substrate.ateapi.v1.AttributeEntry + (*WorkerResources)(nil), // 136: substrate.ateapi.v1.WorkerResources + (*ActorAssignment)(nil), // 137: substrate.ateapi.v1.ActorAssignment + (*AcquireWorkerEpochRequest)(nil), // 138: substrate.ateapi.v1.AcquireWorkerEpochRequest + (*AcquireWorkerEpochResponse)(nil), // 139: substrate.ateapi.v1.AcquireWorkerEpochResponse + (*RegisterWorkerRequest)(nil), // 140: substrate.ateapi.v1.RegisterWorkerRequest + (*RegisterWorkerResponse)(nil), // 141: substrate.ateapi.v1.RegisterWorkerResponse + (*SetWorkerSandboxRuntimesRequest)(nil), // 142: substrate.ateapi.v1.SetWorkerSandboxRuntimesRequest + (*SetWorkerSandboxRuntimesResponse)(nil), // 143: substrate.ateapi.v1.SetWorkerSandboxRuntimesResponse + (*MintWorkerActorCertificateRequest)(nil), // 144: substrate.ateapi.v1.MintWorkerActorCertificateRequest + (*MintWorkerActorCertificateResponse)(nil), // 145: substrate.ateapi.v1.MintWorkerActorCertificateResponse + (*MintWorkerActorJwtRequest)(nil), // 146: substrate.ateapi.v1.MintWorkerActorJwtRequest + (*MintWorkerActorJwtResponse)(nil), // 147: substrate.ateapi.v1.MintWorkerActorJwtResponse + (*RequestActorSuspendRequest)(nil), // 148: substrate.ateapi.v1.RequestActorSuspendRequest + (*RequestActorSuspendResponse)(nil), // 149: substrate.ateapi.v1.RequestActorSuspendResponse + (*ReportActorCrashedRequest)(nil), // 150: substrate.ateapi.v1.ReportActorCrashedRequest + (*ReportActorCrashedResponse)(nil), // 151: substrate.ateapi.v1.ReportActorCrashedResponse + (*ReportActorSnapshotStateRequest)(nil), // 152: substrate.ateapi.v1.ReportActorSnapshotStateRequest + (*ReportActorSnapshotStateResponse)(nil), // 153: substrate.ateapi.v1.ReportActorSnapshotStateResponse + (*ActorSnapshotState)(nil), // 154: substrate.ateapi.v1.ActorSnapshotState + (*SnapshotReport)(nil), // 155: substrate.ateapi.v1.SnapshotReport + (*AccessPolicy)(nil), // 156: substrate.ateapi.v1.AccessPolicy + (*Binding)(nil), // 157: substrate.ateapi.v1.Binding + (*GetGlobalAccessPolicyRequest)(nil), // 158: substrate.ateapi.v1.GetGlobalAccessPolicyRequest + (*CreateGlobalAccessPolicyRequest)(nil), // 159: substrate.ateapi.v1.CreateGlobalAccessPolicyRequest + (*UpdateGlobalAccessPolicyRequest)(nil), // 160: substrate.ateapi.v1.UpdateGlobalAccessPolicyRequest + (*GetAtespaceAccessPolicyRequest)(nil), // 161: substrate.ateapi.v1.GetAtespaceAccessPolicyRequest + (*CreateAtespaceAccessPolicyRequest)(nil), // 162: substrate.ateapi.v1.CreateAtespaceAccessPolicyRequest + (*UpdateAtespaceAccessPolicyRequest)(nil), // 163: substrate.ateapi.v1.UpdateAtespaceAccessPolicyRequest + (*DeleteAtespaceAccessPolicyRequest)(nil), // 164: substrate.ateapi.v1.DeleteAtespaceAccessPolicyRequest + (*ResourceAnnotation)(nil), // 165: substrate.ateapi.v1.ResourceAnnotation + (*MethodAnnotation)(nil), // 166: substrate.ateapi.v1.MethodAnnotation + (*MethodPreviewGate)(nil), // 167: substrate.ateapi.v1.MethodPreviewGate + (*FieldAnnotation)(nil), // 168: substrate.ateapi.v1.FieldAnnotation + (*FieldPreviewGate)(nil), // 169: substrate.ateapi.v1.FieldPreviewGate + nil, // 170: substrate.ateapi.v1.Selector.MatchLabelsEntry + nil, // 171: substrate.ateapi.v1.ActorExternalVolumeStatus.VolumeContextEntry + nil, // 172: substrate.ateapi.v1.CsiVolumeStatus.VolumeContextEntry + (*ResumeActorRequest_Options)(nil), // 173: substrate.ateapi.v1.ResumeActorRequest.Options + (*RevertActorRequest_Options)(nil), // 174: substrate.ateapi.v1.RevertActorRequest.Options + nil, // 175: substrate.ateapi.v1.Worker.LabelsEntry + (*timestamppb.Timestamp)(nil), // 176: google.protobuf.Timestamp + (*descriptorpb.MessageOptions)(nil), // 177: google.protobuf.MessageOptions + (*descriptorpb.MethodOptions)(nil), // 178: google.protobuf.MethodOptions + (*descriptorpb.FieldOptions)(nil), // 179: google.protobuf.FieldOptions } var file_api_ateapi_v1_ateapi_proto_depIdxs = []int32{ 1, // 0: substrate.ateapi.v1.SnapshotStorage.state:type_name -> substrate.ateapi.v1.SnapshotStorageState @@ -10828,18 +12478,18 @@ var file_api_ateapi_v1_ateapi_proto_depIdxs = []int32{ 0, // 2: substrate.ateapi.v1.Snapshot.owner:type_name -> substrate.ateapi.v1.SnapshotOwner 2, // 3: substrate.ateapi.v1.Snapshot.fidelity:type_name -> substrate.ateapi.v1.SnapshotFidelity 11, // 4: substrate.ateapi.v1.Snapshot.durable_snapshot:type_name -> substrate.ateapi.v1.SnapshotStorage - 116, // 5: substrate.ateapi.v1.Snapshot.sandbox_runtime:type_name -> substrate.ateapi.v1.ActorSandboxRuntime - 150, // 6: substrate.ateapi.v1.Selector.match_labels:type_name -> substrate.ateapi.v1.Selector.MatchLabelsEntry - 153, // 7: substrate.ateapi.v1.ResourceMetadata.create_time:type_name -> google.protobuf.Timestamp - 153, // 8: substrate.ateapi.v1.ResourceMetadata.update_time:type_name -> google.protobuf.Timestamp - 153, // 9: substrate.ateapi.v1.ResourceMetadata.delete_time:type_name -> google.protobuf.Timestamp - 16, // 10: substrate.ateapi.v1.ExternalVolumes.volumes:type_name -> substrate.ateapi.v1.ExternalVolumeStatus - 151, // 11: substrate.ateapi.v1.ExternalVolumeStatus.volume_context:type_name -> substrate.ateapi.v1.ExternalVolumeStatus.VolumeContextEntry + 133, // 5: substrate.ateapi.v1.Snapshot.sandbox_runtime:type_name -> substrate.ateapi.v1.ActorSandboxRuntime + 170, // 6: substrate.ateapi.v1.Selector.match_labels:type_name -> substrate.ateapi.v1.Selector.MatchLabelsEntry + 176, // 7: substrate.ateapi.v1.ResourceMetadata.create_time:type_name -> google.protobuf.Timestamp + 176, // 8: substrate.ateapi.v1.ResourceMetadata.update_time:type_name -> google.protobuf.Timestamp + 176, // 9: substrate.ateapi.v1.ResourceMetadata.delete_time:type_name -> google.protobuf.Timestamp + 16, // 10: substrate.ateapi.v1.ExternalVolumes.volumes:type_name -> substrate.ateapi.v1.ActorExternalVolumeStatus + 171, // 11: substrate.ateapi.v1.ActorExternalVolumeStatus.volume_context:type_name -> substrate.ateapi.v1.ActorExternalVolumeStatus.VolumeContextEntry 14, // 12: substrate.ateapi.v1.Actor.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata - 35, // 13: substrate.ateapi.v1.Actor.actor_template:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 13: substrate.ateapi.v1.Actor.actor_template:type_name -> substrate.ateapi.v1.ObjectRef 13, // 14: substrate.ateapi.v1.Actor.worker_selector:type_name -> substrate.ateapi.v1.Selector - 35, // 15: substrate.ateapi.v1.Actor.source_tag:type_name -> substrate.ateapi.v1.ObjectRef - 29, // 16: substrate.ateapi.v1.Actor.status:type_name -> substrate.ateapi.v1.ActorStatus + 40, // 15: substrate.ateapi.v1.Actor.source_tag:type_name -> substrate.ateapi.v1.ObjectRef + 31, // 16: substrate.ateapi.v1.Actor.status:type_name -> substrate.ateapi.v1.ActorStatus 14, // 17: substrate.ateapi.v1.EgressPolicy.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata 20, // 18: substrate.ateapi.v1.EgressPolicy.rules:type_name -> substrate.ateapi.v1.EgressRule 20, // 19: substrate.ateapi.v1.EgressPolicyTemplate.rules:type_name -> substrate.ateapi.v1.EgressRule @@ -10853,276 +12503,316 @@ var file_api_ateapi_v1_ateapi_proto_depIdxs = []int32{ 24, // 27: substrate.ateapi.v1.TlsPassthroughRule.ports:type_name -> substrate.ateapi.v1.Ports 25, // 28: substrate.ateapi.v1.Ports.all:type_name -> substrate.ateapi.v1.AllPorts 27, // 29: substrate.ateapi.v1.HttpRuleEffects.replace_headers:type_name -> substrate.ateapi.v1.CredentialHeader - 28, // 30: substrate.ateapi.v1.CredentialHeader.actor_jwt:type_name -> substrate.ateapi.v1.ActorJwtSource - 4, // 31: substrate.ateapi.v1.ActorStatus.state:type_name -> substrate.ateapi.v1.ActorState - 31, // 32: substrate.ateapi.v1.ActorStatus.worker_assignment:type_name -> substrate.ateapi.v1.WorkerAssignment - 15, // 33: substrate.ateapi.v1.ActorStatus.external_volumes:type_name -> substrate.ateapi.v1.ExternalVolumes - 30, // 34: substrate.ateapi.v1.ActorStatus.crash:type_name -> substrate.ateapi.v1.ActorCrash - 12, // 35: substrate.ateapi.v1.ActorStatus.snapshots:type_name -> substrate.ateapi.v1.Snapshot - 153, // 36: substrate.ateapi.v1.ActorCrash.crash_time:type_name -> google.protobuf.Timestamp - 35, // 37: substrate.ateapi.v1.WorkerAssignment.worker:type_name -> substrate.ateapi.v1.ObjectRef - 116, // 38: substrate.ateapi.v1.WorkerAssignment.sandbox_runtime:type_name -> substrate.ateapi.v1.ActorSandboxRuntime - 12, // 39: substrate.ateapi.v1.TagStatus.snapshot:type_name -> substrate.ateapi.v1.Snapshot - 14, // 40: substrate.ateapi.v1.Tag.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata - 32, // 41: substrate.ateapi.v1.Tag.status:type_name -> substrate.ateapi.v1.TagStatus - 3, // 42: substrate.ateapi.v1.Tag.scope:type_name -> substrate.ateapi.v1.TagScope - 35, // 43: substrate.ateapi.v1.Tag.source_actor:type_name -> substrate.ateapi.v1.ObjectRef - 14, // 44: substrate.ateapi.v1.Atespace.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata - 14, // 45: substrate.ateapi.v1.ActorTemplate.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata - 13, // 46: substrate.ateapi.v1.ActorTemplate.worker_selector:type_name -> substrate.ateapi.v1.Selector - 43, // 47: substrate.ateapi.v1.ActorTemplate.containers:type_name -> substrate.ateapi.v1.Container - 49, // 48: substrate.ateapi.v1.ActorTemplate.volumes:type_name -> substrate.ateapi.v1.Volume - 41, // 49: substrate.ateapi.v1.ActorTemplate.snapshot_config:type_name -> substrate.ateapi.v1.SnapshotConfig - 37, // 50: substrate.ateapi.v1.ActorTemplate.resources:type_name -> substrate.ateapi.v1.ResourceRequirements - 19, // 51: substrate.ateapi.v1.ActorTemplate.golden_egress_policy:type_name -> substrate.ateapi.v1.EgressPolicyTemplate - 40, // 52: substrate.ateapi.v1.ActorTemplate.status:type_name -> substrate.ateapi.v1.ActorTemplateStatus - 38, // 53: substrate.ateapi.v1.ResourceRequirements.limits:type_name -> substrate.ateapi.v1.Resources - 35, // 54: substrate.ateapi.v1.GoldenSnapshotStatus.golden_tag:type_name -> substrate.ateapi.v1.ObjectRef - 153, // 55: substrate.ateapi.v1.GoldenSnapshotStatus.snapshot_time:type_name -> google.protobuf.Timestamp - 39, // 56: substrate.ateapi.v1.ActorTemplateStatus.golden_snapshot_status:type_name -> substrate.ateapi.v1.GoldenSnapshotStatus - 2, // 57: substrate.ateapi.v1.SnapshotConfig.preferred_fidelity:type_name -> substrate.ateapi.v1.SnapshotFidelity - 42, // 58: substrate.ateapi.v1.SnapshotConfig.golden_snapshot_config:type_name -> substrate.ateapi.v1.GoldenSnapshotConfig - 5, // 59: substrate.ateapi.v1.GoldenSnapshotConfig.mode:type_name -> substrate.ateapi.v1.GoldenSnapshotMode - 46, // 60: substrate.ateapi.v1.Container.env:type_name -> substrate.ateapi.v1.EnvVar - 47, // 61: substrate.ateapi.v1.Container.wakeup_probe:type_name -> substrate.ateapi.v1.WakeupProbe - 59, // 62: substrate.ateapi.v1.Container.volume_mounts:type_name -> substrate.ateapi.v1.VolumeMount - 44, // 63: substrate.ateapi.v1.Container.security_context:type_name -> substrate.ateapi.v1.SecurityContext - 37, // 64: substrate.ateapi.v1.Container.resources:type_name -> substrate.ateapi.v1.ResourceRequirements - 45, // 65: substrate.ateapi.v1.SecurityContext.capabilities:type_name -> substrate.ateapi.v1.Capabilities - 48, // 66: substrate.ateapi.v1.WakeupProbe.http_get:type_name -> substrate.ateapi.v1.HttpGetAction - 52, // 67: substrate.ateapi.v1.Volume.durable_dir:type_name -> substrate.ateapi.v1.DurableDirVolumeSource - 50, // 68: substrate.ateapi.v1.Volume.external:type_name -> substrate.ateapi.v1.ExternalVolumeSource - 54, // 69: substrate.ateapi.v1.Volume.system_info:type_name -> substrate.ateapi.v1.SystemInfoVolumeSource - 51, // 70: substrate.ateapi.v1.Volume.image:type_name -> substrate.ateapi.v1.ImageVolumeSource - 53, // 71: substrate.ateapi.v1.ExternalVolumeSource.template:type_name -> substrate.ateapi.v1.ExternalVolumeTemplate - 55, // 72: substrate.ateapi.v1.SystemInfoVolumeSource.data_sources:type_name -> substrate.ateapi.v1.SystemInfoDataSource - 56, // 73: substrate.ateapi.v1.SystemInfoDataSource.actor_metadata:type_name -> substrate.ateapi.v1.ActorMetadataDataSource - 58, // 74: substrate.ateapi.v1.SystemInfoDataSource.trust_bundle:type_name -> substrate.ateapi.v1.TrustBundleDataSource - 57, // 75: substrate.ateapi.v1.ActorMetadataDataSource.items:type_name -> substrate.ateapi.v1.ActorMetadataItem - 6, // 76: substrate.ateapi.v1.ActorMetadataItem.field:type_name -> substrate.ateapi.v1.ActorMetadataField - 34, // 77: substrate.ateapi.v1.CreateAtespaceRequest.atespace:type_name -> substrate.ateapi.v1.Atespace - 35, // 78: substrate.ateapi.v1.GetAtespaceRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef - 94, // 79: substrate.ateapi.v1.ListAtespacesRequest.options:type_name -> substrate.ateapi.v1.ListOptions - 34, // 80: substrate.ateapi.v1.ListAtespacesResponse.atespaces:type_name -> substrate.ateapi.v1.Atespace - 35, // 81: substrate.ateapi.v1.DeleteAtespaceRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef - 93, // 82: substrate.ateapi.v1.DeleteAtespaceRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions - 36, // 83: substrate.ateapi.v1.CreateActorTemplateRequest.actor_template:type_name -> substrate.ateapi.v1.ActorTemplate - 35, // 84: substrate.ateapi.v1.GetActorTemplateRequest.actor_template:type_name -> substrate.ateapi.v1.ObjectRef - 94, // 85: substrate.ateapi.v1.ListActorTemplatesRequest.options:type_name -> substrate.ateapi.v1.ListOptions - 36, // 86: substrate.ateapi.v1.ListActorTemplatesResponse.actor_templates:type_name -> substrate.ateapi.v1.ActorTemplate - 35, // 87: substrate.ateapi.v1.DeleteActorTemplateRequest.actor_template:type_name -> substrate.ateapi.v1.ObjectRef - 93, // 88: substrate.ateapi.v1.DeleteActorTemplateRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions - 35, // 89: substrate.ateapi.v1.GetActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 17, // 90: substrate.ateapi.v1.CreateActorRequest.actor:type_name -> substrate.ateapi.v1.Actor - 17, // 91: substrate.ateapi.v1.UpdateActorRequest.actor:type_name -> substrate.ateapi.v1.Actor - 35, // 92: substrate.ateapi.v1.SuspendActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 75, // 93: substrate.ateapi.v1.SuspendActorRequest.options:type_name -> substrate.ateapi.v1.SuspendOptions - 17, // 94: substrate.ateapi.v1.SuspendActorResponse.actor:type_name -> substrate.ateapi.v1.Actor - 7, // 95: substrate.ateapi.v1.SuspendOptions.mode:type_name -> substrate.ateapi.v1.DurabilityMode - 35, // 96: substrate.ateapi.v1.ResumeActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 17, // 97: substrate.ateapi.v1.ResumeActorResponse.actor:type_name -> substrate.ateapi.v1.Actor - 35, // 98: substrate.ateapi.v1.RevertActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 17, // 99: substrate.ateapi.v1.RevertActorResponse.actor:type_name -> substrate.ateapi.v1.Actor - 35, // 100: substrate.ateapi.v1.DeleteActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 93, // 101: substrate.ateapi.v1.DeleteActorRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions - 35, // 102: substrate.ateapi.v1.GetActorEgressPolicyRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 35, // 103: substrate.ateapi.v1.CreateActorEgressPolicyRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 18, // 104: substrate.ateapi.v1.CreateActorEgressPolicyRequest.egress_policy:type_name -> substrate.ateapi.v1.EgressPolicy - 35, // 105: substrate.ateapi.v1.UpdateActorEgressPolicyRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 18, // 106: substrate.ateapi.v1.UpdateActorEgressPolicyRequest.egress_policy:type_name -> substrate.ateapi.v1.EgressPolicy - 35, // 107: substrate.ateapi.v1.DeleteActorEgressPolicyRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 93, // 108: substrate.ateapi.v1.DeleteActorEgressPolicyRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions - 35, // 109: substrate.ateapi.v1.GetTagRequest.tag:type_name -> substrate.ateapi.v1.ObjectRef - 35, // 110: substrate.ateapi.v1.MintActorJwtRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 153, // 111: substrate.ateapi.v1.MintActorJwtResponse.expire_time:type_name -> google.protobuf.Timestamp - 94, // 112: substrate.ateapi.v1.ListTagsRequest.options:type_name -> substrate.ateapi.v1.ListOptions - 33, // 113: substrate.ateapi.v1.ListTagsResponse.tags:type_name -> substrate.ateapi.v1.Tag - 33, // 114: substrate.ateapi.v1.CreateTagRequest.tag:type_name -> substrate.ateapi.v1.Tag - 33, // 115: substrate.ateapi.v1.UpdateTagRequest.tag:type_name -> substrate.ateapi.v1.Tag - 35, // 116: substrate.ateapi.v1.DeleteTagRequest.tag:type_name -> substrate.ateapi.v1.ObjectRef - 93, // 117: substrate.ateapi.v1.DeleteTagRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions - 35, // 118: substrate.ateapi.v1.ListWorkerActorAssignmentsRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 94, // 119: substrate.ateapi.v1.ListWorkerActorAssignmentsRequest.options:type_name -> substrate.ateapi.v1.ListOptions - 120, // 120: substrate.ateapi.v1.ListWorkerActorAssignmentsResponse.actor_assignments:type_name -> substrate.ateapi.v1.ActorAssignment - 94, // 121: substrate.ateapi.v1.ListWorkersRequest.options:type_name -> substrate.ateapi.v1.ListOptions - 111, // 122: substrate.ateapi.v1.ListWorkersResponse.workers:type_name -> substrate.ateapi.v1.Worker - 35, // 123: substrate.ateapi.v1.GetWorkerRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 111, // 124: substrate.ateapi.v1.CreateWorkerRequest.worker:type_name -> substrate.ateapi.v1.Worker - 111, // 125: substrate.ateapi.v1.UpdateWorkerRequest.worker:type_name -> substrate.ateapi.v1.Worker - 35, // 126: substrate.ateapi.v1.DeleteWorkerRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 93, // 127: substrate.ateapi.v1.DeleteWorkerRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions - 35, // 128: substrate.ateapi.v1.DrainWorkerRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 111, // 129: substrate.ateapi.v1.DrainWorkerResponse.worker:type_name -> substrate.ateapi.v1.Worker - 35, // 130: substrate.ateapi.v1.MarkWorkerAvailableRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 111, // 131: substrate.ateapi.v1.MarkWorkerAvailableResponse.worker:type_name -> substrate.ateapi.v1.Worker - 35, // 132: substrate.ateapi.v1.MarkWorkerUnavailableRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 111, // 133: substrate.ateapi.v1.MarkWorkerUnavailableResponse.worker:type_name -> substrate.ateapi.v1.Worker - 94, // 134: substrate.ateapi.v1.ListActorsRequest.options:type_name -> substrate.ateapi.v1.ListOptions - 17, // 135: substrate.ateapi.v1.ListActorsResponse.actors:type_name -> substrate.ateapi.v1.Actor - 14, // 136: substrate.ateapi.v1.Worker.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata - 152, // 137: substrate.ateapi.v1.Worker.labels:type_name -> substrate.ateapi.v1.Worker.LabelsEntry - 112, // 138: substrate.ateapi.v1.Worker.status:type_name -> substrate.ateapi.v1.WorkerStatus - 8, // 139: substrate.ateapi.v1.WorkerStatus.state:type_name -> substrate.ateapi.v1.WorkerState - 119, // 140: substrate.ateapi.v1.WorkerStatus.capacity:type_name -> substrate.ateapi.v1.WorkerResources - 119, // 141: substrate.ateapi.v1.WorkerStatus.allocated:type_name -> substrate.ateapi.v1.WorkerResources - 113, // 142: substrate.ateapi.v1.WorkerStatus.sandbox_classes:type_name -> substrate.ateapi.v1.WorkerSandboxClass - 114, // 143: substrate.ateapi.v1.WorkerSandboxClass.default_runtime:type_name -> substrate.ateapi.v1.WorkerSandboxRuntime - 114, // 144: substrate.ateapi.v1.WorkerSandboxClass.restorable_runtimes:type_name -> substrate.ateapi.v1.WorkerSandboxRuntime - 117, // 145: substrate.ateapi.v1.WorkerSandboxRuntime.version:type_name -> substrate.ateapi.v1.VersionedSandboxCompat - 115, // 146: substrate.ateapi.v1.WorkerSandboxRuntime.actor_overhead:type_name -> substrate.ateapi.v1.RuntimeOverhead - 117, // 147: substrate.ateapi.v1.ActorSandboxRuntime.version:type_name -> substrate.ateapi.v1.VersionedSandboxCompat - 118, // 148: substrate.ateapi.v1.VersionedSandboxCompat.attributes:type_name -> substrate.ateapi.v1.AttributeEntry - 14, // 149: substrate.ateapi.v1.ActorAssignment.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata - 35, // 150: substrate.ateapi.v1.ActorAssignment.actor:type_name -> substrate.ateapi.v1.ObjectRef - 38, // 151: substrate.ateapi.v1.ActorAssignment.resources:type_name -> substrate.ateapi.v1.Resources - 35, // 152: substrate.ateapi.v1.AcquireWorkerEpochRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 35, // 153: substrate.ateapi.v1.RegisterWorkerRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 119, // 154: substrate.ateapi.v1.RegisterWorkerRequest.capacity:type_name -> substrate.ateapi.v1.WorkerResources - 111, // 155: substrate.ateapi.v1.RegisterWorkerResponse.worker:type_name -> substrate.ateapi.v1.Worker - 35, // 156: substrate.ateapi.v1.SetWorkerSandboxRuntimesRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 113, // 157: substrate.ateapi.v1.SetWorkerSandboxRuntimesRequest.sandbox_classes:type_name -> substrate.ateapi.v1.WorkerSandboxClass - 111, // 158: substrate.ateapi.v1.SetWorkerSandboxRuntimesResponse.worker:type_name -> substrate.ateapi.v1.Worker - 35, // 159: substrate.ateapi.v1.MintWorkerActorCertificateRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 35, // 160: substrate.ateapi.v1.MintWorkerActorCertificateRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 35, // 161: substrate.ateapi.v1.MintWorkerActorJwtRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 153, // 162: substrate.ateapi.v1.MintWorkerActorJwtResponse.expire_time:type_name -> google.protobuf.Timestamp - 35, // 163: substrate.ateapi.v1.RequestActorSuspendRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 35, // 164: substrate.ateapi.v1.RequestActorSuspendRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 17, // 165: substrate.ateapi.v1.RequestActorSuspendResponse.actor:type_name -> substrate.ateapi.v1.Actor - 35, // 166: substrate.ateapi.v1.ReportActorCrashedRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef - 35, // 167: substrate.ateapi.v1.ReportActorCrashedRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 17, // 168: substrate.ateapi.v1.ReportActorCrashedResponse.actor:type_name -> substrate.ateapi.v1.Actor - 35, // 169: substrate.ateapi.v1.ReportActorSnapshotStateRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef - 137, // 170: substrate.ateapi.v1.ReportActorSnapshotStateRequest.state:type_name -> substrate.ateapi.v1.ActorSnapshotState - 138, // 171: substrate.ateapi.v1.ActorSnapshotState.latest_local:type_name -> substrate.ateapi.v1.SnapshotReport - 138, // 172: substrate.ateapi.v1.ActorSnapshotState.uploading:type_name -> substrate.ateapi.v1.SnapshotReport - 138, // 173: substrate.ateapi.v1.ActorSnapshotState.latest_durable:type_name -> substrate.ateapi.v1.SnapshotReport - 153, // 174: substrate.ateapi.v1.ActorSnapshotState.upload_due_time:type_name -> google.protobuf.Timestamp - 2, // 175: substrate.ateapi.v1.SnapshotReport.fidelity:type_name -> substrate.ateapi.v1.SnapshotFidelity - 10, // 176: substrate.ateapi.v1.SnapshotReport.object:type_name -> substrate.ateapi.v1.ObjectSnapshot - 153, // 177: substrate.ateapi.v1.SnapshotReport.local_commit_time:type_name -> google.protobuf.Timestamp - 153, // 178: substrate.ateapi.v1.SnapshotReport.durable_complete_time:type_name -> google.protobuf.Timestamp - 14, // 179: substrate.ateapi.v1.AccessPolicy.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata - 140, // 180: substrate.ateapi.v1.AccessPolicy.bindings:type_name -> substrate.ateapi.v1.Binding - 139, // 181: substrate.ateapi.v1.CreateGlobalAccessPolicyRequest.access_policy:type_name -> substrate.ateapi.v1.AccessPolicy - 139, // 182: substrate.ateapi.v1.UpdateGlobalAccessPolicyRequest.access_policy:type_name -> substrate.ateapi.v1.AccessPolicy - 35, // 183: substrate.ateapi.v1.GetAtespaceAccessPolicyRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef - 35, // 184: substrate.ateapi.v1.CreateAtespaceAccessPolicyRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef - 139, // 185: substrate.ateapi.v1.CreateAtespaceAccessPolicyRequest.access_policy:type_name -> substrate.ateapi.v1.AccessPolicy - 35, // 186: substrate.ateapi.v1.UpdateAtespaceAccessPolicyRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef - 139, // 187: substrate.ateapi.v1.UpdateAtespaceAccessPolicyRequest.access_policy:type_name -> substrate.ateapi.v1.AccessPolicy - 35, // 188: substrate.ateapi.v1.DeleteAtespaceAccessPolicyRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef - 93, // 189: substrate.ateapi.v1.DeleteAtespaceAccessPolicyRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions - 9, // 190: substrate.ateapi.v1.ResourceAnnotation.scope:type_name -> substrate.ateapi.v1.Scope - 154, // 191: substrate.ateapi.v1.resource:extendee -> google.protobuf.MessageOptions - 155, // 192: substrate.ateapi.v1.method:extendee -> google.protobuf.MethodOptions - 148, // 193: substrate.ateapi.v1.resource:type_name -> substrate.ateapi.v1.ResourceAnnotation - 149, // 194: substrate.ateapi.v1.method:type_name -> substrate.ateapi.v1.MethodAnnotation - 70, // 195: substrate.ateapi.v1.Control.GetActor:input_type -> substrate.ateapi.v1.GetActorRequest - 71, // 196: substrate.ateapi.v1.Control.CreateActor:input_type -> substrate.ateapi.v1.CreateActorRequest - 72, // 197: substrate.ateapi.v1.Control.UpdateActor:input_type -> substrate.ateapi.v1.UpdateActorRequest - 73, // 198: substrate.ateapi.v1.Control.SuspendActor:input_type -> substrate.ateapi.v1.SuspendActorRequest - 76, // 199: substrate.ateapi.v1.Control.ResumeActor:input_type -> substrate.ateapi.v1.ResumeActorRequest - 78, // 200: substrate.ateapi.v1.Control.RevertActor:input_type -> substrate.ateapi.v1.RevertActorRequest - 80, // 201: substrate.ateapi.v1.Control.DeleteActor:input_type -> substrate.ateapi.v1.DeleteActorRequest - 81, // 202: substrate.ateapi.v1.Control.GetActorEgressPolicy:input_type -> substrate.ateapi.v1.GetActorEgressPolicyRequest - 82, // 203: substrate.ateapi.v1.Control.CreateActorEgressPolicy:input_type -> substrate.ateapi.v1.CreateActorEgressPolicyRequest - 83, // 204: substrate.ateapi.v1.Control.UpdateActorEgressPolicy:input_type -> substrate.ateapi.v1.UpdateActorEgressPolicyRequest - 84, // 205: substrate.ateapi.v1.Control.DeleteActorEgressPolicy:input_type -> substrate.ateapi.v1.DeleteActorEgressPolicyRequest - 86, // 206: substrate.ateapi.v1.Control.MintActorJwt:input_type -> substrate.ateapi.v1.MintActorJwtRequest - 90, // 207: substrate.ateapi.v1.Control.CreateTag:input_type -> substrate.ateapi.v1.CreateTagRequest - 85, // 208: substrate.ateapi.v1.Control.GetTag:input_type -> substrate.ateapi.v1.GetTagRequest - 88, // 209: substrate.ateapi.v1.Control.ListTags:input_type -> substrate.ateapi.v1.ListTagsRequest - 91, // 210: substrate.ateapi.v1.Control.UpdateTag:input_type -> substrate.ateapi.v1.UpdateTagRequest - 92, // 211: substrate.ateapi.v1.Control.DeleteTag:input_type -> substrate.ateapi.v1.DeleteTagRequest - 97, // 212: substrate.ateapi.v1.Control.ListWorkers:input_type -> substrate.ateapi.v1.ListWorkersRequest - 99, // 213: substrate.ateapi.v1.Control.GetWorker:input_type -> substrate.ateapi.v1.GetWorkerRequest - 100, // 214: substrate.ateapi.v1.Control.CreateWorker:input_type -> substrate.ateapi.v1.CreateWorkerRequest - 101, // 215: substrate.ateapi.v1.Control.UpdateWorker:input_type -> substrate.ateapi.v1.UpdateWorkerRequest - 102, // 216: substrate.ateapi.v1.Control.DeleteWorker:input_type -> substrate.ateapi.v1.DeleteWorkerRequest - 103, // 217: substrate.ateapi.v1.Control.DrainWorker:input_type -> substrate.ateapi.v1.DrainWorkerRequest - 105, // 218: substrate.ateapi.v1.Control.MarkWorkerAvailable:input_type -> substrate.ateapi.v1.MarkWorkerAvailableRequest - 107, // 219: substrate.ateapi.v1.Control.MarkWorkerUnavailable:input_type -> substrate.ateapi.v1.MarkWorkerUnavailableRequest - 95, // 220: substrate.ateapi.v1.Control.ListWorkerActorAssignments:input_type -> substrate.ateapi.v1.ListWorkerActorAssignmentsRequest - 109, // 221: substrate.ateapi.v1.Control.ListActors:input_type -> substrate.ateapi.v1.ListActorsRequest - 60, // 222: substrate.ateapi.v1.Control.CreateAtespace:input_type -> substrate.ateapi.v1.CreateAtespaceRequest - 61, // 223: substrate.ateapi.v1.Control.GetAtespace:input_type -> substrate.ateapi.v1.GetAtespaceRequest - 62, // 224: substrate.ateapi.v1.Control.ListAtespaces:input_type -> substrate.ateapi.v1.ListAtespacesRequest - 64, // 225: substrate.ateapi.v1.Control.DeleteAtespace:input_type -> substrate.ateapi.v1.DeleteAtespaceRequest - 65, // 226: substrate.ateapi.v1.Control.CreateActorTemplate:input_type -> substrate.ateapi.v1.CreateActorTemplateRequest - 66, // 227: substrate.ateapi.v1.Control.GetActorTemplate:input_type -> substrate.ateapi.v1.GetActorTemplateRequest - 67, // 228: substrate.ateapi.v1.Control.ListActorTemplates:input_type -> substrate.ateapi.v1.ListActorTemplatesRequest - 69, // 229: substrate.ateapi.v1.Control.DeleteActorTemplate:input_type -> substrate.ateapi.v1.DeleteActorTemplateRequest - 141, // 230: substrate.ateapi.v1.Control.GetGlobalAccessPolicy:input_type -> substrate.ateapi.v1.GetGlobalAccessPolicyRequest - 142, // 231: substrate.ateapi.v1.Control.CreateGlobalAccessPolicy:input_type -> substrate.ateapi.v1.CreateGlobalAccessPolicyRequest - 143, // 232: substrate.ateapi.v1.Control.UpdateGlobalAccessPolicy:input_type -> substrate.ateapi.v1.UpdateGlobalAccessPolicyRequest - 144, // 233: substrate.ateapi.v1.Control.GetAtespaceAccessPolicy:input_type -> substrate.ateapi.v1.GetAtespaceAccessPolicyRequest - 145, // 234: substrate.ateapi.v1.Control.CreateAtespaceAccessPolicy:input_type -> substrate.ateapi.v1.CreateAtespaceAccessPolicyRequest - 146, // 235: substrate.ateapi.v1.Control.UpdateAtespaceAccessPolicy:input_type -> substrate.ateapi.v1.UpdateAtespaceAccessPolicyRequest - 147, // 236: substrate.ateapi.v1.Control.DeleteAtespaceAccessPolicy:input_type -> substrate.ateapi.v1.DeleteAtespaceAccessPolicyRequest - 121, // 237: substrate.ateapi.v1.WorkerService.AcquireWorkerEpoch:input_type -> substrate.ateapi.v1.AcquireWorkerEpochRequest - 123, // 238: substrate.ateapi.v1.WorkerService.RegisterWorker:input_type -> substrate.ateapi.v1.RegisterWorkerRequest - 125, // 239: substrate.ateapi.v1.WorkerService.SetWorkerSandboxRuntimes:input_type -> substrate.ateapi.v1.SetWorkerSandboxRuntimesRequest - 127, // 240: substrate.ateapi.v1.WorkerService.MintWorkerActorCertificate:input_type -> substrate.ateapi.v1.MintWorkerActorCertificateRequest - 129, // 241: substrate.ateapi.v1.WorkerService.MintWorkerActorJwt:input_type -> substrate.ateapi.v1.MintWorkerActorJwtRequest - 131, // 242: substrate.ateapi.v1.WorkerService.RequestActorSuspend:input_type -> substrate.ateapi.v1.RequestActorSuspendRequest - 135, // 243: substrate.ateapi.v1.WorkerService.ReportActorSnapshotState:input_type -> substrate.ateapi.v1.ReportActorSnapshotStateRequest - 133, // 244: substrate.ateapi.v1.WorkerService.ReportActorCrashed:input_type -> substrate.ateapi.v1.ReportActorCrashedRequest - 17, // 245: substrate.ateapi.v1.Control.GetActor:output_type -> substrate.ateapi.v1.Actor - 17, // 246: substrate.ateapi.v1.Control.CreateActor:output_type -> substrate.ateapi.v1.Actor - 17, // 247: substrate.ateapi.v1.Control.UpdateActor:output_type -> substrate.ateapi.v1.Actor - 74, // 248: substrate.ateapi.v1.Control.SuspendActor:output_type -> substrate.ateapi.v1.SuspendActorResponse - 77, // 249: substrate.ateapi.v1.Control.ResumeActor:output_type -> substrate.ateapi.v1.ResumeActorResponse - 79, // 250: substrate.ateapi.v1.Control.RevertActor:output_type -> substrate.ateapi.v1.RevertActorResponse - 17, // 251: substrate.ateapi.v1.Control.DeleteActor:output_type -> substrate.ateapi.v1.Actor - 18, // 252: substrate.ateapi.v1.Control.GetActorEgressPolicy:output_type -> substrate.ateapi.v1.EgressPolicy - 18, // 253: substrate.ateapi.v1.Control.CreateActorEgressPolicy:output_type -> substrate.ateapi.v1.EgressPolicy - 18, // 254: substrate.ateapi.v1.Control.UpdateActorEgressPolicy:output_type -> substrate.ateapi.v1.EgressPolicy - 18, // 255: substrate.ateapi.v1.Control.DeleteActorEgressPolicy:output_type -> substrate.ateapi.v1.EgressPolicy - 87, // 256: substrate.ateapi.v1.Control.MintActorJwt:output_type -> substrate.ateapi.v1.MintActorJwtResponse - 33, // 257: substrate.ateapi.v1.Control.CreateTag:output_type -> substrate.ateapi.v1.Tag - 33, // 258: substrate.ateapi.v1.Control.GetTag:output_type -> substrate.ateapi.v1.Tag - 89, // 259: substrate.ateapi.v1.Control.ListTags:output_type -> substrate.ateapi.v1.ListTagsResponse - 33, // 260: substrate.ateapi.v1.Control.UpdateTag:output_type -> substrate.ateapi.v1.Tag - 33, // 261: substrate.ateapi.v1.Control.DeleteTag:output_type -> substrate.ateapi.v1.Tag - 98, // 262: substrate.ateapi.v1.Control.ListWorkers:output_type -> substrate.ateapi.v1.ListWorkersResponse - 111, // 263: substrate.ateapi.v1.Control.GetWorker:output_type -> substrate.ateapi.v1.Worker - 111, // 264: substrate.ateapi.v1.Control.CreateWorker:output_type -> substrate.ateapi.v1.Worker - 111, // 265: substrate.ateapi.v1.Control.UpdateWorker:output_type -> substrate.ateapi.v1.Worker - 111, // 266: substrate.ateapi.v1.Control.DeleteWorker:output_type -> substrate.ateapi.v1.Worker - 104, // 267: substrate.ateapi.v1.Control.DrainWorker:output_type -> substrate.ateapi.v1.DrainWorkerResponse - 106, // 268: substrate.ateapi.v1.Control.MarkWorkerAvailable:output_type -> substrate.ateapi.v1.MarkWorkerAvailableResponse - 108, // 269: substrate.ateapi.v1.Control.MarkWorkerUnavailable:output_type -> substrate.ateapi.v1.MarkWorkerUnavailableResponse - 96, // 270: substrate.ateapi.v1.Control.ListWorkerActorAssignments:output_type -> substrate.ateapi.v1.ListWorkerActorAssignmentsResponse - 110, // 271: substrate.ateapi.v1.Control.ListActors:output_type -> substrate.ateapi.v1.ListActorsResponse - 34, // 272: substrate.ateapi.v1.Control.CreateAtespace:output_type -> substrate.ateapi.v1.Atespace - 34, // 273: substrate.ateapi.v1.Control.GetAtespace:output_type -> substrate.ateapi.v1.Atespace - 63, // 274: substrate.ateapi.v1.Control.ListAtespaces:output_type -> substrate.ateapi.v1.ListAtespacesResponse - 34, // 275: substrate.ateapi.v1.Control.DeleteAtespace:output_type -> substrate.ateapi.v1.Atespace - 36, // 276: substrate.ateapi.v1.Control.CreateActorTemplate:output_type -> substrate.ateapi.v1.ActorTemplate - 36, // 277: substrate.ateapi.v1.Control.GetActorTemplate:output_type -> substrate.ateapi.v1.ActorTemplate - 68, // 278: substrate.ateapi.v1.Control.ListActorTemplates:output_type -> substrate.ateapi.v1.ListActorTemplatesResponse - 36, // 279: substrate.ateapi.v1.Control.DeleteActorTemplate:output_type -> substrate.ateapi.v1.ActorTemplate - 139, // 280: substrate.ateapi.v1.Control.GetGlobalAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy - 139, // 281: substrate.ateapi.v1.Control.CreateGlobalAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy - 139, // 282: substrate.ateapi.v1.Control.UpdateGlobalAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy - 139, // 283: substrate.ateapi.v1.Control.GetAtespaceAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy - 139, // 284: substrate.ateapi.v1.Control.CreateAtespaceAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy - 139, // 285: substrate.ateapi.v1.Control.UpdateAtespaceAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy - 139, // 286: substrate.ateapi.v1.Control.DeleteAtespaceAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy - 122, // 287: substrate.ateapi.v1.WorkerService.AcquireWorkerEpoch:output_type -> substrate.ateapi.v1.AcquireWorkerEpochResponse - 124, // 288: substrate.ateapi.v1.WorkerService.RegisterWorker:output_type -> substrate.ateapi.v1.RegisterWorkerResponse - 126, // 289: substrate.ateapi.v1.WorkerService.SetWorkerSandboxRuntimes:output_type -> substrate.ateapi.v1.SetWorkerSandboxRuntimesResponse - 128, // 290: substrate.ateapi.v1.WorkerService.MintWorkerActorCertificate:output_type -> substrate.ateapi.v1.MintWorkerActorCertificateResponse - 130, // 291: substrate.ateapi.v1.WorkerService.MintWorkerActorJwt:output_type -> substrate.ateapi.v1.MintWorkerActorJwtResponse - 132, // 292: substrate.ateapi.v1.WorkerService.RequestActorSuspend:output_type -> substrate.ateapi.v1.RequestActorSuspendResponse - 136, // 293: substrate.ateapi.v1.WorkerService.ReportActorSnapshotState:output_type -> substrate.ateapi.v1.ReportActorSnapshotStateResponse - 134, // 294: substrate.ateapi.v1.WorkerService.ReportActorCrashed:output_type -> substrate.ateapi.v1.ReportActorCrashedResponse - 245, // [245:295] is the sub-list for method output_type - 195, // [195:245] is the sub-list for method input_type - 193, // [193:195] is the sub-list for extension type_name - 191, // [191:193] is the sub-list for extension extendee - 0, // [0:191] is the sub-list for field type_name + 30, // 30: substrate.ateapi.v1.CredentialHeader.actor_jwt:type_name -> substrate.ateapi.v1.ActorJwtSource + 28, // 31: substrate.ateapi.v1.CredentialHeader.token_exchange:type_name -> substrate.ateapi.v1.TokenExchangeSource + 30, // 32: substrate.ateapi.v1.TokenExchangeSource.subject_actor_jwt:type_name -> substrate.ateapi.v1.ActorJwtSource + 29, // 33: substrate.ateapi.v1.TokenExchangeSource.additional_parameters:type_name -> substrate.ateapi.v1.FormEntry + 4, // 34: substrate.ateapi.v1.ActorStatus.state:type_name -> substrate.ateapi.v1.ActorState + 33, // 35: substrate.ateapi.v1.ActorStatus.worker_assignment:type_name -> substrate.ateapi.v1.WorkerAssignment + 15, // 36: substrate.ateapi.v1.ActorStatus.external_volumes:type_name -> substrate.ateapi.v1.ExternalVolumes + 32, // 37: substrate.ateapi.v1.ActorStatus.crash:type_name -> substrate.ateapi.v1.ActorCrash + 12, // 38: substrate.ateapi.v1.ActorStatus.snapshots:type_name -> substrate.ateapi.v1.Snapshot + 176, // 39: substrate.ateapi.v1.ActorCrash.crash_time:type_name -> google.protobuf.Timestamp + 40, // 40: substrate.ateapi.v1.WorkerAssignment.worker:type_name -> substrate.ateapi.v1.ObjectRef + 133, // 41: substrate.ateapi.v1.WorkerAssignment.sandbox_runtime:type_name -> substrate.ateapi.v1.ActorSandboxRuntime + 12, // 42: substrate.ateapi.v1.TagStatus.snapshot:type_name -> substrate.ateapi.v1.Snapshot + 14, // 43: substrate.ateapi.v1.Tag.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata + 34, // 44: substrate.ateapi.v1.Tag.status:type_name -> substrate.ateapi.v1.TagStatus + 3, // 45: substrate.ateapi.v1.Tag.scope:type_name -> substrate.ateapi.v1.TagScope + 40, // 46: substrate.ateapi.v1.Tag.source_actor:type_name -> substrate.ateapi.v1.ObjectRef + 14, // 47: substrate.ateapi.v1.ExternalVolume.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata + 37, // 48: substrate.ateapi.v1.ExternalVolume.status:type_name -> substrate.ateapi.v1.ExternalVolumeStatus + 38, // 49: substrate.ateapi.v1.ExternalVolumeStatus.csi:type_name -> substrate.ateapi.v1.CsiVolumeStatus + 172, // 50: substrate.ateapi.v1.CsiVolumeStatus.volume_context:type_name -> substrate.ateapi.v1.CsiVolumeStatus.VolumeContextEntry + 14, // 51: substrate.ateapi.v1.Atespace.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata + 14, // 52: substrate.ateapi.v1.ActorTemplate.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata + 13, // 53: substrate.ateapi.v1.ActorTemplate.worker_selector:type_name -> substrate.ateapi.v1.Selector + 48, // 54: substrate.ateapi.v1.ActorTemplate.containers:type_name -> substrate.ateapi.v1.Container + 54, // 55: substrate.ateapi.v1.ActorTemplate.volumes:type_name -> substrate.ateapi.v1.Volume + 46, // 56: substrate.ateapi.v1.ActorTemplate.snapshot_config:type_name -> substrate.ateapi.v1.SnapshotConfig + 42, // 57: substrate.ateapi.v1.ActorTemplate.resources:type_name -> substrate.ateapi.v1.ResourceRequirements + 19, // 58: substrate.ateapi.v1.ActorTemplate.golden_egress_policy:type_name -> substrate.ateapi.v1.EgressPolicyTemplate + 45, // 59: substrate.ateapi.v1.ActorTemplate.status:type_name -> substrate.ateapi.v1.ActorTemplateStatus + 43, // 60: substrate.ateapi.v1.ResourceRequirements.limits:type_name -> substrate.ateapi.v1.Resources + 40, // 61: substrate.ateapi.v1.GoldenSnapshotStatus.golden_tag:type_name -> substrate.ateapi.v1.ObjectRef + 176, // 62: substrate.ateapi.v1.GoldenSnapshotStatus.snapshot_time:type_name -> google.protobuf.Timestamp + 44, // 63: substrate.ateapi.v1.ActorTemplateStatus.golden_snapshot_status:type_name -> substrate.ateapi.v1.GoldenSnapshotStatus + 2, // 64: substrate.ateapi.v1.SnapshotConfig.preferred_fidelity:type_name -> substrate.ateapi.v1.SnapshotFidelity + 47, // 65: substrate.ateapi.v1.SnapshotConfig.golden_snapshot_config:type_name -> substrate.ateapi.v1.GoldenSnapshotConfig + 5, // 66: substrate.ateapi.v1.GoldenSnapshotConfig.mode:type_name -> substrate.ateapi.v1.GoldenSnapshotMode + 51, // 67: substrate.ateapi.v1.Container.env:type_name -> substrate.ateapi.v1.EnvVar + 52, // 68: substrate.ateapi.v1.Container.wakeup_probe:type_name -> substrate.ateapi.v1.WakeupProbe + 67, // 69: substrate.ateapi.v1.Container.volume_mounts:type_name -> substrate.ateapi.v1.VolumeMount + 49, // 70: substrate.ateapi.v1.Container.security_context:type_name -> substrate.ateapi.v1.SecurityContext + 42, // 71: substrate.ateapi.v1.Container.resources:type_name -> substrate.ateapi.v1.ResourceRequirements + 50, // 72: substrate.ateapi.v1.SecurityContext.capabilities:type_name -> substrate.ateapi.v1.Capabilities + 53, // 73: substrate.ateapi.v1.WakeupProbe.http_get:type_name -> substrate.ateapi.v1.HttpGetAction + 57, // 74: substrate.ateapi.v1.Volume.durable_dir:type_name -> substrate.ateapi.v1.DurableDirVolumeSource + 55, // 75: substrate.ateapi.v1.Volume.external:type_name -> substrate.ateapi.v1.ExternalVolumeSource + 62, // 76: substrate.ateapi.v1.Volume.system_info:type_name -> substrate.ateapi.v1.SystemInfoVolumeSource + 56, // 77: substrate.ateapi.v1.Volume.image:type_name -> substrate.ateapi.v1.ImageVolumeSource + 58, // 78: substrate.ateapi.v1.ExternalVolumeSource.template:type_name -> substrate.ateapi.v1.ExternalVolumeTemplate + 14, // 79: substrate.ateapi.v1.CsiDriver.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata + 60, // 80: substrate.ateapi.v1.CsiDriver.controller_endpoint:type_name -> substrate.ateapi.v1.CsiDriverEndpoint + 61, // 81: substrate.ateapi.v1.CsiDriver.tls:type_name -> substrate.ateapi.v1.CsiDriverTlsConfig + 63, // 82: substrate.ateapi.v1.SystemInfoVolumeSource.data_sources:type_name -> substrate.ateapi.v1.SystemInfoDataSource + 64, // 83: substrate.ateapi.v1.SystemInfoDataSource.actor_metadata:type_name -> substrate.ateapi.v1.ActorMetadataDataSource + 66, // 84: substrate.ateapi.v1.SystemInfoDataSource.trust_bundle:type_name -> substrate.ateapi.v1.TrustBundleDataSource + 65, // 85: substrate.ateapi.v1.ActorMetadataDataSource.items:type_name -> substrate.ateapi.v1.ActorMetadataItem + 6, // 86: substrate.ateapi.v1.ActorMetadataItem.field:type_name -> substrate.ateapi.v1.ActorMetadataField + 39, // 87: substrate.ateapi.v1.CreateAtespaceRequest.atespace:type_name -> substrate.ateapi.v1.Atespace + 40, // 88: substrate.ateapi.v1.GetAtespaceRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef + 111, // 89: substrate.ateapi.v1.ListAtespacesRequest.options:type_name -> substrate.ateapi.v1.ListOptions + 39, // 90: substrate.ateapi.v1.ListAtespacesResponse.atespaces:type_name -> substrate.ateapi.v1.Atespace + 40, // 91: substrate.ateapi.v1.DeleteAtespaceRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef + 110, // 92: substrate.ateapi.v1.DeleteAtespaceRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions + 59, // 93: substrate.ateapi.v1.CreateCsiDriverRequest.csi_driver:type_name -> substrate.ateapi.v1.CsiDriver + 40, // 94: substrate.ateapi.v1.GetCsiDriverRequest.csi_driver:type_name -> substrate.ateapi.v1.ObjectRef + 111, // 95: substrate.ateapi.v1.ListCsiDriversRequest.options:type_name -> substrate.ateapi.v1.ListOptions + 59, // 96: substrate.ateapi.v1.ListCsiDriversResponse.csi_drivers:type_name -> substrate.ateapi.v1.CsiDriver + 59, // 97: substrate.ateapi.v1.UpdateCsiDriverRequest.csi_driver:type_name -> substrate.ateapi.v1.CsiDriver + 40, // 98: substrate.ateapi.v1.DeleteCsiDriverRequest.csi_driver:type_name -> substrate.ateapi.v1.ObjectRef + 110, // 99: substrate.ateapi.v1.DeleteCsiDriverRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions + 41, // 100: substrate.ateapi.v1.CreateActorTemplateRequest.actor_template:type_name -> substrate.ateapi.v1.ActorTemplate + 40, // 101: substrate.ateapi.v1.GetActorTemplateRequest.actor_template:type_name -> substrate.ateapi.v1.ObjectRef + 111, // 102: substrate.ateapi.v1.ListActorTemplatesRequest.options:type_name -> substrate.ateapi.v1.ListOptions + 41, // 103: substrate.ateapi.v1.ListActorTemplatesResponse.actor_templates:type_name -> substrate.ateapi.v1.ActorTemplate + 40, // 104: substrate.ateapi.v1.DeleteActorTemplateRequest.actor_template:type_name -> substrate.ateapi.v1.ObjectRef + 110, // 105: substrate.ateapi.v1.DeleteActorTemplateRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions + 40, // 106: substrate.ateapi.v1.GetActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 17, // 107: substrate.ateapi.v1.CreateActorRequest.actor:type_name -> substrate.ateapi.v1.Actor + 17, // 108: substrate.ateapi.v1.UpdateActorRequest.actor:type_name -> substrate.ateapi.v1.Actor + 40, // 109: substrate.ateapi.v1.SuspendActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 89, // 110: substrate.ateapi.v1.SuspendActorRequest.options:type_name -> substrate.ateapi.v1.SuspendOptions + 17, // 111: substrate.ateapi.v1.SuspendActorResponse.actor:type_name -> substrate.ateapi.v1.Actor + 7, // 112: substrate.ateapi.v1.SuspendOptions.mode:type_name -> substrate.ateapi.v1.DurabilityMode + 40, // 113: substrate.ateapi.v1.ResumeActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 173, // 114: substrate.ateapi.v1.ResumeActorRequest.options:type_name -> substrate.ateapi.v1.ResumeActorRequest.Options + 17, // 115: substrate.ateapi.v1.ResumeActorResponse.actor:type_name -> substrate.ateapi.v1.Actor + 40, // 116: substrate.ateapi.v1.RevertActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 174, // 117: substrate.ateapi.v1.RevertActorRequest.options:type_name -> substrate.ateapi.v1.RevertActorRequest.Options + 17, // 118: substrate.ateapi.v1.RevertActorResponse.actor:type_name -> substrate.ateapi.v1.Actor + 40, // 119: substrate.ateapi.v1.DeleteActorRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 110, // 120: substrate.ateapi.v1.DeleteActorRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions + 40, // 121: substrate.ateapi.v1.GetActorEgressPolicyRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 122: substrate.ateapi.v1.CreateActorEgressPolicyRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 18, // 123: substrate.ateapi.v1.CreateActorEgressPolicyRequest.egress_policy:type_name -> substrate.ateapi.v1.EgressPolicy + 40, // 124: substrate.ateapi.v1.UpdateActorEgressPolicyRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 18, // 125: substrate.ateapi.v1.UpdateActorEgressPolicyRequest.egress_policy:type_name -> substrate.ateapi.v1.EgressPolicy + 40, // 126: substrate.ateapi.v1.DeleteActorEgressPolicyRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 110, // 127: substrate.ateapi.v1.DeleteActorEgressPolicyRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions + 40, // 128: substrate.ateapi.v1.GetTagRequest.tag:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 129: substrate.ateapi.v1.MintActorJwtRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 176, // 130: substrate.ateapi.v1.MintActorJwtResponse.expire_time:type_name -> google.protobuf.Timestamp + 111, // 131: substrate.ateapi.v1.ListTagsRequest.options:type_name -> substrate.ateapi.v1.ListOptions + 35, // 132: substrate.ateapi.v1.ListTagsResponse.tags:type_name -> substrate.ateapi.v1.Tag + 35, // 133: substrate.ateapi.v1.CreateTagRequest.tag:type_name -> substrate.ateapi.v1.Tag + 35, // 134: substrate.ateapi.v1.UpdateTagRequest.tag:type_name -> substrate.ateapi.v1.Tag + 40, // 135: substrate.ateapi.v1.DeleteTagRequest.tag:type_name -> substrate.ateapi.v1.ObjectRef + 110, // 136: substrate.ateapi.v1.DeleteTagRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions + 40, // 137: substrate.ateapi.v1.GetExternalVolumeRequest.external_volume:type_name -> substrate.ateapi.v1.ObjectRef + 111, // 138: substrate.ateapi.v1.ListExternalVolumesRequest.options:type_name -> substrate.ateapi.v1.ListOptions + 36, // 139: substrate.ateapi.v1.ListExternalVolumesResponse.external_volumes:type_name -> substrate.ateapi.v1.ExternalVolume + 40, // 140: substrate.ateapi.v1.ListWorkerActorAssignmentsRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 111, // 141: substrate.ateapi.v1.ListWorkerActorAssignmentsRequest.options:type_name -> substrate.ateapi.v1.ListOptions + 137, // 142: substrate.ateapi.v1.ListWorkerActorAssignmentsResponse.actor_assignments:type_name -> substrate.ateapi.v1.ActorAssignment + 111, // 143: substrate.ateapi.v1.ListWorkersRequest.options:type_name -> substrate.ateapi.v1.ListOptions + 128, // 144: substrate.ateapi.v1.ListWorkersResponse.workers:type_name -> substrate.ateapi.v1.Worker + 40, // 145: substrate.ateapi.v1.GetWorkerRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 128, // 146: substrate.ateapi.v1.CreateWorkerRequest.worker:type_name -> substrate.ateapi.v1.Worker + 128, // 147: substrate.ateapi.v1.UpdateWorkerRequest.worker:type_name -> substrate.ateapi.v1.Worker + 40, // 148: substrate.ateapi.v1.DeleteWorkerRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 110, // 149: substrate.ateapi.v1.DeleteWorkerRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions + 40, // 150: substrate.ateapi.v1.DrainWorkerRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 128, // 151: substrate.ateapi.v1.DrainWorkerResponse.worker:type_name -> substrate.ateapi.v1.Worker + 40, // 152: substrate.ateapi.v1.MarkWorkerAvailableRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 128, // 153: substrate.ateapi.v1.MarkWorkerAvailableResponse.worker:type_name -> substrate.ateapi.v1.Worker + 40, // 154: substrate.ateapi.v1.MarkWorkerUnavailableRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 128, // 155: substrate.ateapi.v1.MarkWorkerUnavailableResponse.worker:type_name -> substrate.ateapi.v1.Worker + 111, // 156: substrate.ateapi.v1.ListActorsRequest.options:type_name -> substrate.ateapi.v1.ListOptions + 17, // 157: substrate.ateapi.v1.ListActorsResponse.actors:type_name -> substrate.ateapi.v1.Actor + 14, // 158: substrate.ateapi.v1.Worker.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata + 175, // 159: substrate.ateapi.v1.Worker.labels:type_name -> substrate.ateapi.v1.Worker.LabelsEntry + 129, // 160: substrate.ateapi.v1.Worker.status:type_name -> substrate.ateapi.v1.WorkerStatus + 8, // 161: substrate.ateapi.v1.WorkerStatus.state:type_name -> substrate.ateapi.v1.WorkerState + 136, // 162: substrate.ateapi.v1.WorkerStatus.capacity:type_name -> substrate.ateapi.v1.WorkerResources + 136, // 163: substrate.ateapi.v1.WorkerStatus.allocated:type_name -> substrate.ateapi.v1.WorkerResources + 130, // 164: substrate.ateapi.v1.WorkerStatus.sandbox_classes:type_name -> substrate.ateapi.v1.WorkerSandboxClass + 131, // 165: substrate.ateapi.v1.WorkerSandboxClass.default_runtime:type_name -> substrate.ateapi.v1.WorkerSandboxRuntime + 131, // 166: substrate.ateapi.v1.WorkerSandboxClass.restorable_runtimes:type_name -> substrate.ateapi.v1.WorkerSandboxRuntime + 134, // 167: substrate.ateapi.v1.WorkerSandboxRuntime.version:type_name -> substrate.ateapi.v1.VersionedSandboxCompat + 132, // 168: substrate.ateapi.v1.WorkerSandboxRuntime.actor_overhead:type_name -> substrate.ateapi.v1.RuntimeOverhead + 134, // 169: substrate.ateapi.v1.ActorSandboxRuntime.version:type_name -> substrate.ateapi.v1.VersionedSandboxCompat + 135, // 170: substrate.ateapi.v1.VersionedSandboxCompat.attributes:type_name -> substrate.ateapi.v1.AttributeEntry + 14, // 171: substrate.ateapi.v1.ActorAssignment.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata + 40, // 172: substrate.ateapi.v1.ActorAssignment.actor:type_name -> substrate.ateapi.v1.ObjectRef + 43, // 173: substrate.ateapi.v1.ActorAssignment.resources:type_name -> substrate.ateapi.v1.Resources + 40, // 174: substrate.ateapi.v1.AcquireWorkerEpochRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 175: substrate.ateapi.v1.RegisterWorkerRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 136, // 176: substrate.ateapi.v1.RegisterWorkerRequest.capacity:type_name -> substrate.ateapi.v1.WorkerResources + 128, // 177: substrate.ateapi.v1.RegisterWorkerResponse.worker:type_name -> substrate.ateapi.v1.Worker + 40, // 178: substrate.ateapi.v1.SetWorkerSandboxRuntimesRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 130, // 179: substrate.ateapi.v1.SetWorkerSandboxRuntimesRequest.sandbox_classes:type_name -> substrate.ateapi.v1.WorkerSandboxClass + 128, // 180: substrate.ateapi.v1.SetWorkerSandboxRuntimesResponse.worker:type_name -> substrate.ateapi.v1.Worker + 40, // 181: substrate.ateapi.v1.MintWorkerActorCertificateRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 182: substrate.ateapi.v1.MintWorkerActorCertificateRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 183: substrate.ateapi.v1.MintWorkerActorJwtRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 176, // 184: substrate.ateapi.v1.MintWorkerActorJwtResponse.expire_time:type_name -> google.protobuf.Timestamp + 40, // 185: substrate.ateapi.v1.RequestActorSuspendRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 186: substrate.ateapi.v1.RequestActorSuspendRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 17, // 187: substrate.ateapi.v1.RequestActorSuspendResponse.actor:type_name -> substrate.ateapi.v1.Actor + 40, // 188: substrate.ateapi.v1.ReportActorCrashedRequest.worker:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 189: substrate.ateapi.v1.ReportActorCrashedRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 17, // 190: substrate.ateapi.v1.ReportActorCrashedResponse.actor:type_name -> substrate.ateapi.v1.Actor + 40, // 191: substrate.ateapi.v1.ReportActorSnapshotStateRequest.actor:type_name -> substrate.ateapi.v1.ObjectRef + 154, // 192: substrate.ateapi.v1.ReportActorSnapshotStateRequest.state:type_name -> substrate.ateapi.v1.ActorSnapshotState + 155, // 193: substrate.ateapi.v1.ActorSnapshotState.latest_local:type_name -> substrate.ateapi.v1.SnapshotReport + 155, // 194: substrate.ateapi.v1.ActorSnapshotState.uploading:type_name -> substrate.ateapi.v1.SnapshotReport + 155, // 195: substrate.ateapi.v1.ActorSnapshotState.latest_durable:type_name -> substrate.ateapi.v1.SnapshotReport + 176, // 196: substrate.ateapi.v1.ActorSnapshotState.upload_due_time:type_name -> google.protobuf.Timestamp + 2, // 197: substrate.ateapi.v1.SnapshotReport.fidelity:type_name -> substrate.ateapi.v1.SnapshotFidelity + 10, // 198: substrate.ateapi.v1.SnapshotReport.object:type_name -> substrate.ateapi.v1.ObjectSnapshot + 176, // 199: substrate.ateapi.v1.SnapshotReport.local_commit_time:type_name -> google.protobuf.Timestamp + 176, // 200: substrate.ateapi.v1.SnapshotReport.durable_complete_time:type_name -> google.protobuf.Timestamp + 14, // 201: substrate.ateapi.v1.AccessPolicy.metadata:type_name -> substrate.ateapi.v1.ResourceMetadata + 157, // 202: substrate.ateapi.v1.AccessPolicy.bindings:type_name -> substrate.ateapi.v1.Binding + 156, // 203: substrate.ateapi.v1.CreateGlobalAccessPolicyRequest.access_policy:type_name -> substrate.ateapi.v1.AccessPolicy + 156, // 204: substrate.ateapi.v1.UpdateGlobalAccessPolicyRequest.access_policy:type_name -> substrate.ateapi.v1.AccessPolicy + 40, // 205: substrate.ateapi.v1.GetAtespaceAccessPolicyRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef + 40, // 206: substrate.ateapi.v1.CreateAtespaceAccessPolicyRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef + 156, // 207: substrate.ateapi.v1.CreateAtespaceAccessPolicyRequest.access_policy:type_name -> substrate.ateapi.v1.AccessPolicy + 40, // 208: substrate.ateapi.v1.UpdateAtespaceAccessPolicyRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef + 156, // 209: substrate.ateapi.v1.UpdateAtespaceAccessPolicyRequest.access_policy:type_name -> substrate.ateapi.v1.AccessPolicy + 40, // 210: substrate.ateapi.v1.DeleteAtespaceAccessPolicyRequest.atespace:type_name -> substrate.ateapi.v1.ObjectRef + 110, // 211: substrate.ateapi.v1.DeleteAtespaceAccessPolicyRequest.options:type_name -> substrate.ateapi.v1.DeleteOptions + 9, // 212: substrate.ateapi.v1.ResourceAnnotation.scope:type_name -> substrate.ateapi.v1.Scope + 167, // 213: substrate.ateapi.v1.MethodAnnotation.preview_gate:type_name -> substrate.ateapi.v1.MethodPreviewGate + 169, // 214: substrate.ateapi.v1.FieldAnnotation.preview_gate:type_name -> substrate.ateapi.v1.FieldPreviewGate + 177, // 215: substrate.ateapi.v1.resource:extendee -> google.protobuf.MessageOptions + 178, // 216: substrate.ateapi.v1.method:extendee -> google.protobuf.MethodOptions + 179, // 217: substrate.ateapi.v1.field:extendee -> google.protobuf.FieldOptions + 165, // 218: substrate.ateapi.v1.resource:type_name -> substrate.ateapi.v1.ResourceAnnotation + 166, // 219: substrate.ateapi.v1.method:type_name -> substrate.ateapi.v1.MethodAnnotation + 168, // 220: substrate.ateapi.v1.field:type_name -> substrate.ateapi.v1.FieldAnnotation + 84, // 221: substrate.ateapi.v1.Control.GetActor:input_type -> substrate.ateapi.v1.GetActorRequest + 85, // 222: substrate.ateapi.v1.Control.CreateActor:input_type -> substrate.ateapi.v1.CreateActorRequest + 86, // 223: substrate.ateapi.v1.Control.UpdateActor:input_type -> substrate.ateapi.v1.UpdateActorRequest + 87, // 224: substrate.ateapi.v1.Control.SuspendActor:input_type -> substrate.ateapi.v1.SuspendActorRequest + 90, // 225: substrate.ateapi.v1.Control.ResumeActor:input_type -> substrate.ateapi.v1.ResumeActorRequest + 92, // 226: substrate.ateapi.v1.Control.RevertActor:input_type -> substrate.ateapi.v1.RevertActorRequest + 94, // 227: substrate.ateapi.v1.Control.DeleteActor:input_type -> substrate.ateapi.v1.DeleteActorRequest + 95, // 228: substrate.ateapi.v1.Control.GetActorEgressPolicy:input_type -> substrate.ateapi.v1.GetActorEgressPolicyRequest + 96, // 229: substrate.ateapi.v1.Control.CreateActorEgressPolicy:input_type -> substrate.ateapi.v1.CreateActorEgressPolicyRequest + 97, // 230: substrate.ateapi.v1.Control.UpdateActorEgressPolicy:input_type -> substrate.ateapi.v1.UpdateActorEgressPolicyRequest + 98, // 231: substrate.ateapi.v1.Control.DeleteActorEgressPolicy:input_type -> substrate.ateapi.v1.DeleteActorEgressPolicyRequest + 100, // 232: substrate.ateapi.v1.Control.MintActorJwt:input_type -> substrate.ateapi.v1.MintActorJwtRequest + 104, // 233: substrate.ateapi.v1.Control.CreateTag:input_type -> substrate.ateapi.v1.CreateTagRequest + 99, // 234: substrate.ateapi.v1.Control.GetTag:input_type -> substrate.ateapi.v1.GetTagRequest + 102, // 235: substrate.ateapi.v1.Control.ListTags:input_type -> substrate.ateapi.v1.ListTagsRequest + 105, // 236: substrate.ateapi.v1.Control.UpdateTag:input_type -> substrate.ateapi.v1.UpdateTagRequest + 106, // 237: substrate.ateapi.v1.Control.DeleteTag:input_type -> substrate.ateapi.v1.DeleteTagRequest + 107, // 238: substrate.ateapi.v1.Control.GetExternalVolume:input_type -> substrate.ateapi.v1.GetExternalVolumeRequest + 108, // 239: substrate.ateapi.v1.Control.ListExternalVolumes:input_type -> substrate.ateapi.v1.ListExternalVolumesRequest + 114, // 240: substrate.ateapi.v1.Control.ListWorkers:input_type -> substrate.ateapi.v1.ListWorkersRequest + 116, // 241: substrate.ateapi.v1.Control.GetWorker:input_type -> substrate.ateapi.v1.GetWorkerRequest + 117, // 242: substrate.ateapi.v1.Control.CreateWorker:input_type -> substrate.ateapi.v1.CreateWorkerRequest + 118, // 243: substrate.ateapi.v1.Control.UpdateWorker:input_type -> substrate.ateapi.v1.UpdateWorkerRequest + 119, // 244: substrate.ateapi.v1.Control.DeleteWorker:input_type -> substrate.ateapi.v1.DeleteWorkerRequest + 120, // 245: substrate.ateapi.v1.Control.DrainWorker:input_type -> substrate.ateapi.v1.DrainWorkerRequest + 122, // 246: substrate.ateapi.v1.Control.MarkWorkerAvailable:input_type -> substrate.ateapi.v1.MarkWorkerAvailableRequest + 124, // 247: substrate.ateapi.v1.Control.MarkWorkerUnavailable:input_type -> substrate.ateapi.v1.MarkWorkerUnavailableRequest + 112, // 248: substrate.ateapi.v1.Control.ListWorkerActorAssignments:input_type -> substrate.ateapi.v1.ListWorkerActorAssignmentsRequest + 126, // 249: substrate.ateapi.v1.Control.ListActors:input_type -> substrate.ateapi.v1.ListActorsRequest + 68, // 250: substrate.ateapi.v1.Control.CreateAtespace:input_type -> substrate.ateapi.v1.CreateAtespaceRequest + 69, // 251: substrate.ateapi.v1.Control.GetAtespace:input_type -> substrate.ateapi.v1.GetAtespaceRequest + 70, // 252: substrate.ateapi.v1.Control.ListAtespaces:input_type -> substrate.ateapi.v1.ListAtespacesRequest + 72, // 253: substrate.ateapi.v1.Control.DeleteAtespace:input_type -> substrate.ateapi.v1.DeleteAtespaceRequest + 73, // 254: substrate.ateapi.v1.Control.CreateCsiDriver:input_type -> substrate.ateapi.v1.CreateCsiDriverRequest + 74, // 255: substrate.ateapi.v1.Control.GetCsiDriver:input_type -> substrate.ateapi.v1.GetCsiDriverRequest + 75, // 256: substrate.ateapi.v1.Control.ListCsiDrivers:input_type -> substrate.ateapi.v1.ListCsiDriversRequest + 77, // 257: substrate.ateapi.v1.Control.UpdateCsiDriver:input_type -> substrate.ateapi.v1.UpdateCsiDriverRequest + 78, // 258: substrate.ateapi.v1.Control.DeleteCsiDriver:input_type -> substrate.ateapi.v1.DeleteCsiDriverRequest + 79, // 259: substrate.ateapi.v1.Control.CreateActorTemplate:input_type -> substrate.ateapi.v1.CreateActorTemplateRequest + 80, // 260: substrate.ateapi.v1.Control.GetActorTemplate:input_type -> substrate.ateapi.v1.GetActorTemplateRequest + 81, // 261: substrate.ateapi.v1.Control.ListActorTemplates:input_type -> substrate.ateapi.v1.ListActorTemplatesRequest + 83, // 262: substrate.ateapi.v1.Control.DeleteActorTemplate:input_type -> substrate.ateapi.v1.DeleteActorTemplateRequest + 158, // 263: substrate.ateapi.v1.Control.GetGlobalAccessPolicy:input_type -> substrate.ateapi.v1.GetGlobalAccessPolicyRequest + 159, // 264: substrate.ateapi.v1.Control.CreateGlobalAccessPolicy:input_type -> substrate.ateapi.v1.CreateGlobalAccessPolicyRequest + 160, // 265: substrate.ateapi.v1.Control.UpdateGlobalAccessPolicy:input_type -> substrate.ateapi.v1.UpdateGlobalAccessPolicyRequest + 161, // 266: substrate.ateapi.v1.Control.GetAtespaceAccessPolicy:input_type -> substrate.ateapi.v1.GetAtespaceAccessPolicyRequest + 162, // 267: substrate.ateapi.v1.Control.CreateAtespaceAccessPolicy:input_type -> substrate.ateapi.v1.CreateAtespaceAccessPolicyRequest + 163, // 268: substrate.ateapi.v1.Control.UpdateAtespaceAccessPolicy:input_type -> substrate.ateapi.v1.UpdateAtespaceAccessPolicyRequest + 164, // 269: substrate.ateapi.v1.Control.DeleteAtespaceAccessPolicy:input_type -> substrate.ateapi.v1.DeleteAtespaceAccessPolicyRequest + 138, // 270: substrate.ateapi.v1.WorkerService.AcquireWorkerEpoch:input_type -> substrate.ateapi.v1.AcquireWorkerEpochRequest + 140, // 271: substrate.ateapi.v1.WorkerService.RegisterWorker:input_type -> substrate.ateapi.v1.RegisterWorkerRequest + 142, // 272: substrate.ateapi.v1.WorkerService.SetWorkerSandboxRuntimes:input_type -> substrate.ateapi.v1.SetWorkerSandboxRuntimesRequest + 144, // 273: substrate.ateapi.v1.WorkerService.MintWorkerActorCertificate:input_type -> substrate.ateapi.v1.MintWorkerActorCertificateRequest + 146, // 274: substrate.ateapi.v1.WorkerService.MintWorkerActorJwt:input_type -> substrate.ateapi.v1.MintWorkerActorJwtRequest + 148, // 275: substrate.ateapi.v1.WorkerService.RequestActorSuspend:input_type -> substrate.ateapi.v1.RequestActorSuspendRequest + 152, // 276: substrate.ateapi.v1.WorkerService.ReportActorSnapshotState:input_type -> substrate.ateapi.v1.ReportActorSnapshotStateRequest + 150, // 277: substrate.ateapi.v1.WorkerService.ReportActorCrashed:input_type -> substrate.ateapi.v1.ReportActorCrashedRequest + 17, // 278: substrate.ateapi.v1.Control.GetActor:output_type -> substrate.ateapi.v1.Actor + 17, // 279: substrate.ateapi.v1.Control.CreateActor:output_type -> substrate.ateapi.v1.Actor + 17, // 280: substrate.ateapi.v1.Control.UpdateActor:output_type -> substrate.ateapi.v1.Actor + 88, // 281: substrate.ateapi.v1.Control.SuspendActor:output_type -> substrate.ateapi.v1.SuspendActorResponse + 91, // 282: substrate.ateapi.v1.Control.ResumeActor:output_type -> substrate.ateapi.v1.ResumeActorResponse + 93, // 283: substrate.ateapi.v1.Control.RevertActor:output_type -> substrate.ateapi.v1.RevertActorResponse + 17, // 284: substrate.ateapi.v1.Control.DeleteActor:output_type -> substrate.ateapi.v1.Actor + 18, // 285: substrate.ateapi.v1.Control.GetActorEgressPolicy:output_type -> substrate.ateapi.v1.EgressPolicy + 18, // 286: substrate.ateapi.v1.Control.CreateActorEgressPolicy:output_type -> substrate.ateapi.v1.EgressPolicy + 18, // 287: substrate.ateapi.v1.Control.UpdateActorEgressPolicy:output_type -> substrate.ateapi.v1.EgressPolicy + 18, // 288: substrate.ateapi.v1.Control.DeleteActorEgressPolicy:output_type -> substrate.ateapi.v1.EgressPolicy + 101, // 289: substrate.ateapi.v1.Control.MintActorJwt:output_type -> substrate.ateapi.v1.MintActorJwtResponse + 35, // 290: substrate.ateapi.v1.Control.CreateTag:output_type -> substrate.ateapi.v1.Tag + 35, // 291: substrate.ateapi.v1.Control.GetTag:output_type -> substrate.ateapi.v1.Tag + 103, // 292: substrate.ateapi.v1.Control.ListTags:output_type -> substrate.ateapi.v1.ListTagsResponse + 35, // 293: substrate.ateapi.v1.Control.UpdateTag:output_type -> substrate.ateapi.v1.Tag + 35, // 294: substrate.ateapi.v1.Control.DeleteTag:output_type -> substrate.ateapi.v1.Tag + 36, // 295: substrate.ateapi.v1.Control.GetExternalVolume:output_type -> substrate.ateapi.v1.ExternalVolume + 109, // 296: substrate.ateapi.v1.Control.ListExternalVolumes:output_type -> substrate.ateapi.v1.ListExternalVolumesResponse + 115, // 297: substrate.ateapi.v1.Control.ListWorkers:output_type -> substrate.ateapi.v1.ListWorkersResponse + 128, // 298: substrate.ateapi.v1.Control.GetWorker:output_type -> substrate.ateapi.v1.Worker + 128, // 299: substrate.ateapi.v1.Control.CreateWorker:output_type -> substrate.ateapi.v1.Worker + 128, // 300: substrate.ateapi.v1.Control.UpdateWorker:output_type -> substrate.ateapi.v1.Worker + 128, // 301: substrate.ateapi.v1.Control.DeleteWorker:output_type -> substrate.ateapi.v1.Worker + 121, // 302: substrate.ateapi.v1.Control.DrainWorker:output_type -> substrate.ateapi.v1.DrainWorkerResponse + 123, // 303: substrate.ateapi.v1.Control.MarkWorkerAvailable:output_type -> substrate.ateapi.v1.MarkWorkerAvailableResponse + 125, // 304: substrate.ateapi.v1.Control.MarkWorkerUnavailable:output_type -> substrate.ateapi.v1.MarkWorkerUnavailableResponse + 113, // 305: substrate.ateapi.v1.Control.ListWorkerActorAssignments:output_type -> substrate.ateapi.v1.ListWorkerActorAssignmentsResponse + 127, // 306: substrate.ateapi.v1.Control.ListActors:output_type -> substrate.ateapi.v1.ListActorsResponse + 39, // 307: substrate.ateapi.v1.Control.CreateAtespace:output_type -> substrate.ateapi.v1.Atespace + 39, // 308: substrate.ateapi.v1.Control.GetAtespace:output_type -> substrate.ateapi.v1.Atespace + 71, // 309: substrate.ateapi.v1.Control.ListAtespaces:output_type -> substrate.ateapi.v1.ListAtespacesResponse + 39, // 310: substrate.ateapi.v1.Control.DeleteAtespace:output_type -> substrate.ateapi.v1.Atespace + 59, // 311: substrate.ateapi.v1.Control.CreateCsiDriver:output_type -> substrate.ateapi.v1.CsiDriver + 59, // 312: substrate.ateapi.v1.Control.GetCsiDriver:output_type -> substrate.ateapi.v1.CsiDriver + 76, // 313: substrate.ateapi.v1.Control.ListCsiDrivers:output_type -> substrate.ateapi.v1.ListCsiDriversResponse + 59, // 314: substrate.ateapi.v1.Control.UpdateCsiDriver:output_type -> substrate.ateapi.v1.CsiDriver + 59, // 315: substrate.ateapi.v1.Control.DeleteCsiDriver:output_type -> substrate.ateapi.v1.CsiDriver + 41, // 316: substrate.ateapi.v1.Control.CreateActorTemplate:output_type -> substrate.ateapi.v1.ActorTemplate + 41, // 317: substrate.ateapi.v1.Control.GetActorTemplate:output_type -> substrate.ateapi.v1.ActorTemplate + 82, // 318: substrate.ateapi.v1.Control.ListActorTemplates:output_type -> substrate.ateapi.v1.ListActorTemplatesResponse + 41, // 319: substrate.ateapi.v1.Control.DeleteActorTemplate:output_type -> substrate.ateapi.v1.ActorTemplate + 156, // 320: substrate.ateapi.v1.Control.GetGlobalAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy + 156, // 321: substrate.ateapi.v1.Control.CreateGlobalAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy + 156, // 322: substrate.ateapi.v1.Control.UpdateGlobalAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy + 156, // 323: substrate.ateapi.v1.Control.GetAtespaceAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy + 156, // 324: substrate.ateapi.v1.Control.CreateAtespaceAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy + 156, // 325: substrate.ateapi.v1.Control.UpdateAtespaceAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy + 156, // 326: substrate.ateapi.v1.Control.DeleteAtespaceAccessPolicy:output_type -> substrate.ateapi.v1.AccessPolicy + 139, // 327: substrate.ateapi.v1.WorkerService.AcquireWorkerEpoch:output_type -> substrate.ateapi.v1.AcquireWorkerEpochResponse + 141, // 328: substrate.ateapi.v1.WorkerService.RegisterWorker:output_type -> substrate.ateapi.v1.RegisterWorkerResponse + 143, // 329: substrate.ateapi.v1.WorkerService.SetWorkerSandboxRuntimes:output_type -> substrate.ateapi.v1.SetWorkerSandboxRuntimesResponse + 145, // 330: substrate.ateapi.v1.WorkerService.MintWorkerActorCertificate:output_type -> substrate.ateapi.v1.MintWorkerActorCertificateResponse + 147, // 331: substrate.ateapi.v1.WorkerService.MintWorkerActorJwt:output_type -> substrate.ateapi.v1.MintWorkerActorJwtResponse + 149, // 332: substrate.ateapi.v1.WorkerService.RequestActorSuspend:output_type -> substrate.ateapi.v1.RequestActorSuspendResponse + 153, // 333: substrate.ateapi.v1.WorkerService.ReportActorSnapshotState:output_type -> substrate.ateapi.v1.ReportActorSnapshotStateResponse + 151, // 334: substrate.ateapi.v1.WorkerService.ReportActorCrashed:output_type -> substrate.ateapi.v1.ReportActorCrashedResponse + 278, // [278:335] is the sub-list for method output_type + 221, // [221:278] is the sub-list for method input_type + 218, // [218:221] is the sub-list for extension type_name + 215, // [215:218] is the sub-list for extension extendee + 0, // [0:215] is the sub-list for field type_name } func init() { file_api_ateapi_v1_ateapi_proto_init() } @@ -11136,8 +12826,8 @@ func file_api_ateapi_v1_ateapi_proto_init() { GoPackagePath: reflect.TypeOf(x{}).PkgPath(), RawDescriptor: unsafe.Slice(unsafe.StringData(file_api_ateapi_v1_ateapi_proto_rawDesc), len(file_api_ateapi_v1_ateapi_proto_rawDesc)), NumEnums: 10, - NumMessages: 143, - NumExtensions: 2, + NumMessages: 166, + NumExtensions: 3, NumServices: 2, }, GoTypes: file_api_ateapi_v1_ateapi_proto_goTypes, diff --git a/api/ateapi/v1/ateapi.proto b/api/ateapi/v1/ateapi.proto index 51ed7d1e32..cfbb77c029 100644 --- a/api/ateapi/v1/ateapi.proto +++ b/api/ateapi/v1/ateapi.proto @@ -39,7 +39,8 @@ service Control { } // Suspend a given actor to a new snapshot. A running actor is checkpointed - // on its worker. A SUSPENDED actor is returned as it is. + // on its worker. A SUSPENDED actor is returned as it is, unless an + // `options.version` or `options.uid` guard does not match. rpc SuspendActor(SuspendActorRequest) returns (SuspendActorResponse) { option (method).resource = "Actor"; } @@ -120,6 +121,16 @@ service Control { option (method).resource = "Tag"; } + // Get an ExternalVolume. + rpc GetExternalVolume(GetExternalVolumeRequest) returns (ExternalVolume) { + option (method).resource = "ExternalVolume"; + } + + // List ExternalVolumes. + rpc ListExternalVolumes(ListExternalVolumesRequest) returns (ListExternalVolumesResponse) { + option (method).resource = "ExternalVolume"; + } + // List Workers. rpc ListWorkers(ListWorkersRequest) returns (ListWorkersResponse) { option (method).resource = "Worker"; @@ -197,12 +208,43 @@ service Control { option (method).resource = "Atespace"; } - // Delete an empty Atespace. Rejects (FailedPrecondition) if any Actors or - // Tags remain. + // Delete an empty Atespace. Rejects with `FAILED_PRECONDITION` if any + // Actors, ActorTemplates, Tags or ExternalVolumes remain. rpc DeleteAtespace(DeleteAtespaceRequest) returns (Atespace) { option (method).resource = "Atespace"; } + // Create a CsiDriver. + rpc CreateCsiDriver(CreateCsiDriverRequest) returns (CsiDriver) { + option (method) = { + resource : "CsiDriver" + preview_gate : {name : "ExternalVolumes"} + }; + } + + // Get a CsiDriver by name. + rpc GetCsiDriver(GetCsiDriverRequest) returns (CsiDriver) { + option (method).resource = "CsiDriver"; + } + + // List CsiDrivers. + rpc ListCsiDrivers(ListCsiDriversRequest) returns (ListCsiDriversResponse) { + option (method).resource = "CsiDriver"; + } + + // Update a CsiDriver. + rpc UpdateCsiDriver(UpdateCsiDriverRequest) returns (CsiDriver) { + option (method) = { + resource : "CsiDriver" + preview_gate : {name : "ExternalVolumes"} + }; + } + + // Delete a CsiDriver. + rpc DeleteCsiDriver(DeleteCsiDriverRequest) returns (CsiDriver) { + option (method).resource = "CsiDriver"; + } + rpc CreateActorTemplate(CreateActorTemplateRequest) returns (ActorTemplate) { option (method).resource = "ActorTemplate"; } @@ -445,7 +487,7 @@ message ResourceMetadata { // for update operations. // // +k8s:optional - // +k8s:alpha(since: "0.0")=+k8s:monotonic # TODO: get rid of alpha prefix + // +k8s:monotonic // +k8s:minimum=1 // +k8s:update=NoUnset int64 version = 4; @@ -486,11 +528,14 @@ message ExternalVolumes { // +k8s:maxItems=32 # matches the template's volumes bound // +k8s:listType=map // +k8s:listMapKey=name - repeated ExternalVolumeStatus volumes = 1; + repeated ActorExternalVolumeStatus volumes = 1; } -// ExternalVolumeStatus is one actor's view of an external volume it mounts. -message ExternalVolumeStatus { +// ActorExternalVolumeStatus is one actor's view of an external volume it mounts. +// +// (-- TODO(#1637): temporary rename to unblock ExternalVolume.status; delete +// once ExternalVolume replaces ActorStatus.external_volumes. --) +message ActorExternalVolumeStatus { // Name of the volume specified in the actor template. Template volume // names are DNS labels. // @@ -511,24 +556,26 @@ message ExternalVolumeStatus { // +k8s:maxLength=256 // +k8s:update=NoModify // +k8s:update=NoUnset - // +k8s:customValidation # no control characters + // +k8s:format=ate-volume-storage-id string storage_volume_id = 2; - // Internal volume plugin name or CSI driver name, from the StorageClass - // provisioner. Must be a DNS subdomain, optionally prefixed with - // "substrate.io/" (per the CSI spec's driver-name syntax). + // CSI driver name, from the StorageClass provisioner. Must be a DNS + // subdomain of at most 63 characters. + // + // (-- Same rule as `CsiDriver.driver_name`, and the CSI spec's driver name + // limit. --) // // +k8s:required - // +k8s:maxLength=253 + // +k8s:maxLength=63 // +k8s:update=NoModify // +k8s:update=NoUnset # set-once, like name above - // +k8s:customValidation + // +k8s:format=k8s-long-name string volume_type = 3; // volume_context contains metadata returned by the CSI driver during volume - // provisioning, needed by the node plugin for mounting (e.g. attachment - // info). Keys and values are the driver's own, so the map is only bounded, - // not validated. + // provisioning, needed by the node plugin for mounting, such as an NFS + // server and export path. Keys and values are the driver's own, so the map + // is only bounded, not validated. // // +k8s:optional // +k8s:customValidation # at most 40 KiB in total, ten times the CSI limit for map fields @@ -598,7 +645,7 @@ message EgressPolicy { // // +k8s:required // +k8s:subfield(atespace)=+k8s:required - // +k8s:customValidation # name must be "default" + // +k8s:subfield(name)=+k8s:format=ate-singleton-name ResourceMetadata metadata = 1; // Rules are an unordered set of allows. Traffic is denied when no rule @@ -826,23 +873,24 @@ message CredentialHeader { // The case-insensitive HTTP request header to replace when present. // // +k8s:required - // +k8s:customValidation # format + // +k8s:format=ate-http-header-name string header = 1; // Prepended verbatim to the credential value. Include any desired separator; // for example, use "Bearer " (including the space) for Authorization. // // +k8s:optional - // +k8s:customValidation # format + // +k8s:format=ate-http-header-value string prefix = 2; // Source-agnostic reference interpreted by a registered credential provider: // `ate-secret:////` // - // Exactly one of credential_uri and actor_jwt must be set. + // Exactly one of credential_uri, actor_jwt, and token_exchange must be set. // // +k8s:optional // +k8s:unionMember + // +k8s:maxLength=1024 // +k8s:customValidation # format string credential_uri = 3; @@ -852,6 +900,96 @@ message CredentialHeader { // +k8s:optional // +k8s:unionMember ActorJwtSource actor_jwt = 4; + + // A token obtained by exchanging an actor JWT at an OAuth 2.0 token + // exchange endpoint (RFC 8693). + // + // +k8s:optional + // +k8s:unionMember + TokenExchangeSource token_exchange = 5; +} + +// TokenExchangeSource has the gateway mint an actor JWT and exchange it at +// token_url (RFC 8693). The returned token becomes the header value. +message TokenExchangeSource { + // HTTPS URL of the token endpoint, with a DNS hostname and without userinfo, + // query, or fragment. + // + // +k8s:required + // +k8s:maxLength=2048 + // +k8s:customValidation # format + string token_url = 1; + + // The actor JWT sent as the RFC 8693 subject_token. + // + // +k8s:required + ActorJwtSource subject_actor_jwt = 2; + + // RFC 8693 resource parameters, each sent as a separate form entry. Each + // entry must be an absolute URI without a fragment. + // + // +k8s:optional + // +k8s:maxItems=16 + // +k8s:listType=set + // +k8s:eachVal=+k8s:minLength=1 + // +k8s:eachVal=+k8s:maxLength=2048 + // +k8s:customValidation # absolute URI without fragment + repeated string resources = 3; + + // RFC 8693 audience parameters, each sent as a separate form entry. + // + // +k8s:optional + // +k8s:maxItems=16 + // +k8s:listType=set + // +k8s:eachVal=+k8s:minLength=1 + // +k8s:eachVal=+k8s:maxLength=512 + repeated string audiences = 4; + + // RFC 8693 scope parameter, space-joined. + // + // +k8s:optional + // +k8s:maxItems=16 + // +k8s:listType=set + // +k8s:eachVal=+k8s:minLength=1 + // +k8s:eachVal=+k8s:maxLength=256 + // +k8s:customValidation # RFC 6749 scope-token characters + repeated string scopes = 5; + + // RFC 8693 requested_token_type parameter (for example, + // "urn:ietf:params:oauth:token-type:access_token"). Omitted from the form + // post when empty. + // + // +k8s:optional + // +k8s:maxLength=512 + string requested_token_type = 6; + + // Additional application/x-www-form-urlencoded parameters sent with the + // exchange request. Keys may repeat; reserved RFC 8693 parameter names + // (grant_type, subject_token, subject_token_type, actor_token, + // actor_token_type, resource, audience, scope, requested_token_type) are + // rejected. Intended for non-secret configuration (not client credentials). + // + // +k8s:optional + // +k8s:maxItems=16 + // +k8s:listType=atomic + // +k8s:customValidation # reject reserved RFC 8693 parameter names + repeated FormEntry additional_parameters = 7; +} + +// FormEntry is a single key-value entry in an application/x-www-form-urlencoded +// request body. +message FormEntry { + // Parameter name. + // + // +k8s:required + // +k8s:maxLength=128 + string key = 1; + + // Parameter value. + // + // +k8s:required + // +k8s:maxLength=2048 + string value = 2; } // ActorJwtSource has the gateway mint a JWT for the Actor that sent the @@ -909,9 +1047,11 @@ message ActorStatus { // actor. These volumes only live as long as the actor and are deleted with // it. // - // +ate:preview=ExternalVolumes // +k8s:optional - ExternalVolumes external_volumes = 3; + ExternalVolumes external_volumes = 3 [ (field).preview_gate = { + name : "ExternalVolumes" + allow_when_disabled : true + } ]; // crash records why and when the Actor entered CRASHED. It is set with the // CRASHED state and cleared when a revert returns the Actor to SUSPENDED. @@ -942,7 +1082,7 @@ message ActorStatus { // that have become stale and need to be cleaned up. // // +k8s:optional - // +k8s:alpha(since: "0.0")=+k8s:monotonic # TODO: get rid of alpha prefix + // +k8s:monotonic // +k8s:minimum=0 // +k8s:update=NoUnset int32 last_assigned_generation = 7; @@ -981,7 +1121,7 @@ message WorkerAssignment { // // Workers are global-scoped, so this carries no atespace. // - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden // +k8s:required // +k8s:update=NoModify ObjectRef worker = 6; @@ -1053,6 +1193,15 @@ message WorkerAssignment { // +k8s:customValidation # a SPIFFE ID // +k8s:update=NoModify string worker_spiffe_id = 10; + + // actor_activation_uid identifies the Actor's current activation on this + // Worker. Each Run or Restore call starts an activation with a new UUID. The + // field is empty until the Actor becomes RUNNING and for activations started + // by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string actor_activation_uid = 11; } // TagStatus is the server-owned state of a Tag. @@ -1066,8 +1215,13 @@ message TagStatus { // moves between snapshots and is usable only once COMPLETED. Unset until it // is recorded; a tag whose creation failed first never gets one. // + // (-- Custom validation allows an update to record the snapshot once, and then + // only to move its durable_snapshot from PENDING to COMPLETED. --) + // // +k8s:optional + // +k8s:update=NoUnset // +k8s:subfield(durable_snapshot)=+k8s:required + // +k8s:customValidation Snapshot snapshot = 1; // UID of the ActorTemplate the snapshot was taken under. Actors can only be @@ -1075,6 +1229,7 @@ message TagStatus { // // +k8s:required // +k8s:format=k8s-uuid + // +k8s:immutable string actor_template_uid = 2; } @@ -1097,6 +1252,7 @@ message Tag { // status is set by the control plane; it is ignored on write. // // +k8s:optional + // +k8s:update=NoUnset TagStatus status = 2; // scope controls who may create an Actor from this tag. @@ -1116,6 +1272,91 @@ message Tag { ObjectRef source_actor = 4; } +// ExternalVolume is an atespace-scoped record of a storage volume. Identity +// is `metadata.atespace` and `metadata.name`. It is read-only: the server +// creates and deletes it. An atespace cannot be deleted while it holds an +// ExternalVolume. +// +// (-- Nothing creates an ExternalVolume yet. The server-side creation, the +// actor template reference and an import RPC come in later changes. --) +message ExternalVolume { + option (resource) = { + scope : SCOPE_ATESPACE + plural : "ExternalVolumes" + }; + + // Common resource metadata: `atespace`, `name`, `uid`, `version`, + // timestamps. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:required + ResourceMetadata metadata = 1; + + // Server-managed state. + // + // +k8s:optional + // +k8s:update=NoUnset + ExternalVolumeStatus status = 2; +} + +// ExternalVolumeStatus is the server-managed state of an ExternalVolume. +message ExternalVolumeStatus { + // `csi` is the CSI volume backing this ExternalVolume. Unset until the + // server has provisioned it, then never changed. + // + // +k8s:optional + // +k8s:update=NoModify + // +k8s:update=NoUnset + CsiVolumeStatus csi = 1; +} + +// CsiVolumeStatus is the CSI volume backing an ExternalVolume. +message CsiVolumeStatus { + // `volume_id` is the volume's ID in the storage system, in the format the + // CSI driver expects. Its format is the storage system's own: at most 256 + // bytes, with no control characters, tabs or line breaks, and no leading or + // trailing whitespace. Together with `driver_name` it is unique across all + // atespaces. + // + // (-- TODO(#2935): "/" stays allowed because CSI IDs such as GCE PD paths + // contain it, so atelet must stop joining the raw ID into its staging path + // before an ExternalVolume can reach a node. --) + // + // +k8s:required + // +k8s:maxBytes=256 + // +k8s:update=NoModify + // +k8s:update=NoUnset + // +k8s:format=ate-volume-storage-id + // +k8s:customValidation # no tabs, line breaks or surrounding whitespace + string volume_id = 1; + + // `driver_name` is the CSI driver name: a DNS-1123 subdomain of at most 63 + // characters, as the CSI spec requires. + // + // +k8s:required + // +k8s:maxLength=63 + // +k8s:update=NoModify + // +k8s:update=NoUnset + // +k8s:format=k8s-long-name + string driver_name = 2; + + // `volume_context` is the driver metadata the node plugin needs to mount + // the volume, such as an NFS server and export path. It is passed as the + // volume context of the node plugin's stage and publish calls. Keys and + // values are the driver's own, so the map is only bounded: at most 128 + // entries, keys of at most 256 bytes, values of at most 4095 bytes, 4 KiB + // in total, and no NUL bytes. Attachment metadata is per node and not + // recorded here. + // + // +k8s:optional + // +k8s:maxProperties=128 + // +k8s:eachKey=+k8s:minLength=1 + // +k8s:eachKey=+k8s:maxBytes=256 + // +k8s:eachVal=+k8s:maxBytes=4095 + // +k8s:customValidation # at most 4 KiB in total, the CSI limit for map fields; no NUL bytes + map volume_context = 3; +} + // Atespace is the isolation boundary an Actor is created into. Global-scoped: // metadata.atespace is always empty; the atespace's identity is metadata.name. message Atespace { @@ -1127,7 +1368,7 @@ message Atespace { // Common resource metadata: name, uid, version, timestamps. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ResourceMetadata metadata = 1; } @@ -1197,7 +1438,9 @@ message ActorTemplate { // micro-VM is booted at that size. // // +k8s:required - // +k8s:customValidation # cpu and memory limits are both set + // +k8s:subfield(limits)=+k8s:required + // +k8s:subfield(limits)=+k8s:subfield(cpu_millicores)=+k8s:required + // +k8s:subfield(limits)=+k8s:subfield(memory_bytes)=+k8s:required ResourceRequirements resources = 6; // Egress policy for the golden Actor during initialization. The template @@ -1207,10 +1450,10 @@ message ActorTemplate { // If absent, no policy is created. When set, at least one rule is required. // May not be set when snapshot_config.golden_snapshot_config.mode is DISABLED. // - // +ate:preview=GoldenEgressPolicy // +k8s:ifDisabled(GoldenEgressPolicy)=+k8s:forbidden // +k8s:optional - EgressPolicyTemplate golden_egress_policy = 9; + EgressPolicyTemplate golden_egress_policy = 9 + [ (field).preview_gate.name = "GoldenEgressPolicy" ]; // +k8s:optional ActorTemplateStatus status = 7; @@ -1275,14 +1518,16 @@ message SnapshotConfig { // gate. Each path segment may contain only ASCII letters, digits, '_' and // '-'. Each owner's snapshots are stored under // /atespaces/..., so no segment may be "atespaces" in any - // letter case. + // letter case. For a gs:// location, the bucket name and path together may + // be at most 338 characters, so each actor's prefix fits a locally minted + // snapshot transfer token. // - // +ate:preview=PerTemplateSnapshotLocation // +k8s:ifDisabled(PerTemplateSnapshotLocation)=+k8s:forbidden // +k8s:optional // +k8s:maxLength=1024 // +k8s:customValidation # Validate URI - string storage_location = 1; + string storage_location = 1 + [ (field).preview_gate.name = "PerTemplateSnapshotLocation" ]; // preferred_fidelity is the highest fidelity the system packages when it // snapshots the actor. @@ -1436,7 +1681,7 @@ message EnvVar { // // +k8s:required // +k8s:maxLength=256 # guardrail; - // +k8s:customValidation # printable ASCII except '=' + // +k8s:format=ate-env-var-name string name = 1; // value is the literal value. @@ -1473,7 +1718,7 @@ message HttpGetAction { // // +k8s:required // +k8s:maxLength=1024 - // +k8s:customValidation # RFC 3986 path shape; no regex/pattern tag exists + // +k8s:format=ate-http-probe-path string path = 1; // port is the container port to connect to. @@ -1500,11 +1745,11 @@ message Volume { // external is a CSI volume: provisioned for this actor from a template. // - // +ate:preview=ExternalVolumes // +k8s:ifDisabled(ExternalVolumes)=+k8s:forbidden // +k8s:optional // +k8s:unionMember - ExternalVolumeSource external = 3; + ExternalVolumeSource external = 3 + [ (field).preview_gate.name = "ExternalVolumes" ]; // +k8s:optional // +k8s:unionMember @@ -1561,6 +1806,74 @@ message ExternalVolumeTemplate { string storage_class_name = 2; } +// CsiDriver configures how the control plane connects to a CSI driver's +// Controller service. Worker nodes connect to the CSI Node service at the +// standard Substrate socket path. Global-scoped: metadata.atespace must be +// empty. +message CsiDriver { + option (resource) = { + scope : SCOPE_GLOBAL + plural : "CsiDrivers" + }; + + // Common resource metadata: name, uid, version, timestamps. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:forbidden + ResourceMetadata metadata = 1; + + // driver_name is the CSI driver name, e.g. "nfs.csi.k8s.io". It is a DNS + // subdomain of at most 63 characters and is unique across all CsiDrivers. + // + // +k8s:required + // +k8s:maxLength=63 + // +k8s:immutable + // +k8s:format=k8s-long-name + string driver_name = 2; + + // controller_endpoint is the TCP network address of the CSI Controller + // service. + // + // +k8s:required + CsiDriverEndpoint controller_endpoint = 3; + + // tls configures pod-identity mTLS for connections to controller_endpoint. + // Omit to connect in plaintext. + // + // +k8s:optional + CsiDriverTlsConfig tls = 4; +} + +// CsiDriverEndpoint identifies the network address of a CSI Controller service. +message CsiDriverEndpoint { + // host is the DNS name or IP address (IPv4 or IPv6 without a zone ID) of the + // CSI Controller service, e.g. + // "csi-nfs-controller.kube-system.svc.cluster.local" or "127.0.0.1". + // + // +k8s:required + // +k8s:maxLength=253 + // +k8s:customValidation # DNS-1123 subdomain or IPv4/IPv6 address without zone + string host = 1; + + // port is the TCP port number of the CSI Controller service. + // + // +k8s:required + // +k8s:minimum=1 + // +k8s:maximum=65535 + int32 port = 2; +} + +// CsiDriverTlsConfig configures pod-identity mTLS for CSI controller gRPC +// connections. Omit CsiDriver.tls for plaintext. +message CsiDriverTlsConfig { + // server_name is the expected TLS server name on the controller certificate. + // + // +k8s:required + // +k8s:format=k8s-long-name + // +k8s:maxLength=253 + string server_name = 1; +} + // SystemInfoVolumeSource is a read-only volume of substrate-generated // per-actor files (identity fields, projected trust bundles), regenerated by // atelet on every Run/Restore. @@ -1689,7 +2002,7 @@ message CreateAtespaceRequest { message GetAtespaceRequest { // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef atespace = 1; } @@ -1710,7 +2023,7 @@ message ListAtespacesResponse { message DeleteAtespaceRequest { // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef atespace = 1; // Optional per-delete preconditions. @@ -1719,6 +2032,73 @@ message DeleteAtespaceRequest { DeleteOptions options = 2; } +// CreateCsiDriverRequest creates a CsiDriver. +message CreateCsiDriverRequest { + // The driver to create. metadata.name is required and metadata.atespace + // must be empty. + // + // +k8s:required + CsiDriver csi_driver = 1; +} + +// GetCsiDriverRequest identifies the CsiDriver to get. +message GetCsiDriverRequest { + // The driver to get. atespace must be empty. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:forbidden + ObjectRef csi_driver = 1; +} + +// ListCsiDriversRequest asks for a page of CsiDrivers. +message ListCsiDriversRequest { + // Pagination controls. + // + // +k8s:optional + ListOptions options = 1; +} + +// ListCsiDriversResponse is one page of CsiDrivers. +message ListCsiDriversResponse { + // The page of drivers. This list may be empty even if there are more results. + repeated CsiDriver csi_drivers = 1; + + // Pagination token for the next page. Empty if this is the last page. + string next_page_token = 2; +} + +// UpdateCsiDriverRequest updates a CsiDriver. +message UpdateCsiDriverRequest { + // The driver to update. csi_driver.metadata.name identifies which + // resource to update, and metadata.atespace must be empty. + // csi_driver.metadata.uid and csi_driver.metadata.version are + // required preconditions. + // + // controller_endpoint and tls are replaced with what the request carries, + // and any omitted optional field is cleared. driver_name is immutable. + // + // +k8s:required + // +k8s:opaqueType # updates are handled in 2 steps, do not descend + // +k8s:customValidation # descend into metadata + // +k8s:subfield(metadata)=+k8s:required + // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:forbidden + CsiDriver csi_driver = 1; +} + +// DeleteCsiDriverRequest identifies the CsiDriver to delete. +message DeleteCsiDriverRequest { + // The driver to delete. atespace must be empty. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:forbidden + ObjectRef csi_driver = 1; + + // Optional per-delete preconditions. + // + // +k8s:optional + DeleteOptions options = 2; +} + message CreateActorTemplateRequest { // The actor template version to create. Server-assigned metadata (uid, // version, timestamps) is ignored, as are the status fields. @@ -1793,8 +2173,9 @@ message UpdateActorRequest { // // +k8s:required // +k8s:opaqueType # updates are handled in 2 steps, do not descend + // +k8s:customValidation # descend into metadata // +k8s:subfield(metadata)=+k8s:required - // +k8s:customValidation # TODO: when we get nested subfields, require metadata.atespace + // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:required Actor actor = 1; } @@ -1803,7 +2184,7 @@ message SuspendActorRequest { // +k8s:subfield(atespace)=+k8s:required ObjectRef actor = 1; - // options controls how SuspendActor persists the actor's snapshot. + // Optional per-suspend controls and precondition guards. // // +k8s:optional SuspendOptions options = 2; @@ -1813,7 +2194,8 @@ message SuspendActorResponse { Actor actor = 1; } -// SuspendOptions tunes how SuspendActor persists the actor's snapshot. +// SuspendOptions are the optional controls a SuspendActor request may carry. +// A guard that does not match the actor fails the request with `ABORTED`. message SuspendOptions { // mode selects when SuspendActor returns relative to the snapshot reaching // durable storage. If unspecified, defaults to DURABILITY_MODE_ASYNCHRONOUS. @@ -1822,6 +2204,20 @@ message SuspendOptions { // +k8s:minimum=1 // +k8s:maximum=2 # keep this in sync with the DurabilityMode enum DurabilityMode mode = 1; + + // Suspend only if the actor is still at this version. Zero skips the check. + // A call can change `version` before it fails, so read the actor again before + // a retry. + // + // +k8s:optional + // +k8s:minimum=1 + int64 version = 2; + + // Suspend only if the actor still has this uid. Empty skips the check. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string uid = 3; } // DurabilityMode selects when a suspend is acknowledged relative to its @@ -1842,9 +2238,32 @@ enum DurabilityMode { } message ResumeActorRequest { + // Options are the optional controls a ResumeActor request may carry. + // A guard that does not match the actor fails the request with `ABORTED`. + message Options { + // Resume only if the actor is still at this version. Zero skips the check. + // A call can change `version` before it fails, so read the actor again + // before a retry. + // + // +k8s:optional + // +k8s:minimum=1 + int64 version = 1; + + // Resume only if the actor still has this uid. Empty skips the check. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string uid = 2; + } + // +k8s:required // +k8s:subfield(atespace)=+k8s:required ObjectRef actor = 1; + + // Optional per-resume controls and precondition guards. + // + // +k8s:optional + Options options = 2; } message ResumeActorResponse { @@ -1857,10 +2276,33 @@ message ResumeActorResponse { // RevertActorRequest identifies the Actor to revert. message RevertActorRequest { + // Options are the optional controls a RevertActor request may carry. + // A guard that does not match the actor fails the request with `ABORTED`. + message Options { + // Revert only if the actor is still at this version. Zero skips the check. + // A call can change `version` before it fails, so read the actor again + // before a retry. + // + // +k8s:optional + // +k8s:minimum=1 + int64 version = 1; + + // Revert only if the actor still has this uid. Empty skips the check. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string uid = 2; + } + // actor to revert. // +k8s:required // +k8s:subfield(atespace)=+k8s:required ObjectRef actor = 1; + + // Optional per-revert controls and precondition guards. + // + // +k8s:optional + Options options = 2; } // RevertActorResponse holds the reverted Actor. @@ -1892,8 +2334,7 @@ message GetActorEgressPolicyRequest { // Name of the singleton egress policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name string name = 2; } @@ -1942,8 +2383,7 @@ message DeleteActorEgressPolicyRequest { // Name of the singleton egress policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name string name = 2; // Optional per-delete preconditions. @@ -2062,8 +2502,9 @@ message UpdateTagRequest { // // +k8s:required // +k8s:opaqueType # updates are handled in 2 steps, do not descend + // +k8s:customValidation # descend into metadata // +k8s:subfield(metadata)=+k8s:required - // +k8s:customValidation # TODO: when we get nested subfields, require metadata.atespace + // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:required Tag tag = 1; } @@ -2078,6 +2519,38 @@ message DeleteTagRequest { DeleteOptions options = 2; } +// GetExternalVolumeRequest identifies one ExternalVolume. +message GetExternalVolumeRequest { + // The volume to get. + // + // +k8s:required + // +k8s:subfield(atespace)=+k8s:required + ObjectRef external_volume = 1; +} + +// ListExternalVolumesRequest selects a page of ExternalVolumes. +message ListExternalVolumesRequest { + // The atespace to list from. Empty lists across all atespaces. + // + // +k8s:optional + // +k8s:format=k8s-short-name + string atespace = 1; + + // Pagination controls. + // + // +k8s:optional + ListOptions options = 2; +} + +// ListExternalVolumesResponse is one page of ExternalVolumes. +message ListExternalVolumesResponse { + // The volumes in this page. + repeated ExternalVolume external_volumes = 1; + + // Pagination token for the next page. Empty on the last page. + string next_page_token = 2; +} + // DeleteOptions are the optional guards a Delete request may carry. message DeleteOptions { // Delete only if the resource is still at this version, that is, unchanged @@ -2120,7 +2593,7 @@ message ListWorkerActorAssignmentsRequest { // The Worker under which to list Actors. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; // Pagination controls. @@ -2157,7 +2630,7 @@ message GetWorkerRequest { // The Worker to fetch. atespace is always empty; Workers are global-scoped. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; } @@ -2183,8 +2656,9 @@ message UpdateWorkerRequest { // // +k8s:required // +k8s:opaqueType # updates are handled in 2 steps, do not descend + // +k8s:customValidation # descend into metadata // +k8s:subfield(metadata)=+k8s:required - // +k8s:customValidation # TODO: when we get nested subfields, forbid metadata.atespace + // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:forbidden Worker worker = 1; } @@ -2192,7 +2666,7 @@ message DeleteWorkerRequest { // The Worker to deregister. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; // Optional per-delete preconditions. @@ -2205,7 +2679,7 @@ message DrainWorkerRequest { // The Worker to mark as terminating. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; } @@ -2220,7 +2694,7 @@ message MarkWorkerAvailableRequest { // The Worker to mark ACTIVE. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; } @@ -2235,7 +2709,7 @@ message MarkWorkerUnavailableRequest { // The Worker to mark UNAVAILABLE. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; } @@ -2288,7 +2762,7 @@ message Worker { // uid and version are echoed back on UpdateWorker as preconditions. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ResourceMetadata metadata = 1; // Kubernetes coordinates. Immutable, set at creation. @@ -2614,7 +3088,7 @@ message ActorAssignment { // that caused an assignment is what addresses it. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ResourceMetadata metadata = 1; // actor is the Actor that is assigned to the Worker. @@ -2752,7 +3226,7 @@ message AcquireWorkerEpochRequest { // Workers are global-scoped. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; } @@ -2766,7 +3240,7 @@ message RegisterWorkerRequest { // global-scoped. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; // The epoch the worker process acquired through AcquireWorkerEpoch. @@ -2802,7 +3276,7 @@ message SetWorkerSandboxRuntimesRequest { // global-scoped. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; // The epoch the worker process registered with. @@ -2860,7 +3334,7 @@ message MintWorkerActorCertificateRequest { // must be the Worker that the actor is assigned to. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 4; } @@ -2932,7 +3406,7 @@ message RequestActorSuspendRequest { // names the Worker that certificate proves the request came from. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; // The Actor to suspend. It must be assigned to worker; a Worker may speak @@ -2961,7 +3435,7 @@ message ReportActorCrashedRequest { // global-scoped. atelet fills this in from its caller's certificate. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef worker = 1; // The Actor whose sandbox died. It must be assigned to worker. @@ -2982,6 +3456,14 @@ message ReportActorCrashedRequest { // +k8s:required // +k8s:maxLength=4096 string message = 4; + + // activation_uid identifies the runtime that exited. + // Accepted for protocol compatibility; crash handling uses the Actor and + // Worker identities. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string activation_uid = 5; } message ReportActorCrashedResponse { @@ -3095,7 +3577,8 @@ message AccessPolicy { // create_time, and update_time are server-managed. // // +k8s:required - // +k8s:customValidation # name must be "default" + // +k8s:subfield(atespace)=+k8s:forbidden + // +k8s:subfield(name)=+k8s:format=ate-singleton-name ResourceMetadata metadata = 1; // Role bindings granting permissions on the parent resource. @@ -3132,8 +3615,7 @@ message GetGlobalAccessPolicyRequest { // Name of the singleton access policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name string name = 1; } @@ -3160,14 +3642,13 @@ message GetAtespaceAccessPolicyRequest { // The parent Atespace of the access policy resource to retrieve. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef atespace = 1; // Name of the singleton access policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name string name = 2; } @@ -3176,7 +3657,7 @@ message CreateAtespaceAccessPolicyRequest { // Parent Atespace under which to create the policy resource. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef atespace = 1; // The policy to create. metadata.name must be "default" and @@ -3191,7 +3672,7 @@ message UpdateAtespaceAccessPolicyRequest { // Parent Atespace under which to update the policy resource. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef atespace = 1; // Full replacement. Metadata UID and version are required preconditions; @@ -3206,14 +3687,13 @@ message DeleteAtespaceAccessPolicyRequest { // The parent Atespace of the access policy resource to delete. // // +k8s:required - // +k8s:beta(since: "0.0")=+k8s:subfield(atespace)=+k8s:forbidden # TODO: get rid of beta prefix + // +k8s:subfield(atespace)=+k8s:forbidden ObjectRef atespace = 1; // Name of the singleton access policy. Must be "default". // // +k8s:required - // +k8s:format=k8s-short-name - // +k8s:customValidation # must be "default" + // +k8s:format=ate-singleton-name string name = 2; // Optional per-delete preconditions. @@ -3240,6 +3720,8 @@ message ResourceAnnotation { // The resource's plural name, as List methods and their response fields // use it. For example, "AccessPolicies" for AccessPolicy. string plural = 4; + + // TODO: add a preview gate to gate a whole resource. } // Scope is whether a top-level resource belongs to an atespace. @@ -3257,6 +3739,35 @@ message MethodAnnotation { // The message name of the resource the method operates on. For example, // "Actor" for SuspendActor, or "EgressPolicy" for GetActorEgressPolicy. string resource = 1; + + // The preview gate that must be enabled to call the method. Unset if the + // method is generally available. + MethodPreviewGate preview_gate = 2; +} + +// MethodPreviewGate names the preview feature a method is part of. +message MethodPreviewGate { + // The gate name. + string name = 1; + + // TODO: add allow_when_disabled, as FieldPreviewGate has, when a method + // must stay callable while its gate is disabled. +} + +// FieldAnnotation describes a field of the API. +message FieldAnnotation { + // The preview feature the field is part of. Unset if the field is + // generally available. + FieldPreviewGate preview_gate = 1; +} + +// FieldPreviewGate names the preview feature a field is part of. +message FieldPreviewGate { + // The gate name. + string name = 1; + + // allow_when_disabled allows setting the field while the gate is disabled. + bool allow_when_disabled = 2; } extend google.protobuf.MessageOptions { @@ -3266,3 +3777,7 @@ extend google.protobuf.MessageOptions { extend google.protobuf.MethodOptions { MethodAnnotation method = 50000; } + +extend google.protobuf.FieldOptions { + FieldAnnotation field = 50000; +} diff --git a/api/ateapi/v1/ateapi_grpc.pb.go b/api/ateapi/v1/ateapi_grpc.pb.go index e54c306d67..c5416d5ac6 100644 --- a/api/ateapi/v1/ateapi_grpc.pb.go +++ b/api/ateapi/v1/ateapi_grpc.pb.go @@ -50,6 +50,8 @@ const ( Control_ListTags_FullMethodName = "/substrate.ateapi.v1.Control/ListTags" Control_UpdateTag_FullMethodName = "/substrate.ateapi.v1.Control/UpdateTag" Control_DeleteTag_FullMethodName = "/substrate.ateapi.v1.Control/DeleteTag" + Control_GetExternalVolume_FullMethodName = "/substrate.ateapi.v1.Control/GetExternalVolume" + Control_ListExternalVolumes_FullMethodName = "/substrate.ateapi.v1.Control/ListExternalVolumes" Control_ListWorkers_FullMethodName = "/substrate.ateapi.v1.Control/ListWorkers" Control_GetWorker_FullMethodName = "/substrate.ateapi.v1.Control/GetWorker" Control_CreateWorker_FullMethodName = "/substrate.ateapi.v1.Control/CreateWorker" @@ -64,6 +66,11 @@ const ( Control_GetAtespace_FullMethodName = "/substrate.ateapi.v1.Control/GetAtespace" Control_ListAtespaces_FullMethodName = "/substrate.ateapi.v1.Control/ListAtespaces" Control_DeleteAtespace_FullMethodName = "/substrate.ateapi.v1.Control/DeleteAtespace" + Control_CreateCsiDriver_FullMethodName = "/substrate.ateapi.v1.Control/CreateCsiDriver" + Control_GetCsiDriver_FullMethodName = "/substrate.ateapi.v1.Control/GetCsiDriver" + Control_ListCsiDrivers_FullMethodName = "/substrate.ateapi.v1.Control/ListCsiDrivers" + Control_UpdateCsiDriver_FullMethodName = "/substrate.ateapi.v1.Control/UpdateCsiDriver" + Control_DeleteCsiDriver_FullMethodName = "/substrate.ateapi.v1.Control/DeleteCsiDriver" Control_CreateActorTemplate_FullMethodName = "/substrate.ateapi.v1.Control/CreateActorTemplate" Control_GetActorTemplate_FullMethodName = "/substrate.ateapi.v1.Control/GetActorTemplate" Control_ListActorTemplates_FullMethodName = "/substrate.ateapi.v1.Control/ListActorTemplates" @@ -90,7 +97,8 @@ type ControlClient interface { // Update mutable fields on an existing Actor. UpdateActor(ctx context.Context, in *UpdateActorRequest, opts ...grpc.CallOption) (*Actor, error) // Suspend a given actor to a new snapshot. A running actor is checkpointed - // on its worker. A SUSPENDED actor is returned as it is. + // on its worker. A SUSPENDED actor is returned as it is, unless an + // `options.version` or `options.uid` guard does not match. SuspendActor(ctx context.Context, in *SuspendActorRequest, opts ...grpc.CallOption) (*SuspendActorResponse, error) // Resume an actor from its latest snapshot. ResumeActor(ctx context.Context, in *ResumeActorRequest, opts ...grpc.CallOption) (*ResumeActorResponse, error) @@ -129,6 +137,10 @@ type ControlClient interface { // tag that have not yet been suspended still point at that external snapshot // and become unrecoverable, so do not delete a tag while such Actors exist. DeleteTag(ctx context.Context, in *DeleteTagRequest, opts ...grpc.CallOption) (*Tag, error) + // Get an ExternalVolume. + GetExternalVolume(ctx context.Context, in *GetExternalVolumeRequest, opts ...grpc.CallOption) (*ExternalVolume, error) + // List ExternalVolumes. + ListExternalVolumes(ctx context.Context, in *ListExternalVolumesRequest, opts ...grpc.CallOption) (*ListExternalVolumesResponse, error) // List Workers. ListWorkers(ctx context.Context, in *ListWorkersRequest, opts ...grpc.CallOption) (*ListWorkersResponse, error) // Get a Worker. @@ -167,9 +179,19 @@ type ControlClient interface { GetAtespace(ctx context.Context, in *GetAtespaceRequest, opts ...grpc.CallOption) (*Atespace, error) // List Atespaces. ListAtespaces(ctx context.Context, in *ListAtespacesRequest, opts ...grpc.CallOption) (*ListAtespacesResponse, error) - // Delete an empty Atespace. Rejects (FailedPrecondition) if any Actors or - // Tags remain. + // Delete an empty Atespace. Rejects with `FAILED_PRECONDITION` if any + // Actors, ActorTemplates, Tags or ExternalVolumes remain. DeleteAtespace(ctx context.Context, in *DeleteAtespaceRequest, opts ...grpc.CallOption) (*Atespace, error) + // Create a CsiDriver. + CreateCsiDriver(ctx context.Context, in *CreateCsiDriverRequest, opts ...grpc.CallOption) (*CsiDriver, error) + // Get a CsiDriver by name. + GetCsiDriver(ctx context.Context, in *GetCsiDriverRequest, opts ...grpc.CallOption) (*CsiDriver, error) + // List CsiDrivers. + ListCsiDrivers(ctx context.Context, in *ListCsiDriversRequest, opts ...grpc.CallOption) (*ListCsiDriversResponse, error) + // Update a CsiDriver. + UpdateCsiDriver(ctx context.Context, in *UpdateCsiDriverRequest, opts ...grpc.CallOption) (*CsiDriver, error) + // Delete a CsiDriver. + DeleteCsiDriver(ctx context.Context, in *DeleteCsiDriverRequest, opts ...grpc.CallOption) (*CsiDriver, error) CreateActorTemplate(ctx context.Context, in *CreateActorTemplateRequest, opts ...grpc.CallOption) (*ActorTemplate, error) GetActorTemplate(ctx context.Context, in *GetActorTemplateRequest, opts ...grpc.CallOption) (*ActorTemplate, error) ListActorTemplates(ctx context.Context, in *ListActorTemplatesRequest, opts ...grpc.CallOption) (*ListActorTemplatesResponse, error) @@ -375,6 +397,26 @@ func (c *controlClient) DeleteTag(ctx context.Context, in *DeleteTagRequest, opt return out, nil } +func (c *controlClient) GetExternalVolume(ctx context.Context, in *GetExternalVolumeRequest, opts ...grpc.CallOption) (*ExternalVolume, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ExternalVolume) + err := c.cc.Invoke(ctx, Control_GetExternalVolume_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *controlClient) ListExternalVolumes(ctx context.Context, in *ListExternalVolumesRequest, opts ...grpc.CallOption) (*ListExternalVolumesResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListExternalVolumesResponse) + err := c.cc.Invoke(ctx, Control_ListExternalVolumes_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *controlClient) ListWorkers(ctx context.Context, in *ListWorkersRequest, opts ...grpc.CallOption) (*ListWorkersResponse, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ListWorkersResponse) @@ -515,6 +557,56 @@ func (c *controlClient) DeleteAtespace(ctx context.Context, in *DeleteAtespaceRe return out, nil } +func (c *controlClient) CreateCsiDriver(ctx context.Context, in *CreateCsiDriverRequest, opts ...grpc.CallOption) (*CsiDriver, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CsiDriver) + err := c.cc.Invoke(ctx, Control_CreateCsiDriver_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *controlClient) GetCsiDriver(ctx context.Context, in *GetCsiDriverRequest, opts ...grpc.CallOption) (*CsiDriver, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CsiDriver) + err := c.cc.Invoke(ctx, Control_GetCsiDriver_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *controlClient) ListCsiDrivers(ctx context.Context, in *ListCsiDriversRequest, opts ...grpc.CallOption) (*ListCsiDriversResponse, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(ListCsiDriversResponse) + err := c.cc.Invoke(ctx, Control_ListCsiDrivers_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *controlClient) UpdateCsiDriver(ctx context.Context, in *UpdateCsiDriverRequest, opts ...grpc.CallOption) (*CsiDriver, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CsiDriver) + err := c.cc.Invoke(ctx, Control_UpdateCsiDriver_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *controlClient) DeleteCsiDriver(ctx context.Context, in *DeleteCsiDriverRequest, opts ...grpc.CallOption) (*CsiDriver, error) { + cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) + out := new(CsiDriver) + err := c.cc.Invoke(ctx, Control_DeleteCsiDriver_FullMethodName, in, out, cOpts...) + if err != nil { + return nil, err + } + return out, nil +} + func (c *controlClient) CreateActorTemplate(ctx context.Context, in *CreateActorTemplateRequest, opts ...grpc.CallOption) (*ActorTemplate, error) { cOpts := append([]grpc.CallOption{grpc.StaticMethod()}, opts...) out := new(ActorTemplate) @@ -638,7 +730,8 @@ type ControlServer interface { // Update mutable fields on an existing Actor. UpdateActor(context.Context, *UpdateActorRequest) (*Actor, error) // Suspend a given actor to a new snapshot. A running actor is checkpointed - // on its worker. A SUSPENDED actor is returned as it is. + // on its worker. A SUSPENDED actor is returned as it is, unless an + // `options.version` or `options.uid` guard does not match. SuspendActor(context.Context, *SuspendActorRequest) (*SuspendActorResponse, error) // Resume an actor from its latest snapshot. ResumeActor(context.Context, *ResumeActorRequest) (*ResumeActorResponse, error) @@ -677,6 +770,10 @@ type ControlServer interface { // tag that have not yet been suspended still point at that external snapshot // and become unrecoverable, so do not delete a tag while such Actors exist. DeleteTag(context.Context, *DeleteTagRequest) (*Tag, error) + // Get an ExternalVolume. + GetExternalVolume(context.Context, *GetExternalVolumeRequest) (*ExternalVolume, error) + // List ExternalVolumes. + ListExternalVolumes(context.Context, *ListExternalVolumesRequest) (*ListExternalVolumesResponse, error) // List Workers. ListWorkers(context.Context, *ListWorkersRequest) (*ListWorkersResponse, error) // Get a Worker. @@ -715,9 +812,19 @@ type ControlServer interface { GetAtespace(context.Context, *GetAtespaceRequest) (*Atespace, error) // List Atespaces. ListAtespaces(context.Context, *ListAtespacesRequest) (*ListAtespacesResponse, error) - // Delete an empty Atespace. Rejects (FailedPrecondition) if any Actors or - // Tags remain. + // Delete an empty Atespace. Rejects with `FAILED_PRECONDITION` if any + // Actors, ActorTemplates, Tags or ExternalVolumes remain. DeleteAtespace(context.Context, *DeleteAtespaceRequest) (*Atespace, error) + // Create a CsiDriver. + CreateCsiDriver(context.Context, *CreateCsiDriverRequest) (*CsiDriver, error) + // Get a CsiDriver by name. + GetCsiDriver(context.Context, *GetCsiDriverRequest) (*CsiDriver, error) + // List CsiDrivers. + ListCsiDrivers(context.Context, *ListCsiDriversRequest) (*ListCsiDriversResponse, error) + // Update a CsiDriver. + UpdateCsiDriver(context.Context, *UpdateCsiDriverRequest) (*CsiDriver, error) + // Delete a CsiDriver. + DeleteCsiDriver(context.Context, *DeleteCsiDriverRequest) (*CsiDriver, error) CreateActorTemplate(context.Context, *CreateActorTemplateRequest) (*ActorTemplate, error) GetActorTemplate(context.Context, *GetActorTemplateRequest) (*ActorTemplate, error) ListActorTemplates(context.Context, *ListActorTemplatesRequest) (*ListActorTemplatesResponse, error) @@ -804,6 +911,12 @@ func (UnimplementedControlServer) UpdateTag(context.Context, *UpdateTagRequest) func (UnimplementedControlServer) DeleteTag(context.Context, *DeleteTagRequest) (*Tag, error) { return nil, status.Error(codes.Unimplemented, "method DeleteTag not implemented") } +func (UnimplementedControlServer) GetExternalVolume(context.Context, *GetExternalVolumeRequest) (*ExternalVolume, error) { + return nil, status.Error(codes.Unimplemented, "method GetExternalVolume not implemented") +} +func (UnimplementedControlServer) ListExternalVolumes(context.Context, *ListExternalVolumesRequest) (*ListExternalVolumesResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ListExternalVolumes not implemented") +} func (UnimplementedControlServer) ListWorkers(context.Context, *ListWorkersRequest) (*ListWorkersResponse, error) { return nil, status.Error(codes.Unimplemented, "method ListWorkers not implemented") } @@ -846,6 +959,21 @@ func (UnimplementedControlServer) ListAtespaces(context.Context, *ListAtespacesR func (UnimplementedControlServer) DeleteAtespace(context.Context, *DeleteAtespaceRequest) (*Atespace, error) { return nil, status.Error(codes.Unimplemented, "method DeleteAtespace not implemented") } +func (UnimplementedControlServer) CreateCsiDriver(context.Context, *CreateCsiDriverRequest) (*CsiDriver, error) { + return nil, status.Error(codes.Unimplemented, "method CreateCsiDriver not implemented") +} +func (UnimplementedControlServer) GetCsiDriver(context.Context, *GetCsiDriverRequest) (*CsiDriver, error) { + return nil, status.Error(codes.Unimplemented, "method GetCsiDriver not implemented") +} +func (UnimplementedControlServer) ListCsiDrivers(context.Context, *ListCsiDriversRequest) (*ListCsiDriversResponse, error) { + return nil, status.Error(codes.Unimplemented, "method ListCsiDrivers not implemented") +} +func (UnimplementedControlServer) UpdateCsiDriver(context.Context, *UpdateCsiDriverRequest) (*CsiDriver, error) { + return nil, status.Error(codes.Unimplemented, "method UpdateCsiDriver not implemented") +} +func (UnimplementedControlServer) DeleteCsiDriver(context.Context, *DeleteCsiDriverRequest) (*CsiDriver, error) { + return nil, status.Error(codes.Unimplemented, "method DeleteCsiDriver not implemented") +} func (UnimplementedControlServer) CreateActorTemplate(context.Context, *CreateActorTemplateRequest) (*ActorTemplate, error) { return nil, status.Error(codes.Unimplemented, "method CreateActorTemplate not implemented") } @@ -1206,6 +1334,42 @@ func _Control_DeleteTag_Handler(srv interface{}, ctx context.Context, dec func(i return interceptor(ctx, in, info, handler) } +func _Control_GetExternalVolume_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetExternalVolumeRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ControlServer).GetExternalVolume(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Control_GetExternalVolume_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ControlServer).GetExternalVolume(ctx, req.(*GetExternalVolumeRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Control_ListExternalVolumes_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListExternalVolumesRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ControlServer).ListExternalVolumes(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Control_ListExternalVolumes_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ControlServer).ListExternalVolumes(ctx, req.(*ListExternalVolumesRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _Control_ListWorkers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(ListWorkersRequest) if err := dec(in); err != nil { @@ -1458,6 +1622,96 @@ func _Control_DeleteAtespace_Handler(srv interface{}, ctx context.Context, dec f return interceptor(ctx, in, info, handler) } +func _Control_CreateCsiDriver_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(CreateCsiDriverRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ControlServer).CreateCsiDriver(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Control_CreateCsiDriver_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ControlServer).CreateCsiDriver(ctx, req.(*CreateCsiDriverRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Control_GetCsiDriver_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(GetCsiDriverRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ControlServer).GetCsiDriver(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Control_GetCsiDriver_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ControlServer).GetCsiDriver(ctx, req.(*GetCsiDriverRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Control_ListCsiDrivers_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(ListCsiDriversRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ControlServer).ListCsiDrivers(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Control_ListCsiDrivers_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ControlServer).ListCsiDrivers(ctx, req.(*ListCsiDriversRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Control_UpdateCsiDriver_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(UpdateCsiDriverRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ControlServer).UpdateCsiDriver(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Control_UpdateCsiDriver_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ControlServer).UpdateCsiDriver(ctx, req.(*UpdateCsiDriverRequest)) + } + return interceptor(ctx, in, info, handler) +} + +func _Control_DeleteCsiDriver_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(DeleteCsiDriverRequest) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(ControlServer).DeleteCsiDriver(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: Control_DeleteCsiDriver_FullMethodName, + } + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(ControlServer).DeleteCsiDriver(ctx, req.(*DeleteCsiDriverRequest)) + } + return interceptor(ctx, in, info, handler) +} + func _Control_CreateActorTemplate_Handler(srv interface{}, ctx context.Context, dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { in := new(CreateActorTemplateRequest) if err := dec(in); err != nil { @@ -1731,6 +1985,14 @@ var Control_ServiceDesc = grpc.ServiceDesc{ MethodName: "DeleteTag", Handler: _Control_DeleteTag_Handler, }, + { + MethodName: "GetExternalVolume", + Handler: _Control_GetExternalVolume_Handler, + }, + { + MethodName: "ListExternalVolumes", + Handler: _Control_ListExternalVolumes_Handler, + }, { MethodName: "ListWorkers", Handler: _Control_ListWorkers_Handler, @@ -1787,6 +2049,26 @@ var Control_ServiceDesc = grpc.ServiceDesc{ MethodName: "DeleteAtespace", Handler: _Control_DeleteAtespace_Handler, }, + { + MethodName: "CreateCsiDriver", + Handler: _Control_CreateCsiDriver_Handler, + }, + { + MethodName: "GetCsiDriver", + Handler: _Control_GetCsiDriver_Handler, + }, + { + MethodName: "ListCsiDrivers", + Handler: _Control_ListCsiDrivers_Handler, + }, + { + MethodName: "UpdateCsiDriver", + Handler: _Control_UpdateCsiDriver_Handler, + }, + { + MethodName: "DeleteCsiDriver", + Handler: _Control_DeleteCsiDriver_Handler, + }, { MethodName: "CreateActorTemplate", Handler: _Control_CreateActorTemplate_Handler, diff --git a/api/infra/k8s/ate/v1/csidriverconfig_types.go b/api/infra/k8s/ate/v1/csidriverconfig_types.go index 4421086de9..084c200604 100644 --- a/api/infra/k8s/ate/v1/csidriverconfig_types.go +++ b/api/infra/k8s/ate/v1/csidriverconfig_types.go @@ -26,7 +26,7 @@ type CSIDriverConfigSpec struct { // +required // +kubebuilder:validation:MinLength=1 // +kubebuilder:validation:MaxLength=63 - // +kubebuilder:validation:Pattern=`^(substrate\.io/)?([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)$` + // +kubebuilder:validation:Pattern=`^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$` DriverName string `json:"driverName"` // controllerEndpoint is the gRPC endpoint for the CSI Controller service. @@ -98,7 +98,3 @@ type CSIDriverConfigList struct { metav1.ListMeta `json:"metadata,omitempty"` Items []CSIDriverConfig `json:"items"` } - -func init() { - SchemeBuilder.Register(&CSIDriverConfig{}, &CSIDriverConfigList{}) -} diff --git a/api/infra/k8s/ate/v1/groupversion_info.go b/api/infra/k8s/ate/v1/groupversion_info.go index 6339c64c1a..0dc1217ebe 100644 --- a/api/infra/k8s/ate/v1/groupversion_info.go +++ b/api/infra/k8s/ate/v1/groupversion_info.go @@ -18,8 +18,9 @@ package v1 import ( + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" - "sigs.k8s.io/controller-runtime/pkg/scheme" ) var ( @@ -28,13 +29,22 @@ var ( // SchemeGroupVersion is group version used to register these objects SchemeGroupVersion = GroupVersion - // SchemeBuilder is used to add go types to the GroupVersionKind scheme. - SchemeBuilder = &scheme.Builder{GroupVersion: GroupVersion} //nolint:staticcheck // SA1019: scheme.Builder is the conventional kubebuilder pattern for api packages. + schemeBuilder = runtime.NewSchemeBuilder(addKnownTypes) // AddToScheme adds the types in this group-version to the given scheme. - AddToScheme = SchemeBuilder.AddToScheme + AddToScheme = schemeBuilder.AddToScheme ) +func addKnownTypes(scheme *runtime.Scheme) error { + scheme.AddKnownTypes(GroupVersion, + &CSIDriverConfig{}, &CSIDriverConfigList{}, + &SandboxConfig{}, &SandboxConfigList{}, + &WorkerPool{}, &WorkerPoolList{}, + ) + metav1.AddToGroupVersion(scheme, GroupVersion) + return nil +} + // Resource takes an unqualified resource and returns a Group qualified GroupResource func Resource(resource string) schema.GroupResource { return SchemeGroupVersion.WithResource(resource).GroupResource() diff --git a/api/infra/k8s/ate/v1/sandboxconfig_types.go b/api/infra/k8s/ate/v1/sandboxconfig_types.go index 8329b6f03e..bd4cfa8378 100644 --- a/api/infra/k8s/ate/v1/sandboxconfig_types.go +++ b/api/infra/k8s/ate/v1/sandboxconfig_types.go @@ -211,7 +211,3 @@ type SandboxConfigList struct { metav1.ListMeta `json:"metadata,omitempty"` Items []SandboxConfig `json:"items"` } - -func init() { - SchemeBuilder.Register(&SandboxConfig{}, &SandboxConfigList{}) -} diff --git a/api/infra/k8s/ate/v1/workerpool_types.go b/api/infra/k8s/ate/v1/workerpool_types.go index f619b389c3..a0277cdbf5 100644 --- a/api/infra/k8s/ate/v1/workerpool_types.go +++ b/api/infra/k8s/ate/v1/workerpool_types.go @@ -78,7 +78,8 @@ type WorkerPoolPodTemplate struct { // serviceAccountName for the worker pods. The ServiceAccount must exist // in the WorkerPool's namespace. When omitted, the pods run as the - // "ateworker" ServiceAccount, which the controller creates. + // "ateworker" ServiceAccount, which the controller creates. Worker pods + // never get a ServiceAccount token, whichever ServiceAccount they use. // // +optional // +kubebuilder:validation:MinLength=1 @@ -288,7 +289,3 @@ type WorkerPoolList struct { metav1.ListMeta `json:"metadata,omitempty"` Items []WorkerPool `json:"items"` } - -func init() { - SchemeBuilder.Register(&WorkerPool{}, &WorkerPoolList{}) -} diff --git a/api/infra/k8s/ate/v1/zz_generated.deepcopy.go b/api/infra/k8s/ate/v1/zz_generated.deepcopy.go index 7c768dfe54..618775876f 100644 --- a/api/infra/k8s/ate/v1/zz_generated.deepcopy.go +++ b/api/infra/k8s/ate/v1/zz_generated.deepcopy.go @@ -21,7 +21,7 @@ package v1 import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - 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. diff --git a/benchmarking/atunnel/internal/workerhost/workerhost.go b/benchmarking/atunnel/internal/workerhost/workerhost.go index 232e0f4499..046ce4f0e6 100644 --- a/benchmarking/atunnel/internal/workerhost/workerhost.go +++ b/benchmarking/atunnel/internal/workerhost/workerhost.go @@ -29,6 +29,8 @@ import ( "strconv" "sync" + "go.opentelemetry.io/otel/metric/noop" + "go.ate.dev/substrate/internal/ateworker/actornet" "go.ate.dev/substrate/internal/atunnel" "go.ate.dev/substrate/internal/nodepath" @@ -40,7 +42,7 @@ import ( const Atespace = "bench" // ActorPort is where the ingress actor listens inside each sandbox: the port -// of actornet.ActorHTTPUpstream, which ingress proxies to. +// of the actor HTTP upstream, which ingress proxies to. const ActorPort = 80 // Sandbox is one hosted actor, as a process placing an ingress actor in it needs it. @@ -76,7 +78,7 @@ type actor struct { // Start starts atunnel from cfg, as a worker's main does, and hosts actors // actors whose egress tunnels to gatewayAddress. func Start(ctx context.Context, cfg atunnel.Config, actors int, gatewayAddress string) (*Host, error) { - t, err := atunnel.Start(ctx, cfg, actornet.ActorHTTPUpstream) + t, err := atunnel.Start(ctx, cfg, actornet.ActorHTTPUpstream, noop.Meter{}) if err != nil { return nil, err } diff --git a/benchmarking/automation/Dockerfile b/benchmarking/automation/Dockerfile index d981d1e1af..548defdfb4 100644 --- a/benchmarking/automation/Dockerfile +++ b/benchmarking/automation/Dockerfile @@ -62,9 +62,13 @@ RUN python3 -m venv /opt/automation/venv \ && /opt/automation/venv/bin/pip install --no-cache-dir -r /opt/automation/requirements.txt ENV PATH=/opt/automation/venv/bin:$PATH -COPY orchestrator.py util.py controlplane.py /opt/automation/ +COPY orchestrator.py util.py workers.py controlplane.py /opt/automation/ COPY testtypes/ /opt/automation/testtypes/ -COPY manifests/runner-job.yaml.tmpl manifests/nighthawk-ingress-runner-job.yaml.tmpl /opt/automation/manifests/ +COPY workloads/ /opt/automation/workloads/ +COPY manifests/runner-job.yaml.tmpl \ + manifests/nighthawk-ingress-runner-job.yaml.tmpl \ + manifests/nighthawk-egress-runner-job.yaml.tmpl \ + /opt/automation/manifests/ ENV PYTHONUNBUFFERED=1 diff --git a/benchmarking/automation/README.md b/benchmarking/automation/README.md index 0a5952d1be..315ac8f338 100644 --- a/benchmarking/automation/README.md +++ b/benchmarking/automation/README.md @@ -4,9 +4,12 @@ Scheduled, repeatable benchmark runs of a substrate branch. A CronJob on an **orchestration cluster** drives the full build/deploy/run/teardown cycle against a separate **test cluster**, once per entry in [tests.yaml](tests.yaml). Each run uploads results to GCS via `benchmarking/locust/runner.py` -(`type: locust`) or `benchmarking/nighthawk-ingress/runner.py` (`type: nighthawk-ingress`, +(`type: locust`), `benchmarking/nighthawk-ingress/runner.py` (`type: nighthawk-ingress`, the router capacity benchmark — see -[benchmarking/nighthawk-ingress/README.md](../nighthawk-ingress/README.md)). +[benchmarking/nighthawk-ingress/README.md](../nighthawk-ingress/README.md)), or +`benchmarking/nighthawk-egress/runner.py` (`type: nighthawk-egress`, the egress +gateway capacity benchmark, see +[benchmarking/nighthawk-egress/README.md](../nighthawk-egress/README.md)). To run the cold resume tests from your workstation instead, see [ateapi-cold-resume.md](ateapi-cold-resume.md). @@ -18,8 +21,9 @@ To run the cold resume tests from your workstation instead, see `gcloud container clusters get-credentials` for the test cluster. 3. Shallow-clones `--repo` at `--branch`, captures the commit hash. 4. `docker build && docker push` builds the runner image for each test type - in use, tagged with the commit hash: `${KO_DOCKER_REPO}/locust-test:` - and/or `${KO_DOCKER_REPO}/nighthawk-ingress-test:`. + in use, tagged with the commit hash: `${KO_DOCKER_REPO}/locust-test:`, + `${KO_DOCKER_REPO}/nighthawk-ingress-test:` and/or + `${KO_DOCKER_REPO}/nighthawk-egress-test:`. 5. `go run ./cmd/ate-setup deploy ate-system` (with `ATE_CREDENTIAL_PROVIDER` in `.ate-dev-env.sh`, or `--credential-provider` in the test's `ateArgs`; passes `--sandbox-classes=` so `deploy ate-system` @@ -40,10 +44,20 @@ To run the cold resume tests from your workstation instead, see requests=limits and Envoy's thread count to its own `envoyCpu`, then waits for the rollout before deploying workloads. The teardown after each test redeploys substrate, so the pin never outlives its run. + For a `nighthawk-egress` test `benchmarking/workloads/deploy.sh --deploy` + does not run (`USES_SHARED_WORKLOADS = False`). The orchestrator pins + `deployment/atenet-egress` to 1 replica with the cpu requests=limits of + `envoy` and `ext-proc` and Envoy's thread count at 1, runs + `hack/setup-e2e-egress-tls-kind.sh`, and deploys `nighthawk-server` and + the `nighthawk/tester` actor. The teardown after each test deletes them. 6. For each test in `tests.yaml`, or only those named by `--test-name`: - Submits a Job using the just-built image for the test's type (`runner-job.yaml.tmpl` for locust, - `nighthawk-ingress-runner-job.yaml.tmpl` for nighthawk-ingress). + `nighthawk-ingress-runner-job.yaml.tmpl` for nighthawk-ingress, + `nighthawk-egress-runner-job.yaml.tmpl` for nighthawk-egress). + Every Job gets `--run-ts`, one timestamp for the whole invocation, + which names where each run is stored, so all runs of an invocation + share their `run_ts=` path segment. A locust Job also gets `--metadata` with the target cluster's name, location and project, merged with the `BENCHMARK_METADATA` environment variable (a JSON object) if set. A `--metadata` in the test's own @@ -56,7 +70,8 @@ To run the cold resume tests from your workstation instead, see Each entry in `tests.yaml` may set `sandboxClass: gvisor | microvm` (default `gvisor`). This controls both `spec.sandboxClasses[0].name` on the benchmark WorkerPool -and its `workerImage` (`ateworker-gvisor` vs `ateworker-microvm`). +and its `workerImage` (`ateworker-gvisor` vs `ateworker-microvm`). `nighthawk-egress` +deploys its own gVisor rig and accepts only `gvisor`. For `microvm` tests the target cluster must have KVM-capable nodes. The orchestrator uploads the microVM assets, so its Workload Identity principal @@ -97,6 +112,51 @@ kubectl --context= -n substrate-benchmark \ To change the schedule, edit `spec.schedule` in `scratch/cronjob.yaml` (the default is `0 3 * * *`, 3am UTC). +## Running from a workstation + +Two flags replace the CronJob's clone and ConfigMap: + +- `--substrate-dir DIR` builds that checkout as it is, uncommitted changes + included, instead of cloning `--repo` at `--branch`. Passing `--repo` or + `--branch` with it is an error. A dirty tree tags its images and results + `-dirty-`. +- `--env-file FILE` sources that file for every test, whatever its + `targetCluster`, instead of `--target-cluster-dir/.sh`. + Passing `--target-cluster-dir` with it is an error. The checkout's own `.ate-dev-env.sh` is sourced where it is and left + alone; any other file is copied in as `.ate-dev-env.sh` for each test and + removed after it, and the run refuses to start if that would overwrite the + checkout's own file. + +Every test runs `ate-setup delete ate-system` and +`benchmarking/workloads/deploy.sh --delete` on the cluster the env file +names, both before and after it runs. Do not point it at a cluster you +share. The orchestrator runs `gcloud container clusters get-credentials` +into a kubeconfig of its own under a temporary directory, so your kubectl +context is not changed. Scripts that source `.ate-dev-env.sh` themselves, +such as `benchmarking/workloads/deploy.sh`, still use a `KUBECONFIG` that +file exports, so leave it out of the env file. Set up docker auth for the +env file's `KO_DOCKER_REPO` registry before you run it. + +You need Python 3.10 or newer, `docker`, `git`, Go, `gcloud` with the +`gke-gcloud-auth-plugin` component, and `kubectl` on the `PATH`. ko runs +from `hack/tools/ko` through `go tool`. The orchestrator polls `docker info` +first and fails if Docker is not running within 2 minutes. Relative paths +in flags resolve against your current directory. + +```bash +python3 -m venv benchmarking/automation/venv +benchmarking/automation/venv/bin/pip install -r benchmarking/automation/requirements.txt +benchmarking/automation/venv/bin/python -u benchmarking/automation/orchestrator.py \ + --substrate-dir . --env-file .ate-dev-env.sh \ + --dest gs:/// \ + --tests benchmarking/automation/tests.yaml --test-name +``` + +[ateapi-cold-resume.md](ateapi-cold-resume.md) walks through a complete run +of the cold resume tests this way. For a quicker loop that only rebuilds the +runner against a cluster that already has substrate, see +[benchmarking/nighthawk-ingress/run-dev.sh](../nighthawk-ingress/run-dev.sh). + ## Test cluster prerequisites Create the test cluster with the substrate-required beta APIs, Workload @@ -165,13 +225,18 @@ gcloud projects add-iam-policy-binding \ ``` **Runner Job pod** (KSA `benchmark-runner` in namespace `benchmarking` on the -test cluster's project) needs `roles/storage.objectUser` on the destination -bucket so `runner.py` can upload results: +test cluster's project) needs `roles/storage.objectCreator` on the destination +bucket so `runner.py` can upload results, and `roles/storage.objectViewer` so +that a `cel` input with a `from_test` can find and read that test's run (such as +the suite's 1-user run) under `--dest` (without it, the variable is +`invalid` and says why): ```bash RUNNER_PRINCIPAL="principal://iam.googleapis.com/projects//locations/global/workloadIdentityPools/.svc.id.goog/subject/ns/benchmarking/sa/benchmark-runner" gcloud storage buckets add-iam-policy-binding gs:// \ --role=roles/storage.objectCreator --member="${RUNNER_PRINCIPAL}" +gcloud storage buckets add-iam-policy-binding gs:// \ + --role=roles/storage.objectViewer --member="${RUNNER_PRINCIPAL}" ``` ## Updating tests diff --git a/benchmarking/automation/ateapi-cold-resume.md b/benchmarking/automation/ateapi-cold-resume.md index 6264d520e7..ad790ddaf6 100644 --- a/benchmarking/automation/ateapi-cold-resume.md +++ b/benchmarking/automation/ateapi-cold-resume.md @@ -48,10 +48,8 @@ once as in [Prometheus + Grafana](../README.md#optional-prometheus--grafana). ## 3. Workstation -You need `gcloud`, `kubectl`, `docker`, Go, and Python 3 with PyYAML. ko -runs from `hack/tools/ko` through `go tool`, so it need not be installed. -The orchestrator polls `docker info` first and fails if Docker is not -running within 2 minutes. +You need the tools listed in +[Running from a workstation](README.md#running-from-a-workstation). ```bash python3 -m venv benchmarking/automation/venv @@ -80,12 +78,10 @@ header comments in `tests.yaml` describe the fields, such as `poolMaxConns`, keep within Postgres's connection slots as described in [Running at scale](../README.md#running-at-scale). -## 5. Target cluster file +## 5. Env file -The orchestrator copies `.sh` from the `--target-cluster-dir` -directory into the clone as `.ate-dev-env.sh`. Both tests use -`targetCluster: dev`, so step 6 copies your `.ate-dev-env.sh` there as -`dev.sh`. Create it from +`--env-file` points the orchestrator at your `.ate-dev-env.sh` for every +test. Create it from the GKE [ate-dev-env.sh.example](https://github.com/ai-on-gke/substrate-gke/blob/main/tools/setup-gcp/ate-dev-env.sh.example) in substrate-gke if you don't have one. The install needs `PROJECT_ID`, `CLUSTER_NAME`, `CLUSTER_LOCATION`, `KO_DOCKER_REPO`, `SNAPSHOT_LOCATION`, @@ -93,35 +89,19 @@ if you don't have one. The install needs `PROJECT_ID`, `CLUSTER_NAME`, ## 6. Run -The orchestrator clones `--branch` from `--repo`, so commit your changes -first. A `file://` URL clones your local checkout. Set `SUBSTRATE_DIR` to a -directory that does not exist yet, because the default is the pod path -`/workspace/substrate`. The orchestrator runs `gcloud container clusters -get-credentials`, so point `KUBECONFIG` at a separate file to keep your -current context: +`--substrate-dir` builds this checkout as it is, uncommitted changes +included. See [Running from a workstation](README.md#running-from-a-workstation) +for what the two flags do and what the run deletes on the cluster. ```bash -S=$PWD # this checkout D=$HOME/bench-runs/cold-$(date +%Y%m%d-%H%M) -mkdir -p $D/target-clusters -cp $S/.ate-dev-env.sh $D/target-clusters/dev.sh -export KUBECONFIG=$D/kubeconfig - -cat > $D/run.py </ \ - --tests $S/benchmarking/automation/tests.yaml \ + --tests benchmarking/automation/tests.yaml \ --test-name ateapi_cold_resume_pause_fake_smoke \ - --target-cluster-dir $D/target-clusters \ - --manifests-dir $S/benchmarking/automation/manifests \ --junit-output $D/junit.xml 2>&1 | tee $D/orchestrator.log ``` diff --git a/benchmarking/automation/manifests/nighthawk-egress-runner-job.yaml.tmpl b/benchmarking/automation/manifests/nighthawk-egress-runner-job.yaml.tmpl new file mode 100644 index 0000000000..56c724a1b1 --- /dev/null +++ b/benchmarking/automation/manifests/nighthawk-egress-runner-job.yaml.tmpl @@ -0,0 +1,267 @@ +# Copyright 2026 The Agent Substrate 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. + +# Template rendered per test by orchestrator.py for `type: nighthawk-egress` +# entries. Shares the `benchmarking` namespace + `benchmark-runner` +# ServiceAccount with runner-job.yaml.tmpl so the same GKE Workload Identity +# binding grants GCS write access. +apiVersion: v1 +kind: Namespace +metadata: + name: benchmarking + labels: + ate.dev/api-access: "true" +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: benchmark-runner + namespace: benchmarking +--- +# Config of the `invoker` sidecar in the Job below, which runs as benchmark-runner: +# In-cluster Envoy proxy that listens for plaintext HTTP/1.1 and HTTP/2 +# (h2c/gRPC) on 127.0.0.1:19980, injects `ate-target-actor: nighthawk/tester` on every +# request, and forwards upstream over mTLS to +# atenet-router.ate-system.svc.cluster.local:443 using a SPIFFE client +# certificate issued by podidentity.podcert.ate.dev/identity. +# +# TODO(yanavlasov): this is a temporary workaround for nighthawk's cli's inability +# to add headers when invoking traffic driver gRPC service. So this Envoy adds the +# `ate-target-actor: nighthawk/tester` header so that cli can reach the traffic driver. +apiVersion: v1 +kind: ConfigMap +metadata: + name: traffic-driver-invoker + namespace: benchmarking +data: + envoy.yaml: | + # SDS requires a node id and cluster. + node: + id: traffic-driver-invoker + cluster: traffic-driver-invoker + + static_resources: + listeners: + - name: listener_http_19980 + address: + socket_address: + address: 127.0.0.1 + port_value: 19980 + listener_filters: + - name: envoy.filters.listener.http_inspector + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.listener.http_inspector.v3.HttpInspector + filter_chains: + - filters: + - name: envoy.filters.network.http_connection_manager + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager + stat_prefix: ingress_http_19980 + codec_type: AUTO + route_config: + name: local_route + request_headers_to_add: + - header: + key: ate-target-actor + value: nighthawk/tester + append_action: OVERWRITE_IF_EXISTS_OR_ADD + virtual_hosts: + - name: backend + domains: ["*"] + routes: + - match: + prefix: "/" + route: + cluster: atenet_router + timeout: 0s + http_filters: + - name: envoy.filters.http.router + typed_config: + "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router + + clusters: + - name: atenet_router + type: STRICT_DNS + connect_timeout: 5s + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + use_downstream_protocol_config: + http_protocol_options: {} + http2_protocol_options: {} + transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext + sni: atenet-router.ate-system.svc + common_tls_context: + tls_certificate_sds_secret_configs: + - name: podidentity_client_cert + sds_config: + resource_api_version: V3 + path_config_source: + path: /etc/envoy/sds-podidentity-cert.yaml + combined_validation_context: + default_validation_context: + match_typed_subject_alt_names: + - san_type: DNS + matcher: + exact: atenet-router.ate-system.svc + validation_context_sds_secret_config: + name: servicedns_validation_context + sds_config: + resource_api_version: V3 + path_config_source: + path: /etc/envoy/sds-servicedns-validation.yaml + load_assignment: + cluster_name: atenet_router + endpoints: + - lb_endpoints: + - endpoint: + address: + socket_address: + address: atenet-router.ate-system.svc.cluster.local + port_value: 443 + sds-podidentity-cert.yaml: | + resources: + - "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.Secret + name: podidentity_client_cert + tls_certificate: + certificate_chain: { filename: /run/podidentity.podcert.ate.dev/credential-bundle.pem } + private_key: { filename: /run/podidentity.podcert.ate.dev/credential-bundle.pem } + watched_directory: { path: /run/podidentity.podcert.ate.dev } + sds-servicedns-validation.yaml: | + resources: + - "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.Secret + name: servicedns_validation_context + validation_context: + trusted_ca: { filename: /run/servicedns-ca/ca.crt } + watched_directory: { path: /run/servicedns-ca } +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: ${JOB_NAME} + namespace: benchmarking +spec: + backoffLimit: 0 + ttlSecondsAfterFinished: 86400 + template: + metadata: + labels: + app: substrate-benchmark-runner + benchmark: nighthawk-egress + test-name: "${NAME}" + tag: "${TAG}" + spec: + serviceAccountName: benchmark-runner + restartPolicy: Never + tolerations: + - key: ate.dev/benchmarking + operator: Equal + value: "true" + effect: NoSchedule + securityContext: + runAsUser: 65532 + runAsGroup: 65532 + runAsNonRoot: true + fsGroup: 65532 + seccompProfile: + type: RuntimeDefault + initContainers: + - name: invoker + # Same envoyproxy/envoy digest as cmd/dataplane/envoy/Dockerfile. + image: envoyproxy/envoy:v1.40.0@sha256:459f2a6404c340fe6afccd69d85527012d47f3c036765493e6f8f3113fa384de + restartPolicy: Always + command: + - /usr/local/bin/envoy + args: + - -c + - /etc/envoy/envoy.yaml + - --concurrency + - "1" + securityContext: + allowPrivilegeEscalation: false + readOnlyRootFilesystem: true + capabilities: + drop: + - ALL + # No probe: the kubelet cannot reach the loopback listener. runner.py + # waits for the port. + volumeMounts: + - name: invoker-config + mountPath: /etc/envoy + readOnly: true + - name: podidentity + mountPath: /run/podidentity.podcert.ate.dev + readOnly: true + - name: servicedns-ca + mountPath: /run/servicedns-ca + readOnly: true + containers: + - name: runner + image: ${IMAGE} + imagePullPolicy: IfNotPresent + command: + - "python3" + - "/app/runner.py" + securityContext: + allowPrivilegeEscalation: false + capabilities: + drop: + - ALL + args: + - "--name" + - "${NAME}" + - "--tag" + - "${TAG}" + - "--dest" + - "${DEST}" + - "--run-ts" + - "${RUN_TS}" + - "--envoy-cpu" + - "${ENVOY_CPU}" + - "--mode" + - "${MODE}" + volumeMounts: + - name: servicedns-ca + mountPath: /run/servicedns-ca + readOnly: true + resources: + requests: + cpu: "1" + memory: "1Gi" + limits: + cpu: "2" + memory: "2Gi" + volumes: + - name: invoker-config + configMap: + name: traffic-driver-invoker + - name: podidentity + projected: + sources: + - podCertificate: + signerName: podidentity.podcert.ate.dev/identity + keyType: ECDSAP256 + credentialBundlePath: credential-bundle.pem + - name: servicedns-ca + projected: + sources: + - clusterTrustBundle: + signerName: servicedns.podcert.ate.dev/identity + labelSelector: + matchLabels: + podcert.ate.dev/canarying: live + path: ca.crt diff --git a/benchmarking/automation/manifests/nighthawk-ingress-runner-job.yaml.tmpl b/benchmarking/automation/manifests/nighthawk-ingress-runner-job.yaml.tmpl index b51a89de9c..48b4bac847 100644 --- a/benchmarking/automation/manifests/nighthawk-ingress-runner-job.yaml.tmpl +++ b/benchmarking/automation/manifests/nighthawk-ingress-runner-job.yaml.tmpl @@ -82,6 +82,8 @@ spec: - "${TAG}" - "--dest" - "${DEST}" + - "--run-ts" + - "${RUN_TS}" - "--envoy-cpu" - "${ENVOY_CPU}" - "--actors" diff --git a/benchmarking/automation/manifests/runner-job.yaml.tmpl b/benchmarking/automation/manifests/runner-job.yaml.tmpl index 9f9eb86d3e..487d410c54 100644 --- a/benchmarking/automation/manifests/runner-job.yaml.tmpl +++ b/benchmarking/automation/manifests/runner-job.yaml.tmpl @@ -14,7 +14,7 @@ # Per-test Job manifest. Rendered by orchestrator.py at runtime; placeholders # (${JOB_NAME}, ${IMAGE}, ${TEST_FILE}, ${DURATION}, ${USERS}, ${TAG}, -# ${NAME}, ${DEST}) are substituted before kubectl apply. +# ${NAME}, ${DEST}, ${RUN_TS}) are substituted before kubectl apply. apiVersion: v1 kind: Namespace @@ -172,6 +172,8 @@ spec: - "${NAME}" - "--dest" - "${DEST}" + - "--run-ts" + - "${RUN_TS}" env: - name: OTEL_EXPORTER_OTLP_ENDPOINT value: http://opentelemetry-collector.gke-managed-otel.svc.cluster.local:4317 diff --git a/benchmarking/automation/orchestrator.py b/benchmarking/automation/orchestrator.py index 2bd6c6db3c..4a32aba7d3 100644 --- a/benchmarking/automation/orchestrator.py +++ b/benchmarking/automation/orchestrator.py @@ -20,29 +20,34 @@ 1. Pick the tests.yaml entries named by --test-name (default: all) and validate them before any other work [hook: validate]. - 2. Clone the substrate branch once; wait for the DIND sidecar. + 2. Wait for docker; clone the substrate branch once, or build + --substrate-dir as it is. Check every test's workloads against the + checkout before any cluster work [hook: check_workloads]. 3. Per test entry: - a. Source the target cluster's env; gcloud/docker/kubectl setup and - the runner image build [hook: build_image] are cached per - target cluster. + a. Source the target cluster's env file, or --env-file; gcloud/ + docker/kubectl setup and the runner image build [hook: + build_image] are cached per env file. b. Sweep leftovers, deploy substrate, let the type shape the - cluster [hook: pre_test], deploy workloads (+ microvm deps when - the sandbox class needs them). + cluster [hook: pre_test], install the test's workloads + [hook: workloads]. c. Render the type's Job template [hooks: job_tmpl, job_subs], submit it, wait, tail logs, delete the Job. - d. Tear substrate + workloads down again so tests don't pollute - each other, then drop the env file so the next test can't - inherit this one's cluster. + d. Tear substrate + workloads down again [hook: + teardown_workloads] so tests don't pollute each other, then drop + the copied env file so the next test can't inherit this one's + cluster. 4. Exit non-zero if any test didn't complete. """ import argparse +import atexit import json import os import re import shutil import subprocess import sys +import tempfile import time import uuid import xml.etree.ElementTree as ET @@ -56,31 +61,38 @@ from util import ( isolate_block, isolate_install_args, - isolate_workload_args, parse_duration_seconds, run, run_no_check, ) +from workers import SANDBOX_CLASSES SUBSTRATE_DIR = "/workspace/substrate" TARGET_CLUSTER_DIR = "/etc/orchestrator/target-clusters" ENV_FILE_NAME = ".ate-dev-env.sh" -MANIFESTS_DIR = "/opt/automation/manifests" +# The runner Job templates ship next to this script, both in the image and +# in the checkout. +MANIFESTS_DIR = str(Path(__file__).resolve().parent / "manifests") NAMESPACE = "benchmarking" TEST_TYPES = tuple(TYPES) -# Snapshot the process's initial env so apply_config can return to a known -# baseline before sourcing the next config (avoids stale vars carrying over -# from a prior test if that test's config defined keys the next one doesn't). +# Snapshot the process's initial env so apply_env_file can return to a known +# baseline before sourcing the next env file (avoids stale vars carrying over +# from a prior test if that test's env file defined keys the next one doesn't). _ORIG_ENV = dict(os.environ) -def parse_args() -> argparse.Namespace: +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: p = argparse.ArgumentParser(description=__doc__) - p.add_argument("--repo", required=True, help="Git URL of substrate repo to clone") - p.add_argument("--branch", default="main", help="Branch to benchmark") + p.add_argument("--repo", help="Git URL of substrate repo to clone") + p.add_argument("--branch", help="Branch to benchmark (default: main)") + p.add_argument( + "--substrate-dir", + help="Build this checkout as it is, uncommitted changes included, " + "instead of cloning --repo", + ) p.add_argument( "--dest", required=True, @@ -100,8 +112,14 @@ def parse_args() -> argparse.Namespace: ) p.add_argument( "--target-cluster-dir", - default=TARGET_CLUSTER_DIR, - help="Directory containing target cluster configuration scripts (.sh)", + help="Directory containing target cluster configuration scripts " + f"(.sh); default {TARGET_CLUSTER_DIR}", + ) + p.add_argument( + "--env-file", + help="Source this file for every test, whatever its targetCluster, " + "instead of --target-cluster-dir/.sh; for example a " + f"checkout's own {ENV_FILE_NAME}", ) p.add_argument( "--manifests-dir", @@ -112,7 +130,62 @@ def parse_args() -> argparse.Namespace: "--junit-output", help="Path to write a JUnit XML report summarizing test results and durations", ) - return p.parse_args() + args = p.parse_args(argv) + # Reject flags the chosen mode would ignore. + if args.substrate_dir: + if args.repo or args.branch: + p.error("--substrate-dir cannot be combined with --repo or --branch") + # .git is a file in a worktree, so test for either. + if not os.path.exists(os.path.join(args.substrate_dir, ".git")): + p.error(f"--substrate-dir {args.substrate_dir} is not a git checkout") + elif not args.repo: + p.error("one of --repo or --substrate-dir is required") + else: + args.branch = args.branch or "main" + if args.env_file: + if args.target_cluster_dir: + p.error("--env-file cannot be combined with --target-cluster-dir") + else: + args.target_cluster_dir = args.target_cluster_dir or TARGET_CLUSTER_DIR + # main chdirs into the substrate checkout, so keep paths relative to the + # caller's cwd meaning what the caller meant. + for name in ( + "substrate_dir", + "tests", + "target_cluster_dir", + "env_file", + "manifests_dir", + "junit_output", + ): + if getattr(args, name): + setattr(args, name, os.path.abspath(getattr(args, name))) + return args + + +def env_file_for(test: dict[str, Any], args: argparse.Namespace) -> Path: + """The env file a test runs with: --env-file, or the test's + targetCluster under --target-cluster-dir.""" + if args.env_file: + return Path(args.env_file) + return Path(args.target_cluster_dir) / f"{test['targetCluster']}.sh" + + +def check_env_files( + tests: list[dict[str, Any]], args: argparse.Namespace, substrate_dir: str +) -> None: + """Fail fast (ValueError) before any docker or cluster work on a missing + --env-file, and on a checkout whose own .ate-dev-env.sh a copied env + file would overwrite. A missing target cluster file fails only the tests + that name it, in main's loop.""" + if args.env_file and not Path(args.env_file).exists(): + raise ValueError(f"env file not found: {args.env_file}") + files = {env_file_for(t, args) for t in tests} + own = Path(substrate_dir) / ENV_FILE_NAME + if own.exists() and any(not is_own_env_file(f, substrate_dir) for f in files): + raise ValueError( + f"{own} exists and a test would overwrite it; pass it as " + "--env-file or move it away" + ) def select_tests(tests: list[dict], names: list[str]) -> list[dict]: @@ -129,63 +202,65 @@ def select_tests(tests: list[dict], names: list[str]) -> list[dict]: def source_env(path: str) -> None: + # env -0: a developer shell exports multi-line bash functions, which + # newline splitting would turn into bogus keys. result = subprocess.run( - ["bash", "-c", f'set -a; source "{path}"; env'], + ["bash", "-c", f'set -a; source "{path}"; env -0'], check=True, capture_output=True, text=True, ) - for line in result.stdout.splitlines(): - if "=" not in line: + for entry in result.stdout.split("\0"): + if "=" not in entry: continue - k, _, v = line.partition("=") + k, _, v = entry.partition("=") os.environ[k] = v -def apply_target_cluster( - target_cluster: str, target_cluster_dir: str = TARGET_CLUSTER_DIR -) -> None: - """Copy target_cluster_dir/.sh into the cloned - substrate repo as .ate-dev-env.sh (so ate-setup / deploy.sh source - it) and merge it into this process's env (so the orchestrator's own - gcloud / docker / kubectl calls see the same values). Resets os.environ - to the startup baseline first so vars defined by a previous target - cluster don't bleed into the next one.""" - src = Path(target_cluster_dir) / f"{target_cluster}.sh" - if not src.exists(): - raise FileNotFoundError( - f"target cluster {target_cluster!r} not found at {src}" - ) +def is_own_env_file(src: Path, substrate_dir: str) -> bool: + """Whether src is substrate_dir's own .ate-dev-env.sh. That file is + sourced where it is and left alone; any other env file is copied in for + the test and removed after it.""" + return src.resolve() == (Path(substrate_dir) / ENV_FILE_NAME).resolve() + + +def apply_env_file(src: Path, substrate_dir: str = SUBSTRATE_DIR) -> None: + """Install src as the substrate checkout's .ate-dev-env.sh (so ate-setup + / deploy.sh source it) and merge it into this process's env (so the + orchestrator's own gcloud / docker / kubectl calls see the same values). + Resets os.environ to the startup baseline first so vars defined by a + previous env file don't bleed into the next one.""" os.environ.clear() os.environ.update(_ORIG_ENV) - dst = Path(SUBSTRATE_DIR) / ENV_FILE_NAME - shutil.copy(src, dst) + dst = Path(substrate_dir) / ENV_FILE_NAME + if not is_own_env_file(src, substrate_dir): + shutil.copy(src, dst) source_env(str(dst)) for k in ("PROJECT_ID", "CLUSTER_NAME", "CLUSTER_LOCATION", "KO_DOCKER_REPO"): if not os.environ.get(k): - raise RuntimeError( - f"{k} not set after sourcing target cluster {target_cluster!r}" - ) + raise RuntimeError(f"{k} not set after sourcing {src}") -def clear_target_cluster() -> None: - dst = Path(SUBSTRATE_DIR) / ENV_FILE_NAME - if dst.exists(): +def clear_env_file(src: Path, substrate_dir: str = SUBSTRATE_DIR) -> None: + dst = Path(substrate_dir) / ENV_FILE_NAME + if not is_own_env_file(src, substrate_dir) and dst.exists(): dst.unlink() -def gcloud_setup_for_target_cluster() -> None: - """Per-target-cluster gcloud setup: configure docker creds for the new - registry and switch kubectl to the new cluster.""" - run( - [ - "gcloud", - "auth", - "configure-docker", - registry_host(os.environ["KO_DOCKER_REPO"]), - "--quiet", - ] - ) +def gcloud_setup_for_target_cluster(configure_docker: bool) -> None: + """Per-target-cluster gcloud setup: switch kubectl to the new cluster + and, when configure_docker is set, configure docker creds for the new + registry.""" + if configure_docker: + run( + [ + "gcloud", + "auth", + "configure-docker", + registry_host(os.environ["KO_DOCKER_REPO"]), + "--quiet", + ] + ) run( [ "gcloud", @@ -219,7 +294,7 @@ def _json_object(raw: str, what: str) -> dict[str, Any]: def run_metadata() -> dict[str, Any]: """Free-form run facts handed to the runner as --metadata. - Read per test, after apply_target_cluster has reset os.environ; + Read per test, after apply_env_file has reset os.environ; BENCHMARK_METADATA survives that reset because it is part of the startup env (_ORIG_ENV). """ @@ -263,15 +338,28 @@ def split_metadata_flag(test: dict[str, Any]) -> tuple[list[Any], dict[str, Any] def wait_for_docker(timeout: int = 120) -> None: - print("Waiting for DIND sidecar...", flush=True) + """Poll docker info: the CronJob's DIND sidecar starts alongside the + orchestrator, and a workstation's Docker may still be starting too.""" + print("Waiting for docker...", flush=True) start = time.time() while time.time() - start < timeout: r = subprocess.run(["docker", "info"], capture_output=True) if r.returncode == 0: - print("DIND ready.", flush=True) + print("docker ready.", flush=True) return time.sleep(2) - raise RuntimeError("DIND sidecar did not become ready within timeout") + raise RuntimeError(f"docker did not become ready within {timeout}s") + + +def build_tag(substrate_dir: str) -> str: + """HEAD's commit, labeling the runner image and the results. Uncommitted + changes get a unique -dirty suffix: the Job templates pull IfNotPresent, + so a tag reused for different content would run a stale image.""" + git = ["git", "-C", substrate_dir] + commit = subprocess.check_output([*git, "rev-parse", "HEAD"], text=True).strip() + if subprocess.check_output([*git, "status", "--porcelain"], text=True).strip(): + commit += f"-dirty-{uuid.uuid4().hex[:6]}" + return commit def registry_host(ko_docker_repo: str) -> str: @@ -374,13 +462,15 @@ def wait_for_job(name: str, timeout_seconds: int) -> str: return "timeout" -SANDBOX_CLASSES = ("gvisor", "microvm") - - def validate_and_normalize_tests(tests: list[dict[str, Any]]) -> None: """Fail fast (ValueError) on malformed entries, before any cluster work: the type-independent fields here, everything else via the type's validate hook.""" + names = [t.get("name") for t in tests] + duplicates = sorted({n for n in names if names.count(n) > 1}, key=str) + if duplicates: + # A run is stored under its test's name and the invocation's run_ts. + raise ValueError(f"test names must be unique: {', '.join(map(str, duplicates))}") for t in tests: name = t.get("name") if not t.get("targetCluster"): @@ -406,6 +496,9 @@ def validate_and_normalize_tests(tests: list[dict[str, Any]]) -> None: if ttype == "locust": # A malformed --metadata fails here rather than mid-sweep. split_metadata_flag(t) + elif "evaluations" in t: + # Only the locust runner judges evaluations (runner.py --test-entry). + raise ValueError(f"test {name!r}: 'evaluations' is supported only for type locust") isolate_block(t) @@ -445,49 +538,12 @@ def teardown_substrate() -> None: run_no_check(["go", "run", "./cmd/ate-setup", "delete", "ate-system"]) -def deploy_workloads( - worker_count: int = 1, - sandbox_class: str = "gvisor", - actor_memory: str = "", - wait_timeout_secs: int | str = "", - worker_memory: str = "", - fake_atelet_args: Iterable[str] = (), - actor_cpu: str = "", -) -> None: - cmd = [ - "benchmarking/workloads/deploy.sh", - "--deploy", - "--worker-count", - str(worker_count), - "--sandbox-class", - sandbox_class, - ] - # Empty keeps the default in workloads/deploy.sh (256Mi); RAM-consuming - # suites set actorMemory in tests.yaml. - if actor_memory: - cmd += ["--actor-memory", actor_memory] - # Empty keeps the default in workloads/deploy.sh (1 CPU). The scheduler - # books the limit against worker CPU capacity, so dense suites set - # actorCPU in tests.yaml to fit more actors per worker. - # str() because a whole number of cores (actorCPU: 1) parses as an int. - if actor_cpu: - cmd += ["--actor-cpu", str(actor_cpu)] - # Empty leaves the worker pods unsized; set workerMemory in tests.yaml to - # control how many workers the scheduler packs onto a node. - if worker_memory: - cmd += ["--worker-memory", worker_memory] - # Empty keeps deploy.sh's own default; large fleets set workerWaitTimeout - # (whole seconds). - if wait_timeout_secs != "": - cmd += ["--wait-timeout", str(wait_timeout_secs)] - # An isolate block's tuning of fake-atelet, on the fake data plane. - cmd += list(fake_atelet_args) - # deploy.sh itself blocks until every template's golden snapshot exists. - run(cmd) - - -def teardown_workloads() -> None: - run_no_check(["benchmarking/workloads/deploy.sh", "--delete"]) +def teardown_test_workloads(test_types: Iterable[str]) -> None: + types = list(test_types) + if any(TYPES[t].USES_SHARED_WORKLOADS for t in types): + run_no_check(["benchmarking/workloads/deploy.sh", "--delete"]) + for t in types: + TYPES[t].teardown_workloads() def run_test( @@ -495,6 +551,7 @@ def run_test( image: str, dest: str, commit: str, + run_ts: int, manifests_dir: str = MANIFESTS_DIR, ) -> str: name = test["name"] @@ -505,6 +562,7 @@ def run_test( "TAG": commit, "NAME": name, "DEST": dest, + "RUN_TS": run_ts, } mod = TYPES[test_type(test)] tmpl = mod.job_tmpl(manifests_dir) @@ -516,6 +574,9 @@ def run_test( if test_type(test) == "locust": flags, own = split_metadata_flag(test) flags += ["--metadata", json.dumps({**run_metadata(), **own})] + # The whole entry, so runner features (such as observers or evaluations) + # read what they need without adding a new flag per field. + flags += ["--test-entry", json.dumps(test)] manifest = render_template(tmpl, subs, flags) wait_for_no_active_runners() print(f"Submitting Job {job}", flush=True) @@ -575,6 +636,7 @@ def write_junit_xml( def main() -> None: args = parse_args() + substrate_dir = args.substrate_dir or SUBSTRATE_DIR tests = yaml.safe_load(Path(args.tests).read_text())["tests"] try: tests = select_tests(tests, args.test_name) @@ -582,93 +644,112 @@ def main() -> None: validate_and_normalize_tests(tests) # Checks BENCHMARK_METADATA only; cluster vars may not be set yet. run_metadata() + check_env_files(tests, args, substrate_dir) except ValueError as e: sys.exit(str(e)) - # Config-independent setup: DIND + clone the substrate branch once. + # gcloud get-credentials writes the cluster into KUBECONFIG and makes it + # the current context, so give the run its own file rather than the + # caller's ~/.kube/config. Set in _ORIG_ENV too, so it survives + # apply_env_file's reset. + kubeconfig_dir = tempfile.TemporaryDirectory(prefix="orchestrator-") + atexit.register(kubeconfig_dir.cleanup) + kubeconfig = str(Path(kubeconfig_dir.name) / "kubeconfig") + _ORIG_ENV["KUBECONFIG"] = os.environ["KUBECONFIG"] = kubeconfig + + # Every run of this invocation is stored under this timestamp (runner.py + # --run-ts), so a run finds another test's run of the invocation by it. + run_ts = int(time.time()) + print(f"Storing runs under run_ts={run_ts}", flush=True) + + # Config-independent setup: docker, then the substrate checkout. wait_for_docker() - run( - [ - "git", - "clone", - "--depth", - "1", - "--branch", - args.branch, - args.repo, - SUBSTRATE_DIR, - ] - ) - os.chdir(SUBSTRATE_DIR) - commit = subprocess.check_output(["git", "rev-parse", "HEAD"], text=True).strip() - print(f"Building commit {commit}", flush=True) - - # Per-target-cluster caches: re-running setup for the same target - # cluster is wasted work, so we track what was last set up and only - # redo it when the target cluster name changes (substrate images get - # rebuilt by ate-setup each test anyway via ko). Runner - # images are built lazily per test type, so a locust-only tests.yaml - # never builds the nighthawk image and vice versa. - last_target = None + if not args.substrate_dir: + run( + [ + "git", + "clone", + "--depth", + "1", + "--branch", + args.branch, + args.repo, + substrate_dir, + ] + ) + os.chdir(substrate_dir) + # Stubs come from the checkout, so they can only be checked now. A + # problem fails every test that uses the stub, so stop before the loop. + try: + for t in tests: + TYPES[test_type(t)].check_workloads(t) + except ValueError as e: + sys.exit(str(e)) + tag = build_tag(substrate_dir) + print(f"Building {tag} from {substrate_dir}", flush=True) + + # Per-env-file caches: re-running setup for the same env file is + # wasted work, so we track what was last set up and only redo it when + # the env file changes (substrate images get rebuilt by ate-setup each + # test anyway via ko). Runner images are built lazily per test type, so + # a locust-only tests.yaml never builds the nighthawk image and vice + # versa. + last_env_file = None images: dict[str, str] = {} results = [] for i, test in enumerate(tests): - target_cluster = test["targetCluster"] + env_file = env_file_for(test, args) print( - f"\n=== test {i + 1}/{len(tests)}: {test['name']} (targetCluster={target_cluster}) ===", + f"\n=== test {i + 1}/{len(tests)}: {test['name']} (env file {env_file}) ===", flush=True, ) try: - apply_target_cluster(target_cluster, args.target_cluster_dir) + apply_env_file(env_file, substrate_dir) except Exception as e: - print( - f"Failed to apply target cluster {target_cluster!r}: {e}", - flush=True, - ) + print(f"Failed to apply env file {env_file}: {e}", flush=True) results.append((test["name"], "config-error", 0.0, str(e))) + clear_env_file(env_file, substrate_dir) continue + # The env file may export a KUBECONFIG of its own. + os.environ["KUBECONFIG"] = kubeconfig try: - if target_cluster != last_target: - gcloud_setup_for_target_cluster() + if env_file != last_env_file: + # A --substrate-dir run pushes with the docker auth the + # caller already has. + gcloud_setup_for_target_cluster( + configure_docker=not args.substrate_dir + ) images = {} - last_target = target_cluster + last_env_file = env_file ttype = test_type(test) if ttype not in images: - images[ttype] = TYPES[ttype].build_image(commit) + images[ttype] = TYPES[ttype].build_image(tag) # Idempotent sweep before anything else: a previous CronJob # fire that crashed mid-test (or any other process that left # state behind) would otherwise leak its substrate + workloads # into this run. All teardowns use --ignore-not-found, so # this is cheap on a clean cluster. - teardown_workloads() + teardown_test_workloads(TYPES) teardown_substrate() - sandbox_class = test.get("sandboxClass", "gvisor") status = "error" failure_msg = None start_time = time.time() try: deploy_substrate(substrate_args(test)) TYPES[ttype].pre_test(test) - deploy_workloads( - test.get("workerCount", 1), - sandbox_class, - test.get("actorMemory", ""), - test.get("workerWaitTimeout", ""), - test.get("workerMemory", ""), - isolate_workload_args(test), - test.get("actorCPU", ""), - ) + TYPES[ttype].workloads(test) try: status = run_test( test, images[ttype], args.dest, - commit, + tag, + run_ts, args.manifests_dir, ) if status != "complete": @@ -682,15 +763,15 @@ def main() -> None: finally: # Always tear down, even if deploy or run failed, so the # next test (and the next CronJob fire) starts clean. - teardown_workloads() + teardown_test_workloads([ttype]) teardown_substrate() duration = time.time() - start_time results.append((test["name"], status, duration, failure_msg)) finally: - # Drop .ate-dev-env.sh so the next test cannot accidentally - # inherit this one's cluster/project if the next - # apply_target_cluster fails partway through. - clear_target_cluster() + # Drop the copied .ate-dev-env.sh so the next test cannot + # accidentally inherit this one's cluster/project if the next + # apply_env_file fails partway through. + clear_env_file(env_file, substrate_dir) print("\n=== summary ===", flush=True) failed = 0 diff --git a/benchmarking/automation/test_locust.py b/benchmarking/automation/test_locust.py index fec0aad397..2044b4257a 100644 --- a/benchmarking/automation/test_locust.py +++ b/benchmarking/automation/test_locust.py @@ -16,7 +16,10 @@ python3 benchmarking/automation/test_locust.py""" import os +import sys +import tempfile import unittest +from pathlib import Path from unittest import mock import yaml @@ -25,6 +28,8 @@ import orchestrator from testtypes import locust +REPO_ROOT = Path(__file__).resolve().parents[2] + def entry(**fields): return { @@ -60,6 +65,13 @@ def test_missing_required(self): with self.assertRaises(ValueError): locust.validate(test) + # Shape only: the runner validates the rest (benchmarking/evaluate). + def test_evaluations_shape(self): + locust.validate(entry(evaluations=[{"name": "e", "anything": "else"}])) + for bad in ({"evaluations": {"name": "e"}}, {"evaluations": [{"name": ""}]}, {"evaluations": ["e"]}): + with self.subTest(bad=bad), self.assertRaisesRegex(ValueError, "locust test 't': evaluations must"): + locust.validate(entry(**bad)) + class PreTestTest(unittest.TestCase): def shaped(self, test): @@ -80,7 +92,7 @@ def test_shapes_the_control_plane(self): class JobTest(unittest.TestCase): def render(self, test): subs = { - "JOB_NAME": "j", "NAME": "t", "TAG": "c", "IMAGE": "i", "DEST": "d", + "JOB_NAME": "j", "NAME": "t", "TAG": "c", "IMAGE": "i", "DEST": "d", "RUN_TS": 1, **locust.job_subs(test), } tmpl = locust.job_tmpl(os.path.join(os.path.dirname(__file__), "manifests")) @@ -123,5 +135,67 @@ def test_entries_validate(self): orchestrator.validate_and_normalize_tests(tests) +class StubPathTest(unittest.TestCase): + def test_picks_the_tests_entry(self): + self.assertEqual(locust.stub_path(entry()), "benchmarking/locust/tests/resumepaused.py") + + def test_needs_one_tests_entry(self): + for file in ("/app/shapes/ladder_shape.py", "/app/tests/a.py,/app/tests/b.py"): + with self.subTest(file=file), self.assertRaises(ValueError): + locust.validate(entry(file=file)) + + +class WorkloadsTest(unittest.TestCase): + def setUp(self): + # Stub paths are relative to the repo root, where the orchestrator runs. + cwd = os.getcwd() + os.chdir(REPO_ROOT) + self.addCleanup(os.chdir, cwd) + # The orchestrator image has no locust; make importing it fail here too. + patcher = mock.patch.dict(sys.modules, {"locust": None}) + patcher.start() + self.addCleanup(patcher.stop) + + def installed(self, test): + with mock.patch("testtypes.locust.install_all") as install_all: + locust.workloads(test) + install_all.assert_called_once() + return install_all.call_args.args[0] + + def test_every_tests_yaml_stub_loads_without_locust(self): + with open(REPO_ROOT / "benchmarking/automation/tests.yaml") as f: + tests = yaml.safe_load(f)["tests"] + for test in tests: + if test["type"] != "locust": + continue + with self.subTest(test=test["name"]): + self.assertEqual(self.installed(test), [("deploy_sh", test)]) + self.assertNotIn(locust.NO_USERS_ENV, os.environ) + + def test_check_workloads(self): + with open(REPO_ROOT / "benchmarking/automation/tests.yaml") as f: + tests = yaml.safe_load(f)["tests"] + for test in tests: + if test["type"] == "locust": + with self.subTest(test=test["name"]): + locust.check_workloads(test) + with tempfile.TemporaryDirectory() as d: + Path(d, "typo.py").write_text('def workloads(test):\n return [("deploy-sh", test)]\n') + with mock.patch.object(locust, "REPO_STUB_DIR", d): + with self.assertRaisesRegex(ValueError, "locust test 't': unknown workload 'deploy-sh'"): + locust.check_workloads(entry(file="/app/tests/typo.py")) + + def test_stub_that_needs_locust_fails(self): + with self.assertRaisesRegex(ValueError, "must load without locust"): + self.installed(entry(file="/app/tests/sleep.py")) + + def test_stub_without_workloads_fails(self): + with tempfile.TemporaryDirectory() as d: + Path(d, "bare.py").write_text("") + with mock.patch.object(locust, "REPO_STUB_DIR", d): + with self.assertRaisesRegex(ValueError, "does not define workloads"): + self.installed(entry(file="/app/tests/bare.py")) + + if __name__ == "__main__": unittest.main() diff --git a/benchmarking/automation/test_orchestrator.py b/benchmarking/automation/test_orchestrator.py index b29084cd7a..97a7bc9ff3 100644 --- a/benchmarking/automation/test_orchestrator.py +++ b/benchmarking/automation/test_orchestrator.py @@ -14,9 +14,15 @@ """Unit tests for orchestrator.py: python3 benchmarking/automation/test_orchestrator.py""" +import argparse +import contextlib +import io import json import os +import subprocess +import tempfile import unittest +from pathlib import Path from unittest import mock import yaml @@ -25,6 +31,147 @@ from testtypes import locust +class ParseArgsTest(unittest.TestCase): + # This checkout, relative to the test's cwd, which pytest and the + # unittest invocation in the docstring both make this directory. + CHECKOUT = os.path.relpath(os.path.join(os.path.dirname(__file__), "..", "..")) + + def parse(self, *argv): + return orchestrator.parse_args(["--dest", "gs://b", *argv]) + + def assertRejected(self, *argv): + with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): + self.parse(*argv) + + def test_repo_defaults(self): + args = self.parse("--repo", "r") + self.assertEqual(args.branch, "main") + self.assertEqual(args.target_cluster_dir, orchestrator.TARGET_CLUSTER_DIR) + self.assertIsNone(args.substrate_dir) + self.assertIsNone(args.env_file) + + def test_repo_or_substrate_dir_required(self): + self.assertRejected() + + def test_substrate_dir_rejects_clone_flags(self): + self.assertIsNone(self.parse("--substrate-dir", self.CHECKOUT).branch) + self.assertRejected("--substrate-dir", self.CHECKOUT, "--repo", "r") + self.assertRejected("--substrate-dir", self.CHECKOUT, "--branch", "b") + + def test_substrate_dir_must_be_a_checkout(self): + with tempfile.TemporaryDirectory() as empty: + self.assertRejected("--substrate-dir", empty) + self.assertRejected("--substrate-dir", "/nonexistent") + + def test_env_file_rejects_target_cluster_dir(self): + self.assertIsNone(self.parse("--repo", "r", "--env-file", "e").target_cluster_dir) + self.assertRejected("--repo", "r", "--env-file", "e", "--target-cluster-dir", "d") + + def test_paths_are_made_absolute(self): + # main chdirs into the checkout before reading most of them. + args = self.parse( + "--substrate-dir", self.CHECKOUT, "--env-file", "e", "--tests", "t.yaml", + "--manifests-dir", "m", "--junit-output", "out/j.xml", + ) + for name in ("substrate_dir", "env_file", "tests", "manifests_dir", "junit_output"): + self.assertTrue(os.path.isabs(getattr(args, name)), name) + self.assertTrue(os.path.isabs(self.parse("--repo", "r").target_cluster_dir)) + + +ENV = ( + "export PROJECT_ID=p\n" + "export CLUSTER_NAME=c\n" + "export CLUSTER_LOCATION=l\n" + "export KO_DOCKER_REPO=r/x\n" +) + + +class EnvFileTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.checkout = Path(tmp.name) / "substrate" + self.checkout.mkdir() + self.own = self.checkout / orchestrator.ENV_FILE_NAME + self.clusters = Path(tmp.name) / "clusters" + self.clusters.mkdir() + self.dev = self.clusters / "dev.sh" + self.dev.write_text(ENV) + patch = mock.patch.dict(os.environ, {}, clear=True) + patch.start() + self.addCleanup(patch.stop) + + def args(self, **kw): + a = {"env_file": None, "target_cluster_dir": str(self.clusters), **kw} + return mock.Mock(**a) + + def test_env_file_for(self): + test = {"targetCluster": "dev"} + self.assertEqual(orchestrator.env_file_for(test, self.args()), self.dev) + self.assertEqual( + orchestrator.env_file_for(test, self.args(env_file="/e")), Path("/e") + ) + + def test_target_cluster_file_is_copied_then_removed(self): + orchestrator.apply_env_file(self.dev, str(self.checkout)) + self.assertEqual(self.own.read_text(), ENV) + self.assertEqual(os.environ["PROJECT_ID"], "p") + orchestrator.clear_env_file(self.dev, str(self.checkout)) + self.assertFalse(self.own.exists()) + + def test_own_env_file_is_sourced_in_place_and_kept(self): + self.own.write_text(ENV) + orchestrator.apply_env_file(self.own, str(self.checkout)) + self.assertEqual(os.environ["CLUSTER_NAME"], "c") + orchestrator.clear_env_file(self.own, str(self.checkout)) + self.assertEqual(self.own.read_text(), ENV) + + def test_missing_var(self): + self.dev.write_text("export PROJECT_ID=p\n") + with self.assertRaisesRegex(RuntimeError, "CLUSTER_NAME"): + orchestrator.apply_env_file(self.dev, str(self.checkout)) + + def test_exported_bash_function_does_not_pollute_env(self): + # env prints a two-statement function body over two lines, so a + # newline parser would turn the second into the key " Y". + self.dev.write_text(ENV + "f() {\n X=1\n Y=2\n}\nexport -f f\n") + orchestrator.apply_env_file(self.dev, str(self.checkout)) + self.assertEqual(os.environ["KO_DOCKER_REPO"], "r/x") + self.assertNotIn(" Y", os.environ) + self.assertTrue(os.environ["BASH_FUNC_f%%"].endswith("}")) + + def test_check_env_files(self): + dev = {"targetCluster": "dev"} + prod = {"targetCluster": "prod"} + checkout = str(self.checkout) + orchestrator.check_env_files([dev], self.args(), checkout) + # A missing target cluster file fails its own tests, in main. + orchestrator.check_env_files([dev, prod], self.args(), checkout) + own = self.args(env_file=str(self.own)) + with self.assertRaisesRegex(ValueError, "not found"): + orchestrator.check_env_files([dev], own, checkout) + self.own.write_text(ENV) + # --env-file overrides targetCluster, so prod.sh need not exist. + orchestrator.check_env_files([dev, prod], own, checkout) + # A copied file would overwrite the checkout's own. + with self.assertRaisesRegex(ValueError, "overwrite"): + orchestrator.check_env_files([dev], self.args(), checkout) + + +class BuildTagTest(unittest.TestCase): + @mock.patch("orchestrator.subprocess.check_output") + def test_clean_tree_is_the_commit(self, check_output): + check_output.side_effect = ["abc123\n", ""] + self.assertEqual(orchestrator.build_tag("/s"), "abc123") + + @mock.patch("orchestrator.subprocess.check_output") + def test_dirty_tree_gets_a_unique_suffix(self, check_output): + check_output.side_effect = ["abc123\n", " M x.py\n", "abc123\n", " M x.py\n"] + a, b = orchestrator.build_tag("/s"), orchestrator.build_tag("/s") + self.assertRegex(a, r"^abc123-dirty-[0-9a-f]{6}$") + self.assertNotEqual(a, b) + + class SelectTestsTest(unittest.TestCase): TESTS = [{"name": "a"}, {"name": "b"}, {"name": "c"}] @@ -40,17 +187,6 @@ def test_unknown_name(self): orchestrator.select_tests(self.TESTS, ["a", "y", "x"]) -class DeployWorkloadsFakeAteletTest(unittest.TestCase): - @mock.patch("orchestrator.run") - def test_fake_atelet_tuning_goes_to_deploy_sh(self, run): - orchestrator.deploy_workloads( - fake_atelet_args=["--fake-atelet-env", "FAKE_ATELET_DELAY=500ms"], - ) - cmd = run.call_args.args[0] - i = cmd.index("--fake-atelet-env") - self.assertEqual(cmd[i + 1], "FAKE_ATELET_DELAY=500ms") - - class SubstrateArgsTest(unittest.TestCase): def test_ate_args_only(self): self.assertEqual( @@ -122,70 +258,11 @@ def test_teardown_substrate(self, run_no_check): run_no_check.assert_called_once_with(["go", "run", "./cmd/ate-setup", "delete", "ate-system"]) -class DeployWorkloadsTest(unittest.TestCase): - @mock.patch("orchestrator.run") - def test_defaults_omit_optional_flags(self, run): - orchestrator.deploy_workloads() - run.assert_called_once_with( - [ - "benchmarking/workloads/deploy.sh", - "--deploy", - "--worker-count", - "1", - "--sandbox-class", - "gvisor", - ] - ) - - @mock.patch("orchestrator.run") - def test_worker_memory(self, run): - orchestrator.deploy_workloads(worker_memory="12Gi") - cmd = run.call_args.args[0] - i = cmd.index("--worker-memory") - self.assertEqual(cmd[i + 1], "12Gi") - - @mock.patch("orchestrator.run") - def test_whole_core_actor_cpu_is_a_string(self, run): - orchestrator.deploy_workloads(actor_cpu=1) - cmd = run.call_args.args[0] - i = cmd.index("--actor-cpu") - self.assertEqual(cmd[i + 1], "1") - - @mock.patch("orchestrator.run") - def test_all_options(self, run): - orchestrator.deploy_workloads( - worker_count=3, - sandbox_class="microvm", - actor_memory="1536Mi", - wait_timeout_secs=600, - worker_memory="5Gi", - actor_cpu="250m", - ) - run.assert_called_once_with( - [ - "benchmarking/workloads/deploy.sh", - "--deploy", - "--worker-count", - "3", - "--sandbox-class", - "microvm", - "--actor-memory", - "1536Mi", - "--actor-cpu", - "250m", - "--worker-memory", - "5Gi", - "--wait-timeout", - "600", - ] - ) - - class RunnerSizingTest(unittest.TestCase): TMPL = os.path.join(os.path.dirname(__file__), "manifests", "runner-job.yaml.tmpl") def render(self, test): - subs = {"JOB_NAME": "j", "IMAGE": "i", "TAG": "t", "NAME": "n", "DEST": "d"} + subs = {"JOB_NAME": "j", "IMAGE": "i", "TAG": "t", "NAME": "n", "DEST": "d", "RUN_TS": 1} subs.update(locust.job_subs(test)) text = orchestrator.render_template(self.TMPL, subs) job = next(d for d in yaml.safe_load_all(text) if d and d.get("kind") == "Job") @@ -203,7 +280,7 @@ def test_runner_cpu_and_memory(self): self.assertNotIn("limits", res) def test_no_placeholder_survives(self): - subs = {"JOB_NAME": "j", "IMAGE": "i", "TAG": "t", "NAME": "n", "DEST": "d"} + subs = {"JOB_NAME": "j", "IMAGE": "i", "TAG": "t", "NAME": "n", "DEST": "d", "RUN_TS": 1} subs.update(locust.job_subs({"file": "f", "duration": "1m", "users": 1})) self.assertNotIn("${", orchestrator.render_template(self.TMPL, subs)) @@ -228,7 +305,11 @@ def api_client_labels(self): def test_namespace_has_api_access_label(self): want = self.api_client_labels() - for name in ("runner-job.yaml.tmpl", "nighthawk-ingress-runner-job.yaml.tmpl"): + for name in ( + "runner-job.yaml.tmpl", + "nighthawk-ingress-runner-job.yaml.tmpl", + "nighthawk-egress-runner-job.yaml.tmpl", + ): with self.subTest(template=name): text = open(os.path.join(self.HERE, "manifests", name)).read() ns = next( @@ -241,6 +322,398 @@ def test_namespace_has_api_access_label(self): self.assertEqual(ns["metadata"].get("labels", {}).get(k), v) +class NighthawkEgressTest(unittest.TestCase): + def _entry(self, **overrides): + cfg = {"mode": "mitm", **overrides} + return { + "name": "egress_mitm", + "type": "nighthawk-egress", + "targetCluster": "dev", + "duration": "30m", + "nighthawk-egress": cfg, + } + + def test_validate_rejects_bad_entries(self): + from testtypes import nighthawk_egress + + cases = [ + # label, changes to the entry, changes to its nighthawk-egress block, want error + ("no duration", {"duration": None}, {}, "missing 'duration'"), + ("microvm", {"sandboxClass": "microvm"}, {}, "only supports sandboxClass 'gvisor'"), + ("shared-workload field", {"workerCount": 3}, {}, "shared-workload field"), + ("flags at the top level", {"flags": ["--x"]}, {}, "put knobs under 'nighthawk-egress:'"), + ("no block", {"nighthawk-egress": None}, {}, "requires 'nighthawk-egress:' block"), + ("unknown knob", {}, {"connections": 8}, "unknown knob"), + ("envoyCpu", {}, {"envoyCpu": 1}, "unknown knob"), + ("no mode", {}, {"mode": None}, "missing nighthawk-egress.mode"), + ("unknown mode", {}, {"mode": "tcp"}, "mode must be one of"), + ] + for label, changes, cfg_changes, want in cases: + with self.subTest(label=label): + test = {**self._entry(**cfg_changes), **changes} + # None removes the key. + test = {k: v for k, v in test.items() if v is not None} + if test.get("nighthawk-egress"): + test["nighthawk-egress"] = {k: v for k, v in test["nighthawk-egress"].items() if v is not None} + with self.assertRaisesRegex(ValueError, want): + nighthawk_egress.validate(test) + + def test_job_template_renders_args_labels_and_toleration(self): + from testtypes import nighthawk_egress + + test = self._entry(mode="passthrough") + subs = { + "JOB_NAME": "j", + "IMAGE": "i", + "TAG": "6949841e", + "NAME": test["name"], + "DEST": "gs://b/p", + "RUN_TS": 1, + **nighthawk_egress.job_subs(test), + } + tmpl = nighthawk_egress.job_tmpl(os.path.join(os.path.dirname(__file__), "manifests")) + text = orchestrator.render_template(tmpl, subs) + self.assertNotIn("${", text) + job = next(d for d in yaml.safe_load_all(text) if d and d.get("kind") == "Job") + self.assertEqual(job["spec"]["ttlSecondsAfterFinished"], 86400) + self.assertEqual(job["spec"]["template"]["metadata"]["labels"]["tag"], "6949841e") + self.assertIn( + {"key": "ate.dev/benchmarking", "operator": "Equal", "value": "true", "effect": "NoSchedule"}, + job["spec"]["template"]["spec"]["tolerations"], + ) + args = job["spec"]["template"]["spec"]["containers"][0]["args"] + self.assertEqual(args[args.index("--mode") + 1], "passthrough") + self.assertEqual(args[args.index("--envoy-cpu") + 1], "1") + mounts = job["spec"]["template"]["spec"]["containers"][0]["volumeMounts"] + self.assertIn({"name": "servicedns-ca", "mountPath": "/run/servicedns-ca", "readOnly": True}, mounts) + vols = job["spec"]["template"]["spec"]["volumes"] + ca_vol = next(v for v in vols if v["name"] == "servicedns-ca") + ctb = ca_vol["projected"]["sources"][0]["clusterTrustBundle"] + self.assertEqual(ctb["signerName"], "servicedns.podcert.ate.dev/identity") + self.assertEqual(ctb["path"], "ca.crt") + + def test_job_template_runs_the_invoker_sidecar(self): + from testtypes import nighthawk_egress + + test = self._entry() + subs = { + "JOB_NAME": "j", + "IMAGE": "i", + "TAG": "6949841e", + "NAME": test["name"], + "DEST": "gs://b/p", + "RUN_TS": 1, + **nighthawk_egress.job_subs(test), + } + tmpl = nighthawk_egress.job_tmpl(os.path.join(os.path.dirname(__file__), "manifests")) + docs = [d for d in yaml.safe_load_all(orchestrator.render_template(tmpl, subs)) if d] + pod = next(d for d in docs if d["kind"] == "Job")["spec"]["template"]["spec"] + self.assertEqual(pod["serviceAccountName"], "benchmark-runner") + + # restartPolicy Always makes the init container a sidecar: it runs + # beside the runner and does not keep the Job from completing. + (invoker,) = pod["initContainers"] + self.assertEqual(invoker["name"], "invoker") + self.assertEqual(invoker["restartPolicy"], "Always") + self.assertEqual(pod["containers"][0]["name"], "runner") + + volumes = {v["name"]: v for v in pod["volumes"]} + mounts = {m["name"]: m["mountPath"] for m in invoker["volumeMounts"]} + config = next( + d for d in docs + if d["kind"] == "ConfigMap" and d["metadata"]["name"] == volumes["invoker-config"]["configMap"]["name"] + ) + self.assertEqual(config["metadata"]["namespace"], "benchmarking") + envoy = yaml.safe_load(config["data"]["envoy.yaml"]) + + # Only the runner, in the same pod, reaches the listener. A kubelet + # probe cannot. + (listener,) = envoy["static_resources"]["listeners"] + self.assertEqual(listener["address"]["socket_address"], {"address": "127.0.0.1", "port_value": 19980}) + self.assertNotIn("startupProbe", invoker) + + # Every file the Envoy config names must exist in the sidecar's mounts. + tls = envoy["static_resources"]["clusters"][0]["transport_socket"]["typed_config"]["common_tls_context"] + cert_sds = tls["tls_certificate_sds_secret_configs"][0]["sds_config"]["path_config_source"]["path"] + ca_sds = tls["combined_validation_context"]["validation_context_sds_secret_config"]["sds_config"][ + "path_config_source" + ]["path"] + prefix = mounts["invoker-config"] + "/" + for path in (cert_sds, ca_sds): + self.assertTrue(path.startswith(prefix), path) + self.assertIn(path[len(prefix):], config["data"]) + cert = yaml.safe_load(config["data"][cert_sds[len(prefix):]])["resources"][0]["tls_certificate"] + pod_cert = volumes["podidentity"]["projected"]["sources"][0]["podCertificate"] + self.assertEqual(pod_cert["signerName"], "podidentity.podcert.ate.dev/identity") + want = f"{mounts['podidentity']}/{pod_cert['credentialBundlePath']}" + self.assertEqual(cert["certificate_chain"]["filename"], want) + self.assertEqual(cert["private_key"]["filename"], want) + ca = yaml.safe_load(config["data"][ca_sds[len(prefix):]])["resources"][0]["validation_context"] + bundle = volumes["servicedns-ca"]["projected"]["sources"][0]["clusterTrustBundle"] + self.assertEqual(ca["trusted_ca"]["filename"], f"{mounts['servicedns-ca']}/{bundle['path']}") + + def _deployment_json(self, envoy_args: list[str]) -> str: + containers = [{"name": "envoy", "args": envoy_args}, {"name": "ext-proc", "args": ["router", "--mode=egress"]}] + return json.dumps({"spec": {"replicas": 2, "template": {"spec": {"containers": containers}}}}) + + @mock.patch("testtypes.nighthawk_egress.run") + def test_shape_atenet_egress(self, run): + from testtypes import nighthawk_egress + + cases = [ + # label, envoy args of the live Deployment, want envoy args in the patch + ( + "no concurrency flag", + ["-c", "/etc/envoy/envoy.yaml", "--service-node", "atenet-egress"], + ["-c", "/etc/envoy/envoy.yaml", "--service-node", "atenet-egress", "--concurrency", "2"], + ), + ( + "two-argument flag", + ["-c", "/etc/envoy/envoy.yaml", "--concurrency", "1", "--service-node", "atenet-egress"], + ["-c", "/etc/envoy/envoy.yaml", "--service-node", "atenet-egress", "--concurrency", "2"], + ), + ] + cpu = {"requests": {"cpu": "2000m"}, "limits": {"cpu": "2000m"}} + for label, envoy_args, want_args in cases: + with self.subTest(label=label): + run.reset_mock() + run.side_effect = [ + subprocess.CompletedProcess(args=[], returncode=0, stdout=self._deployment_json(envoy_args)), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + ] + nighthawk_egress.shape_atenet_egress(2) + + get, patch, rollout = (c.args[0] for c in run.call_args_list) + self.assertEqual(get, ["kubectl", "-n", "ate-system", "get", "deployment/atenet-egress", "-o", "json"]) + # stdout only, so the stderr of a failed read stays on the log. + self.assertEqual(run.call_args_list[0].kwargs, {"stdout": subprocess.PIPE, "text": True}) + self.assertEqual( + patch[:7], + ["kubectl", "-n", "ate-system", "patch", "deployment/atenet-egress", "--type=strategic", "-p"], + ) + self.assertEqual( + json.loads(patch[7]), + { + "spec": { + "replicas": 1, + "template": { + "spec": { + "containers": [ + {"name": "envoy", "args": want_args, "resources": cpu}, + {"name": "ext-proc", "resources": cpu}, + ] + } + }, + } + }, + ) + self.assertEqual( + rollout, + ["kubectl", "-n", "ate-system", "rollout", "status", "deployment/atenet-egress", "--timeout=300s"], + ) + + @mock.patch("testtypes.nighthawk_egress.run") + def test_shape_atenet_egress_needs_the_envoy_container(self, run): + from testtypes import nighthawk_egress + + dep = {"spec": {"template": {"spec": {"containers": [{"name": "ext-proc"}]}}}} + run.return_value = subprocess.CompletedProcess(args=[], returncode=0, stdout=json.dumps(dep)) + with self.assertRaisesRegex(RuntimeError, "no envoy container"): + nighthawk_egress.shape_atenet_egress(1) + run.assert_called_once() + + @mock.patch("testtypes.nighthawk_egress.run") + def test_pre_test(self, run): + from testtypes import nighthawk_egress + + run.side_effect = [ + subprocess.CompletedProcess(args=[], returncode=0, stdout=self._deployment_json(["-c", "/etc/envoy/envoy.yaml"])), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout="gke_proj_loc_cluster\n"), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + ] + nighthawk_egress.pre_test(self._entry(mode="mitm")) + + # The first three calls pin the gateway, see test_shape_atenet_egress. + pin = json.loads(run.call_args_list[1].args[0][7]) + self.assertEqual(pin["spec"]["template"]["spec"]["containers"][0]["resources"]["limits"], {"cpu": "1000m"}) + context, tls, server, driver = run.call_args_list[3:] + self.assertEqual(context.args[0], ["kubectl", "config", "current-context"]) + self.assertEqual(context.kwargs, {"stdout": subprocess.PIPE, "text": True}) + self.assertEqual(tls.args[0], ["hack/setup-e2e-egress-tls-kind.sh"]) + self.assertEqual(tls.kwargs["env"]["KUBECTL_CONTEXT"], "gke_proj_loc_cluster") + self.assertEqual(server.args[0], ["benchmarking/nighthawk-egress/deploy.sh", "--deploy"]) + self.assertEqual(driver.args[0], ["benchmarking/nighthawk-egress/deploy-traffic-driver.sh", "--deploy"]) + + def test_main_deploys_shared_workloads_only_for_types_that_use_them(self): + from testtypes import nighthawk_egress + + ingress_entry = { + "name": "ingress_2cpu", + "type": "nighthawk-ingress", + "targetCluster": "dev", + "duration": "30m", + "workerCount": 50, + "nighthawk-ingress": {"envoyCpu": 2, "tailLatencySloMs": 25}, + } + cases = [ + # label, tests.yaml entry, want deploy_workloads calls, want egress teardown calls + ("nighthawk-ingress", ingress_entry, 1, 1), # the sweep before the test + ("nighthawk-egress", self._entry(), 0, 2), # the sweep, and the teardown after the test + ] + for label, entry, want_deploys, want_egress_teardowns in cases: + with self.subTest(label=label), tempfile.TemporaryDirectory() as tmp: + tests_path = os.path.join(tmp, "tests.yaml") + with open(tests_path, "w") as f: + yaml.safe_dump({"tests": [entry]}, f) + args = argparse.Namespace( + tests=tests_path, + test_name=None, + branch="b", + repo="r", + substrate_dir=None, + dest="gs://b/p", + target_cluster_dir=tmp, + env_file=None, + manifests_dir=tmp, + junit_output=None, + ) + ttype = orchestrator.TYPES[entry["type"]] + with ( + mock.patch("orchestrator.parse_args", return_value=args), + mock.patch("orchestrator.wait_for_docker"), + mock.patch("orchestrator.run"), + mock.patch("orchestrator.run_no_check"), + mock.patch("orchestrator.os.chdir"), + # One patch for four: Python caps nested blocks at 20. + mock.patch.multiple( + "orchestrator", + build_tag=mock.DEFAULT, + check_env_files=mock.DEFAULT, + apply_env_file=mock.DEFAULT, + clear_env_file=mock.DEFAULT, + ), + # main points KUBECONFIG at a file of its own. + mock.patch.dict(os.environ), + mock.patch.dict(orchestrator._ORIG_ENV), + mock.patch("orchestrator.gcloud_setup_for_target_cluster"), + mock.patch("orchestrator.deploy_substrate"), + mock.patch("orchestrator.teardown_substrate"), + mock.patch("orchestrator.run_test", return_value="complete"), + mock.patch("workloads.deploy_sh.install") as deploy_workloads, + mock.patch.object(ttype, "build_image", return_value="img"), + mock.patch.object(ttype, "pre_test"), + mock.patch.object(nighthawk_egress, "teardown_workloads") as egress_teardown, + self.assertRaises(SystemExit) as exit_, + ): + orchestrator.main() + self.assertEqual(exit_.exception.code, 0) + self.assertEqual(deploy_workloads.call_count, want_deploys) + self.assertEqual(egress_teardown.call_count, want_egress_teardowns) + + @mock.patch("testtypes.nighthawk_egress.run_no_check") + @mock.patch("orchestrator.run_no_check") + def test_teardown_workloads_contract(self, orch_run_no_check, egress_run_no_check): + # Locust-only teardown runs shared workloads delete and never touches nighthawk-egress. + orchestrator.teardown_test_workloads(["locust"]) + orch_run_no_check.assert_called_once_with(["benchmarking/workloads/deploy.sh", "--delete"]) + egress_run_no_check.assert_not_called() + + orch_run_no_check.reset_mock() + egress_run_no_check.reset_mock() + + # nighthawk-ingress-only teardown runs shared workloads delete and never touches nighthawk-egress. + orchestrator.teardown_test_workloads(["nighthawk-ingress"]) + orch_run_no_check.assert_called_once_with(["benchmarking/workloads/deploy.sh", "--delete"]) + egress_run_no_check.assert_not_called() + + orch_run_no_check.reset_mock() + egress_run_no_check.reset_mock() + + # The sweep over every type skips deploy-traffic-driver.sh --delete when namespace/nighthawk does not exist, + # so locust / nighthawk-ingress runs do not need kubectl-ate. + egress_run_no_check.return_value = subprocess.CompletedProcess(args=[], returncode=0, stdout="") + orchestrator.teardown_test_workloads(orchestrator.TYPES) + orch_run_no_check.assert_called_once_with(["benchmarking/workloads/deploy.sh", "--delete"]) + egress_run_no_check.assert_called_once_with( + ["kubectl", "get", "namespace", "nighthawk", "-o", "name", "--ignore-not-found"], + stdout=subprocess.PIPE, + text=True, + ) + + orch_run_no_check.reset_mock() + egress_run_no_check.reset_mock() + + # nighthawk-egress teardown when ate-api-server exists runs both delete scripts and deletes the namespace. + egress_run_no_check.side_effect = [ + subprocess.CompletedProcess(args=[], returncode=0, stdout="namespace/nighthawk\n"), + subprocess.CompletedProcess(args=[], returncode=0, stdout="deployment.apps/ate-api-server\n"), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + ] + orchestrator.teardown_test_workloads(["nighthawk-egress"]) + orch_run_no_check.assert_not_called() + self.assertEqual( + [c.args[0] for c in egress_run_no_check.call_args_list], + [ + ["kubectl", "get", "namespace", "nighthawk", "-o", "name", "--ignore-not-found"], + ["kubectl", "get", "deployment", "ate-api-server", "-n", "ate-system", "-o", "name", "--ignore-not-found"], + ["benchmarking/nighthawk-egress/deploy-traffic-driver.sh", "--delete"], + ["benchmarking/nighthawk-egress/deploy.sh", "--delete"], + ["kubectl", "delete", "namespace", "nighthawk", "--ignore-not-found"], + ], + ) + + egress_run_no_check.reset_mock() + + # When namespace/nighthawk exists but ate-api-server is gone, delete K8s manifests directly, without kubectl-ate. + egress_run_no_check.side_effect = [ + subprocess.CompletedProcess(args=[], returncode=0, stdout="namespace/nighthawk\n"), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + ] + orchestrator.teardown_test_workloads(["nighthawk-egress"]) + self.assertEqual( + [c.args[0] for c in egress_run_no_check.call_args_list], + [ + ["kubectl", "get", "namespace", "nighthawk", "-o", "name", "--ignore-not-found"], + ["kubectl", "get", "deployment", "ate-api-server", "-n", "ate-system", "-o", "name", "--ignore-not-found"], + ["kubectl", "delete", "--ignore-not-found", "-f", "benchmarking/nighthawk-egress/traffic-driver.yaml.tmpl"], + ["benchmarking/nighthawk-egress/deploy.sh", "--delete"], + ["kubectl", "delete", "namespace", "nighthawk", "--ignore-not-found"], + ], + ) + + egress_run_no_check.reset_mock() + + # A failed read of namespace/nighthawk does not skip the teardown. + egress_run_no_check.side_effect = [ + subprocess.CompletedProcess(args=[], returncode=1, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + subprocess.CompletedProcess(args=[], returncode=0, stdout=""), + ] + orchestrator.teardown_test_workloads(["nighthawk-egress"]) + self.assertEqual( + [c.args[0] for c in egress_run_no_check.call_args_list], + [ + ["kubectl", "get", "namespace", "nighthawk", "-o", "name", "--ignore-not-found"], + ["kubectl", "get", "deployment", "ate-api-server", "-n", "ate-system", "-o", "name", "--ignore-not-found"], + ["kubectl", "delete", "--ignore-not-found", "-f", "benchmarking/nighthawk-egress/traffic-driver.yaml.tmpl"], + ["benchmarking/nighthawk-egress/deploy.sh", "--delete"], + ["kubectl", "delete", "namespace", "nighthawk", "--ignore-not-found"], + ], + ) + + class JobNameTest(unittest.TestCase): COMMIT = "ac41c06deadbeef" @@ -307,7 +780,7 @@ class Rendered(Exception): mock.patch.dict(os.environ, CLUSTER_ENV, clear=True), \ mock.patch.object(orchestrator, "render_template", side_effect=Rendered) as render, \ self.assertRaises(Rendered): - orchestrator.run_test(test, "img", "dest", "abcdef0123") + orchestrator.run_test(test, "img", "dest", "abcdef0123", 1700000000) return render.call_args.args[2] def test_locust_job_gets_metadata(self): @@ -341,19 +814,82 @@ def test_bad_test_metadata_fails_clearly(self): # Caught by validation, before any cluster work. test = {"name": "n", "type": "locust", "targetCluster": "t", - "file": "f", "duration": "1m", "users": 1, + "file": "/app/tests/glutton.py", "duration": "1m", "users": 1, "flags": ["--metadata", "{bad"]} with self.assertRaisesRegex(ValueError, "not valid JSON"): orchestrator.validate_and_normalize_tests([test]) + def test_locust_job_gets_the_whole_test_entry(self): + class Rendered(Exception): + pass + + fake = mock.Mock(job_tmpl=mock.Mock(return_value="t"), job_subs=mock.Mock(return_value={})) + test = {"name": "n", "type": "locust", "duration": "1m", "flags": ["--x"], "observers": [{"name": "pprof"}]} + with mock.patch.dict(orchestrator.TYPES, {"locust": fake}), \ + mock.patch.dict(os.environ, CLUSTER_ENV, clear=True), \ + mock.patch.object(orchestrator, "render_template", side_effect=Rendered) as render, \ + self.assertRaises(Rendered): + orchestrator.run_test(test, "img", "dest", "abcdef0123", 1700000000) + args = render.call_args.args[2] + self.assertEqual(json.loads(args[args.index("--test-entry") + 1]), test) + + def test_every_job_gets_the_invocation_run_ts(self): + for ttype in orchestrator.TYPES: + with self.subTest(ttype=ttype): + tmpl = orchestrator.TYPES[ttype].job_tmpl(os.path.join(os.path.dirname(__file__), "manifests")) + subs = {"JOB_NAME": "j", "IMAGE": "i", "TAG": "t", "NAME": "n", "DEST": "d", "RUN_TS": 1700000000} + text = orchestrator.render_template(tmpl, subs) + job = next(d for d in yaml.safe_load_all(text) if d and d.get("kind") == "Job") + args = job["spec"]["template"]["spec"]["containers"][0]["args"] + self.assertEqual(args[args.index("--run-ts") + 1], "1700000000") + + def test_test_names_must_be_unique(self): + test = {"name": "n", "type": "locust", "targetCluster": "t", "file": "f", "duration": "1m", "users": 1} + with self.assertRaisesRegex(ValueError, "test names must be unique: n$"): + orchestrator.validate_and_normalize_tests([test, dict(test)]) + + def test_evaluations_only_on_locust(self): + test = {"name": "n", "type": "nighthawk-ingress", "targetCluster": "t", "evaluations": [{"name": "e"}]} + with mock.patch.object(orchestrator.TYPES["nighthawk-ingress"], "validate"), \ + self.assertRaisesRegex(ValueError, "test 'n': 'evaluations' is supported only for type locust"): + orchestrator.validate_and_normalize_tests([test]) + def test_metadata_survives_yaml(self): md = json.dumps({"cluster_name": "c: d", "q": "\"'"}) - subs = {"JOB_NAME": "j", "IMAGE": "i", "TAG": "t", "NAME": "n", "DEST": "d"} + subs = {"JOB_NAME": "j", "IMAGE": "i", "TAG": "t", "NAME": "n", "DEST": "d", "RUN_TS": 1} subs.update(locust.job_subs({"file": "f", "duration": "1m", "users": 1})) text = orchestrator.render_template(RunnerSizingTest.TMPL, subs, ["--metadata", md]) job = next(d for d in yaml.safe_load_all(text) if d and d.get("kind") == "Job") self.assertEqual(job["spec"]["template"]["spec"]["containers"][0]["args"][-1], md) +class CheckWorkloadsTest(unittest.TestCase): + def test_main_checks_workloads_before_any_cluster_work(self): + entry = {"name": "t", "type": "locust", "targetCluster": "dev", "file": "/app/tests/glutton.py", + "duration": "1m", "users": 1} + with tempfile.TemporaryDirectory() as tmp: + tests_path = os.path.join(tmp, "tests.yaml") + with open(tests_path, "w") as f: + yaml.safe_dump({"tests": [entry]}, f) + args = argparse.Namespace(tests=tests_path, test_name=None, branch="b", repo="r", substrate_dir=None, + dest="gs://b/p", target_cluster_dir=tmp, env_file=None, manifests_dir=tmp, + junit_output=None) + with ( + mock.patch("orchestrator.parse_args", return_value=args), + mock.patch("orchestrator.check_env_files"), + mock.patch("orchestrator.wait_for_docker"), + mock.patch("orchestrator.run"), + mock.patch("orchestrator.os.chdir"), + mock.patch.dict(os.environ), + mock.patch.dict(orchestrator._ORIG_ENV), + mock.patch("orchestrator.deploy_substrate") as deploy_substrate, + mock.patch.object(locust, "check_workloads", side_effect=ValueError("bad stub")), + self.assertRaises(SystemExit) as exit_, + ): + orchestrator.main() + self.assertEqual(exit_.exception.code, "bad stub") + deploy_substrate.assert_not_called() + + if __name__ == "__main__": unittest.main() diff --git a/benchmarking/automation/test_workers.py b/benchmarking/automation/test_workers.py new file mode 100644 index 0000000000..b4bba44122 --- /dev/null +++ b/benchmarking/automation/test_workers.py @@ -0,0 +1,202 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for workers.py: python3 benchmarking/automation/test_workers.py""" + +import os +import subprocess +import unittest +from pathlib import Path +from unittest import mock + +import yaml + +import workers + +REPO_ROOT = Path(__file__).resolve().parents[2] + + +class ConfigTest(unittest.TestCase): + def test_defaults(self): + self.assertEqual( + workers.config({"name": "t", "workerMemory": None}), + workers.Config(count=1, sandbox_class="gvisor", memory="", wait_timeout_secs=300, fake_atelet_env=()), + ) + + def test_from_test(self): + cfg = workers.config( + { + "name": "t", + "workerCount": 4, + "sandboxClass": "microvm", + "workerMemory": "8Gi", + "workerWaitTimeout": "900", + "isolate": {"delay": "500ms", "mintActorCertificate": False}, + } + ) + self.assertEqual( + cfg, + workers.Config( + count=4, + sandbox_class="microvm", + memory="8Gi", + wait_timeout_secs=900, + fake_atelet_env=("FAKE_ATELET_DELAY=500ms", "FAKE_ATELET_MINT_ACTOR_CERTIFICATE=false"), + ), + ) + + def test_invalid(self): + for bad in ( + {"workerCount": -1}, + {"workerCount": "2"}, + {"workerCount": True}, + {"sandboxClass": "kata"}, + {"workerMemory": 8}, + {"workerMemory": 0}, + {"workerMemory": False}, + {"workerWaitTimeout": "5m"}, + {"workerWaitTimeout": "²"}, + {"workerWaitTimeout": True}, + {"isolate": {"bogus": "1s"}}, + ): + with self.subTest(bad=bad), self.assertRaisesRegex(ValueError, "test 't'"): + workers.config({"name": "t", **bad}) + + +class RenderPoolTest(unittest.TestCase): + def setUp(self): + # render_pool reads the manifest relative to the repo root. + cwd = os.getcwd() + os.chdir(REPO_ROOT) + self.addCleanup(os.chdir, cwd) + + def docs(self, cfg): + rendered = workers.render_pool(cfg) + self.assertNotIn("${", rendered) + return list(yaml.safe_load_all(rendered)) + + def test_unsized(self): + namespace, pool = self.docs(workers.Config(count=3)) + self.assertEqual(namespace["kind"], "Namespace") + self.assertEqual(namespace["metadata"]["name"], workers.NAMESPACE) + self.assertEqual(pool["kind"], "WorkerPool") + self.assertEqual(pool["metadata"]["name"], workers.POOL_NAME) + self.assertEqual(pool["spec"]["replicas"], 3) + self.assertEqual(pool["spec"]["sandboxClasses"], [{"name": "gvisor"}]) + self.assertEqual(pool["spec"]["workerImage"], "ko://go.ate.dev/substrate/cmd/ateworker-gvisor") + self.assertNotIn("resources", pool["spec"]["template"]) + + def test_sized_microvm(self): + _, pool = self.docs(workers.Config(sandbox_class="microvm", memory="8Gi")) + self.assertEqual(pool["spec"]["sandboxClasses"], [{"name": "microvm"}]) + self.assertEqual(pool["spec"]["workerImage"], "ko://go.ate.dev/substrate/cmd/ateworker-microvm") + self.assertEqual( + pool["spec"]["template"]["resources"], + {"requests": {"memory": "8Gi"}, "limits": {"memory": "8Gi"}}, + ) + + +def completed(stdout=""): + return subprocess.CompletedProcess(args=[], returncode=0, stdout=stdout) + + +class InstallTest(unittest.TestCase): + def setUp(self): + patcher = mock.patch("workers.render_pool", return_value="POOL") + patcher.start() + self.addCleanup(patcher.stop) + + def install(self, test, fake=False, tuning_before="", tuning_after=""): + """Run install with run() faked; return the commands it ran.""" + tuning = iter([tuning_before, tuning_after]) + + def fake_run(cmd, **kwargs): + if cmd[:3] == ["kubectl", "get", "deployment/fake-workersync"]: + return completed("deployment.apps/fake-workersync" if fake else "") + if cmd[:4] == ["kubectl", "get", "configmap", "fake-atelet-tuning"]: + return completed(next(tuning)) + if cmd[:3] == ["kubectl", "get", "daemonset"]: + return completed("daemonset.apps/atelet-v1") + return completed() + + with mock.patch("workers.run", side_effect=fake_run) as run: + workers.install({"name": "t", **test}) + return run.call_args_list + + @staticmethod + def cmds(calls): + return [c.args[0] for c in calls] + + def test_gvisor(self): + calls = self.install({"workerCount": 2}) + cmds = self.cmds(calls) + apply = next(c for c in calls if c.args[0][:3] == ["hack/run-tool.sh", "ko", "apply"]) + self.assertEqual(apply.kwargs["input"], "POOL") + self.assertEqual( + cmds[-2:], + [ + ["kubectl", "wait", "--for=create", "deployment/benchmark-worker", + "--namespace=benchmark-workloads", "--timeout=300s"], + ["kubectl", "rollout", "status", "deployment/benchmark-worker", + "--namespace=benchmark-workloads", "--timeout=300s"], + ], + ) + + def test_fake_data_plane_waits_on_pool_status(self): + cmds = self.cmds(self.install({"workerCount": 5, "workerWaitTimeout": 60}, fake=True)) + self.assertEqual( + cmds[-1], + ["kubectl", "wait", "--for=jsonpath={.status.readyReplicas}=5", + "workerpool/benchmark-worker", "--namespace=benchmark-workloads", "--timeout=60s"], + ) + self.assertFalse(any(c[:2] == ["kubectl", "rollout"] for c in cmds)) + + def test_fake_data_plane_zero_workers_skips_wait(self): + cmds = self.cmds(self.install({"workerCount": 0}, fake=True)) + self.assertEqual(cmds[-1], ["hack/run-tool.sh", "ko", "apply", "-f", "-"]) + + def test_tuning_restarts_fake_atelet_when_changed(self): + cmds = self.cmds( + self.install({"isolate": {"delay": "1s"}}, fake=True, tuning_before="{}", tuning_after='{"X":"1"}') + ) + create = next(c for c in cmds if c[:3] == ["kubectl", "create", "configmap"]) + self.assertIn("--from-literal=FAKE_ATELET_DELAY=1s", create) + restart = cmds.index(["kubectl", "rollout", "restart", "--namespace=ate-system", "daemonset.apps/atelet-v1"]) + self.assertLess(restart, cmds.index(["hack/run-tool.sh", "ko", "apply", "-f", "-"])) + + def test_tuning_unchanged_skips_restart(self): + cmds = self.cmds(self.install({"isolate": None}, fake=True, tuning_before="{}", tuning_after="{}")) + self.assertFalse(any(c[:3] == ["kubectl", "rollout", "restart"] for c in cmds)) + + def test_isolate_without_fake_data_plane_fails(self): + with self.assertRaises(RuntimeError): + self.install({"isolate": {"delay": "1s"}}, fake=False) + + +class TeardownTest(unittest.TestCase): + @mock.patch("workers.run_no_check") + def test_removes_pool_and_namespace(self, run_no_check): + workers.teardown() + self.assertEqual( + [c.args[0] for c in run_no_check.call_args_list], + [ + ["kubectl", "delete", "workerpool", "benchmark-worker", + "--namespace=benchmark-workloads", "--ignore-not-found"], + ["kubectl", "delete", "namespace", "benchmark-workloads", "--ignore-not-found"], + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/automation/test_workloads.py b/benchmarking/automation/test_workloads.py new file mode 100644 index 0000000000..9f58058985 --- /dev/null +++ b/benchmarking/automation/test_workloads.py @@ -0,0 +1,89 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for workloads/: python3 benchmarking/automation/test_workloads.py""" + +import unittest +from unittest import mock + +import workloads +from workloads import deploy_sh + + +class InstallAllTest(unittest.TestCase): + def setUp(self): + self.installed = [] + fake = mock.Mock(install=self.installed.append) + patcher = mock.patch.dict(workloads.WORKLOADS, {"a": fake, "b": fake}) + patcher.start() + self.addCleanup(patcher.stop) + + def test_installs_in_order(self): + workloads.install_all([("b", {"x": 1}), ("a", {"x": 2})]) + self.assertEqual(self.installed, [{"x": 1}, {"x": 2}]) + + def test_rejects_before_installing_anything(self): + with self.assertRaisesRegex(ValueError, "unknown workload 'nope'"): + workloads.install_all([("a", {}), ("nope", {})]) + self.assertEqual(self.installed, []) + + +class DeployShTest(unittest.TestCase): + def cmd(self, test): + with mock.patch("workloads.deploy_sh.run") as run: + deploy_sh.install(test) + run.assert_called_once() + return run.call_args.args[0] + + def test_defaults_omit_optional_flags(self): + self.assertEqual( + self.cmd({"name": "t"}), + ["benchmarking/workloads/deploy.sh", "--deploy", "--worker-count", "1", "--sandbox-class", "gvisor"], + ) + + def test_whole_core_actor_cpu_is_a_string(self): + cmd = self.cmd({"actorCPU": 1}) + self.assertEqual(cmd[cmd.index("--actor-cpu") + 1], "1") + + def test_fake_atelet_tuning(self): + cmd = self.cmd({"isolate": {"delay": "500ms"}}) + self.assertEqual(cmd[cmd.index("--fake-atelet-env") + 1], "FAKE_ATELET_DELAY=500ms") + + def test_all_options(self): + self.assertEqual( + self.cmd( + { + "workerCount": 3, + "sandboxClass": "microvm", + "actorMemory": "1536Mi", + "workerWaitTimeout": 600, + "workerMemory": "5Gi", + "actorCPU": "250m", + } + ), + [ + "benchmarking/workloads/deploy.sh", + "--deploy", + "--worker-count", "3", + "--sandbox-class", "microvm", + "--actor-memory", "1536Mi", + "--actor-cpu", "250m", + "--worker-memory", "5Gi", + "--wait-timeout", "600", + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/automation/tests.yaml b/benchmarking/automation/tests.yaml index f1a239d81f..5d3476ef82 100644 --- a/benchmarking/automation/tests.yaml +++ b/benchmarking/automation/tests.yaml @@ -17,7 +17,8 @@ # # Fields shared by every entry: # -# type Required. Selects the runner: "locust" | "nighthawk-ingress". +# type Required. Selects the runner: "locust" | "nighthawk-ingress" | +# "nighthawk-egress". # Each type's own fields are described in its section. # targetCluster Required. Names a config file under # /etc/orchestrator/target-clusters/ (e.g. `targetCluster: @@ -25,7 +26,8 @@ # orchestrator copies that file into the cloned repo as # .ate-dev-env.sh before the test runs and deletes it # after, so different tests can target different clusters -# / projects from one CronJob run. +# / projects from one CronJob run. --env-file overrides +# this: every test sources that file instead. # sandboxClass Optional (default "gvisor"). Sandbox runtime for the # benchmark WorkerPool: "gvisor" | "microvm". # workerCount Optional (default 1). WorkerPool replica count for the @@ -112,6 +114,24 @@ # seconds, or the step falls short of its rate. A resumepaused iteration is a # resume plus a pause, so size it by the p99 of both together. # +# Optional `evaluations` judges the run against conditions on its results: +# runner.py writes the verdicts to evaluation.json and adds rows to +# stats.jsonl (evaluation_, and evaluations for the summary); they never +# fail the run. The orchestrator passes the whole entry to runner.py as +# --test-entry. A cel input's `from_test` names another test of this file +# (such as its 1-user test, listed earlier), whose run from the same +# orchestrator invocation it reads. See benchmarking/evaluate/README.md; check +# a file with `cd benchmarking && python3 -m evaluate --check-config --tests-file F`. +# +# evaluations: +# - name: envelope +# variables: +# - name: trial +# source: run_results +# source_cfg: {metric: trial_summary, measurements: [aggregate_failure_ratio]} +# conditions: +# - {name: failure_ratio, cel: "trial.aggregate_failure_ratio <= 0.001"} +# # An optional `controlPlane:` block shapes the control plane for a capacity # run; pre_test applies it after the deploy. Its `apiServer:` section, which # is required, sizes ate-api-server: @@ -139,6 +159,17 @@ # the "Configuration knobs" table in benchmarking/nighthawk-ingress/README.md. # `workerCount` is required: the benchmark warms one actor per worker, so # it is also the actor fleet size. +# +# ---- type: nighthawk-egress --------------------------------------------------------- +# +# Runs the Nighthawk adaptive egress-gateway capacity benchmark. `duration` is +# the job-wait budget only; the test knobs live in a `nighthawk-egress:` block. +# Deploys its own gVisor rig (`USES_SHARED_WORKLOADS = False`), so `sandboxClass` +# must be `gvisor` and shared-workload fields (`workerCount`, `actorMemory`, +# `actorCPU`, `workerMemory`, `workerWaitTimeout`, `isolate`) are rejected. +# The block takes `mode` (`http`, `mitm` or `passthrough`), which is required. +# The gateway runs at 1 CPU. See the "Configuration knobs" table in +# benchmarking/nighthawk-egress/README.md. tests: - name: glutton_baseline_1_user @@ -698,6 +729,24 @@ tests: nighthawk-ingress: envoyCpu: 16 tailLatencySloMs: 25 + - name: egress_gatewaycap_http_1cpu + description: "Egress gateway capacity (cleartext HTTP): Nighthawk adaptive max-RPS search under a 25ms tail-latency SLO, Envoy at 1 CPU" + type: nighthawk-egress + targetCluster: dev + duration: 30m + ateArgs: + - "--cordon-system-infra-components" + nighthawk-egress: + mode: http + - name: egress_gatewaycap_mitm_1cpu + description: "Egress gateway capacity (TLS MITM): Nighthawk adaptive max-RPS search under a 25ms tail-latency SLO, Envoy at 1 CPU" + type: nighthawk-egress + targetCluster: dev + duration: 30m + ateArgs: + - "--cordon-system-infra-components" + nighthawk-egress: + mode: mitm # ate-api-server and Postgres cold resume ceiling on the fake data plane. # Each user owns one actor: its first iteration creates the actor and # makes it cold, in the step that adds the user, and every later one diff --git a/benchmarking/automation/testtypes/__init__.py b/benchmarking/automation/testtypes/__init__.py index f304428be0..95bb862f34 100644 --- a/benchmarking/automation/testtypes/__init__.py +++ b/benchmarking/automation/testtypes/__init__.py @@ -19,10 +19,15 @@ validate(test) preflight, before any cluster work. Raises ValueError on a malformed entry; may normalize it (nighthawk-ingress requires workerCount). + check_workloads(test) after the checkout, before any cluster work, for + every test: raises ValueError if the test's + workloads can't be resolved from the checkout. build_image(commit) builds + pushes the runner image; called lazily, once per (target cluster, type). - pre_test(test) after deploy_substrate, before deploy_workloads — - the type's chance to shape the cluster. + pre_test(test) after deploy_substrate, before workloads: the + type's chance to shape the cluster. + workloads(test) installs the workloads the test needs (see + workloads/) and waits until they are ready. job_tmpl(manifests_dir) path of the type's own Job template. job_subs(test) the type's ${...} substitutions for it. The test @@ -30,8 +35,14 @@ orchestrator renders the template, submits the Job, waits, tails logs, deletes it. -No post_test hook: teardown is type-independent today. Name it here when -a type needs one. + teardown_workloads() cleans up type-specific workloads. The sweep + before each test calls it for every type. + + USES_SHARED_WORKLOADS + True when the type's workloads come from + benchmarking/workloads/deploy.sh, so the shared + delete runs at teardown. A type with False deletes + its own workloads in teardown_workloads(). Adding a test type = one new module here + one entry in TYPES. """ @@ -39,21 +50,27 @@ from typing import Any, Protocol from testtypes import locust +from testtypes import nighthawk_egress from testtypes import nighthawk_ingress class TestType(Protocol): TEST_TYPE: str + USES_SHARED_WORKLOADS: bool def validate(self, test: dict[str, Any]) -> None: ... + def check_workloads(self, test: dict[str, Any]) -> None: ... def build_image(self, commit: str) -> str: ... def pre_test(self, test: dict[str, Any]) -> None: ... + def workloads(self, test: dict[str, Any]) -> None: ... def job_tmpl(self, manifests_dir: str) -> str: ... def job_subs(self, test: dict[str, Any]) -> dict[str, Any]: ... + def teardown_workloads(self) -> None: ... TYPES: dict[str, TestType] = { locust.TEST_TYPE: locust, + nighthawk_egress.TEST_TYPE: nighthawk_egress, nighthawk_ingress.TEST_TYPE: nighthawk_ingress, } @@ -62,5 +79,15 @@ def job_subs(self, test: dict[str, Any]) -> dict[str, Any]: ... # (orchestrator, run-dev.sh, the unit tests) fails at import instead of # mid-benchmark. for _name, _mod in TYPES.items(): - for _hook in ("validate", "build_image", "pre_test", "job_tmpl", "job_subs"): + for _hook in ( + "validate", + "check_workloads", + "build_image", + "pre_test", + "workloads", + "job_tmpl", + "job_subs", + "teardown_workloads", + "USES_SHARED_WORKLOADS", + ): assert hasattr(_mod, _hook), f"test type {_name!r} missing hook {_hook!r}" diff --git a/benchmarking/automation/testtypes/locust.py b/benchmarking/automation/testtypes/locust.py index 3dcf542519..06357ea9e4 100644 --- a/benchmarking/automation/testtypes/locust.py +++ b/benchmarking/automation/testtypes/locust.py @@ -20,15 +20,39 @@ An optional `controlPlane:` block shapes ate-api-server and Postgres for a capacity run (see controlplane.py); without it pre_test leaves the cluster as installed. + +The runner gets the whole entry (--test-entry) and judges the run against +its optional `evaluations:` (benchmarking/evaluate/README.md). This image +doesn't ship the evaluate package, so validate checks their shape only; the +runner checks the rest before its run, and `python -m evaluate +--check-config` checks a tests file offline. + +The test's stub (the /app/tests/ entry in `file`) says which workloads the +test needs, through a workloads(test) function that returns (name, config) +pairs for workloads.install_all. """ +import importlib.util import os from typing import Any import controlplane from util import build_and_push +from workloads import install_all, resolve TEST_TYPE = "locust" +USES_SHARED_WORKLOADS = True + + +def teardown_workloads() -> None: + pass + +# The runner image's stub directory, and where the stubs are in the repo. +IMAGE_STUB_DIR = "/app/tests/" +REPO_STUB_DIR = "benchmarking/locust/tests" +# Set while the orchestrator loads a stub, so the stub skips its locust +# imports and User class. The orchestrator image has no locust. +NO_USERS_ENV = "LOCUST_NO_USERS" def control_plane_config(test: dict[str, Any]) -> dict[str, Any] | None: @@ -38,11 +62,34 @@ def control_plane_config(test: dict[str, Any]) -> dict[str, Any] | None: return controlplane.config(test["controlPlane"]) +def validate_evaluations_shape(test: dict[str, Any]) -> None: + """Raises ValueError unless evaluations is a list of mappings with a name.""" + name = test.get("name") + evaluations = test.get("evaluations", []) + if not isinstance(evaluations, list) or not all( + isinstance(e, dict) and isinstance(e.get("name"), str) and e["name"] for e in evaluations + ): + raise ValueError(f"locust test {name!r}: evaluations must be a list of mappings, each with a name") + + +def stub_path(test: dict[str, Any]) -> str: + """The repo path of the test's stub. Raises ValueError unless `file` + has exactly one /app/tests/ entry.""" + stubs = [f for f in str(test["file"]).split(",") if f.startswith(IMAGE_STUB_DIR)] + if len(stubs) != 1: + raise ValueError( + f"locust test {test.get('name')!r}: file needs one {IMAGE_STUB_DIR} entry, got {test['file']!r}" + ) + return os.path.join(REPO_STUB_DIR, stubs[0].removeprefix(IMAGE_STUB_DIR)) + + def validate(test: dict[str, Any]) -> None: name = test.get("name") for field in ("file", "duration", "users"): if field not in test: raise ValueError(f"locust test {name!r} missing {field!r}") + validate_evaluations_shape(test) + stub_path(test) if "controlPlane" not in test: return try: @@ -68,6 +115,41 @@ def pre_test(test: dict[str, Any]) -> None: controlplane.shape(cfg) +def _stub_workloads(test: dict[str, Any]) -> list[tuple[str, dict[str, Any]]]: + """The (name, config) pairs the test's stub returns. Runs from the repo + root of the branch under test, so the stub comes from that branch.""" + path = stub_path(test) + spec = importlib.util.spec_from_file_location("locust_stub", path) + stub = importlib.util.module_from_spec(spec) + prev = os.environ.get(NO_USERS_ENV) + os.environ[NO_USERS_ENV] = "1" + try: + spec.loader.exec_module(stub) + except ImportError as e: + raise ValueError(f"{path} must load without locust when {NO_USERS_ENV}=1: {e}") from e + finally: + if prev is None: + del os.environ[NO_USERS_ENV] + else: + os.environ[NO_USERS_ENV] = prev + if not hasattr(stub, "workloads"): + raise ValueError(f"{path} does not define workloads(test)") + return list(stub.workloads(test)) + + +def check_workloads(test: dict[str, Any]) -> None: + """Load the test's stub and look up the workloads it names.""" + try: + resolve(_stub_workloads(test)) + except ValueError as e: + raise ValueError(f"locust test {test.get('name')!r}: {e}") from None + + +def workloads(test: dict[str, Any]) -> None: + """Install the workloads the test's stub asks for.""" + install_all(_stub_workloads(test)) + + def job_tmpl(manifests_dir: str) -> str: return os.path.join(manifests_dir, "runner-job.yaml.tmpl") diff --git a/benchmarking/automation/testtypes/nighthawk_egress.py b/benchmarking/automation/testtypes/nighthawk_egress.py new file mode 100644 index 0000000000..022b9ea4d9 --- /dev/null +++ b/benchmarking/automation/testtypes/nighthawk_egress.py @@ -0,0 +1,211 @@ +# Copyright 2026 The Agent Substrate 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. + +"""`type: nighthawk-egress` test definition for the benchmark orchestrator.""" + +import json +import os +import subprocess +from typing import Any + +from util import build_and_push, run, run_no_check + +TEST_TYPE = "nighthawk-egress" +DOCKERFILE = "benchmarking/nighthawk-egress/Dockerfile" +USES_SHARED_WORKLOADS = False +# The rig loads the gateway from one actor and is sized for one Envoy worker thread. +ENVOY_CPU = 1 + +_REQUIRED = ("mode",) +_VALID_MODES = ("http", "mitm", "passthrough") +_UNSUPPORTED_TOP_LEVEL_KEYS = ( + "workerCount", + "actorMemory", + "actorCPU", + "workerMemory", + "workerWaitTimeout", + "isolate", +) + + +def shape_atenet_egress(envoy_cpu: int) -> None: + """Pin deployment/atenet-egress to 1 replica and envoy_cpu cores, then wait for rollout.""" + # stdout only, so the stderr of a failed read stays on the log. + res = run( + ["kubectl", "-n", "ate-system", "get", "deployment/atenet-egress", "-o", "json"], + stdout=subprocess.PIPE, + text=True, + ) + dep = json.loads(res.stdout) + containers = dep["spec"]["template"]["spec"]["containers"] + envoy = next((c for c in containers if c["name"] == "envoy"), None) + if envoy is None: + raise RuntimeError("deployment/atenet-egress has no envoy container") + + args = list(envoy.get("args", [])) + filtered: list[str] = [] + skip_next = False + for a in args: + if skip_next: + skip_next = False + continue + if a == "--concurrency": + skip_next = True + continue + filtered.append(a) + # Envoy takes "--concurrency N" (patchAtenetEgressEnvoyConcurrency in cmd/ate-setup/internal/steps/overlay.go). + filtered.extend(["--concurrency", str(envoy_cpu)]) + + target_m = envoy_cpu * 1000 + cpu_res = {"requests": {"cpu": f"{target_m}m"}, "limits": {"cpu": f"{target_m}m"}} + patch_containers = [ + {"name": "envoy", "args": filtered, "resources": cpu_res}, + {"name": "ext-proc", "resources": cpu_res}, + ] + patch = {"spec": {"replicas": 1, "template": {"spec": {"containers": patch_containers}}}} + + run( + [ + "kubectl", + "-n", + "ate-system", + "patch", + "deployment/atenet-egress", + "--type=strategic", + "-p", + json.dumps(patch), + ] + ) + run( + [ + "kubectl", + "-n", + "ate-system", + "rollout", + "status", + "deployment/atenet-egress", + "--timeout=300s", + ] + ) + + +def validate(test: dict[str, Any]) -> None: + name = test.get("name", "") + if "duration" not in test: + raise ValueError(f"nighthawk-egress test '{name}' missing 'duration'") + sandbox_class = test.get("sandboxClass", "gvisor") + if sandbox_class != "gvisor": + raise ValueError( + f"nighthawk-egress test '{name}' only supports sandboxClass 'gvisor', got {sandbox_class!r}" + ) + unsupported = sorted(set(_UNSUPPORTED_TOP_LEVEL_KEYS) & set(test)) + if unsupported: + raise ValueError( + f"nighthawk-egress test '{name}' does not support shared-workload field(s): {unsupported}" + ) + cfg = test.get("nighthawk-egress") + if not isinstance(cfg, dict): + raise ValueError(f"nighthawk-egress test '{name}' requires 'nighthawk-egress:' block") + unknown = set(cfg) - set(_REQUIRED) + if unknown: + raise ValueError( + f"nighthawk-egress test '{name}' has unknown knob(s): {sorted(unknown)}" + ) + for k in _REQUIRED: + if k not in cfg: + raise ValueError(f"nighthawk-egress test '{name}' missing nighthawk-egress.{k}") + mode = cfg["mode"] + if mode not in _VALID_MODES: + raise ValueError( + f"nighthawk-egress test '{name}': mode must be one of {_VALID_MODES}, got {mode!r}" + ) + if "flags" in test: + raise ValueError(f"nighthawk-egress test '{name}': put knobs under 'nighthawk-egress:'") + + +def build_image(commit: str) -> str: + return build_and_push( + f"{os.environ['KO_DOCKER_REPO']}/nighthawk-egress-test:{commit}", + DOCKERFILE, + ) + + +def pre_test(test: dict[str, Any]) -> None: + shape_atenet_egress(ENVOY_CPU) + # Pass the active kubeconfig context so setup-e2e-egress-tls-kind.sh does not default to kind-kind. + ctx = run(["kubectl", "config", "current-context"], stdout=subprocess.PIPE, text=True).stdout.strip() + env = {**os.environ, "KUBECTL_CONTEXT": ctx} + run(["hack/setup-e2e-egress-tls-kind.sh"], env=env) + run(["benchmarking/nighthawk-egress/deploy.sh", "--deploy"]) + run(["benchmarking/nighthawk-egress/deploy-traffic-driver.sh", "--deploy"]) + + +def check_workloads(test: dict[str, Any]) -> None: + """pre_test deploys the nighthawk-egress workloads, so there is nothing to check.""" + + +def workloads(test: dict[str, Any]) -> None: + """pre_test deploys the nighthawk-egress workloads.""" + + +def teardown_workloads() -> None: + # stderr stays on the log, so a failed read does not look like a missing namespace. + ns = run_no_check( + ["kubectl", "get", "namespace", "nighthawk", "-o", "name", "--ignore-not-found"], + stdout=subprocess.PIPE, + text=True, + ) + if ns.returncode == 0 and not ns.stdout.strip(): + return + api = run_no_check( + [ + "kubectl", + "get", + "deployment", + "ate-api-server", + "-n", + "ate-system", + "-o", + "name", + "--ignore-not-found", + ], + stdout=subprocess.PIPE, + text=True, + ) + if api.stdout.strip(): + run_no_check(["benchmarking/nighthawk-egress/deploy-traffic-driver.sh", "--delete"]) + else: + run_no_check( + [ + "kubectl", + "delete", + "--ignore-not-found", + "-f", + "benchmarking/nighthawk-egress/traffic-driver.yaml.tmpl", + ] + ) + run_no_check(["benchmarking/nighthawk-egress/deploy.sh", "--delete"]) + run_no_check(["kubectl", "delete", "namespace", "nighthawk", "--ignore-not-found"]) + + +def job_tmpl(manifests_dir: str) -> str: + return os.path.join(manifests_dir, "nighthawk-egress-runner-job.yaml.tmpl") + + +def job_subs(test: dict[str, Any]) -> dict[str, str]: + cfg = test["nighthawk-egress"] + return { + "ENVOY_CPU": str(ENVOY_CPU), + "MODE": str(cfg["mode"]), + } diff --git a/benchmarking/automation/testtypes/nighthawk_ingress.py b/benchmarking/automation/testtypes/nighthawk_ingress.py index c601939523..6cebd8d085 100644 --- a/benchmarking/automation/testtypes/nighthawk_ingress.py +++ b/benchmarking/automation/testtypes/nighthawk_ingress.py @@ -26,8 +26,15 @@ from typing import Any from util import build_and_push, parse_duration_seconds, run +from workloads import install_all TEST_TYPE = "nighthawk-ingress" +USES_SHARED_WORKLOADS = True + + +def teardown_workloads() -> None: + pass + # Defaults for the tests.yaml `nighthawk-ingress:` block; envoyCpu has no default — # it is the benchmark's independent variable. Documented in @@ -178,6 +185,15 @@ def pre_test(test: dict[str, Any]) -> None: ) +def check_workloads(test: dict[str, Any]) -> None: + """Always deploy_sh, so there is nothing to check.""" + + +def workloads(test: dict[str, Any]) -> None: + """Every nighthawk-ingress test uses deploy.sh's default workloads.""" + install_all([("deploy_sh", test)]) + + def job_subs(test: dict[str, Any]) -> dict[str, Any]: """Template substitutions specific to the nighthawk runner Job.""" nh = config(test) diff --git a/benchmarking/automation/util.py b/benchmarking/automation/util.py index f0eb0f459d..bd46634170 100644 --- a/benchmarking/automation/util.py +++ b/benchmarking/automation/util.py @@ -120,16 +120,25 @@ def isolate_install_args(test: dict) -> list[str]: return [] if isolate_block(test) is None else ["--fake-data-plane"] -def isolate_workload_args(test: dict) -> list[str]: - """Return the benchmarking/workloads/deploy.sh flags that tune fake-atelet - for a tests.yaml entry's isolate block, or none without a block.""" +def isolate_tuning_env(test: dict) -> list[str]: + """Return the FAKE_ATELET_=VALUE entries a tests.yaml entry's + isolate block tunes fake-atelet with, or none without a block.""" block = isolate_block(test) or {} - args = [] + entries = [] for key, env in ISOLATE_TUNING.items(): if key not in block: continue value = block[key] if isinstance(value, bool): value = "true" if value else "false" - args += ["--fake-atelet-env", f"{env}={value}"] + entries.append(f"{env}={value}") + return entries + + +def isolate_workload_args(test: dict) -> list[str]: + """Return the benchmarking/workloads/deploy.sh flags that tune fake-atelet + for a tests.yaml entry's isolate block, or none without a block.""" + args = [] + for entry in isolate_tuning_env(test): + args += ["--fake-atelet-env", entry] return args diff --git a/benchmarking/automation/workers.py b/benchmarking/automation/workers.py new file mode 100644 index 0000000000..addd59bf3b --- /dev/null +++ b/benchmarking/automation/workers.py @@ -0,0 +1,197 @@ +# Copyright 2026 The Agent Substrate 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. + +"""The benchmark workers, shared by every test type. + +A test's workers are the benchmark WorkerPool. How many, which sandbox +class and how big come from the tests.yaml entry (workerCount, sandboxClass, +workerMemory, workerWaitTimeout, and the isolate block's fake-atelet +tuning), not from the test's workloads: + + workers.config(test) preflight, before any cluster work + workers.install(test) after deploy_substrate: fake-atelet tuning, the + WorkerPool, and a wait for its workers + workers.teardown() after the test, before teardown_substrate + +The sandbox class's SandboxConfig comes from deploy_substrate, which passes +--sandbox-classes to ate-setup. The WorkerPool is rendered from +manifests/workloads.yaml.tmpl, the same file workloads/deploy.sh uses. +Commands run from the substrate repo root, like the rest of the orchestrator. +""" + +from dataclasses import dataclass +from string import Template +from typing import Any + +from util import isolate_tuning_env, run, run_no_check + +POOL_MANIFEST = "benchmarking/workloads/manifests/workloads.yaml.tmpl" +NAMESPACE = "benchmark-workloads" +POOL_NAME = "benchmark-worker" +SANDBOX_CLASSES = ("gvisor", "microvm") +DEFAULT_WAIT_TIMEOUT_SECS = 300 + + +@dataclass(frozen=True) +class Config: + """A test's workers, resolved from its tests.yaml entry.""" + + count: int = 1 + sandbox_class: str = "gvisor" + # Worker pod memory, set as both request and limit. Empty leaves the pod + # unsized. + memory: str = "" + wait_timeout_secs: int = DEFAULT_WAIT_TIMEOUT_SECS + # FAKE_ATELET_=VALUE entries from the isolate block. + fake_atelet_env: tuple[str, ...] = () + + +def config(test: dict[str, Any]) -> Config: + """The workers a tests.yaml entry asks for, with defaults filled in. + Raises ValueError on a malformed entry.""" + name = test.get("name") + count = test.get("workerCount", 1) + if isinstance(count, bool) or not isinstance(count, int) or count < 0: + raise ValueError(f"test {name!r}: workerCount must be a whole number, got {count!r}") + sandbox_class = test.get("sandboxClass", "gvisor") + if sandbox_class not in SANDBOX_CLASSES: + raise ValueError( + f"test {name!r}: sandboxClass must be one of {list(SANDBOX_CLASSES)}, got {sandbox_class!r}" + ) + memory = test.get("workerMemory") + if memory is None: + memory = "" + if not isinstance(memory, str): + raise ValueError(f"test {name!r}: workerMemory must be a quantity like 8Gi, got {memory!r}") + timeout = test.get("workerWaitTimeout", DEFAULT_WAIT_TIMEOUT_SECS) + # A whole number of seconds; YAML may load it as an int or a string. + if isinstance(timeout, bool) or not str(timeout).isdecimal(): + raise ValueError( + f"test {name!r}: workerWaitTimeout must be a whole number of seconds, got {timeout!r}" + ) + try: + fake_atelet_env = isolate_tuning_env(test) + except ValueError as e: + raise ValueError(f"test {name!r}: {e}") from None + return Config( + count=count, + sandbox_class=sandbox_class, + memory=memory, + wait_timeout_secs=int(timeout), + fake_atelet_env=tuple(fake_atelet_env), + ) + + +def render_pool(cfg: Config) -> str: + """The WorkerPool manifest for cfg, as deploy.sh substitutes it.""" + # One flow-style line, so an unsized pod leaves only a blank line. + resources = "" + if cfg.memory: + resources = ( + f'resources: {{requests: {{memory: "{cfg.memory}"}}, ' + f'limits: {{memory: "{cfg.memory}"}}}}' + ) + with open(POOL_MANIFEST) as f: + return Template(f.read()).substitute( + WORKER_COUNT=cfg.count, + SANDBOX_CLASS=cfg.sandbox_class, + WORKER_RESOURCES=resources, + ) + + +def install(test: dict[str, Any]) -> Config: + """Set up the test's workers and wait until they are ready. Needs the + substrate CRDs, so it runs after deploy_substrate.""" + cfg = config(test) + fake = _fake_data_plane() + # Before the pool, so its fake Workers are served by the tuned fake-atelet. + if fake: + _tune_fake_atelet(cfg) + elif cfg.fake_atelet_env: + raise RuntimeError("an isolate block needs substrate installed with --fake-data-plane") + print( + f"Installing workers (count={cfg.count}, sandbox_class={cfg.sandbox_class}, " + f"memory={cfg.memory or 'unset'})...", + flush=True, + ) + # ko resolves the ko:// worker image before kubectl sees it. + run(["hack/run-tool.sh", "ko", "apply", "-f", "-"], input=render_pool(cfg), text=True) + _wait_ready(cfg, fake) + return cfg + + +def teardown() -> None: + """Remove the workers. Safe to run on a clean cluster. Runs after the + test's ActorTemplates are deleted, and before teardown_substrate, which + removes the CRDs these objects need.""" + run_no_check( + ["kubectl", "delete", "workerpool", POOL_NAME, f"--namespace={NAMESPACE}", "--ignore-not-found"] + ) + run_no_check(["kubectl", "delete", "namespace", NAMESPACE, "--ignore-not-found"]) + + +def _wait_ready(cfg: Config, fake: bool) -> None: + timeout = f"--timeout={cfg.wait_timeout_secs}s" + if fake: + # No Deployment is made for the pool; fake-workersync counts a fake + # Worker ready once its capacity is reported, and writes that to the + # pool's status. + if cfg.count > 0: + run( + [ + "kubectl", "wait", + f"--for=jsonpath={{.status.readyReplicas}}={cfg.count}", + f"workerpool/{POOL_NAME}", f"--namespace={NAMESPACE}", timeout, + ] + ) + return + run(["kubectl", "wait", "--for=create", f"deployment/{POOL_NAME}", f"--namespace={NAMESPACE}", timeout]) + run(["kubectl", "rollout", "status", f"deployment/{POOL_NAME}", f"--namespace={NAMESPACE}", timeout]) + + +def _kubectl_output(args: list[str]) -> str: + return run(["kubectl", *args], capture_output=True, text=True).stdout.strip() + + +def _fake_data_plane() -> bool: + """Whether substrate was installed with --fake-data-plane, which serves + the WorkerPool with fake Workers instead of worker pods.""" + return bool( + _kubectl_output( + ["get", "deployment/fake-workersync", "--namespace=ate-system", "-o", "name", "--ignore-not-found"] + ) + ) + + +def _tune_fake_atelet(cfg: Config) -> None: + """Write cfg's tuning, and nothing else, to the fake-atelet-tuning + ConfigMap fake-atelet loads its flags from, and restart fake-atelet when + that changes the ConfigMap.""" + get = ["get", "configmap", "fake-atelet-tuning", "--namespace=ate-system", "-o", "jsonpath={.data}"] + before = _kubectl_output([*get, "--ignore-not-found"]) + manifest = _kubectl_output( + [ + "create", "configmap", "fake-atelet-tuning", "--namespace=ate-system", + *(f"--from-literal={e}" for e in cfg.fake_atelet_env), + "--dry-run=client", "-o", "yaml", + ] + ) + run(["kubectl", "apply", "-f", "-"], input=manifest, text=True) + if _kubectl_output(get) == before: + return + print(f"Restarting fake-atelet with its new tuning ({' '.join(cfg.fake_atelet_env) or 'defaults'})...", flush=True) + # The DaemonSet name carries the version, so it is addressed by label. + for ds in _kubectl_output(["get", "daemonset", "--namespace=ate-system", "-l", "app=atelet", "-o", "name"]).split(): + run(["kubectl", "rollout", "restart", "--namespace=ate-system", ds]) + run(["kubectl", "rollout", "status", "--namespace=ate-system", ds, f"--timeout={cfg.wait_timeout_secs}s"]) diff --git a/benchmarking/automation/workloads/__init__.py b/benchmarking/automation/workloads/__init__.py new file mode 100644 index 0000000000..94cecd7f17 --- /dev/null +++ b/benchmarking/automation/workloads/__init__.py @@ -0,0 +1,57 @@ +# Copyright 2026 The Agent Substrate 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. + +"""One module per workload type. Workloads are shared across test types. + +Each module implements: + + install(config) installs the workload and waits until it is ready. + +A test type's workloads(test) hook decides which workloads a test needs, +as (name, config) pairs, and passes them to install_all. Tests name a +workload by its WORKLOADS key, so the locust stubs, which live outside +benchmarking/automation, never import these modules. + +Adding a workload = one new module here + one entry in WORKLOADS. +""" + +from typing import Any, Iterable, Protocol + +from workloads import deploy_sh + + +class Workload(Protocol): + def install(self, config: dict[str, Any]) -> None: ... + + +WORKLOADS: dict[str, Workload] = { + "deploy_sh": deploy_sh, +} + + +def resolve(entries: Iterable[tuple[str, dict[str, Any]]]) -> list[tuple[Workload, dict[str, Any]]]: + """Look up each (name, config) pair. Raises ValueError on an unknown name.""" + resolved = [] + for name, config in entries: + if name not in WORKLOADS: + raise ValueError(f"unknown workload {name!r} (want one of {list(WORKLOADS)})") + resolved.append((WORKLOADS[name], config)) + return resolved + + +def install_all(entries: Iterable[tuple[str, dict[str, Any]]]) -> None: + """Install each (name, config) pair in order. Raises ValueError on an + unknown name, before anything is installed.""" + for module, config in resolve(entries): + module.install(config) diff --git a/benchmarking/automation/workloads/deploy_sh.py b/benchmarking/automation/workloads/deploy_sh.py new file mode 100644 index 0000000000..d36e2173c5 --- /dev/null +++ b/benchmarking/automation/workloads/deploy_sh.py @@ -0,0 +1,60 @@ +# Copyright 2026 The Agent Substrate 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. + +"""The deploy_sh workload: benchmarking/workloads/deploy.sh --deploy. + +deploy.sh sets up the WorkerPool and its default ActorTemplates and waits +for their golden snapshots. Its config is the test's whole tests.yaml +entry, because deploy.sh sizes the pool and the actors from the entry's +workerCount, sandboxClass, workerMemory, workerWaitTimeout, actorMemory, +actorCPU and isolate fields. +""" + +from typing import Any + +from util import isolate_workload_args, run + + +def install(test: dict[str, Any]) -> None: + cmd = [ + "benchmarking/workloads/deploy.sh", + "--deploy", + "--worker-count", + str(test.get("workerCount", 1)), + "--sandbox-class", + test.get("sandboxClass", "gvisor"), + ] + # Empty keeps the default in workloads/deploy.sh (256Mi); RAM-consuming + # suites set actorMemory in tests.yaml. + if actor_memory := test.get("actorMemory", ""): + cmd += ["--actor-memory", actor_memory] + # Empty keeps the default in workloads/deploy.sh (1 CPU). The scheduler + # books the limit against worker CPU capacity, so dense suites set + # actorCPU in tests.yaml to fit more actors per worker. + # str() because a whole number of cores (actorCPU: 1) parses as an int. + if actor_cpu := test.get("actorCPU", ""): + cmd += ["--actor-cpu", str(actor_cpu)] + # Empty leaves the worker pods unsized; set workerMemory in tests.yaml to + # control how many workers the scheduler packs onto a node. + if worker_memory := test.get("workerMemory", ""): + cmd += ["--worker-memory", worker_memory] + # Empty keeps deploy.sh's own default; large fleets set workerWaitTimeout + # (whole seconds). + wait_timeout_secs = test.get("workerWaitTimeout", "") + if wait_timeout_secs != "": + cmd += ["--wait-timeout", str(wait_timeout_secs)] + # An isolate block's tuning of fake-atelet, on the fake data plane. + cmd += isolate_workload_args(test) + # deploy.sh itself blocks until every template's golden snapshot exists. + run(cmd) diff --git a/benchmarking/deploy_locust.sh b/benchmarking/deploy_locust.sh index bf207fa68c..2dbac2e800 100755 --- a/benchmarking/deploy_locust.sh +++ b/benchmarking/deploy_locust.sh @@ -28,6 +28,8 @@ BENCHMARKING_DIR="${ROOT}/benchmarking" WORKER_COUNT=1 SANDBOX_CLASS=gvisor SKIP_BUILD=0 +# Empty keeps the default in locust/deploy.sh (glutton). +BENCHMARK_USER_CLASS="" OTLP_ENDPOINT="" # Empty keeps the default in workloads/deploy.sh (256Mi). ACTOR_MEMORY="" @@ -58,6 +60,8 @@ usage() { echo " external volume; setting it deploys glutton-storage." echo " --wait-timeout SECONDS Forwarded to workloads/deploy.sh. The timeout in seconds for" echo " waiting for the workers to be ready (default: 300)" + echo " --user-class NAME Forwarded to locust/deploy.sh. Locust user class," + echo " lowercase; runs locust/tests/NAME.py (default: glutton)." echo " --skip-build Skip locust image build/push (use the existing :latest image)" echo " -h|--help Show this help message" echo "" @@ -92,6 +96,8 @@ while [[ "$#" -gt 0 ]]; do --storage-class-name=*) STORAGE_CLASS_NAME="${1#*=}" ;; --wait-timeout) shift; WAIT_TIMEOUT_SECS="$1" ;; --wait-timeout=*) WAIT_TIMEOUT_SECS="${1#*=}" ;; + --user-class) shift; BENCHMARK_USER_CLASS="$1" ;; + --user-class=*) BENCHMARK_USER_CLASS="${1#*=}" ;; --skip-build) SKIP_BUILD=1 ;; -h|--help) usage; exit 0 ;; *) @@ -153,7 +159,14 @@ if [[ "${action}" == "deploy" ]]; then echo echo "=== Deploying locust ===" - "${BENCHMARKING_DIR}/locust/deploy.sh" --deploy + # An empty --user-class must not be forwarded, or it would override the + # default in locust/deploy.sh with an empty string and fail the + # tests/.py existence check. + locust_args=(--deploy) + if [[ -n "${BENCHMARK_USER_CLASS}" ]]; then + locust_args+=(--user-class "${BENCHMARK_USER_CLASS}") + fi + "${BENCHMARKING_DIR}/locust/deploy.sh" "${locust_args[@]}" elif [[ "${action}" == "delete" ]]; then echo "=== Deleting locust ===" "${BENCHMARKING_DIR}/locust/deploy.sh" --delete diff --git a/benchmarking/evaluate/README.md b/benchmarking/evaluate/README.md new file mode 100644 index 0000000000..11df3b63d4 --- /dev/null +++ b/benchmarking/evaluate/README.md @@ -0,0 +1,395 @@ +# Run evaluations + +`evaluate` judges a finished benchmark run against CEL conditions declared in +its test entry, and returns the verdicts as a `Report`. +Depends on [`cel-expr-python`](https://github.com/cel-expr/cel-python) and +[pydantic](https://docs.pydantic.dev/) (`requirements.txt`, Python 3.11 or later). + +## Model + +- A **source** reads the run and returns several named **values**, or + says it can't judge the run (`invalid`, with a reason). Sources: + `cel`, `run_results`. +- A **variable** is one source query: `{name, source, source_cfg}`. Its values + are exposed to CEL as a map under `` (`.`, or + `[""]` when `` contains dots or CEL keywords). +- A **condition** is `{name, cel}`: a [CEL](https://cel.dev/) boolean + expression over the variables. +- An **evaluation** is a named set of variables and conditions, AND-ed: it + `fail`s if any condition failed, else is `invalid` if any condition or + variable is invalid, else `pass`es. Evaluations are judged independently, with no hierarchy between + them. +- The run's **summary** combines its evaluations the same way. +- `passed` is true for `pass` only, and false for both `fail` and `invalid`, + so an alert should key on `passed`. + +## Config + +Evaluations live in the test entry, next to the test they judge. This one +checks two envelope health gates: + +```yaml +- name: sweperf_150u_c3hc192metal_microvm + # ... + evaluations: + - name: envelope_health + description: "Failure ratio and worker memory within the scalability envelope" + variables: + - name: trial + source: run_results + source_cfg: {metric: trial_summary, measurements: [aggregate_failure_ratio, allocatable_ram_gb]} + - name: server + source: run_results + source_cfg: {metric: server_summary, measurements: [working_set_node_max_gb]} + conditions: + - {name: failure_rate, cel: "trial.aggregate_failure_ratio <= 0.001"} + - {name: worker_memory, cel: "server.working_set_node_max_gb < 0.85 * trial.allocatable_ram_gb"} +``` + +- Evaluation, variable and condition names match `^[a-z][a-z0-9_]*$`, at most + 64 characters, and are unique where they live. A variable name can't contain + `__` or end in `_` (see [Outputs](#outputs)). CEL itself rejects a + variable named after a CEL type (`int`, `map`) or a keyword (`in`, `true`) + when a condition compiles. Value names come from the source + and may be any non-empty string + (`locust_ResumeActor`, `metric_nighthawk.builtin_attempted_rps`, `p99.9`). + Unknown or non-string mapping keys are errors, and `source_cfg` holds JSON + values only, so a YAML date in it is an error too. There is no version field + while the schema is experimental. +- Conditions are standard CEL, compiled when the evaluations load, with + `round(x, digits)` added. Each must evaluate to `bool`: a bare value such as + `trial.ok` compiles, and a result that isn't a bool makes the condition `invalid`. +- Values enter CEL as doubles, whatever number type the source returns, + since they come from JSON, which has one number type, and as ints `a / b` + would be integer division. The results keep the source's own value types. + CEL has no arithmetic between int and double, so write `2.0 * t.x`, not + `2 * t.x`; the same goes for comparing a double expression + (`round(t.x, 1) >= 90.0`). A value compared directly may use an int + literal (`t.x <= 1500`). Mixing int and double fails when the evaluations + load if CEL can see both types; otherwise (`t.x * 100 >= 99`, where + `t.x` is only known at run time) the condition is `invalid` on every run, + so it never passes. +- Missing or null values are omitted from ``'s map: reading one + directly fails lookup and makes the condition `invalid`, while + `has(.)` returns `false` without error. A value CEL can't + hold makes the conditions `invalid`. An `invalid` variable is left out of + the CEL data, so a condition that reads it is `invalid` with CEL's error, + and the evaluation is `invalid` even if no condition reads it: a source + failure never lets an evaluation pass. +- CEL `==` and `!=` across distinct dynamic types (`1.1 == "1.10"`, + `true == 1.0`) evaluate to `false` and `true` without raising an error. Float + division inside a condition follows IEEE-754 (`1.0 / 0.0` produces `+Inf` + and `0.0 / 0.0` produces `NaN`). + +## Sources + +A source is a class with three hooks (`sources/base.py`): + +| hook | runs | does | +|---|---|---| +| `validate(cfg)`, a classmethod | when the evaluations are loaded | raises `ValueError` for a bad `source_cfg` | +| `init(run)` | once, when the run starts (its files may not exist yet) | takes the `BenchmarkRunContext`, the run being evaluated: which run it is (`identity`: `uri`, and `test_name`, `tag`, `run_date`, `run_ts` when known), where it is stored, and its stored artifacts (`artifact(name)`, a local path or None); the source chooses what it reads. `run_of(test)` returns the run of another test from the same invocation or raises `LookupError` | +| `query(cfg)` | after the run, once per distinct `source_cfg` | returns named values (numbers, bools, strings or null), or raises `SourceInvalid(reason, values)` when it can't judge the run | + +Value names come from `source_cfg` or are fixed by the source, never from the +run's data. The evaluator creates one instance of each source the evaluations +name. The values of a `SourceInvalid` are kept in the results, while the +variable and the conditions reading it become `invalid`. Any other exception +from a hook makes the source's variables `invalid` with the error, and so does +a value of another type, such as a list or a mapping, or a value name that +isn't a non-empty string. Sources never write files. A new source is a class +in `sources/` and a line in `SOURCES`. + +### `cel` + +Binds data read from runs to CEL, and evaluates named expressions into +values. The source has no notion of what the data means: what counts as +good, which run to compare against, and every formula live in the config. + +```yaml +source: cel +source_cfg: + inputs: # the data, each a CEL variable + - name: stats + reader: json_lines + reader_cfg: {file: stats.jsonl} + locals: # optional: ordered list of named in-between results + - name: trials + cel: "stats.lines.filter(l, l.metric == 'trial_summary')" + checks: # optional: what must hold for the values to mean anything + - name: has_trial + cel: "size(trials) > 0" + values: # the outputs + - name: cores + cel: "size(trials) > 0 ? dyn(trials[size(trials) - 1].measurements.allocatable_cores) : null" +``` + +- `inputs: [{name: , from_test: ?, reader: , reader_cfg: {...}}, ...]`: + each input names a reader and its `reader_cfg`, and the reader's data + becomes the CEL variable ``. By default the reader reads this run. With `from_test:` it + reads that test's run from the same invocation (`run_of`), which lets a + config compare two runs. +- `locals: [{name: , cel: }, ...]`: ordered list of named in-between + results, such as a filtered list or a median. They are evaluated top to + bottom, so each local may read inputs and earlier locals by bare name. + Entries can share locals through YAML anchors. A local holds whatever CEL + produces, including `timestamp` and `duration`. +- `checks: [{name: , cel: }, ...]`: conditions the data must meet before the + values mean anything (for example, both runs used the same mode). A check + that is false or fails to evaluate makes the variable `invalid`, and the + reason names the check. Unlike an evaluation's conditions, a check judges + the data, not the run. +- `values: [{name: , cel: }, ...]`: the outputs. Each must give a double, bool, + string or `null`; a whole number such as `size(x)` must be converted with + `double()`. Use CEL's native `null` with `dyn()` for missing or empty cases + (`size(xs) > 0 ? dyn(...) : null`). A non-finite float (`0.0 / 0.0`) also + becomes `null`. +- Names match `^[a-z][a-z0-9_]*$` and are unique within each list. An input + and a local can't share a name. + Whole numbers stay integers here (`size(x) - 1` indexes a list), so write + doubles as `1500.0`. +- Functions beyond standard CEL: the CEL math extension (`ext_math`: + `math.least`, `math.greatest`, `math.round`, ...), plus two explicitly + defined numeric helpers: `round(x, digits)` (Python-style rounding, shared + with evaluation conditions) and `percentile(xs, p)` over `list(double)` + (linear interpolation between the closest ranks, `p` from 0 to 100, raising + an error on an empty list like `math.least`/`math.greatest`). + +What is checked, when, and what happens on a mismatch: + +| what | when | on a mismatch | +|---|---|---| +| unknown `source_cfg` key or reader, bad `reader_cfg`, bad or repeated names | config load | the evaluations fail to load | +| `select` / `until` expressions on `json_lines` | config load | load error | +| every expression compiles with inferred local types, and value return types can be double, bool, string or null | config load | load error | +| reader output has its declared `fields`, of their types | run time | `TypeError` makes the variable `invalid` | +| missing JSON keys inside `lines` or `data` | run time | reading a missing key makes the variable `invalid`, unless guarded with `has()` | +| a reader can't read its run (absent file, unhashable `unique_by`, `select` eval error, no run of `from_test`) | run time | `invalid`, and the reason names the input | +| a local, check or value fails to evaluate, or a value gives another type | run time | `invalid`, and the reason names it | + +A reader is a class in `sources/cel/` and a line in `READERS` +(`sources/cel/reader.py`): its `Config` (a pydantic model of its +`reader_cfg`), its `fields` (the top-level fields of its data and their +types, checked at run time; inputs are `map(string, dyn)` in CEL, so a field +name is not checked at config load) and `read(run, cfg)`, which raises +`ReadError` when the run can't be read. A reader exposes data and +passes no judgment on it. All numbers are doubles, and a field a record lacks +is absent rather than null. + +#### `json` + +One JSON object file from the run: `{name: summary, reader: json, reader_cfg: {file: server_summary.json}}`. + +- `data`: the parsed JSON object, with leaf coercion as in `run_results`. +- `uri`: where the run is stored. + +#### `json_lines` + +Filtered lines of one of the run's JSON-lines or prefixed-JSON files: + +```yaml +- name: records + reader: json_lines + reader_cfg: + file: logs.txt + prefix: "[boomer] " + until: "has(line.msg) && line.msg == 'sweperf shutdown started'" + select: "has(line.msg) && line.msg == 'sweperf task record' && has(line.v) && line.v == 1.0" +``` + +- `lines`: selected JSON objects, in file order. Values are coerced as in + `run_results`: numbers and numeric strings without `_` become doubles, + `"true"`/`"false"` become bools, and a null or non-finite number is left out. +- `unparsed_lines`: `[{line_no, text, error}]` for each prefixed (or, when + `prefix` is unset, non-blank) line that isn't a JSON object. +- `uri`: where the run is stored. +- Optional `reader_cfg` keys: + - `prefix`: skip lines not starting with `prefix` and strip it before + parsing JSON (without it, blank lines are skipped). + - `until`: CEL boolean expression over `line`; stop reading when a parsed + object matches (that line is not emitted). + - `select`: CEL boolean expression over `line`; keep only matching objects. + - `unique_by`: field name; keep only the first selected object per distinct + value of that field (useful to bound list size before CEL evaluation). + +Goodput, as config only: a task is good when it ended in the steady phase, +didn't fail, woke within limits (slowest resume 1.5 s, slowest time to first +execute 1 s), and its command time (`cel_ms`) and wall time stayed within 1.5x +of the 1-user run's medians. + +```yaml +- name: sweperf_astropy_150_users_think + # ... + evaluations: + - name: goodput_strict + variables: + - name: goodput + source: cel + source_cfg: + inputs: + - name: records + reader: json_lines + reader_cfg: + file: logs.txt + prefix: "[boomer] " + until: "has(line.msg) && line.msg == 'sweperf shutdown started'" + select: "has(line.msg) && line.msg == 'sweperf task record' && has(line.v) && line.v == 1.0" + - name: failures + reader: json_lines + reader_cfg: + file: logs.txt + prefix: "[boomer] " + until: "has(line.msg) && line.msg == 'sweperf shutdown started'" + select: "has(line.msg) && line.msg in ['ResumeActor failed in step', 'execute steps failed', 'SuspendActor failed', 'SuspendActorAsync failed'] && has(line.actor) && line.actor != ''" + unique_by: actor + - name: shutdown + reader: json_lines + reader_cfg: + file: logs.txt + prefix: "[boomer] " + select: "has(line.msg) && line.msg == 'sweperf shutdown started'" + - {name: summary, reader: json, reader_cfg: {file: server_summary.json}} + - {name: stats, reader: json_lines, reader_cfg: {file: stats.jsonl}} + - name: one_user + from_test: sweperf_astropy_1_user + reader: json_lines + reader_cfg: + file: logs.txt + prefix: "[boomer] " + until: "has(line.msg) && line.msg == 'sweperf shutdown started'" + select: "has(line.msg) && line.msg == 'sweperf task record' && has(line.v) && line.v == 1.0" + - {name: one_user_stats, from_test: sweperf_astropy_1_user, reader: json_lines, reader_cfg: {file: stats.jsonl}} + locals: + - {name: lo, cel: "timestamp(int(summary.data.metadata.steady_start_ts))"} + - {name: steady_end, cel: "timestamp(int(summary.data.metadata.steady_end_ts))"} + - {name: stop, cel: "size(shutdown.lines) > 0 ? timestamp(shutdown.lines[0].time) : steady_end"} + - {name: hi, cel: "stop < steady_end ? stop : steady_end"} + - {name: window_s_raw, cel: "double((hi - lo).getSeconds()) + double((hi - lo).getMilliseconds()) / 1000.0"} + - {name: hours, cel: "math.greatest(window_s_raw, 0.0) / 3600.0"} + - {name: done, cel: "records.lines.filter(t, timestamp(t.end) >= lo && timestamp(t.end) <= hi)"} + - {name: recorded, cel: "records.lines.map(t, t.actor)"} + - {name: lost, cel: "failures.lines.filter(f, !(f.actor in recorded) && timestamp(f.time) >= lo && timestamp(f.time) <= hi)"} + - {name: ref_cel_ms, cel: "round(percentile(one_user.lines.filter(t, !t.failed).map(t, t.cel_ms), 50.0), 3)"} + - {name: ref_wall_ms, cel: "round(percentile(one_user.lines.filter(t, !t.failed).map(t, t.wall_ms), 50.0), 3)"} + - {name: trials, cel: "stats.lines.filter(l, l.metric == 'trial_summary')"} + - {name: cores, cel: "trials[size(trials) - 1].measurements.allocatable_cores"} + - {name: run_async, cel: "stats.lines.exists(l, has(l.metric) && l.metric == 'grpc_SuspendActorAsync')"} + - {name: run_sync, cel: "stats.lines.exists(l, has(l.metric) && l.metric == 'grpc_SuspendActor')"} + - {name: one_async, cel: "one_user_stats.lines.exists(l, has(l.metric) && l.metric == 'grpc_SuspendActorAsync')"} + - {name: one_sync, cel: "one_user_stats.lines.exists(l, has(l.metric) && l.metric == 'grpc_SuspendActor')"} + - {name: run_mode, cel: "run_async && run_sync ? 'mixed' : (run_async ? 'async' : (run_sync ? 'sync' : ''))"} + - {name: one_mode, cel: "one_async && one_sync ? 'mixed' : (one_async ? 'async' : (one_sync ? 'sync' : ''))"} + - {name: good, cel: "done.filter(t, !t.failed && t.resume_max_ms <= 1500.0 && t.ttfe_max_ms <= 1000.0 && t.cel_ms <= 1.5 * ref_cel_ms && t.wall_ms <= 1.5 * ref_wall_ms)"} + checks: + - {name: has_shutdown, cel: "size(shutdown.lines) > 0"} + - {name: same_lifecycle_mode, cel: "'' in [run_mode, one_mode] || run_mode == one_mode"} + - {name: one_user_has_clean_tasks, cel: "one_user.lines.exists(t, !t.failed)"} + - {name: tasks_in_steady_window, cel: "size(done) + size(lost) > 0"} + values: + - {name: good, cel: "double(size(good))"} + - {name: good_ratio_pct, cel: "round(100.0 * double(size(good)) / double(size(done) + size(lost)), 2)"} + - {name: good_per_vcpu_hour, cel: "round(double(size(good)) / hours / cores, 4)"} + - {name: cel_ms_ratio_p90, cel: "size(done) > 0 ? dyn(round(percentile(done.map(t, t.cel_ms / ref_cel_ms), 90.0), 3)) : null"} + conditions: + - {name: good_ratio, cel: "goodput.good_ratio_pct >= 80.0"} +``` + +### `run_results` + +The measurements of one `stats.jsonl` row: + +```yaml +source_cfg: + metric: trial_summary # if repeated, the last row wins + measurements: [aggregate_failure_ratio] # returned under the same names +``` + +Numeric strings without `_` become floats and `"true"`/`"false"` bools. Strings +with `_` (`"2026_11"`) stay strings. A measurement the row lacks, or a number +that isn't finite (NaN, an infinity, `1e999`), is null. Blank lines are skipped; +any other line that isn't a JSON object with a `metric` makes the variable +`invalid`, naming the line, since the runner writes one such object per line. + +## Results + +`Evaluator.evaluate` returns a `Report` (`evaluator.py`): the run, the +`summary` (`status`, `passed`, `failed`, `invalid`), and per evaluation its +status and reason, each condition with its CEL expression and verdict, each +variable with its values (and why it is invalid), and the evaluation as loaded +(`config`). An evaluation's reason names the conditions that failed, else the +invalid conditions and variables. + +## Outputs + +A `Report` writes both (`write_json`, `append_stats_rows`): + +- `evaluation.json`: the `Report` as JSON. When the evaluations failed to + load, `error` says why and nothing is judged. +- `stats.jsonl` rows in the file's usual five keys: one `evaluation_` row + per evaluation and one `evaluations` row for the summary. Measurements are + strings, or null. An evaluation's row has its `status`, `passed`, `reason`, + `failed_conditions` and `invalid_conditions`, and each value as + `__`. Value names follow the rule in + [Sources](#sources), so the keys stay bounded. A variable name can't contain + `__` or end in `_`, so no two values share a key. + +## In the runner + +The orchestrator passes the whole `locust` test entry to `runner.py` as +`--test-entry` (JSON), and the runner reads its `evaluations`. Before the +load test, the runner loads them and runs the +sources' `init`, so a config error is in `logs.txt` from the start. As its +last step after the run, it runs the queries, writes `evaluation.json` (a +config error goes there too), uploads it with the run's other files, appends +the rows to `stats.jsonl`, and logs one line per evaluation. `status.json` and +the exit code don't change: an evaluation never fails a run. + +The orchestrator passes every run of one invocation the same `--run-ts`, +which names where the run is stored, so the runner's `run_of(test)` returns the +run stored at the same path with `test`'s name (`rundir.py`), or none. On a +`gs://` `--dest`, this needs read access to the bucket (see the +[automation README](../automation/README.md#iam-prerequisites)). + +## Evaluating stored runs + +```sh +cd benchmarking +python3 -m evaluate RUN... (--evaluations JSON|@FILE | --tests-file FILE --test-name NAME | --from-run) [--out DIR] +python3 -m evaluate --check-config --tests-file automation/tests.yaml # check the blocks only +``` + +`RUN` is a run directory or `gs://.../runs//run_date=.../run_ts=.../run_tag=.../`, +whose artifacts are each downloaded to a temporary directory when a source +first reads one (a `gs://` `RUN` needs `pip install google-cloud-storage`, which +the runner image has). A `RUN` stored in the runner's layout, local or +`gs://`, reads the runs from the same invocation that the runner would give it, +under the same ``, and any other `RUN` has none. `--from-run` re-reads the +evaluations the run was judged with, from its `evaluation.json`. The outputs go to `--out` (directly for a single run, or under +`//run_ts=/` for several runs; by default +`./evaluate-out//run_ts=/`), never into the stored run: +`evaluation.json` and `evaluation_rows.jsonl`. Runs without +`run_ts` in their path require `--out` (single run only), and runs resolving to +the same output directory fail up front rather than overwriting each other. With +several runs, per-run I/O or `--from-run` errors are printed to stderr while +later runs still evaluate. Exit status: 0 evaluated (whatever the verdict), 2 +config error, 1 I/O error (with several runs, 1 if any had an I/O error, else 2 +if any had a config error). `--tests-file` needs PyYAML. + +## Layout + +| file | | +|---|---| +| `config.py` | loads and validates an `evaluations` block (pydantic models) | +| `cel_env.py` | shared CEL environment, helpers (`round`, `percentile`), and evaluation | +| `evaluator.py` | runs the source hooks and judges a run into a `Report`, which writes `evaluation.json` and the `stats.jsonl` rows | +| `sources/` | the hooks (`base.py`) and the sources | +| `rundir.py` | the runner's storage layout: opening local or `gs://` runs (a `gs://` artifact is downloaded on first use), and the run of another test from the same invocation | +| `__init__.py` | `prepare`, which `runner.py` calls | +| `__main__.py` | the CLI | + +## Tests + +```sh +hack/verify/benchmarking-python.sh # as CI runs them; or, with requirements.txt installed: +cd benchmarking/evaluate && python3 -m unittest discover -s unit_tests +``` diff --git a/benchmarking/evaluate/__init__.py b/benchmarking/evaluate/__init__.py new file mode 100644 index 0000000000..0ed4e204f7 --- /dev/null +++ b/benchmarking/evaluate/__init__.py @@ -0,0 +1,38 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Run evaluations: judge a finished benchmark run against conditions declared in its test entry. + +A test entry's `evaluations:` (config.py) name sources, which read the run's +files into values (sources/), and CEL conditions over those values +(cel_env.py). evaluator.py judges them into a Report, which writes +evaluation.json and stats.jsonl rows. runner.py calls prepare when a run +starts, and writes the Report once the run has finished. rundir.py is the +runner's storage layout, where the runs of one invocation are found. +`python -m evaluate` (__main__.py) judges a stored run with the same code. +Depends on cel-expr-python and pydantic (requirements.txt). See README.md. +""" + +from typing import Any + +from . import config +from .config import ConfigError # noqa: F401 +from .evaluator import Evaluator, Report, error_report # noqa: F401 +from .sources.base import BenchmarkRunContext, LocalArtifacts, RunIdentity # noqa: F401 + + +def prepare(evaluations: Any, run: BenchmarkRunContext) -> Evaluator: + """The evaluator of run, whose sources have run their init hook. Raises ConfigError when evaluations + (a test entry's block, as parsed) is invalid.""" + return Evaluator(config.load(evaluations), run) diff --git a/benchmarking/evaluate/__main__.py b/benchmarking/evaluate/__main__.py new file mode 100644 index 0000000000..ed45d62b62 --- /dev/null +++ b/benchmarking/evaluate/__main__.py @@ -0,0 +1,218 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Evaluates stored benchmark runs with the code the runner uses, read-only on the runs. + + python -m evaluate RUN... (--evaluations JSON|@FILE | --tests-file FILE --test-name NAME | --from-run) + [--out DIR] + python -m evaluate --check-config (--evaluations JSON|@FILE | --tests-file FILE [--test-name NAME]) + +RUN is a run directory or gs://.../runs//run_date=.../run_ts=.../run_tag=.../ +(an artifact is downloaded when first read). A RUN stored in the runner's layout reads the +runs from the same invocation that the runner would give it, under the same ; +any other RUN has none. --from-run re-reads the evaluations a run was evaluated with (its +evaluation.json); give new ones to re-evaluate it with new conditions. Writes +evaluation.json and evaluation_rows.jsonl (the rows the runner appends to +stats.jsonl) to --out (directly for a single run, or under //run_ts=/ +for several runs; default ./evaluate-out//run_ts=/); never into the +stored run. Runs without run_ts in their path require --out (single run only); +runs that resolve to the same output directory fail up front. With several runs, per-run +errors are reported to stderr and later runs still evaluate. + +Exit status: 0 evaluated (whatever the verdict), 2 config error, 1 I/O error +(with several runs, 1 if any failed with an I/O error, else 2 if any failed with a config error). +""" + +import argparse +import json +import os +import sys +import tempfile +from pathlib import Path +from typing import Any, Optional + +from . import config, rundir +from .evaluator import Evaluator +from .sources.base import BenchmarkRunContext, RunIdentity + + +class UsageError(Exception): + pass + + +def read_json_arg(value: str) -> Any: + """JSON given inline or as @FILE.""" + text = Path(value[1:]).read_text(encoding="utf-8") if value.startswith("@") else value + return json.loads(text) + + +def tests_file_entries(path: str) -> list[dict[str, Any]]: + try: + import yaml # pylint: disable=import-outside-toplevel + except ImportError as e: + raise UsageError("--tests-file needs PyYAML (pip install pyyaml)") from e + try: + with open(path, encoding="utf-8") as f: + doc = yaml.safe_load(f) or {} + except yaml.YAMLError as e: + raise config.ConfigError(f"{path}: {e}") from e + tests = doc.get("tests") if isinstance(doc, dict) else None + if not isinstance(tests, list): + raise config.ConfigError(f"{path}: no top-level tests list") + return [t for t in tests if isinstance(t, dict)] + + +def tests_file_entry(path: str, name: str) -> dict[str, Any]: + for t in tests_file_entries(path): + if t.get("name") == name: + return t + raise config.ConfigError(f"{path}: no test named {name!r}") + + +def from_run_evaluations(run: BenchmarkRunContext, uri: str) -> Any: + path = run.artifact("evaluation.json") + if path is None: + raise config.ConfigError(f"--from-run: {uri} has no evaluation.json") + report = json.loads(path.read_text(encoding="utf-8")) + if not isinstance(report, dict): + raise config.ConfigError(f"--from-run: {uri.rstrip('/')}/evaluation.json is not a JSON object") + if report.get("error"): + raise config.ConfigError(f"--from-run: the run's evaluations did not load: {report['error']}") + evs = report.get("evaluations", []) + if not isinstance(evs, list) or not all(isinstance(ev, dict) and "config" in ev for ev in evs): + raise config.ConfigError(f"--from-run: {uri.rstrip('/')}/evaluation.json has invalid evaluations") + return [ev["config"] for ev in evs] + + +def check_config(a: argparse.Namespace) -> int: + if a.evaluations is not None: + blocks = [("--evaluations", read_json_arg(a.evaluations))] + elif a.tests_file and a.test_name: + blocks = [(a.test_name, tests_file_entry(a.tests_file, a.test_name).get("evaluations", []))] + elif a.tests_file: + blocks = [(t.get("name"), t["evaluations"]) for t in tests_file_entries(a.tests_file) if "evaluations" in t] + else: + raise UsageError("--check-config needs --evaluations or --tests-file") + bad = 0 + for name, block in blocks: + try: + n = len(config.load(block)) + print(f"{name}: ok ({n} evaluations)") + except config.ConfigError as e: + bad += 1 + print(f"{name}: {e}", file=sys.stderr) + return 2 if bad else 0 + + +def out_dir(a: argparse.Namespace, identity: RunIdentity, several: bool) -> Path: + if a.out and not several: + return Path(a.out) + if identity.run_ts is None: + raise config.ConfigError( + f"{identity.uri}: run_ts is undefined (not in the runner's layout); pass --out for a single run" + ) + leaf = Path(identity.test_name or Path(identity.uri).name) / f"run_ts={identity.run_ts}" + return Path(a.out or "evaluate-out") / leaf + + +def evaluate_runs(a: argparse.Namespace) -> int: + with tempfile.TemporaryDirectory() as tmp: + raw_evaluations = None + if a.evaluations is not None: + raw_evaluations = read_json_arg(a.evaluations) + elif a.tests_file: + if not a.test_name: + raise UsageError("--tests-file needs --test-name") + raw_evaluations = tests_file_entry(a.tests_file, a.test_name).get("evaluations", []) + elif not a.from_run: + raise UsageError("give --evaluations, --tests-file with --test-name, or --from-run") + evaluations = config.load(raw_evaluations) if raw_evaluations is not None else None + several = len(a.runs) > 1 + targets: list[tuple[str, str, Path]] = [] + seen_outs: dict[Path, str] = {} + for uri in a.runs: + # Identity comes from the path as given, unresolved: a link placed in a runs/ tree is named by its own path. + norm_uri = uri if uri.startswith("gs://") else os.path.abspath(uri) + out = out_dir(a, rundir.identity_from_uri(norm_uri), several) + resolved_out = out.resolve() + if resolved_out in seen_outs: + raise config.ConfigError( + f"runs {seen_outs[resolved_out]!r} and {uri!r} map to the same output directory {out}" + ) + seen_outs[resolved_out] = uri + targets.append((uri, norm_uri, out)) + + io_error_types = rundir.io_errors() + io_error = False + config_error = False + for i, (uri, norm_uri, out) in enumerate(targets): + try: + run = rundir.open_run(norm_uri, Path(tmp) / f"r{i}") + evals = evaluations if evaluations is not None else config.load(from_run_evaluations(run, uri)) + report = Evaluator(evals, run).evaluate() + # The rows carry the run's own data timestamp, as the runner's do. + stamp = rundir.data_timestamp(run.artifacts) or report.evaluated_at + report.write_json(out / "evaluation.json") + (out / "evaluation_rows.jsonl").unlink(missing_ok=True) + report.append_stats_rows(out / "evaluation_rows.jsonl", stamp) + except (config.ConfigError, json.JSONDecodeError) as e: + config_error = True + print(f"config error: {uri}: {e}", file=sys.stderr) + continue + except io_error_types as e: + io_error = True + print(f"I/O error: {uri}: {e}", file=sys.stderr) + continue + print(f"== {uri}") + for line in report.summary_lines(): + print(line) + print(f"wrote {out / 'evaluation.json'}", flush=True) + if io_error: + return 1 + if config_error: + return 2 + return 0 + + +def main(argv: Optional[list[str]] = None) -> int: + p = argparse.ArgumentParser(prog="python -m evaluate", description=__doc__, + formatter_class=argparse.RawDescriptionHelpFormatter) + p.add_argument("runs", nargs="*", metavar="RUN", help="run directory or gs:// run path") + src = p.add_mutually_exclusive_group() + src.add_argument("--evaluations", help="the evaluations block as JSON, or @FILE") + src.add_argument("--tests-file", help="a tests.yaml; with --test-name, that entry's evaluations") + src.add_argument("--from-run", action="store_true", help="the evaluations in the run's evaluation.json") + p.add_argument("--test-name", help="the tests-file entry") + p.add_argument("--out", help="output directory (default ./evaluate-out//run_ts=/)") + p.add_argument("--check-config", action="store_true", help="validate the evaluations only") + a = p.parse_args(argv) + try: + if a.check_config: + return check_config(a) + if not a.runs: + raise UsageError("give at least one RUN") + return evaluate_runs(a) + except UsageError as e: + p.error(str(e)) + except (config.ConfigError, json.JSONDecodeError) as e: + print(f"config error: {e}", file=sys.stderr) + return 2 + except rundir.io_errors() as e: + print(f"I/O error: {e}", file=sys.stderr) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/benchmarking/evaluate/cel_env.py b/benchmarking/evaluate/cel_env.py new file mode 100644 index 0000000000..b1aef384fc --- /dev/null +++ b/benchmarking/evaluate/cel_env.py @@ -0,0 +1,114 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Shared CEL environment, explicit helpers, and evaluation. + +Beyond standard CEL and its math extension (ext_math), only two explicit +numeric helpers are exposed: +- round(x, digits): Python-style rounding for doubles (shared with evaluation conditions). +- percentile(xs, p): linear-interpolation percentile over list(double), raising + ValueError on an empty list like math.least/math.greatest. +""" + +import math +from typing import Any, Mapping, Optional + +from cel_expr_python import cel + + +def _round(x: float, digits: float) -> float: + if not float(digits).is_integer(): + raise ValueError(f"round: digits {digits} isn't a whole number") + return round(x, int(digits)) + + +# round(x, digits) as Python rounds, so an expression can keep a fixed number of decimals. +ROUND = cel.FunctionDecl("round", [ + cel.Overload(f"round_double_{t.name().lower()}", return_type=cel.Type.DOUBLE, parameters=[cel.Type.DOUBLE, t], + impl=_round) for t in (cel.Type.DOUBLE, cel.Type.INT)]) + + +def _percentile(xs: list, p: float) -> float: + """The p-th percentile of xs (p from 0 to 100), interpolated linearly + between the closest ranks; raises ValueError when xs is empty.""" + if not 0.0 <= p <= 100.0: + raise ValueError(f"percentile: p {p} isn't between 0 and 100") + s = sorted(float(x) for x in xs) + if not s: + raise ValueError("percentile: empty list") + if not all(math.isfinite(x) for x in s): + raise ValueError("percentile: non-finite value") + k = (len(s) - 1) * p / 100.0 + lo = math.floor(k) + hi = min(lo + 1, len(s) - 1) + return s[lo] + (s[hi] - s[lo]) * (k - lo) + + +PERCENTILE = cel.FunctionDecl( + "percentile", + [cel.Overload("percentile_list_double", return_type=cel.Type.DOUBLE, + parameters=[cel.Type.List(cel.Type.DOUBLE), cel.Type.DOUBLE], impl=_percentile)], +) + + +def to_cel(values: Mapping[str, Any]) -> dict[str, Any]: + """values as CEL reads them: ints as doubles, and no key for None, so has() + tests presence. Source values come from JSON, which has one number type, and + as ints `a / b` would be integer division.""" + return {k: float(v) if isinstance(v, int) and not isinstance(v, bool) else v + for k, v in values.items() if v is not None} + + +def evaluate_condition(expr: cel.Expression, data: Mapping[str, Any]) -> bool: + """Whether the boolean expr is true for data. Raises ValueError with CEL's + error when it fails to evaluate, for example on a key data lacks or a value + CEL can't hold.""" + try: + result = expr.eval(data=data) + except RuntimeError as e: # a value CEL can't take in, such as a string with a lone surrogate + raise ValueError(str(e)) from None + if result.type() == cel.Type.ERROR: + raise ValueError(str(result.value())) + if result.type() != cel.Type.BOOL: + raise ValueError(f"gives a {result.type().name().lower()}, not a bool") + return result.value() + + +class Env: + """A CEL environment with variables and functions.""" + + def __init__( + self, + variables: Mapping[str, cel.Type], + functions: tuple[cel.FunctionDecl, ...] = (), + extensions: tuple[cel.CelExtensionBase, ...] = (), + ): + self.variables = dict(variables) + try: + self.env = cel.NewEnv(variables=self.variables, functions=list(functions), extensions=list(extensions)) + except RuntimeError as e: + raise ValueError(str(e)) from None + + def compile(self, expression: str, where: str, + gives: Optional[tuple[cel.Type, ...]] = (cel.Type.BOOL,)) -> cel.Expression: + """expression compiled. Raises ValueError unless it type-checks and gives + one of gives (any type when gives is None).""" + try: + expr = self.env.compile(expression) + except RuntimeError as e: # a syntax or type error, or a variable CEL already declares + raise ValueError(f"{where}: {e}") from None + if gives is not None and expr.return_type() not in gives: + wanted = " or a ".join(t.name().lower() for t in gives if t != cel.Type.DYN) + raise ValueError(f"{where}: must give a {wanted}, gives {expr.return_type().name()}") + return expr diff --git a/benchmarking/evaluate/config.py b/benchmarking/evaluate/config.py new file mode 100644 index 0000000000..f59cae0345 --- /dev/null +++ b/benchmarking/evaluate/config.py @@ -0,0 +1,129 @@ +# Copyright 2026 The Agent Substrate 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. + +"""The `evaluations:` block of a test entry: loading and validation. + + evaluations: + - name: envelope_health # unique in the test + description: "..." # optional + variables: # each is one source query, with several named values + - {name: trial, source: run_results, source_cfg: {...}} + conditions: # AND-ed + - {name: failure_ratio, cel: "trial.aggregate_failure_ratio <= 0.001"} + +The models below give the shape. Loading also checks what a shape can't: that +names are unique, each variable's source_cfg (by its source's validate hook), +and that each condition compiles, so a bad config fails before a run is read. +There is no version field while the schema is experimental. +""" + +from typing import Annotated, Any + +from cel_expr_python import cel +from pydantic import Field, JsonValue, PrivateAttr, TypeAdapter, ValidationError, field_validator, model_validator + +from . import cel_env +from .sources import SOURCES +from .sources.base import Model, Name, describe + +CelExpression = cel.Expression + + +class ConfigError(ValueError): + """The evaluations block is invalid; the message names where.""" + + +# A variable name can't contain "__" or end in "_": stats.jsonl rows key each value as +# __, so trial__x with value y and trial with value x__y would collide. +VariableName = Annotated[str, Field(pattern=r"^[a-z][a-z0-9]*(_[a-z0-9]+)*$", max_length=64)] + + +class Variable(Model): + name: VariableName + source: str + # JSON, as the results echo it: a YAML date or a non-string key is an error here. + # Validation builds new containers, so later edits to the input don't reach it. + source_cfg: dict[str, JsonValue] = {} + + @field_validator("source") + @classmethod + def _known(cls, source: str) -> str: + if source not in SOURCES: + raise ValueError(f"source {source!r} is not one of {sorted(SOURCES)}") + return source + + @model_validator(mode="after") + def _source_cfg(self) -> "Variable": + try: + SOURCES[self.source].validate(self.source_cfg) + except ValueError as e: + raise ValueError(f"source_cfg: {e}") from None + return self + + +class Condition(Model): + name: Name + cel: str + _expr: CelExpression = PrivateAttr() # compiled by the Evaluation, which knows the variables + + @property + def expr(self) -> CelExpression: + return self._expr + + +class Evaluation(Model): + name: Name + description: str = "" + # Lists, not tuples: pydantic counts a tuple's length after dropping the items that failed, + # so one bad item would also report the tuple as empty. + variables: list[Variable] = Field(min_length=1) + conditions: list[Condition] = Field(min_length=1) + + @model_validator(mode="after") + def _compile(self) -> "Evaluation": + _unique([v.name for v in self.variables], "variable") + _unique([c.name for c in self.conditions], "condition") + env = cel_env.Env({v.name: cel.Type.Map(cel.Type.STRING, cel.Type.DYN) for v in self.variables}, + functions=(cel_env.ROUND,)) + for c in self.conditions: + # DYN too, as when a condition is just a value (`trial.ok`); a non-bool + # result then makes the condition invalid when it runs. + c._expr = env.compile(c.cel, f"condition {c.name!r}: cel", # pylint: disable=protected-access + gives=(cel.Type.BOOL, cel.Type.DYN)) + return self + + +_EVALUATIONS = TypeAdapter(Annotated[list[Evaluation], Field(min_length=1)]) + + +def load(evaluations: Any) -> list[Evaluation]: + """The evaluations of a test entry, validated; raises ConfigError.""" + try: + out = _EVALUATIONS.validate_python(evaluations) + _unique([e.name for e in out], "evaluation") + except ValidationError as e: + raise ConfigError(f"evaluations: {describe(e)}") from None + except ValueError as e: + raise ConfigError(f"evaluations: {e}") from None + return out + + +def to_json(evaluations: list[Evaluation]) -> list[dict[str, Any]]: + """The evaluations as loaded, defaults filled: what the results echo, and load() reads back.""" + return [e.model_dump(mode="json") for e in evaluations] + + +def _unique(names: list[str], what: str) -> None: + if dupes := sorted({n for n in names if names.count(n) > 1}): + raise ValueError(f"{what} names repeated: {dupes}") diff --git a/benchmarking/evaluate/evaluator.py b/benchmarking/evaluate/evaluator.py new file mode 100644 index 0000000000..e82f89b200 --- /dev/null +++ b/benchmarking/evaluate/evaluator.py @@ -0,0 +1,271 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Judges one run against its evaluations, into a Report. + +Creating an Evaluator runs the sources' init hook: one instance of each source +the evaluations name, given the run, before the run's data exists. evaluate() +runs the query hook once the data is there, once per distinct (source, +source_cfg), and judges the CEL conditions. A variable whose source couldn't +judge the run is invalid and left out of the CEL data, so a condition that +reads it fails to evaluate. A condition passes, fails, or is invalid when it +fails to evaluate. An evaluation fails if any condition failed, else is invalid +if any condition or variable is invalid, else passes: a source failure never +lets an evaluation pass. The run summary combines the evaluations as +fail, else invalid, else pass. A Report writes itself as evaluation.json and as +rows for the run's stats.jsonl. +""" + +import json +import math +from dataclasses import asdict, dataclass +from datetime import datetime, timezone +from pathlib import Path +from typing import Any, Final, Literal, Mapping, NamedTuple, Optional, Sequence + +from . import cel_env +from .config import Condition, Evaluation, to_json +from .sources import SOURCES +from .sources.base import BenchmarkRunContext, RunIdentity, Scalar, Source, SourceInvalid + +Status = Literal["pass", "fail", "invalid"] +PASS: Final = "pass" +FAIL: Final = "fail" +INVALID: Final = "invalid" + + +@dataclass(frozen=True) +class ConditionResult: + name: str + cel: str + status: Status + passed: bool + reason: str # why it failed or is invalid, "" when it passed + + +@dataclass(frozen=True) +class VariableResult: + name: str + source: str + status: Literal["ok", "invalid"] + invalid_reason: Optional[str] # None when the source resolved the values + values: Mapping[str, Scalar] + + +@dataclass(frozen=True) +class EvaluationResult: + name: str + description: str + status: Status + passed: bool + reason: str # the conditions that failed, else the invalid conditions and variables; "" when it passed + conditions: tuple[ConditionResult, ...] + variables: tuple[VariableResult, ...] + config: Mapping[str, Any] # the evaluation as loaded (config.to_json) + + +@dataclass(frozen=True) +class Summary: + status: Status + passed: bool + failed: tuple[str, ...] # the evaluations that failed + invalid: tuple[str, ...] # the evaluations that are invalid + + +@dataclass(frozen=True) +class Report: + """A run judged against its evaluations.""" + run: Mapping[str, str] # which run was judged: its RunIdentity.record() + evaluated_at: Optional[str] # None when the evaluations failed to load + error: Optional[str] # why the evaluations failed to load, None when they loaded + summary: Summary + evaluations: tuple[EvaluationResult, ...] + + def write_json(self, path: Path) -> None: + """Writes the report to path as JSON (evaluation.json).""" + path.parent.mkdir(parents=True, exist_ok=True) + path.write_text(json.dumps(asdict(self), indent=2, allow_nan=False) + "\n", encoding="utf-8") + + def stats_rows(self, timestamp: str) -> list[dict[str, Any]]: + """Rows for the run's stats.jsonl, with its five keys (timestamp, tag, + test_name, metric, measurements) and string measurements, so the + existing pipeline picks them up: one `evaluation_` row per + evaluation, then an `evaluations` row for the summary. + + An evaluation's row has its status, passed, reason, failed_conditions and + invalid_conditions, and each value of each variable as __, so a dashboard reads the numbers next to the verdict. Variable names + come from the config, and value names follow the query hook's rule + (sources/base.py), so the keys stay bounded. A variable name has no "__" + and doesn't end in "_" (config.py), so no two values share a key. A report + whose evaluations failed to load gets only the summary row, carrying the + error. + """ + def row(metric: str, measurements: dict[str, Any]) -> dict[str, Any]: + return {"timestamp": timestamp, "tag": self.run.get("tag", ""), + "test_name": self.run.get("test_name", ""), "metric": metric, + "measurements": {k: _measurement(v) for k, v in measurements.items()}} + + rows = [] + for ev in self.evaluations: + m: dict[str, Any] = { + "status": ev.status, "passed": ev.passed, "reason": ev.reason, + "failed_conditions": ",".join(c.name for c in ev.conditions if c.status == FAIL), + "invalid_conditions": ",".join(c.name for c in ev.conditions if c.status == INVALID), + } + for var in ev.variables: + for name, value in var.values.items(): + m[f"{var.name}__{name}"] = value + rows.append(row(f"evaluation_{ev.name}", m)) + s = self.summary + rows.append(row(SUMMARY_METRIC, {"status": s.status, "passed": s.passed, "failed": ",".join(s.failed), + "invalid": ",".join(s.invalid), "error": self.error or ""})) + return rows + + def append_stats_rows(self, path: Path, timestamp: str) -> None: + """Appends stats_rows(timestamp) to path.""" + with open(path, "a", encoding="utf-8") as f: + f.write("".join(json.dumps(r) + "\n" for r in self.stats_rows(timestamp))) + + def summary_lines(self) -> list[str]: + """One line per evaluation, with failed or invalid condition reasons, for logs.""" + if self.error: + return [f"evaluations not run: {self.error}"] + lines = [] + for ev in self.evaluations: + line = f"evaluation {ev.name}: {ev.status}" + if ev.reason: + line += f" ({ev.reason})" + details = list(dict.fromkeys(c.reason for c in ev.conditions if c.reason)) + lines.append(line + "".join(f"\n {d}" for d in details)) + lines.append(f"summary: {self.summary.status} ({len(self.evaluations)} evaluations)") + return lines + + +# The summary row's metric, which no evaluation_ can equal. +SUMMARY_METRIC = "evaluations" + + +def _measurement(v: Any) -> Optional[str]: + """v as a stats.jsonl measurement: a string, or None.""" + if v is None: + return None + if isinstance(v, bool): + return "true" if v else "false" + if isinstance(v, float) and v.is_integer(): + return str(int(v)) if abs(v) < 1e15 else repr(v) + return str(v) + + +class ResolvedValues(NamedTuple): + """A variable's values, and why its source couldn't resolve them (None when it could).""" + values: dict[str, Scalar] + invalid_reason: Optional[str] + + +class Evaluator: + def __init__(self, evaluations: list[Evaluation], run: BenchmarkRunContext): + self.evaluations = evaluations + self.run = run + # Each source the evaluations name, or why its init failed. + self.sources: dict[str, Source | str] = {} + for name in dict.fromkeys(v.source for e in evaluations for v in e.variables): + try: + source = SOURCES[name]() + source.init(run) + self.sources[name] = source + except Exception as e: # pylint: disable=broad-except # a source bug must not cost the others + self.sources[name] = f"init failed: {type(e).__name__}: {e}" + + def evaluate(self, now: Optional[datetime] = None) -> Report: + """The run's Report.""" + now = now or datetime.now(timezone.utc) + # Each distinct source query runs once per run, and every variable that makes it shares the values. + resolved_queries: dict[tuple[str, str], ResolvedValues] = {} + evaluation_results = [] + for ev, echoed in zip(self.evaluations, to_json(self.evaluations)): + resolved_variables = {} # by variable name + variables = [] + for v in ev.variables: + key = (v.source, json.dumps(v.source_cfg, sort_keys=True)) + if key not in resolved_queries: + resolved_queries[key] = self._resolve_variable(v.source, v.source_cfg) + r = resolved_variables[v.name] = resolved_queries[key] + variables.append(VariableResult(name=v.name, source=v.source, + status="ok" if r.invalid_reason is None else INVALID, + invalid_reason=r.invalid_reason, values=r.values)) + data = {name: cel_env.to_cel(r.values) for name, r in resolved_variables.items() + if r.invalid_reason is None} + conditions = tuple(_condition(c, data) for c in ev.conditions) + status, failed, invalid = _combine(conditions) + invalid_variables = [f"variable {v.name} is invalid: {v.invalid_reason}" + for v in variables if v.status == INVALID] + if status == PASS and invalid_variables: + status = INVALID + if failed: + reason = f"failed: {', '.join(failed)}" + else: + reason = "; ".join(([f"invalid: {', '.join(invalid)}"] if invalid else []) + invalid_variables) + evaluation_results.append(EvaluationResult( + name=ev.name, description=ev.description, status=status, passed=status == PASS, reason=reason, + conditions=conditions, variables=tuple(variables), config=echoed)) + status, failed, invalid = _combine(evaluation_results) + return Report(run=self.run.identity.record(), + evaluated_at=now.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), error=None, + summary=Summary(status=status, passed=status == PASS, failed=failed, invalid=invalid), + evaluations=tuple(evaluation_results)) + + def _resolve_variable(self, source_name: str, cfg: Mapping[str, Any]) -> ResolvedValues: + """The values of one source query: scalars under non-empty string + names. A float that isn't finite becomes None. Anything else makes the + variable invalid.""" + source = self.sources[source_name] + if isinstance(source, str): + return ResolvedValues({}, source) + try: + raw, invalid_reason = dict(source.query(cfg)), None + except SourceInvalid as e: + raw, invalid_reason = dict(e.values), e.reason + except Exception as e: # pylint: disable=broad-except + return ResolvedValues({}, f"error: {type(e).__name__}: {e}") + for k, v in raw.items(): + if not isinstance(k, str) or not k: + return ResolvedValues({}, f"value name {k!r} must be a non-empty string") + if not isinstance(v, Scalar): + return ResolvedValues({}, f"value {k!r} is a {type(v).__name__}: a value must be a number, " + "bool, string or null") + values = {k: None if isinstance(v, float) and not math.isfinite(v) else v for k, v in raw.items()} + return ResolvedValues(values, invalid_reason) + + +def error_report(identity: RunIdentity, error: str) -> Report: + """The Report of evaluations that failed to load: no verdict, and why.""" + return Report(run=identity.record(), evaluated_at=None, error=error, + summary=Summary(status=INVALID, passed=False, failed=(), invalid=()), evaluations=()) + + +def _combine(results: Sequence[ConditionResult | EvaluationResult]) -> tuple[Status, tuple[str, ...], tuple[str, ...]]: + """fail if any result failed, else invalid if any is invalid, else pass; and the names of each.""" + failed = tuple(r.name for r in results if r.status == FAIL) + invalid = tuple(r.name for r in results if r.status == INVALID) + return (FAIL if failed else INVALID if invalid else PASS), failed, invalid + + +def _condition(c: Condition, data: Mapping[str, Any]) -> ConditionResult: + try: + passed = cel_env.evaluate_condition(c.expr, data) + except ValueError as e: + return ConditionResult(name=c.name, cel=c.cel, status=INVALID, passed=False, reason=f"{c.name}: {e}") + return ConditionResult(name=c.name, cel=c.cel, status=PASS if passed else FAIL, passed=passed, + reason="" if passed else f"{c.name}: {c.cel}") diff --git a/benchmarking/evaluate/requirements.txt b/benchmarking/evaluate/requirements.txt new file mode 100644 index 0000000000..1aa84b8160 --- /dev/null +++ b/benchmarking/evaluate/requirements.txt @@ -0,0 +1,19 @@ +# Copyright 2026 The Agent Substrate 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. + +# cel-expr-python for CEL conditions and the cel source, pydantic for the config's shape. +# PyYAML is for the tests and for `python -m evaluate --tests-file`. +cel-expr-python==0.1.3 +pydantic>=2 +PyYAML diff --git a/benchmarking/evaluate/rundir.py b/benchmarking/evaluate/rundir.py new file mode 100644 index 0000000000..c67496a696 --- /dev/null +++ b/benchmarking/evaluate/rundir.py @@ -0,0 +1,159 @@ +# Copyright 2026 The Agent Substrate 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. + +"""The runner's storage layout, and the runs of one invocation. + +The runner stores each run under +/runs//run_date=/run_ts=/run_tag=/, with + a local directory or gs://bucket/path. run_ts is the orchestrator's +timestamp for the invocation, which all its runs share, so the run of another +test from the same invocation is stored at the same path with that test's name. + +This module is the only one that knows that layout or touches gs://: it opens +a stored run as a BenchmarkRunContext whose identity comes from the layout and +whose artifacts are read from the store, a gs:// one downloaded on first use +(read-only on the store), through the google-cloud-storage library. +""" + +import functools +import re +import tempfile +from pathlib import Path +from typing import Callable, Optional + +from .sources.base import ArtifactStore, BenchmarkRunContext, LocalArtifacts, RunIdentity, no_other_runs +from .sources.run_results import read_stats + +RUN_PATH = re.compile(r"^(?P.*)/runs/(?P[^/]+)/run_date=(?P[^/]+)/run_ts=(?P\d+)" + r"/run_tag=(?P[^/]+)/?$") + + +def identity_from_uri(uri: str) -> RunIdentity: + """The identity of the run stored at uri: test_name, tag, run_date and run_ts too when it is in the runner's layout.""" + uri = uri.rstrip("/") + m = RUN_PATH.match(uri) + if not m: + return RunIdentity(uri=uri) + return RunIdentity(uri=uri, test_name=m["test"], tag=m["tag"], run_date=m["date"], run_ts=int(m["ts"])) + + +class GcsArtifacts: + """A run's artifacts under a gs:// prefix, each downloaded on first use into tmp. Never writes to GCS.""" + + def __init__(self, uri: str, tmp: Path): + self.uri = uri.rstrip("/") + self.tmp = tmp + self._fetched: dict[str, Optional[Path]] = {} + + def fetch(self, name: str) -> Optional[Path]: + """Raises google-cloud-storage's exception on a read error.""" + if name not in self._fetched: + self._fetched[name] = _gcs_download(f"{self.uri}/{name}", self.tmp / name) + return self._fetched[name] + + +def open_run(uri: str, tmp: Path) -> BenchmarkRunContext: + """The run stored at uri, a local directory or gs://, whose gs:// artifacts are downloaded under tmp, and + whose run_of is same_invocation's. Raises FileNotFoundError when nothing is stored there.""" + uri = uri.rstrip("/") + if uri.startswith("gs://"): + if not _gcs_list(f"{uri}/"): + raise FileNotFoundError(f"no objects under {uri}/") + tmp.mkdir(parents=True, exist_ok=True) + artifacts = GcsArtifacts(uri, Path(tempfile.mkdtemp(prefix="run-", dir=tmp))) + else: + if not Path(uri).is_dir(): + raise FileNotFoundError(f"no run directory {uri}") + artifacts = LocalArtifacts(Path(uri)) + return BenchmarkRunContext(identity_from_uri(uri), artifacts, run_of=same_invocation(uri, tmp)) + + +def same_invocation(uri: str, tmp: Path) -> Callable[[str], BenchmarkRunContext]: + """BenchmarkRunContext.run_of for the run stored at uri: the run of test stored at the same path with + test in place of uri's test, opened under tmp once, or LookupError when there is none. A uri outside + the runner's layout has no other runs.""" + m = RUN_PATH.match(uri.rstrip("/")) + if not m: + return no_other_runs + + @functools.cache + def run_of(test: str) -> BenchmarkRunContext: + other = f"{m['root']}/runs/{test}/run_date={m['date']}/run_ts={m['ts']}/run_tag={m['tag']}" + try: + return open_run(other, tmp) + except FileNotFoundError: + raise LookupError(f"no run of {test} at {other}") from None + + return run_of + + +def data_timestamp(artifacts: ArtifactStore) -> str: + """The timestamp the run's stats.jsonl rows carry (trial_summary's); "" without one + or when stats.jsonl is corrupt (the evaluation then says why).""" + try: + stats = read_stats(artifacts.fetch("stats.jsonl")) + except ValueError: + return "" + row = stats.get("trial_summary") or next(iter(stats.values()), {}) + return str(row.get("timestamp") or "") + + +def io_errors() -> tuple[type[BaseException], ...]: + """Read errors open_run / artifacts.fetch can raise: OSError, plus google-cloud-storage's + API and auth errors when those optional packages are installed.""" + errs: list[type[BaseException]] = [OSError] + try: + from google.api_core.exceptions import GoogleAPIError # pylint: disable=import-outside-toplevel + errs.append(GoogleAPIError) + except ImportError: + pass + try: + from google.auth.exceptions import GoogleAuthError # pylint: disable=import-outside-toplevel + errs.append(GoogleAuthError) + except ImportError: + pass + return tuple(errs) + + +def _split(uri: str) -> tuple[str, str]: + bucket, _, path = uri[len("gs://"):].partition("/") + return bucket, path + + +@functools.cache +def _storage_client(): + """The google-cloud-storage client, created on first use. Raises OSError when the library is not installed.""" + try: + from google.cloud import storage # pylint: disable=import-outside-toplevel + except ImportError as e: + raise OSError("reading gs:// needs google-cloud-storage (pip install google-cloud-storage)") from e + return storage.Client() + + +def _gcs_list(prefix: str) -> list[str]: + """gs:// URIs of the objects under prefix. A listing error raises google-cloud-storage's exception (a + google.api_core or google.auth error), as does every gs:// read here.""" + bucket, path = _split(prefix) + return [f"gs://{bucket}/{b.name}" for b in _storage_client().list_blobs(bucket, prefix=path)] + + +def _gcs_download(uri: str, dest: Path) -> Optional[Path]: + """Downloads the object uri to dest; None when there is no such object. Never writes to GCS.""" + bucket, path = _split(uri) + blob = _storage_client().bucket(bucket).get_blob(path) + if blob is None: + return None + dest.parent.mkdir(parents=True, exist_ok=True) + blob.download_to_filename(str(dest)) + return dest diff --git a/benchmarking/evaluate/sources/__init__.py b/benchmarking/evaluate/sources/__init__.py new file mode 100644 index 0000000000..fd7496f0e6 --- /dev/null +++ b/benchmarking/evaluate/sources/__init__.py @@ -0,0 +1,21 @@ +# Copyright 2026 The Agent Substrate 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. + +"""The sources, by the name a variable's `source` key gives (hooks: base.py).""" + +from .base import BenchmarkRunContext, Scalar, Source, SourceInvalid # noqa: F401 +from .cel import Cel +from .run_results import RunResults + +SOURCES: dict[str, type[Source]] = {"cel": Cel, "run_results": RunResults} diff --git a/benchmarking/evaluate/sources/base.py b/benchmarking/evaluate/sources/base.py new file mode 100644 index 0000000000..dea588e1a6 --- /dev/null +++ b/benchmarking/evaluate/sources/base.py @@ -0,0 +1,159 @@ +# Copyright 2026 The Agent Substrate 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. + +"""The source hooks: how the evaluator reads a run through a source. + +A source is a class, picked by a variable's `source` key, with three hooks: + + validate(cfg) A classmethod. Raises ValueError for a bad source_cfg. Called + when the evaluations are loaded, before anything is read. + init(run) Once per run, when the run starts, so its files may not exist + yet: what the source will read. The default stores run as + self.run for query to read. + query(cfg) Once per distinct source_cfg, after the run: named values, or + SourceInvalid when the source can't judge the run. Value names + come from source_cfg or are fixed by the source, never from the + run's data. + +Sources read the run only through its BenchmarkRunContext and never write +files, so the same code serves the runner, which evaluates the run it just +finished, and a re-evaluation of a stored run. +""" + +from dataclasses import dataclass +from pathlib import Path +from typing import Annotated, Any, Callable, Mapping, Optional, Protocol, TypeVar, Union + +from pydantic import BaseModel, ConfigDict, Field, ValidationError + +Scalar = Union[int, float, bool, str, None] + +# A name the config defines: an evaluation, variable or condition. +Name = Annotated[str, Field(pattern=r"^[a-z][a-z0-9_]*$", max_length=64)] + + +class Model(BaseModel): + """A config shape: unknown keys are errors and loaded values don't change.""" + model_config = ConfigDict(extra="forbid", frozen=True) + + +ModelT = TypeVar("ModelT", bound=BaseModel) + + +def parse(model: type[ModelT], obj: Any) -> ModelT: + """obj as a model, or ValueError with describe's message.""" + try: + return model.model_validate(obj) + except ValidationError as e: + raise ValueError(describe(e)) from None + + +def describe(e: ValidationError) -> str: + """e's errors on one line, each after where it is in the input.""" + def text(err) -> str: + return str(err["ctx"]["error"]) if err["type"] == "value_error" else err["msg"] + return "; ".join(f"{'.'.join(map(str, err['loc']))}: {text(err)}" if err["loc"] else text(err) + for err in e.errors()) + + +def no_other_runs(test: str) -> "BenchmarkRunContext": + """BenchmarkRunContext.run_of of a run that has no other runs to read.""" + raise LookupError(f"no run of {test}") + + +@dataclass(frozen=True) +class RunIdentity: + """Which run it is. uri is where the run is stored; the other fields are + None when they aren't known, as for a local directory outside the runner's + layout.""" + uri: str + test_name: Optional[str] = None + tag: Optional[str] = None + run_date: Optional[str] = None # YYYY-MM-DD + run_ts: Optional[int] = None # unix seconds + + def record(self) -> dict[str, str]: + """The known fields as strings, as a Report records them.""" + known = {"test_name": self.test_name, "tag": self.tag, "run_date": self.run_date, + "run_ts": None if self.run_ts is None else str(self.run_ts), "uri": self.uri} + return {k: v for k, v in known.items() if v is not None} + + +class ArtifactStore(Protocol): + """Where a run's artifacts are stored.""" + + def fetch(self, name: str) -> Optional[Path]: + """The local path of the stored artifact name; None when the run didn't store it.""" + + +@dataclass(frozen=True) +class LocalArtifacts: + """A run's artifacts in a local directory, under the names they are stored under.""" + dir: Path + + def fetch(self, name: str) -> Optional[Path]: + path = self.dir / name + return path if path.is_file() else None + + +@dataclass(frozen=True) +class BenchmarkRunContext: + """The run being evaluated: which run it is (identity), where it is stored + (identity.uri, artifacts) and its stored artifacts. Each source chooses + what it reads: one of the run's artifacts, by name, or another store, + keyed by the run's identity. + + run_of(test) returns the run of another test from the same invocation + (e.g. the suite's 1-user run), with its own identity, or raises + LookupError saying why there is none; whoever creates the context says + where that run is stored. Call it from query. It may be called once per + input that reads the other run, so an implementation that is costly to + call caches its lookups. + """ + identity: RunIdentity + artifacts: ArtifactStore + run_of: Callable[[str], "BenchmarkRunContext"] = no_other_runs + + def artifact(self, name: str) -> Optional[Path]: + """The local path of the run's stored artifact name, fetched on first + use; None when the run didn't store it (or hasn't yet). Raises + ValueError for a name outside the run.""" + if name.startswith("/") or ".." in name.split("/"): + raise ValueError(f"artifact name {name!r} is outside the run") + return self.artifacts.fetch(name) + + +class SourceInvalid(Exception): + """The source can't judge the run: why, and the values it measured anyway.""" + + def __init__(self, reason: str, values: Optional[Mapping[str, Scalar]] = None): + super().__init__(reason) + self.reason = reason + self.values = dict(values or {}) + + +class Source: + """A source; see the module docstring for when each hook runs.""" + + run: BenchmarkRunContext + + @classmethod + def validate(cls, cfg: Mapping[str, Any]) -> None: + raise NotImplementedError + + def init(self, run: BenchmarkRunContext) -> None: + self.run = run + + def query(self, cfg: Mapping[str, Any]) -> Mapping[str, Scalar]: + raise NotImplementedError diff --git a/benchmarking/evaluate/sources/cel/__init__.py b/benchmarking/evaluate/sources/cel/__init__.py new file mode 100644 index 0000000000..d786eaedec --- /dev/null +++ b/benchmarking/evaluate/sources/cel/__init__.py @@ -0,0 +1,227 @@ +# Copyright 2026 The Agent Substrate 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. + +"""The cel source: binds data read from runs to CEL, and evaluates named expressions into values. + + source_cfg: + inputs: # the data: each is a CEL variable + - {name: stats, reader: json_lines, reader_cfg: {file: stats.jsonl}} + - {name: other, from_test: some_other_test, reader: json_lines, reader_cfg: {file: stats.jsonl}} + locals: # optional: ordered list of named in-between results + - {name: rows, cel: "stats.lines.filter(l, l.metric == 'trial_summary')"} + checks: # optional: what must hold for the values to mean anything + - {name: has_rows, cel: "size(rows) > 0"} + values: # the outputs: each a double, bool, string or null + - {name: cores, cel: "size(rows) > 0 ? dyn(rows[size(rows) - 1].measurements.allocatable_cores) : null"} + +An input names a reader (READERS) and its reader_cfg. By default it reads this +run; with `from_test:` it reads that test's run from the same invocation +(BenchmarkRunContext.run_of). Locals are evaluated top to bottom, each +reading inputs and earlier locals by name. The source knows nothing about what +the data means: what is good, which run to compare against and every formula +live in the config. + +At run time, an input that can't be read, a local, check or value that fails +to evaluate, and a check that is false make the variable invalid, and the +reason names which. A value that isn't finite becomes null. +""" + +import json +import math +from dataclasses import dataclass +from typing import Annotated, Any, Mapping, Optional + +from cel_expr_python import cel +from cel_expr_python.ext import ext_math +from pydantic import Field, JsonValue, field_validator, model_validator + +from ... import cel_env +from ..base import BenchmarkRunContext, Model, Name, Scalar, Source, SourceInvalid, parse +from .json_file import Json +from .json_lines import JsonLines +from .reader import Reader, ReadError, check_data + +READERS: dict[str, type[Reader]] = {"json": Json, "json_lines": JsonLines} +VALUE_TYPES = (cel.Type.DOUBLE, cel.Type.BOOL, cel.Type.STRING, cel.Type.NULL) +FUNCTIONS = (cel_env.ROUND, cel_env.PERCENTILE) +EXTENSIONS = (ext_math.ExtMath(),) + + +class Input(Model): + """An input: its name, the test whose run it reads (None: this run), a reader and the reader's config.""" + name: Name + from_test: Optional[Annotated[str, Field(min_length=1)]] = None + reader: str + reader_cfg: dict[str, JsonValue] = {} + + @field_validator("reader") + @classmethod + def _known(cls, reader: str) -> str: + if reader not in READERS: + raise ValueError(f"reader {reader!r} is not one of {sorted(READERS)}") + return reader + + @model_validator(mode="after") + def _reader_cfg(self) -> "Input": + try: + parse(READERS[self.reader].Config, self.reader_cfg) + except ValueError as e: + raise ValueError(f"reader_cfg: {e}") from None + return self + + +class NamedCel(Model): + """A local, check or value: a name and a CEL expression.""" + name: Name + cel: str + + +class Config(Model): + # Lists, not tuples, as in config.Evaluation. + inputs: list[Input] = Field(min_length=1) + locals: list[NamedCel] = [] + checks: list[NamedCel] = [] + values: list[NamedCel] = Field(min_length=1) + + +@dataclass(frozen=True) +class Expression: + kind: str # "local", "check" or "value", for error messages + name: str + expr: cel.Expression + + +@dataclass(frozen=True) +class Program: + """A source_cfg, compiled: the inputs, the locals in list order, the checks and the values.""" + inputs: tuple[Input, ...] + locals: tuple[Expression, ...] + checks: tuple[Expression, ...] + values: tuple[Expression, ...] + + +def _unique(names: list[str], where: str) -> None: + if repeated := sorted({n for n in names if names.count(n) > 1}): + raise ValueError(f"{where}: names repeated: {repeated}") + + +def compile_cfg(cfg: Mapping[str, Any]) -> Program: + """The program of cfg. Raises ValueError for a bad cfg.""" + c = parse(Config, cfg) + input_names = [i.name for i in c.inputs] + local_names = [local.name for local in c.locals] + _unique(input_names, "inputs") + _unique(local_names, "locals") + _unique([check.name for check in c.checks], "checks") + _unique([value.name for value in c.values], "values") + if clash := sorted(set(input_names) & set(local_names)): + raise ValueError(f"locals: {clash} are also inputs") + + # Compile locals top-to-bottom so each local can read inputs and earlier + # locals with their inferred CEL return type (including TIMESTAMP/DURATION). + var_types: dict[str, cel.Type] = {name: cel.Type.Map(cel.Type.STRING, cel.Type.DYN) for name in input_names} + local_exprs: list[Expression] = [] + for local in c.locals: + expr = cel_env.Env(var_types, FUNCTIONS, EXTENSIONS).compile(local.cel, f"local {local.name!r}", None) + var_types[local.name] = expr.return_type() + local_exprs.append(Expression(kind="local", name=local.name, expr=expr)) + + env = cel_env.Env(var_types, FUNCTIONS, EXTENSIONS) + + def compiled(kind: str, section: list[NamedCel], gives: tuple[cel.Type, ...]) -> tuple[Expression, ...]: + return tuple(Expression(kind=kind, name=n.name, expr=env.compile(n.cel, f"{kind} {n.name!r}", gives)) + for n in section) + + return Program( + inputs=tuple(c.inputs), + locals=tuple(local_exprs), + checks=compiled("check", c.checks, (cel.Type.BOOL, cel.Type.DYN)), + values=compiled("value", c.values, (*VALUE_TYPES, cel.Type.DYN)), + ) + + +def run_program(program: Program, data: dict[str, Any]) -> dict[str, Scalar]: + """The values of program over data (the inputs' data by input name). + Raises ValueError, naming the expression, when a local, check or value + fails to evaluate, or a check is false.""" + data = dict(data) + for local in program.locals: + data[local.name] = _eval(local, data) + for check in program.checks: + ok = _eval(check, data) + if not isinstance(ok, bool): + raise ValueError(f"check {check.name!r} gives a {type(ok).__name__}: it must give a bool") + if not ok: + raise ValueError(f"check {check.name!r} is false") + values: dict[str, Scalar] = {} + for value in program.values: + x = _eval(value, data) + if x is not None and type(x) not in (float, bool, str): # pylint: disable=unidiomatic-typecheck # int is not a double + raise ValueError( + f"value {value.name!r} gives a {type(x).__name__}: it must give a double, bool, string or null") + values[value.name] = None if isinstance(x, float) and not math.isfinite(x) else x + return values + + +def _eval(e: Expression, data: Mapping[str, Any]) -> Any: + try: + result = e.expr.eval(data=data) + except RuntimeError as err: # a value CEL can't take in, such as a string with a lone surrogate + raise ValueError(f"{e.kind} {e.name!r} failed to evaluate: {err}") from None + if result.type() == cel.Type.ERROR: + raise ValueError(f"{e.kind} {e.name!r} failed to evaluate: {result.value()}") + return result.plain_value() # lists and maps as Python ones, which a later expression can read + + +class Cel(Source): + @classmethod + def validate(cls, cfg: Mapping[str, Any]) -> None: + compile_cfg(cfg) + + def init(self, run: BenchmarkRunContext) -> None: + super().init(run) + self._reads: dict[tuple[Optional[str], str, str], Mapping[str, Any] | ReadError] = {} + + def query(self, cfg: Mapping[str, Any]) -> Mapping[str, Scalar]: + program = compile_cfg(cfg) + data = {i.name: self._read(i) for i in program.inputs} + try: + return run_program(program, data) + except ValueError as e: + raise SourceInvalid(str(e)) from None + + def _read(self, i: Input) -> Mapping[str, Any]: + """The data of input i, read once per run and reader config; SourceInvalid naming it when it can't be read.""" + key = (i.from_test, i.reader, json.dumps(i.reader_cfg, sort_keys=True)) + if key not in self._reads: + try: + reader = READERS[i.reader] + data = reader().read(self._run_to_read(i), parse(reader.Config, i.reader_cfg)) + check_data(reader, data) + self._reads[key] = data + except ReadError as e: + self._reads[key] = e + found = self._reads[key] + if isinstance(found, ReadError): + raise SourceInvalid(f"input {i.name!r}: {found}") + return found + + def _run_to_read(self, i: Input) -> BenchmarkRunContext: + """This run, or the run of i.from_test; ReadError when there is none.""" + if i.from_test is None: + return self.run + try: + return self.run.run_of(i.from_test) + except LookupError as e: + raise ReadError(str(e)) from None diff --git a/benchmarking/evaluate/sources/cel/json_file.py b/benchmarking/evaluate/sources/cel/json_file.py new file mode 100644 index 0000000000..8fff6096d6 --- /dev/null +++ b/benchmarking/evaluate/sources/cel/json_file.py @@ -0,0 +1,53 @@ +# Copyright 2026 The Agent Substrate 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. + +"""json: one JSON object file from the run. + + - {name: summary, reader: json, reader_cfg: {file: server_summary.json}} + + summary.data the parsed JSON object, with leaf coercion as in run_results + summary.uri where the run is stored +""" + +import json +from typing import Annotated, Any, Mapping + +import pydantic + +from ..base import BenchmarkRunContext, Model +from .json_lines import coerce_json +from .reader import Field, Reader, ReadError, to_data + + +class Config(Model): + file: Annotated[str, pydantic.Field(min_length=1)] # the name of one of the run's files + + +class Json(Reader): + fields = (Field("data", "map"), Field("uri", "string")) + Config = Config + + def read(self, run: BenchmarkRunContext, cfg: Config) -> Mapping[str, Any]: + name = cfg.file + path = run.artifact(name) + if path is None: + raise ReadError(f"{name} absent") + with open(path, encoding="utf-8", errors="replace") as f: + try: + parsed = json.load(f) + except ValueError as e: + raise ReadError(f"{name}: not JSON: {e}") from None + if not isinstance(parsed, dict): + raise ReadError(f"{name}: not a JSON object") + return to_data({"data": coerce_json(parsed), "uri": run.identity.uri}) diff --git a/benchmarking/evaluate/sources/cel/json_lines.py b/benchmarking/evaluate/sources/cel/json_lines.py new file mode 100644 index 0000000000..b8471bf892 --- /dev/null +++ b/benchmarking/evaluate/sources/cel/json_lines.py @@ -0,0 +1,157 @@ +# Copyright 2026 The Agent Substrate 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. + +"""json_lines: filtered lines of one of the run's JSON-lines or prefixed-JSON log files. + + - {name: stats, reader: json_lines, reader_cfg: {file: stats.jsonl}} + - name: records + reader: json_lines + reader_cfg: + file: logs.txt + prefix: "[boomer] " + until: "has(line.msg) && line.msg == 'shutdown'" + select: "has(line.msg) && line.msg == 'record'" + unique_by: actor + + .lines selected JSON objects, in file order + .unparsed_lines [{line_no, text, error}] for prefixed (or non-blank) lines that aren't JSON objects + .uri where the run is stored + +reader_cfg, besides `file`: +- `prefix`: skip lines without this prefix, and strip it before parsing JSON. + Without `prefix`, blank lines are skipped. +- `until`: CEL boolean expression over `line`; stop reading when a parsed + object matches (that line is not emitted). +- `select`: CEL boolean expression over `line`; keep only matching objects. +- `unique_by`: field name; keep only the first selected object per distinct + value of that field. + +Values are coerced as in run_results: numbers and numeric strings become +doubles, "true"/"false" become bools, and a null or non-finite number is +left out, so has() tests for it. +""" + +import json +from typing import Annotated, Any, Mapping, Optional + +import pydantic +from cel_expr_python import cel +from cel_expr_python.ext import ext_math + +from ... import cel_env +from ..base import BenchmarkRunContext, Model +from ..run_results import coerce +from .reader import Field, Reader, ReadError, to_data + + +def coerce_json(v: Any) -> Any: + """A JSON value with coerce applied to each leaf.""" + if isinstance(v, dict): + return {k: coerce_json(x) for k, x in v.items()} + if isinstance(v, list): + return [coerce_json(x) for x in v] + return coerce(v) + + +def _line_env() -> cel_env.Env: + return cel_env.Env( + {"line": cel.Type.Map(cel.Type.STRING, cel.Type.DYN)}, + extensions=(ext_math.ExtMath(),), + ) + + +def _compile_line_expr(raw: str, where: str) -> cel.Expression: + return _line_env().compile(raw, where, (cel.Type.BOOL, cel.Type.DYN)) + + +def _eval_line_bool(expr: cel.Expression, line: Mapping[str, Any], line_no: int, where: str) -> bool: + try: + result = expr.eval(data={"line": line}) + except RuntimeError as e: + raise ReadError(f"line {line_no}: {where} failed: {e}") from None + if result.type() != cel.Type.BOOL: + detail = result.value() if result.type() == cel.Type.ERROR else f"gave {result.type().name()}" + raise ReadError(f"line {line_no}: {where} failed: {detail}") + return result.value() + + +NonEmpty = Annotated[str, pydantic.Field(min_length=1)] + + +class Config(Model): + file: NonEmpty # the name of one of the run's files + prefix: str = "" + select: Optional[str] = None + until: Optional[str] = None + unique_by: Optional[NonEmpty] = None # a field name + + @pydantic.field_validator("select", "until") + @classmethod + def _compiles(cls, expression: Optional[str], info: pydantic.ValidationInfo) -> Optional[str]: + if expression is not None: + _compile_line_expr(expression, info.field_name) + return expression + + +class JsonLines(Reader): + fields = (Field("lines", "list"), Field("unparsed_lines", "list"), Field("uri", "string")) + Config = Config + + def read(self, run: BenchmarkRunContext, cfg: Config) -> Mapping[str, Any]: + o = cfg + name, prefix, unique_by = o.file, o.prefix, o.unique_by + path = run.artifact(name) + if path is None: + raise ReadError(f"{name} absent") + until_expr = None if o.until is None else _compile_line_expr(o.until, "until") + select_expr = None if o.select is None else _compile_line_expr(o.select, "select") + + lines, unparsed = [], [] + seen: set[tuple[type, Any]] = set() + with open(path, encoding="utf-8", errors="replace") as f: + for n, text in enumerate(f, 1): + raw = text.rstrip("\n") + if prefix: + if not raw.startswith(prefix): + continue + payload = raw[len(prefix):] + else: + if not raw.strip(): + continue + payload = raw + try: + parsed = json.loads(payload) + error = "" if isinstance(parsed, dict) else "not a JSON object" + except ValueError as e: + error = f"not JSON: {e}" + if error: + unparsed.append({"line_no": n, "text": raw, "error": error}) + continue + coerced = to_data(coerce_json(parsed)) + if until_expr is not None and _eval_line_bool(until_expr, coerced, n, "until"): + break + if select_expr is not None and not _eval_line_bool(select_expr, coerced, n, "select"): + continue + if unique_by is not None: + if unique_by not in coerced: + raise ReadError(f"line {n}: unique_by {unique_by!r}: field missing") + val = coerced[unique_by] + if isinstance(val, (dict, list)): + raise ReadError(f"line {n}: unique_by {unique_by!r}: unhashable {type(val).__name__}") + dedup = (type(val), val) + if dedup in seen: + continue + seen.add(dedup) + lines.append(coerced) + return to_data({"lines": lines, "unparsed_lines": unparsed, "uri": run.identity.uri}) diff --git a/benchmarking/evaluate/sources/cel/reader.py b/benchmarking/evaluate/sources/cel/reader.py new file mode 100644 index 0000000000..2fd0f2cee1 --- /dev/null +++ b/benchmarking/evaluate/sources/cel/reader.py @@ -0,0 +1,85 @@ +# Copyright 2026 The Agent Substrate 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. + +"""What the cel source needs from a reader: a class that turns one run's files into CEL data. + +A reader exposes data and passes no judgment on it. Its data is a mapping +with the top-level fields it declares; lists hold maps or doubles, and a +field a record lacks is absent rather than null, so has() tests for it. +""" + +import dataclasses +import math +from dataclasses import dataclass +from typing import Any, ClassVar, Literal, Mapping + +from ..base import BenchmarkRunContext, Model + +FieldType = Literal["double", "string", "bool", "list", "map"] +PY_TYPES: dict[str, type | tuple[type, ...]] = {"double": float, "string": str, "bool": bool, "list": list, + "map": dict} + + +class ReadError(Exception): + """The reader can't read the run: why (e.g. the file is absent).""" + + +@dataclass(frozen=True) +class Field: + """A top-level field of a reader's data, with its type, checked by check_data.""" + name: str + type: FieldType + optional: bool = False + + +class Reader: + """A reader; the cel source makes one per input that names it.""" + + fields: ClassVar[tuple[Field, ...]] + Config: ClassVar[type[Model]] # the input's reader_cfg; validating it raises ValueError for a bad one + + def read(self, run: BenchmarkRunContext, cfg: Any) -> Mapping[str, Any]: + """The run's data, read as cfg (a Config) says. Raises ReadError when the run can't be read.""" + raise NotImplementedError + + +def check_data(reader: type[Reader], data: Mapping[str, Any]) -> None: + """Raises TypeError unless data has the reader's fields, of their types, and no others.""" + declared = {f.name: f for f in reader.fields} + if unknown := set(data) - set(declared): + raise TypeError(f"{reader.__name__} gave undeclared fields {sorted(unknown)}") + for f in reader.fields: + if f.name not in data: + if not f.optional: + raise TypeError(f"{reader.__name__} gave no {f.name}") + elif isinstance(data[f.name], bool) != (f.type == "bool") or not isinstance(data[f.name], PY_TYPES[f.type]): + raise TypeError(f"{reader.__name__}: {f.name} is a {type(data[f.name]).__name__}, not a {f.type}") + + +def to_data(obj: Any) -> Any: + """A dataclass (or list or dict of them) as CEL data: dicts and lists, + numbers as doubles, a None or non-finite field left out.""" + if dataclasses.is_dataclass(obj) and not isinstance(obj, type): + obj = {f.name: getattr(obj, f.name) for f in dataclasses.fields(obj)} + if isinstance(obj, dict): + return {k: to_data(v) for k, v in obj.items() if _present(v)} + if isinstance(obj, (list, tuple)): + return [to_data(v) for v in obj if _present(v)] + if isinstance(obj, int) and not isinstance(obj, bool): + return float(obj) + return obj + + +def _present(v: Any) -> bool: + return v is not None and not (isinstance(v, float) and not math.isfinite(v)) diff --git a/benchmarking/evaluate/sources/run_results.py b/benchmarking/evaluate/sources/run_results.py new file mode 100644 index 0000000000..b187c36e67 --- /dev/null +++ b/benchmarking/evaluate/sources/run_results.py @@ -0,0 +1,114 @@ +# Copyright 2026 The Agent Substrate 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. + +"""The run_results source: measurements of one stats.jsonl row, as values. + + source_cfg: + metric: trial_summary # the row's metric; if repeated, the last row wins + measurements: [aggregate_failure_ratio] # returned as values under the same names + +stats.jsonl keeps measurements as strings: numeric strings without '_' become +floats, "true" and "false" become bools, and a measurement the row lacks or a +non-finite number becomes None. +""" + +import json +import math +from pathlib import Path +from typing import Annotated, Any, Mapping, Optional + +from pydantic import Field, field_validator + +from .base import Model, Scalar, Source, SourceInvalid, parse + + +def read_stats(path: Optional[Path]) -> dict[str, dict[str, Any]]: + """stats.jsonl rows by metric name; the last row of a metric wins. + + The runner writes one JSON object with a "metric" per line, so blank lines + are skipped and any other line raises ValueError naming its line number. + """ + rows: dict[str, dict[str, Any]] = {} + if path is None or not path.exists(): + return rows + with open(path, encoding="utf-8") as f: + for n, line in enumerate(f, 1): + if not line.strip(): + continue + try: + row = json.loads(line) + except ValueError as e: + raise ValueError(f"stats.jsonl line {n} isn't JSON: {e}") from None + if not isinstance(row, dict) or not isinstance(row.get("metric"), str) or not row["metric"]: + raise ValueError(f"stats.jsonl line {n} isn't an object with a metric") + rows[row["metric"]] = row + return rows + + +def coerce(v: Any) -> Scalar: + """A measurement as a value: finite numbers (and numeric strings without '_') as float, + "true"/"false" as bool, and non-finite numbers as None.""" + if v is None or isinstance(v, bool): + return v + if isinstance(v, (int, float)): + return float(v) if math.isfinite(v) else None + if isinstance(v, str): + s = v.strip().lower() + if s in ("true", "false"): + return s == "true" + if "_" not in v: + try: + x = float(v) + except ValueError: + return v + return x if math.isfinite(x) else None + return v + return json.dumps(v, sort_keys=True) # a nested value, kept readable + + +class Config(Model): + metric: Annotated[str, Field(min_length=1)] + measurements: list[Annotated[str, Field(min_length=1)]] = Field(min_length=1) + + @field_validator("measurements") + @classmethod + def _distinct(cls, names: list[str]) -> list[str]: + if len(set(names)) != len(names): + raise ValueError("listed twice") + return names + + +class RunResults(Source): + @classmethod + def validate(cls, cfg: Mapping[str, Any]) -> None: + parse(Config, cfg) + + def init(self, run) -> None: + super().init(run) + self._rows: Optional[dict[str, dict[str, Any]]] = None + + def query(self, cfg: Mapping[str, Any]) -> Mapping[str, Scalar]: + if self._rows is None: + path = self.run.artifact("stats.jsonl") + if path is None: + raise SourceInvalid("stats.jsonl absent") + try: + self._rows = read_stats(path) + except ValueError as e: + raise SourceInvalid(str(e)) from None + row = self._rows.get(cfg["metric"]) + if row is None: + raise SourceInvalid(f"no stats.jsonl row {cfg['metric']}") + measurements = row.get("measurements") if isinstance(row.get("measurements"), dict) else {} + return {name: coerce(measurements.get(name)) for name in cfg["measurements"]} diff --git a/benchmarking/evaluate/unit_tests/test_cel.py b/benchmarking/evaluate/unit_tests/test_cel.py new file mode 100644 index 0000000000..1d0bef1c7b --- /dev/null +++ b/benchmarking/evaluate/unit_tests/test_cel.py @@ -0,0 +1,451 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for the cel source, its CEL helpers, and the json / json_lines readers.""" + +import dataclasses +import json +import math +import sys +import tempfile +import unittest +from pathlib import Path +from typing import Optional +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from cel_expr_python import cel as cel_lib # noqa: E402 +from cel_expr_python.ext import ext_math # noqa: E402 + +from evaluate import cel_env # noqa: E402 +from evaluate.sources import cel # noqa: E402 +from evaluate.sources.base import BenchmarkRunContext, LocalArtifacts, RunIdentity, SourceInvalid # noqa: E402 +from evaluate.sources.cel import json_file, json_lines, reader # noqa: E402 + +def stats_input(name: str = "stats", **reader_cfg) -> dict: + """An input reading stats.jsonl with json_lines, with more reader_cfg.""" + return {"name": name, "reader": "json_lines", "reader_cfg": {"file": "stats.jsonl", **reader_cfg}} + + +STATS = [stats_input()] + + +def stats_row(metric: str, **measurements) -> dict: + return {"timestamp": "2026-10-24T11:16:49Z", "tag": "abc", "test_name": "t", "metric": metric, + "measurements": measurements} + + +def local_run(d: Path, uri: Optional[str] = None) -> BenchmarkRunContext: + return BenchmarkRunContext(RunIdentity(uri or str(d)), LocalArtifacts(d)) + + +NO_RUN = local_run(Path(tempfile.gettempdir()) / "evaluate-unit-tests-no-run") # holds no files + + +def read_lines(run: BenchmarkRunContext, reader_cfg: dict) -> dict: + return dict(json_lines.JsonLines().read(run, json_lines.Config(**reader_cfg))) + + +def read_json(run: BenchmarkRunContext, reader_cfg: dict) -> dict: + return dict(json_file.Json().read(run, json_file.Config(**reader_cfg))) + + +def write_stats(d: Path, lines: list, *, summary: Optional[object] = None) -> BenchmarkRunContext: + """A run whose stats.jsonl holds lines (dicts are dumped as JSON), plus optional summary.json.""" + d.mkdir(parents=True, exist_ok=True) + path = d / "stats.jsonl" + path.write_text("".join((json.dumps(x) if isinstance(x, dict) else x) + "\n" for x in lines), encoding="utf-8") + if summary is not None: + spath = d / "summary.json" + spath.write_text(json.dumps(summary) if isinstance(summary, (dict, list)) else str(summary), encoding="utf-8") + return local_run(d) + + +def query(run: BenchmarkRunContext, cfg: dict) -> tuple[dict, Optional[str]]: + """One query of run through the hooks: the values, and why the variable is invalid (None when valid).""" + cel.Cel.validate(cfg) + source = cel.Cel() + source.init(run) + try: + return dict(source.query(cfg)), None + except SourceInvalid as e: + return e.values, e.reason + + +def query_lines(lines: list, cfg: dict) -> tuple[dict, Optional[str]]: + with tempfile.TemporaryDirectory() as tmp: + return query(write_stats(Path(tmp), lines), {"inputs": STATS, **cfg}) + + +def evaluate(expression: str, **data): + """expression over data, with the cel source's functions and math extension.""" + env = cel_env.Env( + {k: cel_lib.Type.DYN for k in data}, + (cel_env.ROUND, cel_env.PERCENTILE), + extensions=(ext_math.ExtMath(),), + ) + result = env.compile(expression, "test", None).eval(data=data) + if result.type() == cel_lib.Type.ERROR: + raise ValueError(result.value()) + return result.plain_value() + + +class FunctionsTest(unittest.TestCase): + def test_percentile(self): + self.assertEqual(evaluate("percentile(xs, 50.0)", xs=[4.0, 1.0, 3.0, 2.0]), 2.5) + self.assertEqual(evaluate("percentile(xs, 90.0)", xs=[1.0, 2.0, 3.0, 4.0, 5.0]), 4.6) + self.assertEqual(evaluate("percentile(xs, 0.0)", xs=[3.0, 1.0]), 1.0) + self.assertEqual(evaluate("percentile(xs, 100.0)", xs=[3.0, 1.0]), 3.0) + self.assertEqual(evaluate("percentile(xs, 99.0)", xs=[7.0]), 7.0) + with self.assertRaisesRegex(ValueError, "empty list"): + evaluate("percentile(xs, 50.0)", xs=[]) + with self.assertRaisesRegex(ValueError, "non-finite"): + evaluate("percentile(xs, 50.0)", xs=[1.0, float("nan")]) + with self.assertRaisesRegex(ValueError, "between 0 and 100"): + evaluate("percentile(xs, 101.0)", xs=[1.0]) + + def test_ext_math(self): + self.assertEqual(evaluate("[math.least(xs), math.greatest(xs)]", xs=[2.0, -1.0, 5.0]), [-1.0, 5.0]) + self.assertEqual(evaluate("math.least(2.0, -1.0)"), -1.0) + with self.assertRaises(ValueError): + evaluate("math.least(xs)", xs=[]) + + def test_a_list_of_another_type_is_an_error(self): + with self.assertRaises(ValueError): + evaluate("percentile(xs, 50.0)", xs=["a"]) + + +class ConfigTest(unittest.TestCase): + VALID = {"inputs": STATS, "locals": [{"name": "rows", "cel": "stats.lines"}], + "checks": [{"name": "some", "cel": "size(rows) > 0"}], + "values": [{"name": "n", "cel": "double(size(rows))"}]} + + def test_valid(self): + cel.Cel.validate(self.VALID) + cel.Cel.validate({"inputs": STATS, "values": [{"name": "n", "cel": "double(size(stats.lines))"}]}) + cel.Cel.validate({"inputs": STATS, "values": [{"name": "n", "cel": "size(stats.lines) > 0 ? dyn(1.0) : null"}]}) + + def test_invalid(self): + cases = { + "rules: Extra inputs are not permitted": {**self.VALID, "rules": []}, + "inputs: Field required": {"values": [{"name": "n", "cel": "1.0"}]}, + "inputs: List should have at least 1 item": {**self.VALID, "inputs": []}, + "inputs.0.name: String should match pattern": {**self.VALID, "inputs": [stats_input("Stats")]}, + "inputs: names repeated: \\['stats'\\]": {**self.VALID, "inputs": [stats_input(), stats_input()]}, + "inputs.0.file: Extra inputs are not permitted": {**self.VALID, "inputs": [ + {"name": "stats", "reader": "json_lines", "file": "stats.jsonl"}]}, + "locals: Input should be a valid list": {**self.VALID, "locals": {"rows": "stats.lines"}}, + "locals.0.name: String should match pattern": {**self.VALID, "locals": [ + {"name": "Rows", "cel": "stats.lines"}]}, + "locals: names repeated: \\['rows'\\]": {**self.VALID, "locals": [ + {"name": "rows", "cel": "stats.lines"}, {"name": "rows", "cel": "stats.lines"}]}, + "locals.0.extra: Extra inputs are not permitted": {**self.VALID, "locals": [ + {"name": "rows", "cel": "stats.lines", "extra": 1}]}, + "reader 'csv' is not one of": {**self.VALID, "inputs": [{"name": "stats", "reader": "csv"}]}, + "inputs.0: reader_cfg: file: Field required": {**self.VALID, "inputs": [ + {"name": "stats", "reader": "json_lines"}]}, + "inputs.0: reader_cfg: unknown: Extra inputs are not permitted": { + **self.VALID, "inputs": [stats_input(unknown="true")]}, + "inputs.0: reader_cfg: prefix: Input should be a valid string": { + **self.VALID, "inputs": [stats_input(prefix=1)]}, + "inputs.0: reader_cfg: unique_by: String should have at least 1 character": { + **self.VALID, "inputs": [stats_input(unique_by="")]}, + "inputs.0: reader_cfg: select: .*Syntax error": { + **self.VALID, "inputs": [stats_input(select="line.a +")]}, + "inputs.0: reader_cfg: until: .*must give a bool": { + **self.VALID, "inputs": [stats_input(until="size(line)")]}, + "inputs.0.from_test: String should have at least 1 character": { + **self.VALID, "inputs": [{**stats_input(), "from_test": ""}]}, + "locals: \\['stats'\\] are also inputs": {**self.VALID, "locals": [ + {"name": "stats", "cel": "1.0"}, {"name": "rows", "cel": "stats"}]}, + "local 'rows': .*Syntax error": {**self.VALID, "locals": [ + {"name": "in", "cel": "1.0"}, {"name": "rows", "cel": "in"}]}, + "variable 'int' declared multiple times": {**self.VALID, "locals": [ + {"name": "int", "cel": "1.0"}, {"name": "rows", "cel": "stats.lines"}]}, + "check 'some'": {**self.VALID, "checks": [{"name": "some", "cel": "size(rows) +"}]}, + "checks: names repeated: \\['some'\\]": {**self.VALID, "checks": [ + {"name": "some", "cel": "true"}, {"name": "some", "cel": "true"}]}, + "values: names repeated: \\['n'\\]": {**self.VALID, "values": [ + {"name": "n", "cel": "1.0"}, {"name": "n", "cel": "2.0"}]}, + "values: List should have at least 1 item": {**self.VALID, "values": []}, + "check 'some': must give a bool": {**self.VALID, "checks": [{"name": "some", "cel": "size(rows)"}]}, + "value 'n': must give a double or a bool or a string or a null": { + **self.VALID, "values": [{"name": "n", "cel": "size(rows)"}]}, + "undeclared reference to 'nope'": {**self.VALID, "values": [{"name": "n", "cel": "nope"}]}, + "undeclared reference to 'later'": {**self.VALID, "locals": [ + {"name": "rows", "cel": "later"}, {"name": "later", "cel": "stats.lines"}]}, + "undeclared reference to 'rows'": {**self.VALID, "locals": [ + {"name": "rows", "cel": "rows"}]}, + "value 'n': .*no matching overload": {**self.VALID, "values": [ + {"name": "n", "cel": "double(size(rows)) / 2"}]}, + } + for want, cfg in cases.items(): + with self.subTest(want=want), self.assertRaisesRegex(ValueError, want): + cel.Cel.validate(cfg) + + def test_inputs_and_locals_need_not_be_read(self): + """Config load accepts inputs and locals that nothing reads, so entries can share them through YAML anchors.""" + cel.Cel.validate({**self.VALID, "inputs": [*STATS, stats_input("other")]}) + cel.Cel.validate({**self.VALID, "checks": [], "values": [{"name": "n", "cel": "1.0"}]}) + + def test_a_failed_local_makes_the_variable_invalid_even_if_unread(self): + """Like an input that can't be read: every local must evaluate.""" + locals_ = [{"name": "rows", "cel": "stats.lines"}, + {"name": "sixth", "cel": "rows[5]"}] + v, why = query_lines([stats_row("trial_summary")], + {"locals": locals_, "values": [{"name": "n", "cel": "double(size(rows))"}]}) + self.assertEqual(v, {}) + self.assertRegex(why, "^local 'sixth' failed to evaluate: .*Index error") + + +class QueryTest(unittest.TestCase): + LINES = [stats_row("trial_summary", allocatable_cores="192"), stats_row("grpc_ResumeActor", failure_count=2), + stats_row("trial_summary", allocatable_cores=88)] + + def test_locals_checks_and_values(self): + v, why = query_lines(self.LINES, { + "locals": [ + {"name": "trials", "cel": "stats.lines.filter(l, l.metric == 'trial_summary')"}, + {"name": "cores", "cel": "trials.map(l, l.measurements.allocatable_cores)"}, + {"name": "last", "cel": "cores[size(cores) - 1]"}, + ], + "checks": [{"name": "has_trial", "cel": "size(trials) > 0"}], + "values": [ + {"name": "cores", "cel": "last"}, + {"name": "most", "cel": "math.greatest(cores)"}, + {"name": "name", "cel": "trials[0].metric"}, + {"name": "many", "cel": "size(cores) > 1"}, + {"name": "per_zero", "cel": "last / 0.0"}, + {"name": "nullable", "cel": "size(cores) > 5 ? dyn(last) : null"}, + ], + }) + self.assertIsNone(why) + self.assertEqual(v, {"cores": 88.0, "most": 192.0, "name": "trial_summary", "many": True, + "per_zero": None, "nullable": None}) + + def test_timestamps_and_durations_in_locals(self): + v, why = query_lines([ + {"time": "2026-10-11T07:00:00.250Z", "val": 10.0}, + {"time": "2026-10-11T07:01:00.750Z", "val": 20.0}, + {"time": "2026-10-11T07:03:00.000Z", "val": 30.0}, + ], { + "locals": [ + {"name": "lo", "cel": "timestamp(int(1791702000.0))"}, + {"name": "hi", "cel": "timestamp('2026-10-11T07:02:00Z')"}, + {"name": "span", "cel": "hi - lo"}, + {"name": "kept", "cel": "stats.lines.filter(r, timestamp(r.time) >= lo && timestamp(r.time) <= hi)"}, + ], + "values": [ + {"name": "count", "cel": "double(size(kept))"}, + {"name": "span_s", "cel": "double(span.getSeconds())"}, + ], + }) + self.assertIsNone(why) + self.assertEqual(v, {"count": 2.0, "span_s": 120.0}) + + def test_a_false_check_makes_the_variable_invalid(self): + v, why = query_lines(self.LINES, {"checks": [{"name": "no_failures", "cel": "stats.lines.all(l, !has(l.measurements.failure_count)" + " || l.measurements.failure_count == 0.0)"}], + "values": [{"name": "n", "cel": "double(size(stats.lines))"}]}) + self.assertEqual((v, why), ({}, "check 'no_failures' is false")) + + def test_errors_make_the_variable_invalid_and_name_the_expression(self): + cases = { + "check 'c' failed to evaluate: .*Key not found": ( + {"checks": [{"name": "c", "cel": "stats.lines.all(l, l.measurements.allocatable_cores > 0.0)"}]}, {}), + "local 'l' failed to evaluate: .*Key not found": ( + {"locals": [{"name": "l", "cel": "stats.lines.map(l, l.measurements.allocatable_cores)"}]}, + [{"name": "n", "cel": "math.greatest(l)"}]), + "value 'n' failed to evaluate: .*Key not found": ( + {}, [{"name": "n", "cel": "math.greatest(stats.lines.map(l, l.measurements.allocatable_cores))"}]), + "value 'n' failed to evaluate: .*empty list": ( + {}, [{"name": "n", "cel": "percentile(stats.lines.filter(l, false).map(l, 1.0), 50.0)"}]), + } + for want, (cfg, values) in cases.items(): + with self.subTest(want=want): + v, why = query_lines(self.LINES, + {**cfg, "values": values or [{"name": "n", "cel": "double(size(stats.lines))"}]}) + self.assertEqual(v, {}) + self.assertRegex(why, want) + + def test_an_input_that_cant_be_read_makes_the_variable_invalid(self): + with tempfile.TemporaryDirectory() as tmp: + run = local_run(Path(tmp)) + cfg = {"inputs": STATS, "values": [{"name": "n", "cel": "double(size(stats.lines))"}]} + self.assertEqual(query(run, cfg), ({}, "input 'stats': stats.jsonl absent")) + other = {"inputs": [{**stats_input("other"), "from_test": "t1"}], + "values": [{"name": "n", "cel": "double(size(other.lines))"}]} + self.assertEqual(query(write_stats(Path(tmp), self.LINES), other), + ({}, "input 'other': no run of t1")) + + def test_an_input_with_from_test_reads_that_tests_run(self): + with tempfile.TemporaryDirectory() as tmp: + this = write_stats(Path(tmp) / "this", self.LINES) + other = write_stats(Path(tmp) / "t1", [stats_row("trial_summary", allocatable_cores=4)]) + asked = [] + + def run_of(test: str) -> BenchmarkRunContext: + asked.append(test) + return other + + cfg = {"inputs": [*STATS, {**stats_input("other"), "from_test": "t1"}], + "values": [{"name": "ratio", "cel": "stats.lines[0].measurements.allocatable_cores / " + "other.lines[0].measurements.allocatable_cores"}, + {"name": "other_uri", "cel": "other.uri"}]} + self.assertEqual(query(dataclasses.replace(this, run_of=run_of), cfg), + ({"ratio": 48.0, "other_uri": str(Path(tmp) / "t1")}, None)) + self.assertEqual(asked, ["t1"]) + + def test_each_input_is_read_once_per_run(self): + cfg = {"inputs": STATS, "values": [{"name": "n", "cel": "double(size(stats.lines))"}]} + other = {"inputs": [stats_input("s")], "values": [{"name": "m", "cel": "double(size(s.lines))"}]} + with tempfile.TemporaryDirectory() as tmp: + source = cel.Cel() + source.init(write_stats(Path(tmp), self.LINES)) + with mock.patch.object(json_lines.JsonLines, "read", autospec=True, + side_effect=json_lines.JsonLines.read) as read: + self.assertEqual(source.query(cfg), {"n": 3.0}) + self.assertEqual(source.query(other), {"m": 3.0}) + self.assertEqual(read.call_count, 1) + + def test_a_reader_bug_is_not_reported_as_an_unreadable_input(self): + with tempfile.TemporaryDirectory() as tmp: + source = cel.Cel() + source.init(write_stats(Path(tmp), self.LINES)) + with mock.patch.object(json_lines.JsonLines, "read", side_effect=KeyError("bug")), \ + self.assertRaises(KeyError): + source.query({"inputs": STATS, "values": [{"name": "n", "cel": "1.0"}]}) + + def test_init_reads_nothing(self): + source = cel.Cel() + with mock.patch.object(json_lines.JsonLines, "read") as read: + source.init(NO_RUN) + read.assert_not_called() + + +class JsonLinesTest(unittest.TestCase): + def test_lines_are_coerced_as_in_run_results(self): + with tempfile.TemporaryDirectory() as tmp: + data = read_lines(write_stats(Path(tmp), [ + {"metric": "m", "measurements": {"n": "12.5", "i": 3, "flag": "true", "s": "2026_11", "none": None, + "nan": "NaN"}, "list": [1, "2"]}, + "", "not json", "[1, 2]", + ]), {"file": "stats.jsonl"}) + self.assertEqual(data["lines"], [{"metric": "m", "measurements": {"n": 12.5, "i": 3.0, "flag": True, + "s": "2026_11"}, "list": [1.0, 2.0]}]) + self.assertEqual([(u["line_no"], u["text"]) for u in data["unparsed_lines"]], [(3.0, "not json"), (4.0, "[1, 2]")]) + self.assertRegex(data["unparsed_lines"][0]["error"], "^not JSON: ") + self.assertEqual(data["unparsed_lines"][1]["error"], "not a JSON object") + self.assertTrue(data["uri"]) + + def test_prefix_until_select_and_unique_by(self): + with tempfile.TemporaryDirectory() as tmp: + d = Path(tmp) + log = d / "logs.txt" + log.write_text("\n".join([ + "plain runner line not json", + '[boomer] {"msg": "fail", "actor": "a1", "step": "resume"}', + '[boomer] {"msg": "fail", "actor": "a1", "step": "execute"}', + '[boomer] {"msg": "other", "actor": "a9"}', + '[boomer] {"msg": "fail", "actor": "a2", "step": "suspend"}', + '[boomer] {"msg": "shutdown"}', + '[boomer] {"msg": "fail", "actor": "a3", "step": "resume"}', + ]) + "\n", encoding="utf-8") + run = local_run(log.parent, uri="run1") + data = read_lines(run, { + "file": "logs.txt", + "prefix": "[boomer] ", + "until": "has(line.msg) && line.msg == 'shutdown'", + "select": "has(line.msg) && line.msg == 'fail'", + "unique_by": "actor", + }) + self.assertEqual(data["lines"], [ + {"msg": "fail", "actor": "a1", "step": "resume"}, + {"msg": "fail", "actor": "a2", "step": "suspend"}, + ]) + self.assertEqual(data["unparsed_lines"], []) + self.assertEqual(data["uri"], "run1") + + def test_unique_by_distinguishes_bool_and_int(self): + with tempfile.TemporaryDirectory() as tmp: + data = read_lines(write_stats(Path(tmp), [ + {"k": True, "n": 1}, {"k": 1, "n": 2}, {"k": True, "n": 3}, + ]), {"file": "stats.jsonl", "unique_by": "k"}) + self.assertEqual([x["n"] for x in data["lines"]], [1.0, 2.0]) + + def test_errors(self): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaisesRegex(reader.ReadError, "stats.jsonl absent"): + read_lines(NO_RUN, {"file": "stats.jsonl"}) + run = write_stats(Path(tmp), [{"a": {"nested": 1}}]) + with self.assertRaisesRegex(reader.ReadError, "line 1: select failed: .*Key not found"): + read_lines(run, {"file": "stats.jsonl", "select": "line.missing == 1.0"}) + with self.assertRaisesRegex(reader.ReadError, "line 1: unique_by 'missing': field missing"): + read_lines(run, {"file": "stats.jsonl", "unique_by": "missing"}) + with self.assertRaisesRegex(reader.ReadError, "line 1: unique_by 'a': unhashable dict"): + read_lines(run, {"file": "stats.jsonl", "unique_by": "a"}) + null_run = write_stats(Path(tmp) / "null", [{"a": None, "b": 1}, {"a": "x", "b": 2}]) + selected = read_lines(null_run, {"file": "stats.jsonl", "select": "has(line.a)"}) + self.assertEqual(selected["lines"], [{"a": "x", "b": 2.0}]) + with self.assertRaisesRegex(reader.ReadError, "line 1: unique_by 'a': field missing"): + read_lines(null_run, {"file": "stats.jsonl", "unique_by": "a"}) + + +class JsonFileTest(unittest.TestCase): + def test_reads_and_coerces_json_object(self): + with tempfile.TemporaryDirectory() as tmp: + run = write_stats(Path(tmp), [], summary={"metadata": {"steady_start_ts": "100", "ok": "true", "x": None}}) + data = read_json(run, {"file": "summary.json"}) + self.assertEqual(data["data"], {"metadata": {"steady_start_ts": 100.0, "ok": True}}) + self.assertEqual(data["uri"], str(Path(tmp))) + + def test_errors(self): + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaisesRegex(reader.ReadError, "summary.json absent"): + read_json(NO_RUN, {"file": "summary.json"}) + bad = write_stats(Path(tmp) / "bad", [], summary="{oops") + with self.assertRaisesRegex(reader.ReadError, "summary.json: not JSON: "): + read_json(bad, {"file": "summary.json"}) + arr = write_stats(Path(tmp) / "arr", [], summary=[1, 2]) + with self.assertRaisesRegex(reader.ReadError, "summary.json: not a JSON object"): + read_json(arr, {"file": "summary.json"}) + + +class ReaderTest(unittest.TestCase): + def test_check_data(self): + class R(reader.Reader): + fields = (reader.Field("xs", "list"), reader.Field("n", "double"), reader.Field("ok", "bool", optional=True)) + + reader.check_data(R, {"xs": [], "n": 1.0}) + reader.check_data(R, {"xs": [], "n": 1.0, "ok": False}) + for bad, want in (({"xs": []}, "gave no n"), ({"xs": [], "n": 1.0, "extra": 1.0}, "undeclared fields"), + ({"xs": [], "n": True}, "n is a bool, not a double"), ({"xs": [], "n": 1}, "not a double"), + ({"xs": [], "n": 1.0, "ok": 1.0}, "ok is a float, not a bool")): + with self.subTest(bad=bad), self.assertRaisesRegex(TypeError, want): + reader.check_data(R, bad) + + def test_to_data(self): + @dataclasses.dataclass + class D: + a: int + b: Optional[float] = None + c: float = math.inf + + self.assertEqual(reader.to_data({"d": [D(1)], "n": None, "s": "x", "t": True}), + {"d": [{"a": 1.0}], "s": "x", "t": True}) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/evaluate/unit_tests/test_cli.py b/benchmarking/evaluate/unit_tests/test_cli.py new file mode 100644 index 0000000000..97a6e4b7a3 --- /dev/null +++ b/benchmarking/evaluate/unit_tests/test_cli.py @@ -0,0 +1,287 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for the CLI, `python -m evaluate`, on stored runs. + +Runs are stand-in directories built by the tests; GCS is mocked. +""" + +import contextlib +import io +import json +import shutil +import sys +import tempfile +import unittest +from datetime import datetime, timezone +from pathlib import Path +from typing import Optional +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from evaluate import __main__ as cli # noqa: E402 +from evaluate import rundir # noqa: E402 + +T0 = 1791700000 # 2026-10-11T07:06:40Z +TAG = "abc123" + + +def boomer(sec: float, msg: str, **kw) -> str: + t = datetime.fromtimestamp(T0 + sec, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f000Z") + return "[boomer] " + json.dumps({"time": t, "level": "INFO", "msg": msg, **kw}) + + +def record(sec: float, actor: str, wall_ms: float = 8000.0) -> str: + end = datetime.fromtimestamp(T0 + sec, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%S.%f000Z") + return boomer(sec, "sweperf task record", v=1, user=1, actor=actor, end=end, cel_ms=6000.0, wall_ms=wall_ms, + resume_max_ms=200.0, ttfe_max_ms=210.0, retries=0, failed=False, fail_step="", fail_cycle=0) + + +def write_run(d: Path, records: list[str]) -> Path: + d.mkdir(parents=True, exist_ok=True) + (d / "logs.txt").write_text("\n".join([*records, boomer(60, "sweperf shutdown started")]) + "\n") + trial = {"timestamp": "2026-10-11T07:06:40Z", "tag": TAG, "test_name": d.name, "metric": "trial_summary", + "measurements": {"node_count": "1", "allocatable_cores": "100", "allocatable_ram_gb": "400", + "aggregate_failure_ratio": "0.0005"}} + (d / "stats.jsonl").write_text(json.dumps(trial) + "\n") + (d / "server_summary.json").write_text(json.dumps({"metadata": { + "start_ts": T0, "end_ts": T0 + 60, "steady_start_ts": T0, "steady_end_ts": T0 + 60}})) + return d + + +def run_path(root, test: str, run_date: str, run_ts: int) -> Path: + """Where the runner stores a run of test under root.""" + return Path(root) / "runs" / test / f"run_date={run_date}" / f"run_ts={run_ts}" / f"run_tag={TAG}" + + +def stored(root: Path, test: str, run_ts: int, records=None) -> Path: + date = datetime.fromtimestamp(run_ts, tz=timezone.utc).strftime("%Y-%m-%d") + d = run_path(root, test, date, run_ts) + return write_run(d, records or [record(10, "a1"), record(20, "a2", wall_ms=9000.0)]) + + +def evaluations(limit: float = 90) -> list[dict]: + """goodput_strict against the run of t1 (the 1-user run), and an envelope check.""" + rec_sel = "has(line.msg) && line.msg == 'sweperf task record' && has(line.v) && line.v == 1.0" + goodput_cfg = { + "inputs": [ + {"name": "run", "reader": "json_lines", "reader_cfg": {"file": "logs.txt", "prefix": "[boomer] ", "select": rec_sel}}, + {"name": "one_user", "from_test": "t1", "reader": "json_lines", + "reader_cfg": {"file": "logs.txt", "prefix": "[boomer] ", "select": rec_sel}}, + ], + "locals": [ + {"name": "ref_wall_ms", "cel": "percentile(one_user.lines.filter(t, !t.failed).map(t, t.wall_ms), 50.0)"}, + {"name": "slow_wall", "cel": "run.lines.filter(t, t.wall_ms > 1.5 * ref_wall_ms)"}, + {"name": "good", + "cel": "run.lines.filter(t, !t.failed && t.resume_max_ms <= 1500.0 && t.wall_ms <= 1.5 * ref_wall_ms)"}, + ], + "values": [ + {"name": "good_ratio_pct", "cel": "round(100.0 * double(size(good)) / double(size(run.lines)), 2)"}, + {"name": "good", "cel": "double(size(good))"}, + {"name": "slow_wall", "cel": "double(size(slow_wall))"}, + {"name": "one_user_run", "cel": "one_user.uri"}, + ]} + return [ + {"name": "goodput_strict", "variables": [{"name": "goodput", "source": "cel", "source_cfg": goodput_cfg}], + "conditions": [{"name": "good_ratio", "cel": f"goodput.good_ratio_pct >= {limit}"}]}, + {"name": "envelope", + "variables": [{"name": "trial", "source": "run_results", + "source_cfg": {"metric": "trial_summary", "measurements": ["aggregate_failure_ratio"]}}], + "conditions": [{"name": "failure_ratio", "cel": "trial.aggregate_failure_ratio <= 0.001"}]}, + ] + + +def goodput(out: Path) -> dict: + """The goodput variable of the evaluation.json in out.""" + return json.loads((out / "evaluation.json").read_text())["evaluations"][0]["variables"][0] + + +class CliTest(unittest.TestCase): + def run_cli(self, *argv: str) -> tuple[int, str, str]: + out, err = io.StringIO(), io.StringIO() + with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): + rc = cli.main(list(argv)) + return rc, out.getvalue(), err.getvalue() + + def test_evaluates_and_reevaluates_from_run(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + t1 = stored(root, "t1", T0) + run = stored(root, "t150", T0, records=[record(10, "a1"), record(20, "a2", wall_ms=13000.0)]) + evs = root / "evs.json" + evs.write_text(json.dumps(evaluations(limit=75))) + out = root / "out" + rc, printed, _ = self.run_cli(f"{run}/", "--evaluations", f"@{evs}", "--out", str(out)) + self.assertEqual(rc, 0) + rows = [json.loads(line) for line in (out / "evaluation_rows.jsonl").read_text().splitlines()] + self.assertEqual({r["timestamp"] for r in rows}, {"2026-10-11T07:06:40Z"}) # from the run's stats.jsonl + self.assertEqual(len(rows), 3) + # t1's run is the 1-user run: a2's 13 s is over 1.5 x its 8.5 s median. + self.assertIn("evaluation goodput_strict: fail (failed: good_ratio)", printed) + values = goodput(out)["values"] + self.assertEqual((values["one_user_run"], values["slow_wall"]), (str(t1), 1.0)) + report = json.loads((out / "evaluation.json").read_text()) + self.assertEqual((report["run"]["test_name"], report["run"]["run_ts"]), ("t150", str(T0))) + self.assertFalse((run / "evaluation.json").exists()) # never writes into the stored run + # The stored run's evaluation.json (as the runner uploads it) re-evaluates as recorded. + (run / "evaluation.json").write_text((out / "evaluation.json").read_text()) + rc, printed, _ = self.run_cli(str(run), "--from-run", "--out", str(root / "o2")) + self.assertEqual(rc, 0) + self.assertEqual(json.loads((root / "o2" / "evaluation.json").read_text())["summary"], report["summary"]) + + def test_runs_of_other_tests_need_the_runners_layout(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + t1 = stored(root, "t1", T0) + flat = write_run(root / "flat", [record(10, "a1")]) + rc, _, _ = self.run_cli(str(flat), "--evaluations", json.dumps(evaluations()), "--out", str(root / "o1")) + self.assertEqual(rc, 0) + self.assertEqual(goodput(root / "o1")["invalid_reason"], "input 'one_user': no run of t1") + # A symlink into a runs/ tree is stored there: its path gives the identity and the dest. + link = run_path(tmp, "t150", "2026-10-11", T0) + link.parent.mkdir(parents=True) + link.symlink_to(flat) + rc, _, _ = self.run_cli(str(link), "--evaluations", json.dumps(evaluations()), "--out", str(root / "o2")) + self.assertEqual(rc, 0) + report = json.loads((root / "o2" / "evaluation.json").read_text()) + self.assertEqual(report["run"]["run_ts"], str(T0)) + self.assertEqual(goodput(root / "o2")["values"]["one_user_run"], str(t1)) + + def test_gcs_run(self): + """A gs:// RUN is read, and the other test's run from the same invocation too, under the same gs:// dest.""" + with tempfile.TemporaryDirectory() as tmp: + bucket = Path(tmp) / "bucket" + + def gcs_list(prefix: str) -> list[str]: + local = bucket / prefix[len("gs://b/"):] + return [f"gs://b/{p.relative_to(bucket)}" for p in local.rglob("*") if p.is_file()] + + def gcs_download(uri: str, dest: Path) -> Optional[Path]: + src = bucket / uri[len("gs://b/"):] + if not src.is_file(): + return None + dest.parent.mkdir(parents=True, exist_ok=True) + return Path(shutil.copyfile(src, dest)) + + t1 = stored(bucket / "p", "t1", T0) + run = stored(bucket / "p", "t150", T0) + uri = f"gs://b/{run.relative_to(bucket)}" + with mock.patch.object(rundir, "_gcs_list", side_effect=gcs_list), \ + mock.patch.object(rundir, "_gcs_download", side_effect=gcs_download): + rc, _, _ = self.run_cli(uri, "--evaluations", json.dumps(evaluations()), "--out", f"{tmp}/out") + self.assertEqual(rc, 0) + values = goodput(Path(tmp) / "out")["values"] + self.assertEqual((values["one_user_run"], values["good"]), (f"gs://b/{t1.relative_to(bucket)}", 2.0)) + + def test_exit_codes(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + run = write_run(root / "run", [record(10, "a1")]) + self.assertEqual(self.run_cli(str(run), "--evaluations", '[{"name": 1}]')[0], 2) + # Missing evaluation.json under --from-run is a config error. + rc, _, err = self.run_cli(str(run), "--from-run", "--out", str(root / "o1")) + self.assertEqual(rc, 2) + self.assertIn("has no evaluation.json", err) + # Missing run directory is an I/O error. + self.assertEqual(self.run_cli(str(root / "missing"), "--evaluations", + json.dumps(evaluations()), "--out", str(root / "o2"))[0], 1) + # Without --out (or with several runs), an undefined run_ts fails up front. + rc, _, err = self.run_cli(str(run), "--evaluations", json.dumps(evaluations())) + self.assertEqual(rc, 2) + self.assertIn("run_ts is undefined", err) + run2 = write_run(root / "run2", [record(10, "a1")]) + rc, _, err = self.run_cli(str(run), str(run2), "--evaluations", json.dumps(evaluations()), + "--out", str(root / "o3")) + self.assertEqual(rc, 2) + self.assertIn("run_ts is undefined", err) + # Two runs resolving to the same output directory fail up front rather than overwriting. + d1 = stored(root / "dest1", "t150", T0) + d2 = stored(root / "dest2", "t150", T0) + rc, _, err = self.run_cli(str(d1), str(d2), "--evaluations", json.dumps(evaluations()), + "--out", str(root / "o4")) + self.assertEqual(rc, 2) + self.assertIn("same output directory", err) + self.assertEqual(self.run_cli("--check-config", "--evaluations", json.dumps(evaluations()))[0], 0) + with self.assertRaises(SystemExit): + self.run_cli(str(run)) # no evaluations given + + def test_several_runs_continue_past_per_run_errors(self): + with tempfile.TemporaryDirectory() as tmp: + root = Path(tmp) + missing = run_path(root, "t150", "2026-10-11", T0) + good = stored(root, "t150", T0 + 60) + out = root / "out1" + rc, _, err = self.run_cli(str(missing), str(good), "--evaluations", json.dumps(evaluations()), + "--out", str(out)) + self.assertEqual(rc, 1) + self.assertIn("I/O error:", err) + self.assertTrue((out / "t150" / f"run_ts={T0 + 60}" / "evaluation.json").is_file()) + + # Under --from-run, a run without evaluation.json is reported while later runs still evaluate. + no_eval = stored(root, "t150", T0 + 120) + with_eval = stored(root, "t150", T0 + 180) + (with_eval / "evaluation.json").write_text( + (out / "t150" / f"run_ts={T0 + 60}" / "evaluation.json").read_text() + ) + out2 = root / "out2" + rc, _, err = self.run_cli(str(no_eval), str(with_eval), "--from-run", "--out", str(out2)) + self.assertEqual(rc, 2) + self.assertIn("has no evaluation.json", err) + self.assertTrue((out2 / "t150" / f"run_ts={T0 + 180}" / "evaluation.json").is_file()) + + # Malformed evaluation.json is a per-run config error; mixed I/O + config errors return 1. + malformed = stored(root, "t150", T0 + 240) + (malformed / "evaluation.json").write_text(json.dumps({"evaluations": [{}]})) + out3 = root / "out3" + rc, _, err = self.run_cli(str(missing), str(malformed), str(with_eval), "--from-run", "--out", str(out3)) + self.assertEqual(rc, 1) + self.assertIn("I/O error:", err) + self.assertIn("has invalid evaluations", err) + self.assertTrue((out3 / "t150" / f"run_ts={T0 + 180}" / "evaluation.json").is_file()) + + # Non-OSError read errors registered by rundir.io_errors() (e.g. GCS API/auth errors) also continue. + class FakeGcsError(Exception): + pass + + out4 = root / "out4" + with mock.patch.object(rundir, "io_errors", return_value=(OSError, FakeGcsError)), \ + mock.patch.object(rundir, "_gcs_list", side_effect=FakeGcsError("forbidden")): + rc, _, err = self.run_cli(f"gs://b/runs/t150/run_date=2026-10-11/run_ts={T0}/run_tag={TAG}", + str(with_eval), "--from-run", "--out", str(out4)) + self.assertEqual(rc, 1) + self.assertIn("I/O error:", err) + self.assertTrue((out4 / "t150" / f"run_ts={T0 + 180}" / "evaluation.json").is_file()) + + def test_check_config_on_a_tests_file(self): + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "tests.yaml" + path.write_text(json.dumps({"tests": [{"name": "ok", "evaluations": evaluations()}, + {"name": "bad", "evaluations": [{"name": "Bad"}]}, + {"name": "none"}]})) + rc, out, err = self.run_cli("--check-config", "--tests-file", str(path)) + self.assertEqual(rc, 2) + self.assertIn("ok: ok (2 evaluations)", out) + self.assertIn("bad: evaluations: 0.name: String should match pattern", err) + rc, out, _ = self.run_cli("--check-config", "--tests-file", str(path), "--test-name", "ok") + self.assertEqual((rc, out), (0, "ok: ok (2 evaluations)\n")) + bad_yaml = Path(tmp) / "bad.yaml" + bad_yaml.write_text("tests: [\n") + rc, _, err = self.run_cli("--check-config", "--tests-file", str(bad_yaml)) + self.assertEqual(rc, 2) + self.assertIn("config error:", err) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/evaluate/unit_tests/test_evaluator.py b/benchmarking/evaluate/unit_tests/test_evaluator.py new file mode 100644 index 0000000000..71be96a778 --- /dev/null +++ b/benchmarking/evaluate/unit_tests/test_evaluator.py @@ -0,0 +1,573 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for config loading, CEL conditions, the evaluator and run_results. + +Runs are stand-in directories built by the tests. +""" + +import json +import re +import sys +import tempfile +import unittest +from datetime import date, datetime, timedelta, timezone +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from evaluate import cel_env, config, evaluator # noqa: E402 +from evaluate.evaluator import ConditionResult, Summary # noqa: E402 +from evaluate.sources import SOURCES, BenchmarkRunContext, Source, SourceInvalid # noqa: E402 +from evaluate.sources.base import LocalArtifacts, RunIdentity # noqa: E402 +from evaluate.sources.run_results import RunResults, coerce # noqa: E402 + +TAG = "abc123" +NOW = datetime(2026, 11, 2, 10, 0, 0, tzinfo=timezone.utc) +IDENTITY = RunIdentity(uri="gs://b/runs/t150", test_name="t150", tag=TAG, run_ts=1791700000) + + +def local_run(d: Path) -> BenchmarkRunContext: + return BenchmarkRunContext(IDENTITY, LocalArtifacts(d)) + + +NO_RUN = local_run(Path(tempfile.gettempdir()) / "evaluate-unit-tests-no-run") # holds no files + + +def stats_row(metric: str, **m) -> dict: + return {"timestamp": "2026-10-11T07:06:40Z", "tag": TAG, "test_name": "t150", "metric": metric, + "measurements": {k: None if v is None else str(v) for k, v in m.items()}} + + +def write_run(d: Path, rows: list[dict] = ()) -> BenchmarkRunContext: + d.mkdir(parents=True, exist_ok=True) + trial = stats_row("trial_summary", aggregate_failure_ratio=0.0005, allocatable_ram_gb=400, ok=True) + (d / "stats.jsonl").write_text("".join(json.dumps(r) + "\n" for r in [trial, *rows])) + return local_run(d) + + +def evaluations(limit: float = 0.001) -> list[dict]: + """envelope_health from the design: run_results over two stats rows.""" + return [{ + "name": "envelope_health", + "variables": [ + {"name": "trial", "source": "run_results", + "source_cfg": {"metric": "trial_summary", "measurements": ["aggregate_failure_ratio", "allocatable_ram_gb"]}}, + {"name": "server", "source": "run_results", + "source_cfg": {"metric": "server_summary", "measurements": ["working_set_node_max_gb"]}}], + "conditions": [ + {"name": "failure_rate", "cel": f"trial.aggregate_failure_ratio <= {limit}"}, + {"name": "worker_memory", "cel": "server.working_set_node_max_gb < 0.85 * trial.allocatable_ram_gb"}], + }] + + +def judge(run: BenchmarkRunContext, evs: list[dict]) -> evaluator.Report: + return evaluator.Evaluator(config.load(evs), run).evaluate(now=NOW) + + +class Fake(Source): + """A source that records its hooks, for the lifecycle and scalar type tests.""" + calls: list = [] + + @classmethod + def validate(cls, cfg): + if set(cfg) - {"answer", "values", "invalid", "boom"}: + raise ValueError("unknown keys") + + def init(self, run): + super().init(run) + Fake.calls.append(("init", run)) + + def query(self, cfg): + Fake.calls.append(("query", cfg)) + if cfg.get("boom"): + raise RuntimeError("boom") + if "values" in cfg: + values = dict(cfg["values"]) + else: + values = {"answer": cfg.get("answer")} + if "invalid" in cfg: + raise SourceInvalid(cfg["invalid"], values) + return values + + +def fake_evaluation(name: str, cfg: dict, cel_expr: str = "f.answer == 42") -> dict: + return {"name": name, "variables": [{"name": "f", "source": "fake", "source_cfg": cfg}], + "conditions": [{"name": "c", "cel": cel_expr}]} + + +class ConfigTest(unittest.TestCase): + def test_load_and_echo(self): + evs = config.load(evaluations()) + self.assertEqual([(e.name, len(e.variables), len(e.conditions)) for e in evs], [("envelope_health", 2, 2)]) + echoed = config.to_json(evs) + self.assertEqual(config.to_json(config.load(echoed)), echoed) + self.assertEqual(echoed[0]["description"], "") + # Evaluation and condition names allow double underscores; external keys allow capitals and dots. + dotted = [{ + "name": "ingress__rps", + "variables": [{"name": "nh", "source": "run_results", "source_cfg": { + "metric": "nighthawk", "measurements": ["metric_nighthawk.builtin_attempted_rps", "p99.9"]}}], + "conditions": [{"name": "rps__min", + "cel": 'nh["metric_nighthawk.builtin_attempted_rps"] >= 2.0 * nh["p99.9"]'}], + }] + self.assertEqual(config.load(dotted)[0].conditions[0].name, "rps__min") + + def test_errors(self): + def broken(path: str, value) -> list: + evs = evaluations() + obj = evs[0] + *head, last = path.split(".") + for key in head: + obj = obj[int(key)] if key.isdigit() else obj[key] + if value is KeyError: + del obj[last] + else: + obj[int(last) if last.isdigit() else last] = value + return evs + + cases = { + "evaluations: Input should be a valid list": {"name": "x"}, + "evaluations: List should have at least 1 item": [], + "evaluations: 0.name: String should match pattern '^[a-z][a-z0-9_]*$'": [{"name": "Bad"}], + "0.7: Keys should be strings": [{**evaluations()[0], 7: "x"}], + "0.variables.0.source: Input should be a valid string": broken("variables.0.source", ["run_results"]), + "0.severity: Extra inputs are not permitted": broken("severity", "record"), + "0.actions: Extra inputs are not permitted": broken("actions", []), + "0.name: String should match pattern": broken("name", "Envelope"), + "0.variables.0.name: String should have at most 64 characters": broken("variables.0.name", "a" * 65), + "0.variables: List should have at least 1 item": broken("variables", []), + "0.conditions: Field required": broken("conditions", KeyError), + "0.conditions: List should have at least 1 item": broken("conditions", []), + "0.description: Input should be a valid string": broken("description", 1), + "0.variables.0.source: source 'prometheus' is not one of": broken("variables.0.source", "prometheus"), + "0.variables.0.source_cfg: Input should be a valid dictionary": broken("variables.0.source_cfg", ["x"]), + "0.variables.0.source_cfg.0.[key]: Input should be a valid string": broken("variables.0.source_cfg", {0: "x"}), + "0.variables.0: source_cfg: measurements: Field required": broken( + "variables.0.source_cfg", {"metric": "trial_summary"}), + "0.conditions.0.0: Keys should be strings": broken("conditions.0", {"name": "failure_rate", 0: "x"}), + "0.conditions.0.type: Extra inputs are not permitted": broken( + "conditions.0", {"name": "failure_rate", "type": "threshold", "check": {}}), + "0.conditions.0.cel: Field required": broken("conditions.0", {"name": "failure_rate"}), + "0.conditions.0.cel: Input should be a valid string": broken("conditions.0.cel", ["<="]), + "Syntax error": broken("conditions.0.cel", "trial.aggregate_failure_ratio <="), + "undeclared reference to 'gp.goodput_ratio_pct'": broken("conditions.0.cel", "gp.goodput_ratio_pct >= 80"), + "condition 'failure_rate': cel: must give a bool, gives DOUBLE": broken( + "conditions.0.cel", "trial.aggregate_failure_ratio + 1.0"), + "no matching overload": broken("conditions.0.cel", "trial.aggregate_failure_ratio + 1 > 1.0"), + "0: condition names repeated": broken("conditions", evaluations()[0]["conditions"] * 2), + "0: variable names repeated": broken("variables.1.name", "trial"), + "evaluations: evaluation names repeated": evaluations() + evaluations(), + # trial__x with value y and trial with value x__y would both be trial__x__y. + "0.variables.0.name: String should match pattern '^[a-z][a-z0-9]*(_[a-z0-9]+)*$'": broken( + "variables.0.name", "trial__x"), + "0.variables.1.name: String should match pattern": broken("variables.1.name", "server_"), + } + for message, evs in cases.items(): + with self.assertRaisesRegex(config.ConfigError, re.escape(message), msg=message): + config.load(evs) + + def test_one_bad_item_is_one_error(self): + evs = evaluations() + evs[0]["variables"] = evs[0]["variables"][:1] + evs[0]["conditions"] = [{"name": "c", "cel": 1}] + evs[0]["variables"][0]["source_cfg"] = None # an error; leaving source_cfg out means {} + with self.assertRaises(config.ConfigError) as e: + config.load(evs) + self.assertEqual(str(e.exception), "evaluations: 0.variables.0.source_cfg: Input should be a valid dictionary; " + "0.conditions.0.cel: Input should be a valid string") + + def test_cel_names_cannot_name_a_variable(self): + # CEL rejects a built-in type name as a variable, whether or not a condition reads it. + for type_name in ("int", "double", "map", "dyn", "type"): + evs = evaluations() + evs[0]["variables"][0]["name"] = type_name + with self.assertRaisesRegex(config.ConfigError, f"variable '{type_name}' declared multiple times"): + config.load(evs) + # A keyword parses as itself, so a condition that uses one as a variable doesn't compile. + for keyword in ("true", "null", "in", "return"): + evs = evaluations() + evs[0]["variables"][0]["name"] = keyword + evs[0]["conditions"][0]["cel"] = f"{keyword}.aggregate_failure_ratio <= 0.001" + with self.assertRaisesRegex(config.ConfigError, "condition 'failure_rate': cel: INVALID_ARGUMENT"): + config.load(evs) + + def test_conditions_need_not_read_every_variable(self): + evs = evaluations() + evs[0]["conditions"] = [{"name": "constant", "cel": "1 < 2"}] + self.assertEqual(len(config.load(evs)[0].variables), 2) + + def test_source_cfg_is_json(self): + with mock.patch.dict(SOURCES, {"fake": Fake}): + cases = { + "0.variables.0.source_cfg.values.dict.when: input was not a valid JSON value": + {"values": {"when": date(2026, 11, 11)}}, + "0.variables.0.source_cfg.values.dict.1.[key]: Input should be a valid string": {"values": {1: "x"}}, + } + for message, cfg in cases.items(): + with self.assertRaisesRegex(config.ConfigError, re.escape(message), msg=message): + config.load([fake_evaluation("e", cfg)]) + + def test_source_cfg_is_a_copy_of_the_input(self): + with mock.patch.dict(SOURCES, {"fake": Fake}): + evs = [fake_evaluation("e", {"values": {"answer": 42, "list": [{"a": 1}]}})] + loaded = config.load(evs) + evs[0]["variables"][0]["source_cfg"]["values"]["answer"] = 0 + evs[0]["variables"][0]["source_cfg"]["values"]["list"][0]["a"] = 2 + self.assertEqual(loaded[0].variables[0].source_cfg, {"values": {"answer": 42, "list": [{"a": 1}]}}) + + def test_source_cfg_defaults_to_empty(self): + with mock.patch.dict(SOURCES, {"fake": Fake}): + ev = fake_evaluation("e", {}) + del ev["variables"][0]["source_cfg"] + self.assertEqual(config.load([ev])[0].variables[0].source_cfg, {}) + with self.assertRaisesRegex(config.ConfigError, "0.variables.0: source_cfg: unknown keys"): + config.load([fake_evaluation("e", {"what": 1})]) + + +class RunResultsTest(unittest.TestCase): + def query(self, run: BenchmarkRunContext, cfg: dict): + RunResults.validate(cfg) + source = RunResults() + source.init(run) + return source.query(cfg) + + def test_values(self): + with tempfile.TemporaryDirectory() as tmp: + nh_row = {"timestamp": "2026-10-11T07:06:40Z", "tag": TAG, "test_name": "t150", "metric": "nighthawk", + "measurements": {"metric_nighthawk.builtin_attempted_rps": "1250.5", "p99.9": "4.2", + "release": "2026_11"}} + run = write_run(Path(tmp), [stats_row("grpc_ResumeActor", p90=420), stats_row("grpc_ResumeActor", p90=430), + stats_row("server_summary", oom_events_node=None, mode="async"), + stats_row("phases", locust_ResumeActor=812.5), nh_row]) + self.assertEqual(self.query(run, {"metric": "trial_summary", "measurements": ["ok", "allocatable_ram_gb", + "nope"]}), + {"ok": True, "allocatable_ram_gb": 400.0, "nope": None}) + self.assertEqual(self.query(run, {"metric": "grpc_ResumeActor", "measurements": ["p90"]}), + {"p90": 430.0}) + self.assertEqual(self.query(run, {"metric": "phases", "measurements": ["locust_ResumeActor"]}), + {"locust_ResumeActor": 812.5}) + self.assertEqual(self.query(run, {"metric": "nighthawk", + "measurements": ["metric_nighthawk.builtin_attempted_rps", "p99.9", + "release"]}), + {"metric_nighthawk.builtin_attempted_rps": 1250.5, "p99.9": 4.2, "release": "2026_11"}) + self.assertEqual(self.query(run, {"metric": "server_summary", "measurements": ["oom_events_node", "mode"]}), + {"oom_events_node": None, "mode": "async"}) + + def test_numbers_that_are_not_finite_are_null(self): + self.assertEqual(coerce("1_000"), "1_000") + with tempfile.TemporaryDirectory() as tmp: + run = write_run(Path(tmp)) + with open(run.artifacts.dir / "stats.jsonl", "a", encoding="utf-8") as f: + f.write('{"metric": "m", "measurements": {"nan": NaN, "inf": -Infinity, "big": "1e999", ' + '"snan": "nan", "sinf": "-inf", "ok": "2"}}\n') + self.assertEqual(self.query(run, {"metric": "m", + "measurements": ["nan", "inf", "big", "snan", "sinf", "ok"]}), + {"nan": None, "inf": None, "big": None, "snan": None, "sinf": None, "ok": 2.0}) + + def test_blank_lines_are_skipped_and_other_lines_must_be_rows(self): + with tempfile.TemporaryDirectory() as tmp: + run = write_run(Path(tmp)) + with open(run.artifacts.dir / "stats.jsonl", "a", encoding="utf-8") as f: + f.write("\n \n") + self.assertEqual(self.query(run, {"metric": "trial_summary", "measurements": ["ok"]}), {"ok": True}) + for line, message in (("not json", "stats.jsonl line 4 isn't JSON"), + ("[1, 2]", "stats.jsonl line 4 isn't an object with a metric"), + ('{"measurements": {}}', "stats.jsonl line 4 isn't an object with a metric"), + ('{"metric": ""}', "stats.jsonl line 4 isn't an object with a metric")): + bad = write_run(Path(tmp) / "bad") + with open(bad.artifacts.dir / "stats.jsonl", "a", encoding="utf-8") as f: + f.write(f"\n\n{line}\n") + with self.assertRaisesRegex(SourceInvalid, re.escape(message), msg=line): + self.query(bad, {"metric": "trial_summary", "measurements": ["ok"]}) + + def test_invalid(self): + with tempfile.TemporaryDirectory() as tmp: + run = write_run(Path(tmp)) + with self.assertRaisesRegex(SourceInvalid, "no stats.jsonl row ladder_step_001"): + self.query(run, {"metric": "ladder_step_001", "measurements": ["users"]}) + with self.assertRaisesRegex(SourceInvalid, "stats.jsonl absent"): + self.query(NO_RUN, {"metric": "trial_summary", "measurements": ["ok"]}) + + def test_validate(self): + RunResults.validate({"metric": "m", "measurements": ["locust_ResumeActor", "p99.9", "a__b"]}) + cases = { + "Input should be a valid dictionary": [], + "0: Keys should be strings": {"metric": "m", "measurements": ["a"], 0: "x"}, + "run: Extra inputs are not permitted": {"metric": "m", "measurements": ["a"], "run": "baseline"}, + "metric: Field required": {"measurements": ["a"]}, + "measurements: Field required": {"metric": "m"}, + "metric: String should have at least 1 character": {"metric": "", "measurements": ["a"]}, + "measurements: List should have at least 1 item": {"metric": "m", "measurements": []}, + "measurements.0: String should have at least 1 character": {"metric": "m", "measurements": [""]}, + "measurements: listed twice": {"metric": "m", "measurements": ["a", "a"]}, + } + for message, cfg in cases.items(): + with self.assertRaisesRegex(ValueError, re.escape(message), msg=message): + RunResults.validate(cfg) + + +class EvaluateTest(unittest.TestCase): + def test_report(self): + with tempfile.TemporaryDirectory() as tmp: + run = write_run(Path(tmp), [stats_row("server_summary", working_set_node_max_gb=350)]) + report = judge(run, evaluations()) + pass_run = write_run(Path(tmp) / "pass", [stats_row("server_summary", working_set_node_max_gb=300)]) + pass_report = judge(pass_run, evaluations()) + (ev,) = report.evaluations + self.assertEqual((report.run, report.evaluated_at), ( + {"test_name": "t150", "tag": TAG, "run_ts": "1791700000", "uri": "gs://b/runs/t150"}, "2026-11-02T10:00:00Z")) + self.assertEqual((ev.status, ev.passed, ev.reason), ("fail", False, "failed: worker_memory")) + worker_memory = "server.working_set_node_max_gb < 0.85 * trial.allocatable_ram_gb" + self.assertEqual(ev.conditions, ( + ConditionResult(name="failure_rate", cel="trial.aggregate_failure_ratio <= 0.001", status="pass", + passed=True, reason=""), + ConditionResult(name="worker_memory", cel=worker_memory, status="fail", passed=False, + reason=f"worker_memory: {worker_memory}"), + )) + self.assertEqual(ev.variables[0].values, {"aggregate_failure_ratio": 0.0005, "allocatable_ram_gb": 400.0}) + self.assertEqual(ev.config, config.to_json(config.load(evaluations()))[0]) + self.assertEqual(report.summary, Summary(status="fail", passed=False, failed=("envelope_health",), invalid=())) + self.assertEqual((pass_report.evaluations[0].reason, pass_report.summary), + ("", Summary(status="pass", passed=True, failed=(), invalid=()))) + + def test_cel_operators_and_int_float_arithmetic(self): + with mock.patch.dict(SOURCES, {"fake": Fake}): + evs = [{ + "name": "math", + "variables": [{"name": "counts", "source": "fake", + "source_cfg": {"values": {"good": 9, "records": 10, "pct": 90.04, "ok": True}}}], + "conditions": [ + {"name": "ratio", "cel": "counts.good / counts.records >= 0.9"}, + {"name": "scaled", "cel": "2.0 * counts.good == 18.0 && counts.records / 2.0 == 5.0"}, + {"name": "scaled_float", "cel": "1.5 * counts.records <= 15.0"}, + {"name": "rounded_pct", "cel": "round(counts.pct, 1) >= 90.0"}, + {"name": "rounded_int", "cel": "round(counts.good, 0) == 9.0"}, + {"name": "int_literal_compare", "cel": "counts.records <= 1500 && counts.pct > 90"}, + {"name": "logic", "cel": "counts.ok && !(counts.good < 1 || counts.records == 0)"}, + ], + }] + report = judge(NO_RUN, evs) + (ev,) = report.evaluations + self.assertEqual(ev.status, "pass") + # Source int and bool values stay untouched in the results. + self.assertEqual(ev.variables[0].values, {"good": 9, "records": 10, "pct": 90.04, "ok": True}) + self.assertTrue(all(isinstance(ev.variables[0].values[k], int) for k in ("good", "records"))) + self.assertIs(ev.variables[0].values["ok"], True) + + def test_int_literal_with_a_value_of_unknown_type_makes_the_condition_invalid(self): + with mock.patch.dict(SOURCES, {"fake": Fake}): + report = judge(NO_RUN, [fake_evaluation("e", {"answer": 1}, "f.answer * 100 >= 99")]) + (c,) = report.evaluations[0].conditions + self.assertEqual(c.status, "invalid") + self.assertIn("No matching overloads found : _*_(double, int64)", c.reason) + + def test_int_literal_mixed_with_a_double_is_a_config_error(self): + # Values are doubles in CEL, which has no int-double overloads for arithmetic, nor for comparing + # an expression known to be a double: write 2.0. A value compared directly is dyn, so f.answer <= 1500 works. + with mock.patch.dict(SOURCES, {"fake": Fake}): + for expression in ("2 * f.answer > 1.0", "round(f.answer, 1) >= 90", "f.answer / 2.0 == 1"): + with self.assertRaisesRegex(config.ConfigError, "no matching overload", msg=expression): + config.load([fake_evaluation("e", {}, cel_expr=expression)]) + + def test_external_measurement_keys(self): + evs = [{"name": "phases", "variables": [ + {"name": "phases", "source": "run_results", + "source_cfg": {"metric": "phase_breakdown_summary", "measurements": ["locust_ResumeActor"]}}, + {"name": "nh", "source": "run_results", + "source_cfg": {"metric": "nighthawk", + "measurements": ["metric_nighthawk.builtin_attempted_rps", "p99.9", "release"]}}], + "conditions": [ + {"name": "resume", "cel": "phases.locust_ResumeActor <= 1000"}, + {"name": "rps", "cel": 'nh["metric_nighthawk.builtin_attempted_rps"] >= 500'}, + {"name": "p999", "cel": 'nh["p99.9"] <= 5 && nh.release == "2026_11"'}]}] + phase_row = {"timestamp": "2026-10-11T07:06:40Z", "tag": TAG, "test_name": "t150", + "metric": "phase_breakdown_summary", "measurements": {"locust_ResumeActor": "812.5"}} + nh_row = {"timestamp": "2026-10-11T07:06:40Z", "tag": TAG, "test_name": "t150", "metric": "nighthawk", + "measurements": {"metric_nighthawk.builtin_attempted_rps": "600", "p99.9": "4.2", + "release": "2026_11"}} + with tempfile.TemporaryDirectory() as tmp: + run = write_run(Path(tmp), [phase_row, nh_row]) + report = judge(run, evs) + self.assertEqual(report.summary.status, "pass") + self.assertEqual(report.evaluations[0].variables[1].values, + {"metric_nighthawk.builtin_attempted_rps": 600.0, "p99.9": 4.2, "release": "2026_11"}) + + def test_cross_type_equality_and_eval_errors(self): + evs = [{"name": "types", + "variables": [{"name": "build", "source": "run_results", + "source_cfg": {"metric": "build", "measurements": ["version", "tag"]}}], + "conditions": [ + {"name": "numeric", "cel": "build.version == 1.1"}, + {"name": "cross_eq", "cel": 'build.version == "1.10"'}, + {"name": "cross_neq", "cel": 'build.version != "1.10"'}, + {"name": "words", "cel": 'build.tag == "rel-1.10"'}, + {"name": "overflow", "cel": "int(build.version * 1e300) > int(0)"}, + ]}] + with tempfile.TemporaryDirectory() as tmp: + report = judge(write_run(Path(tmp), [stats_row("build", version="1.10", tag="rel-1.10")]), evs) + by_name = {c.name: c for c in report.evaluations[0].conditions} + self.assertEqual([by_name[k].status for k in ("numeric", "cross_eq", "cross_neq", "words", "overflow")], + ["pass", "fail", "pass", "pass", "invalid"]) + self.assertIn("overflow: OUT_OF_RANGE:", by_name["overflow"].reason) + + def test_null_and_missing_keys_with_has(self): + """Null or missing measurements omit the map key: direct reads become invalid (even with !=), + while has() tests presence cleanly.""" + evs = [{"name": "health", "variables": [{"name": "server", "source": "run_results", "source_cfg": { + "metric": "server_summary", "measurements": ["oom_events_node", "oom_events_worker_restarts"]}}], + "conditions": [ + {"name": "node_ooms_eq", "cel": "server.oom_events_node == 0"}, + {"name": "node_ooms_neq", "cel": "server.oom_events_node != 0"}, + {"name": "missing_neq", "cel": "server.unlisted != 0"}, + {"name": "has_null", "cel": "has(server.oom_events_node)"}, + {"name": "not_has_null", "cel": "!has(server.oom_events_node)"}, + {"name": "has_restarts", "cel": "has(server.oom_events_worker_restarts)"}, + {"name": "restarts", "cel": "server.oom_events_worker_restarts == 0"}]}] + with tempfile.TemporaryDirectory() as tmp: + run = write_run(Path(tmp), [stats_row("server_summary", oom_events_node=None, oom_events_worker_restarts=0)]) + report = judge(run, evs) + conds = {c.name: c for c in report.evaluations[0].conditions} + self.assertEqual(conds["node_ooms_eq"].status, "invalid") + self.assertIn("node_ooms_eq: NOT_FOUND:", conds["node_ooms_eq"].reason) + self.assertEqual(conds["node_ooms_neq"].status, "invalid") + self.assertEqual(conds["missing_neq"].status, "invalid") + self.assertEqual((conds["has_null"].status, conds["not_has_null"].status), ("fail", "pass")) + self.assertEqual((conds["has_restarts"].status, conds["restarts"].status), ("pass", "pass")) + self.assertIsNone(report.evaluations[0].variables[0].values["oom_events_node"]) + + def test_a_condition_reading_an_invalid_variable_is_invalid(self): + with tempfile.TemporaryDirectory() as tmp: + report = judge(write_run(Path(tmp)), evaluations()) + (ev,) = report.evaluations + self.assertEqual((ev.variables[1].status, ev.variables[1].invalid_reason), + ("invalid", "no stats.jsonl row server_summary")) + self.assertEqual([c.status for c in ev.conditions], ["pass", "invalid"]) + self.assertEqual(ev.conditions[1].reason, + 'worker_memory: UNKNOWN: No value with name "server" found in Activation') + self.assertEqual((ev.status, ev.passed, ev.reason), ( + "invalid", False, "invalid: worker_memory; variable server is invalid: no stats.jsonl row server_summary")) + self.assertEqual(report.summary, + Summary(status="invalid", passed=False, failed=(), invalid=("envelope_health",))) + + def test_an_invalid_variable_no_condition_reads_makes_the_evaluation_invalid(self): + evs = evaluations() + evs[0]["conditions"] = evs[0]["conditions"][:1] # reads trial only; server has no row + with tempfile.TemporaryDirectory() as tmp: + report = judge(write_run(Path(tmp)), evs) + (ev,) = report.evaluations + self.assertEqual([c.status for c in ev.conditions], ["pass"]) + self.assertEqual((ev.status, ev.passed, ev.reason), + ("invalid", False, "variable server is invalid: no stats.jsonl row server_summary")) + + def test_a_failed_condition_beats_an_invalid_variable(self): + with tempfile.TemporaryDirectory() as tmp: + report = judge(write_run(Path(tmp)), evaluations(limit=0.0001)) + (ev,) = report.evaluations + self.assertEqual(ev.variables[1].status, "invalid") + self.assertEqual([c.status for c in ev.conditions], ["fail", "invalid"]) + self.assertEqual((ev.status, ev.reason), ("fail", "failed: failure_rate")) + + def test_a_condition_may_be_a_bare_value(self): + with mock.patch.dict(SOURCES, {"fake": Fake}): + def status(values, cel_expr): + return judge(NO_RUN, [fake_evaluation("e", {"values": values}, cel_expr)]).evaluations[0].conditions[0] + self.assertEqual(status({"ok": True}, "f.ok").status, "pass") + self.assertEqual(status({"ok": False}, "f.ok").status, "fail") + c = status({"name": "n"}, "f.name") + self.assertEqual((c.status, c.reason), ("invalid", "c: gives a string, not a bool")) + + def test_evaluated_at_is_utc(self): + with tempfile.TemporaryDirectory() as tmp: + run = write_run(Path(tmp), [stats_row("server_summary", working_set_node_max_gb=300)]) + pacific = timezone(timedelta(hours=-8)) + report = evaluator.Evaluator(config.load(evaluations()), run).evaluate( + now=datetime(2026, 11, 2, 2, 0, 0, tzinfo=pacific)) + self.assertEqual(report.evaluated_at, "2026-11-02T10:00:00Z") + + def test_evaluate_condition_turns_a_runtime_error_into_a_value_error(self): + # A stub, since the real trigger (a string with a lone surrogate) is undefined behavior in the macOS build. + expr = mock.Mock() + expr.eval.side_effect = RuntimeError("basic_string: construction from null is not valid") + with self.assertRaisesRegex(ValueError, "^basic_string: construction from null is not valid$"): + cel_env.evaluate_condition(expr, {}) + + +class HooksTest(unittest.TestCase): + """The evaluator's side of the source hooks: validate at load, init once, query per distinct cfg.""" + + def setUp(self): + Fake.calls = [] + patcher = mock.patch.dict(SOURCES, {"fake": Fake}) + patcher.start() + self.addCleanup(patcher.stop) + + def test_init_once_then_one_query_per_distinct_cfg(self): + run = NO_RUN + evs = config.load([fake_evaluation("a", {"answer": 42}), fake_evaluation("b", {"answer": 42}), + fake_evaluation("c", {"answer": 7}, cel_expr="f.answer == 7")]) + e = evaluator.Evaluator(evs, run) + self.assertEqual(Fake.calls, [("init", run)]) + report = e.evaluate(now=NOW) + self.assertEqual(Fake.calls[1:], [("query", {"answer": 42}), ("query", {"answer": 7})]) + self.assertEqual(report.summary.status, "pass") + + def test_source_invalid_keeps_its_values(self): + for reason in ("no baseline", ""): # the exception makes the variable invalid, whatever its reason says + report = judge(NO_RUN, [fake_evaluation("a", {"answer": 42, "invalid": reason})]) + (var,) = report.evaluations[0].variables + self.assertEqual((var.status, var.invalid_reason, var.values), ("invalid", reason, {"answer": 42})) + self.assertEqual(report.evaluations[0].conditions[0].reason, + 'c: UNKNOWN: No value with name "f" found in Activation') + self.assertEqual(report.evaluations[0].reason, f"invalid: c; variable f is invalid: {reason}") + self.assertEqual(report.summary.status, "invalid") + + def test_non_finite_floats_from_source_are_normalized_at_boundary(self): + for val in (float("nan"), float("inf"), float("-inf")): + with mock.patch.object(Fake, "query", return_value={"answer": val}): + report = judge(NO_RUN, [fake_evaluation("a", {"answer": 1})]) + self.assertEqual(report.evaluations[0].variables[0].values, {"answer": None}) + self.assertEqual(report.evaluations[0].conditions[0].status, "invalid") + with mock.patch.object(Fake, "query", side_effect=SourceInvalid("bad", {"answer": float("nan")})): + report = judge(NO_RUN, [fake_evaluation("a", {"answer": 1})]) + self.assertEqual(report.evaluations[0].variables[0].values, {"answer": None}) + + def test_values_must_be_scalars_with_string_names(self): + scalar = "a value must be a number, bool, string or null" + cases = { + f"value 'nested' is a dict: {scalar}": {"answer": 42, "nested": {"p50": 1.0}}, + f"value 'nested' is a list: {scalar}": {"answer": 42, "nested": [1.0]}, + f"value 'nested' is a tuple: {scalar}": {"answer": 42, "nested": (1.0,)}, + "value name '' must be a non-empty string": {"answer": 42, "": 1.0}, + "value name 1 must be a non-empty string": {"answer": 42, 1: 1.0}, + } + for reason, values in cases.items(): + for query in ({"return_value": values}, {"side_effect": SourceInvalid("bad", values)}): + with mock.patch.object(Fake, "query", **query): + report = judge(NO_RUN, [fake_evaluation("a", {"answer": 42})]) + (var,) = report.evaluations[0].variables + self.assertEqual((var.status, var.invalid_reason, var.values), ("invalid", reason, {})) + self.assertEqual(report.evaluations[0].conditions[0].status, "invalid") + + def test_errors_become_invalid(self): + report = judge(NO_RUN, [fake_evaluation("a", {"boom": True})]) + self.assertEqual(report.evaluations[0].variables[0].invalid_reason, "error: RuntimeError: boom") + with mock.patch.object(Fake, "init", side_effect=OSError("no disk")): + report = judge(NO_RUN, [fake_evaluation("a", {"answer": 42})]) + self.assertEqual(report.evaluations[0].variables[0].invalid_reason, "init failed: OSError: no disk") + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/evaluate/unit_tests/test_report.py b/benchmarking/evaluate/unit_tests/test_report.py new file mode 100644 index 0000000000..be541c3918 --- /dev/null +++ b/benchmarking/evaluate/unit_tests/test_report.py @@ -0,0 +1,139 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for what a Report writes: evaluation.json, the stats.jsonl rows and the log lines.""" + +import json +import sys +import tempfile +import unittest +from dataclasses import replace +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from evaluate.evaluator import ( # noqa: E402 + ConditionResult, EvaluationResult, Report, Summary, VariableResult, error_report) +from evaluate.sources.base import RunIdentity # noqa: E402 + +TAG = "abc123" +WORKER_MEMORY = "server.working_set_node_max_gb < 0.85 * trial.allocatable_ram_gb" +FAILURE_RATE = ConditionResult(name="failure_rate", cel="trial.aggregate_failure_ratio <= 0.001", status="pass", + passed=True, reason="") +ENVELOPE = EvaluationResult( + name="envelope_health", description="", status="fail", passed=False, reason="failed: worker_memory", + conditions=(FAILURE_RATE, ConditionResult(name="worker_memory", cel=WORKER_MEMORY, status="fail", passed=False, + reason=f"worker_memory: {WORKER_MEMORY}")), + variables=(VariableResult(name="trial", source="run_results", status="ok", invalid_reason=None, + values={"aggregate_failure_ratio": 0.0005, "allocatable_ram_gb": 400.0}), + VariableResult(name="server", source="run_results", status="ok", invalid_reason=None, + values={"working_set_node_max_gb": 350.0})), + config={"name": "envelope_health"}) + + +def report(ev: EvaluationResult, summary: Summary) -> Report: + return Report(run={"test_name": "t150", "tag": TAG}, evaluated_at="2026-11-02T10:00:00Z", error=None, + summary=summary, evaluations=(ev,)) + + +FAILED = report(ENVELOPE, Summary(status="fail", passed=False, failed=("envelope_health",), invalid=())) + + +class ReportTest(unittest.TestCase): + def test_rows(self): + rows = FAILED.stats_rows("ts") + self.assertEqual([r["metric"] for r in rows], ["evaluation_envelope_health", "evaluations"]) + self.assertEqual({(r["timestamp"], r["tag"], r["test_name"]) for r in rows}, {("ts", TAG, "t150")}) + self.assertTrue(all(set(r) == {"timestamp", "tag", "test_name", "metric", "measurements"} for r in rows)) + self.assertEqual(rows[0]["measurements"], { + "status": "fail", "passed": "false", "reason": "failed: worker_memory", + "failed_conditions": "worker_memory", "invalid_conditions": "", + "trial__aggregate_failure_ratio": "0.0005", "trial__allocatable_ram_gb": "400", + "server__working_set_node_max_gb": "350"}) + self.assertEqual(rows[1]["measurements"], {"status": "fail", "passed": "false", "failed": "envelope_health", + "invalid": "", "error": ""}) + + def test_value_names_are_kept_and_nulls_stay_null(self): + nh = VariableResult(name="nh", source="run_results", status="ok", invalid_reason=None, + values={"metric_nighthawk.builtin_attempted_rps": 600.0, "p99.9": None, + "release": "2026_11"}) + passed = replace(ENVELOPE, status="pass", passed=True, reason="", conditions=(FAILURE_RATE,), variables=(nh,)) + m = report(passed, Summary(status="pass", passed=True, failed=(), invalid=())).stats_rows("ts")[0]["measurements"] + self.assertEqual({k: v for k, v in m.items() if k.startswith("nh__")}, { + "nh__metric_nighthawk.builtin_attempted_rps": "600", "nh__p99.9": None, "nh__release": "2026_11"}) + + def test_summary_lines(self): + self.assertEqual(FAILED.summary_lines(), [ + f"evaluation envelope_health: fail (failed: worker_memory)\n worker_memory: {WORKER_MEMORY}", + "summary: fail (1 evaluations)", + ]) + why = "server is invalid: no stats.jsonl row server_summary" + invalid = replace(ENVELOPE, status="invalid", reason="invalid: worker_memory, headroom", conditions=( + FAILURE_RATE, + ConditionResult(name="worker_memory", cel=WORKER_MEMORY, status="invalid", passed=False, reason=why), + ConditionResult(name="headroom", cel="server.working_set_node_max_gb < 100", status="invalid", + passed=False, reason=why))) + summary = Summary(status="invalid", passed=False, failed=(), invalid=("envelope_health",)) + self.assertEqual(report(invalid, summary).summary_lines(), [ + f"evaluation envelope_health: invalid (invalid: worker_memory, headroom)\n {why}", + "summary: invalid (1 evaluations)", + ]) + passed = replace(ENVELOPE, status="pass", passed=True, reason="", conditions=(FAILURE_RATE,)) + self.assertEqual(report(passed, Summary(status="pass", passed=True, failed=(), invalid=())).summary_lines(), [ + "evaluation envelope_health: pass", + "summary: pass (1 evaluations)", + ]) + + def test_error_report(self): + failed_to_load = error_report(RunIdentity(uri="/runs/t150", test_name="t150"), + "config: evaluations: 0.name: String should match pattern") + self.assertEqual(failed_to_load.run, {"test_name": "t150", "uri": "/runs/t150"}) + rows = failed_to_load.stats_rows("ts") + self.assertEqual([(r["metric"], r["measurements"]) for r in rows], [("evaluations", { + "status": "invalid", "passed": "false", "failed": "", "invalid": "", + "error": "config: evaluations: 0.name: String should match pattern"})]) + self.assertEqual(failed_to_load.summary_lines(), + ["evaluations not run: config: evaluations: 0.name: String should match pattern"]) + + def test_evaluation_json_and_appended_rows(self): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "run" / "evaluation.json" + FAILED.write_json(out) + doc = json.loads(out.read_text()) + # The report is serialized before anything is written. + bad = Path(tmp) / "bad.json" + with self.assertRaises(TypeError): + replace(FAILED, run={"bad": object()}).write_json(bad) + self.assertFalse(bad.exists()) + rows = Path(tmp) / "stats.jsonl" + rows.write_text('{"metric": "trial_summary"}\n') + FAILED.append_stats_rows(rows, "ts") + metrics = [json.loads(line)["metric"] for line in rows.read_text().splitlines()] + self.assertEqual(metrics, ["trial_summary", "evaluation_envelope_health", "evaluations"]) + self.assertEqual(list(doc), ["run", "evaluated_at", "error", "summary", "evaluations"]) + self.assertEqual(doc["summary"], {"status": "fail", "passed": False, "failed": ["envelope_health"], + "invalid": []}) + (ev,) = doc["evaluations"] + self.assertEqual(list(ev), ["name", "description", "status", "passed", "reason", "conditions", "variables", + "config"]) + self.assertEqual(list(ev["conditions"][0].items()), [ + ("name", "failure_rate"), ("cel", "trial.aggregate_failure_ratio <= 0.001"), ("status", "pass"), + ("passed", True), ("reason", "")]) + self.assertEqual(list(ev["variables"][1].items()), [ + ("name", "server"), ("source", "run_results"), ("status", "ok"), ("invalid_reason", None), + ("values", {"working_set_node_max_gb": 350.0})]) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/evaluate/unit_tests/test_rundir.py b/benchmarking/evaluate/unit_tests/test_rundir.py new file mode 100644 index 0000000000..7fda5b7097 --- /dev/null +++ b/benchmarking/evaluate/unit_tests/test_rundir.py @@ -0,0 +1,161 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for rundir: stored runs, and the run of another test from the same invocation. + +Runs are stand-in directories in the runner's layout; GCS is mocked. +""" + +import sys +import tempfile +import unittest +from datetime import datetime, timezone +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from evaluate import rundir # noqa: E402 +from evaluate.sources.base import RunIdentity, no_other_runs # noqa: E402 + +T0 = 1791700000 # 2026-10-11T07:06:40Z +TAG = "abc123" + + +def write_run(d: Path) -> Path: + d.mkdir(parents=True, exist_ok=True) + (d / "logs.txt").write_text("[boomer] {}\n") + return d + + +def stored(root: Path, test: str, run_ts: int, tag: str = TAG) -> Path: + date = datetime.fromtimestamp(run_ts, tz=timezone.utc).strftime("%Y-%m-%d") + return write_run(root / "runs" / test / f"run_date={date}" / f"run_ts={run_ts}" / f"run_tag={tag}") + + +class IdentityTest(unittest.TestCase): + def test_identity_from_uri(self): + self.assertEqual(rundir.identity_from_uri(f"gs://b/p/runs/t1/run_date=2026-10-11/run_ts={T0}/run_tag=x/"), + RunIdentity(uri=f"gs://b/p/runs/t1/run_date=2026-10-11/run_ts={T0}/run_tag=x", + test_name="t1", tag="x", run_date="2026-10-11", run_ts=T0)) + self.assertEqual(rundir.identity_from_uri("/tmp/run"), RunIdentity(uri="/tmp/run")) + + +class OpenRunTest(unittest.TestCase): + def test_local_run(self): + with tempfile.TemporaryDirectory() as tmp: + d = write_run(Path(tmp) / "run") + run = rundir.open_run(f"{d}/", Path(tmp) / "x") + self.assertEqual(run.identity, RunIdentity(uri=str(d))) + self.assertIs(run.run_of, no_other_runs) # not in the runner's layout + self.assertEqual(run.artifact("logs.txt"), d / "logs.txt") + self.assertIsNone(run.artifact("server_summary.json")) + with self.assertRaisesRegex(FileNotFoundError, "no run directory"): + rundir.open_run(str(Path(tmp) / "missing"), Path(tmp) / "x") + + def test_gcs_run_downloads_each_artifact_on_first_use(self): + uri = f"gs://b/p/runs/t1/run_date=2026-10-11/run_ts={T0}/run_tag={TAG}" + path = uri[len("gs://b/"):] + stored_names = {f"{path}/logs.txt", f"{path}/custom/extra.json"} + downloads = [] + + class Blob: + def __init__(self, name): + self.name = name + + def download_to_filename(self, dest): + Path(dest).write_text(self.name) + + def get_blob(name): + downloads.append(name) + return Blob(name) if name in stored_names else None + + client = mock.Mock() + client.list_blobs.return_value = [Blob(n) for n in stored_names] + client.bucket.return_value.get_blob.side_effect = get_blob + with tempfile.TemporaryDirectory() as tmp: + with mock.patch.object(rundir, "_storage_client", return_value=client): + run = rundir.open_run(uri, Path(tmp)) + self.assertEqual(run.identity, rundir.identity_from_uri(uri)) + self.assertEqual(downloads, []) # nothing is read until a source asks + # A file the framework knows nothing about is there too, for the source that reads it. + self.assertEqual(run.artifact("custom/extra.json").read_text(), f"{path}/custom/extra.json") + self.assertEqual(run.artifact("logs.txt").read_text(), f"{path}/logs.txt") + self.assertEqual(run.artifact("logs.txt").parent.parent, Path(tmp)) + self.assertIsNone(run.artifact("server_summary.json")) + self.assertIsNone(run.artifact("server_summary.json")) + with self.assertRaisesRegex(ValueError, "outside the run"): + run.artifact("../escape.txt") + self.assertEqual(downloads, [f"{path}/custom/extra.json", f"{path}/logs.txt", + f"{path}/server_summary.json"]) # each once + client.list_blobs.return_value = [] + with mock.patch.object(rundir, "_storage_client", return_value=client), \ + self.assertRaisesRegex(FileNotFoundError, f"no objects under {uri}/"): + rundir.open_run(uri, Path(tmp)) + + +class SameInvocationTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.uri = str(self.root / f"runs/t150/run_date=2026-10-11/run_ts={T0}/run_tag={TAG}") + + def test_the_run_of_another_test_has_the_same_run_ts(self): + want = stored(self.root, "t1", T0) + stored(self.root, "t1", T0 - 600) # another invocation + found = rundir.same_invocation(self.uri, self.root / "tmp")("t1") + self.assertEqual(found.identity, rundir.identity_from_uri(str(want))) + self.assertEqual(found.artifact("logs.txt"), want / "logs.txt") + + def test_no_run_of_the_test_in_the_invocation(self): + stored(self.root, "t1", T0 - 600) + stored(self.root, "t1", T0, tag="other") + with self.assertRaises(LookupError) as raised: + rundir.same_invocation(self.uri, self.root / "tmp")("t1") + self.assertEqual(str(raised.exception), + f"no run of t1 at {self.root}/runs/t1/run_date=2026-10-11/run_ts={T0}/run_tag={TAG}") + + def test_a_stored_run_reads_the_runs_of_its_invocation(self): + stored(self.root, "t1", T0) + run = rundir.open_run(str(stored(self.root, "t150", T0)), self.root / "tmp") + self.assertEqual(run.run_of("t1").identity.test_name, "t1") + self.assertIs(rundir.same_invocation("/tmp/run", self.root / "tmp"), no_other_runs) + + def test_a_found_run_is_reused(self): + stored(self.root, "t1", T0) + run_of = rundir.same_invocation(self.uri, self.root / "tmp") + with mock.patch.object(rundir, "open_run", wraps=rundir.open_run) as opened: + self.assertIs(run_of("t1"), run_of("t1")) + for _ in range(2): + with self.assertRaises(LookupError): + run_of("t9") + self.assertEqual([c.args[0].split("/runs/")[1].split("/")[0] for c in opened.call_args_list], + ["t1", "t9", "t9"]) # a miss is looked up again + + def test_a_read_error_is_raised_as_is(self): + """Only a missing run is a LookupError; the evaluator records any other error as the variable's reason.""" + class Forbidden(Exception): + pass + + client = mock.Mock() + client.list_blobs.side_effect = Forbidden("403 no storage.objects.list") + uri = f"gs://b/p/runs/t150/run_date=2026-10-11/run_ts={T0}/run_tag={TAG}" + with mock.patch.object(rundir, "_storage_client", return_value=client), \ + self.assertRaisesRegex(Forbidden, "403"): + rundir.same_invocation(uri, self.root / "tmp")("t1") + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/evaluate/unit_tests/test_test_entries.py b/benchmarking/evaluate/unit_tests/test_test_entries.py new file mode 100644 index 0000000000..b6d942fcc2 --- /dev/null +++ b/benchmarking/evaluate/unit_tests/test_test_entries.py @@ -0,0 +1,67 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Every evaluations block checked into the repository loads: the tests*.yaml +entries the orchestrator runs (its image can only check their shape), and the +examples in the docs.""" + +import re +import sys +import unittest +from pathlib import Path + +import yaml + +ROOT = Path(__file__).resolve().parents[3] +sys.path.insert(0, str(ROOT / "benchmarking")) + +from evaluate import config # noqa: E402 + + +class TestEntriesTest(unittest.TestCase): + def test_tests_yaml_evaluations_load(self): + files = sorted((ROOT / "benchmarking" / "automation").glob("tests*.yaml")) + self.assertTrue(files) + for path in files: + for test in yaml.safe_load(path.read_text())["tests"]: + if "evaluations" in test: + with self.subTest(file=path.name, test=test["name"]): + config.load(test["evaluations"]) + + def test_documented_examples_load(self): + docs = [ROOT / "benchmarking" / "evaluate" / "README.md", ROOT / "benchmarking" / "automation" / "tests.yaml"] + blocks = [] + for path in docs: + text = path.read_text() + if path.suffix == ".yaml": # the commented example in the header + lines = text.splitlines() + start = lines.index("# evaluations:") + example = [] + for line in lines[start:]: + if not line.startswith("# "): + break + example.append(line[4:]) + text = "```yaml\n" + "\n".join(example) + "\n```" + for block in re.findall(r"```yaml\n(.*?)```", text, re.S): + doc = yaml.safe_load(block) + entries = doc if isinstance(doc, list) else [doc] + blocks += [(path.name, e["evaluations"]) for e in entries if isinstance(e, dict) and "evaluations" in e] + self.assertGreaterEqual(len(blocks), 3) + for name, block in blocks: + with self.subTest(doc=name): + config.load(block) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/lib/kubectl-ate.sh b/benchmarking/lib/kubectl-ate.sh new file mode 100644 index 0000000000..85872d9d50 --- /dev/null +++ b/benchmarking/lib/kubectl-ate.sh @@ -0,0 +1,28 @@ +# Copyright 2026 The Agent Substrate 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. + +# shellcheck shell=bash +# Sourced by the benchmarking deploy scripts, which run from the repository root. + +# build_kubectl_ate builds kubectl-ate from the tree into a temporary directory +# that is removed when the script exits, and points KUBECTL_ATE_BIN at it. +KUBECTL_ATE_BIN="" + +build_kubectl_ate() { + local dir + dir="$(mktemp -d)" + trap 'rm -rf '"${dir}" EXIT + KUBECTL_ATE_BIN="${dir}/kubectl-ate" + go build -o "${KUBECTL_ATE_BIN}" ./cmd/kubectl-ate +} diff --git a/benchmarking/locust/Dockerfile b/benchmarking/locust/Dockerfile index 8fb8f61a6a..1a62248355 100644 --- a/benchmarking/locust/Dockerfile +++ b/benchmarking/locust/Dockerfile @@ -63,6 +63,10 @@ COPY benchmarking/locust/phase_breakdown.py /app/phase_breakdown.py COPY benchmarking/locust/ladder_steps.py /app/ladder_steps.py COPY benchmarking/locust/turnover_window.py /app/turnover_window.py COPY benchmarking/analysis/phase_report.py /app/phase_report.py +# Run evaluations (the --test-entry's evaluations), imported by runner.py as the evaluate package. +# The modules only: the directory also holds the tests and a local venv. +COPY benchmarking/evaluate/*.py /app/evaluate/ +COPY benchmarking/evaluate/sources/ /app/evaluate/sources/ ENV PYTHONPATH=/app:/app/deps ENV PYTHONUNBUFFERED=1 diff --git a/benchmarking/locust/build_and_push.sh b/benchmarking/locust/build_and_push.sh index 8e01d64889..b2276c2a95 100755 --- a/benchmarking/locust/build_and_push.sh +++ b/benchmarking/locust/build_and_push.sh @@ -19,8 +19,9 @@ set -o errexit -o nounset -o pipefail ROOT="$(git rev-parse --show-toplevel)" cd "${ROOT}" -# Source the environment variables if configured -if [[ -f .ate-dev-env.sh ]]; then +# Source the environment variables if configured, like the hack/ scripts; +# set NO_DEV_ENV to skip this and take every setting from the caller. +if [[ -f .ate-dev-env.sh ]] && [[ -z "${NO_DEV_ENV:-}" ]]; then source .ate-dev-env.sh fi diff --git a/benchmarking/locust/codegen/requirements.txt b/benchmarking/locust/codegen/requirements.txt index e5617d172d..50b64ca1ac 100644 --- a/benchmarking/locust/codegen/requirements.txt +++ b/benchmarking/locust/codegen/requirements.txt @@ -12,8 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. -# Build-time dependencies for generate.sh and for the nighthawk-ingress -# image's descriptor build. Kept apart from the load test's runtime +# Build-time dependencies for generate.sh and for the descriptor build of the +# nighthawk-ingress and nighthawk-egress images. Kept apart from the load test's runtime # requirements.txt so that generating the protos does not pull in locust, the # opentelemetry exporters and google-cloud-storage. # diff --git a/benchmarking/locust/common/boomer_config.py b/benchmarking/locust/common/boomer_config.py index b784d1e579..0d7e1ae0fb 100644 --- a/benchmarking/locust/common/boomer_config.py +++ b/benchmarking/locust/common/boomer_config.py @@ -24,7 +24,7 @@ * --mem-target / --mem-churn / --mem-read → common.memload_config.add_memload_arguments * --cpu-cores / --cpu-duty-cycle → common.cpuload_config.add_cpuload_arguments * --max-pings-per-wake → common.ping_config.add_ping_arguments - * --target-rps → common.rate_config.add_rate_arguments + * --target-rps / --burst-size → common.rate_config.add_rate_arguments This module ties them together so boomer-Go workers can pick up the values the operator set in the web UI form: @@ -86,6 +86,7 @@ class that consumes it. "--spawn-concurrency": int, "--actor-deadline": float, "--target-rps": float, + "--burst-size": int, } diff --git a/benchmarking/locust/common/rate_config.py b/benchmarking/locust/common/rate_config.py index 92925b1ce4..9815de2fcc 100644 --- a/benchmarking/locust/common/rate_config.py +++ b/benchmarking/locust/common/rate_config.py @@ -12,7 +12,7 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Request-rate runtime flag, for boomer user classes that pace +"""Request-rate runtime flags, for boomer user classes that pace (resumepaused, and agentsession in turnover mode).""" from locust import events @@ -34,3 +34,16 @@ def add_rate_arguments(parser: LocustArgumentParser) -> None: ), include_in_web_ui=True, ) + parser.add_argument( + "--burst-size", + type=int, + default=0, + env_var="LOCUST_BURST_SIZE", + help=( + "For resumepaused only: release cold resumes in waves of up to " + "this many users every burst_size/target_rps seconds instead of " + "spacing them one by one. 0 paces smoothly; positive values " + "require --target-rps > 0" + ), + include_in_web_ui=True, + ) diff --git a/benchmarking/locust/deploy.sh b/benchmarking/locust/deploy.sh index e7a641b5ed..537e39400f 100755 --- a/benchmarking/locust/deploy.sh +++ b/benchmarking/locust/deploy.sh @@ -19,8 +19,9 @@ set -o errexit -o nounset -o pipefail ROOT="$(git rev-parse --show-toplevel)" cd "${ROOT}" -# Source the environment variables if configured -if [[ -f .ate-dev-env.sh ]]; then +# Source the environment variables if configured, like the hack/ scripts; +# set NO_DEV_ENV to skip this and take every setting from the caller. +if [[ -f .ate-dev-env.sh ]] && [[ -z "${NO_DEV_ENV:-}" ]]; then source .ate-dev-env.sh fi diff --git a/benchmarking/locust/requirements.txt b/benchmarking/locust/requirements.txt index a76e292a41..9c35c266e5 100644 --- a/benchmarking/locust/requirements.txt +++ b/benchmarking/locust/requirements.txt @@ -28,3 +28,6 @@ opentelemetry-instrumentation-grpc opentelemetry-instrumentation-requests google-cloud-storage kubernetes +# Run evaluations (benchmarking/evaluate/requirements.txt). +cel-expr-python==0.1.3 +pydantic>=2 diff --git a/benchmarking/locust/runner.py b/benchmarking/locust/runner.py index 0908752094..253481a80e 100644 --- a/benchmarking/locust/runner.py +++ b/benchmarking/locust/runner.py @@ -30,6 +30,7 @@ import argparse import csv +import functools import json import os import re @@ -41,7 +42,7 @@ import time from datetime import datetime, timezone from pathlib import Path -from typing import IO, Any, TextIO +from typing import IO, TYPE_CHECKING, Any, Callable, TextIO from cluster_facts import ( EMPTY_FACTS, @@ -57,6 +58,9 @@ from ladder_steps import append_ladder_steps from turnover_window import append_turnover_window, fill_done_ts +if TYPE_CHECKING: + import evaluate + # Path inside the locust image to the boomer-worker binary baked in by # benchmarking/locust/Dockerfile. BOOMER_BINARY = "/app/boomer-worker" @@ -105,13 +109,26 @@ def parse_args() -> argparse.Namespace: ) p.add_argument("--tag", required=True, help="Tag for this run") p.add_argument( - "--name", required=True, help="Name for this run; used as locust --csv prefix" + "--name", required=True, help="Name for this run (the test's name in tests.yaml)" ) p.add_argument( "--dest", required=True, help="Root destination (gs://bucket/path or local path)", ) + p.add_argument( + "--run-ts", + type=int, + default=None, + help=( + "Unix seconds that name where the run is stored " + "(/runs//run_date=.../run_ts=.../run_tag=). The " + "orchestrator passes every run of one invocation the same value, so " + "a run finds another test's run of the invocation by it. Default: " + "now. Used for nothing else: time windows, such as the Prometheus " + "queries, use the runner's clock" + ), + ) p.add_argument( "--allow-empty-stats", action="store_true", @@ -194,6 +211,18 @@ def parse_args() -> argparse.Namespace: "and a 10s scrape" ), ) + p.add_argument( + "--test-entry", + type=json_object, + default={}, + help=( + "The run's test entry from tests.yaml, as a JSON object. The runner " + "reads its `evaluations` (see benchmarking/evaluate/README.md): " + "their sources are set up before the run; after it they judge the " + "run, and the verdicts are written to evaluation.json, plus rows " + "in stats.jsonl. They never change the exit code or status.json" + ), + ) p.add_argument( "--phase-breakdown", action=argparse.BooleanOptionalAction, @@ -210,6 +239,17 @@ def parse_args() -> argparse.Namespace: return args +def json_object(value: str) -> dict[str, Any]: + """An argparse type: a JSON object.""" + try: + obj = json.loads(value) + except ValueError as e: + raise argparse.ArgumentTypeError(f"not JSON: {e}") from None + if not isinstance(obj, dict): + raise argparse.ArgumentTypeError("not a JSON object") + return obj + + # Tests whose User class is implemented in Python. Closed set: new load # generators are written in boomer, so anything else runs on boomer. Remove # entries as these are retired; when empty, drop needs_boomer entirely. @@ -296,11 +336,75 @@ def log_run_config(args: argparse.Namespace, dest_prefix: str, work_dir: Path, l " extra flags:", ] lines += [f" {flag}" for flag in pair_flags(args.locust_extra)] or [" (none)"] + lines.append(" test entry:") + entry = json.dumps(args.test_entry, indent=2) if args.test_entry else "(none)" + lines += [f" {line}" for line in entry.splitlines()] lines.append("====================") for line in lines: tee(logs, line) +def prepare_evaluations( + args: argparse.Namespace, artifacts_dir: Path, uri: str, tmp: Path, logs: TextIO +) -> Callable[[], "evaluate.Report"] | None: + """What judges the run once it has finished; None when the test entry + has no evaluations or the evaluate package can't be imported. + + Evaluations judge whether the run's results meet the test entry's + conditions (benchmarking/evaluate/README.md). + + They are loaded here, before the run, so a config error is at the top of + logs.txt. An error is only logged: the run goes ahead, and the returned + callable gives the report saying why the run wasn't judged. + + Their sources read the run's artifacts in artifacts_dir, under the names + they are stored under at uri, and the runs of other tests from the same + invocation, stored next to uri (evaluate/rundir.py). tmp holds what is + downloaded. + """ + evaluations = args.test_entry.get("evaluations") + if evaluations is None: + return None + # Imported here, not at the top: the runner works without the package. + try: + import evaluate # benchmarking/evaluate, at /app/evaluate in the image + from evaluate import rundir + except ImportError as e: + tee(logs, f"Warning: evaluations will not be judged: can't import evaluate: {e}") + return None + run = evaluate.BenchmarkRunContext( + rundir.identity_from_uri(uri), + evaluate.LocalArtifacts(artifacts_dir), + run_of=rundir.same_invocation(uri, tmp), + ) + try: + return evaluate.prepare(evaluations, run).evaluate + except evaluate.ConfigError as e: + error = f"config: {e}" + except Exception as e: # never cost the run its load test + error = f"evaluate failed to load or prepare the evaluations: {type(e).__name__}: {e}" + tee(logs, f"Warning: evaluations will not be judged: {error}") + return functools.partial(evaluate.error_report, run.identity, error) + + +def run_evaluations( + judge: Callable[[], "evaluate.Report"], + artifacts_dir: Path, + stats_generated: bool, + data_ts: str, + logs: TextIO, +) -> None: + """Judges the finished run with judge from prepare_evaluations, and + writes the report: evaluation.json, and rows in stats.jsonl when the run + has stats.""" + report = judge() + report.write_json(artifacts_dir / "evaluation.json") + if stats_generated: + report.append_stats_rows(artifacts_dir / "stats.jsonl", data_ts) + for line in report.summary_lines(): + tee(logs, line) + + def extract_trace_record(prefix: str, line: str) -> dict[str, str] | None: """Parse `line` into a trace record dict (TRACE_COLUMNS keys) if it describes a sampled span, else return None. Handles boomer slog JSON @@ -556,36 +660,45 @@ def main() -> None: path_ts = now.strftime("%Y%m%dT%H%M%SZ") # RFC 3339 / ISO 8601 extended for the JSONL data column data_ts = now.strftime("%Y-%m-%dT%H:%M:%SZ") - # Hive partition values for the GCS layout - run_date = now.strftime("%Y-%m-%d") - run_ts = int(now.timestamp()) - - work_dir = Path(f"/tmp/{path_ts}-locust-runner") - work_dir.mkdir(parents=True, exist_ok=True) - csv_prefix = work_dir / args.name - stats_csv = work_dir / f"{args.name}_stats.csv" - jsonl_path = work_dir / f"{args.name}.jsonl" - logs_path = work_dir / f"{args.name}_logs.txt" - traces_path = work_dir / f"{args.name}_traces.txt" - status_path = work_dir / f"{args.name}_status.json" - server_summary_json = work_dir / f"{args.name}_server_summary.json" - + start_ts = int(now.timestamp()) + # Hive partition values for the GCS layout, from the orchestrator's + # --run-ts, which every run of one invocation shares. + stored_at = now if args.run_ts is None else datetime.fromtimestamp(args.run_ts, timezone.utc) prefix = ( f"{args.dest.rstrip('/')}/runs/{args.name}" - f"/run_date={run_date}/run_ts={run_ts}/run_tag={args.tag}" + f"/run_date={stored_at.strftime('%Y-%m-%d')}/run_ts={int(stored_at.timestamp())}" + f"/run_tag={args.tag}" ) + work_dir = Path(f"/tmp/{path_ts}-locust-runner") + # Everything in artifacts/ is uploaded under prefix, by the same name. + artifacts = work_dir / "artifacts" + artifacts.mkdir(parents=True, exist_ok=True) + # locust names its CSVs _stats.csv etc.; they are moved into + # artifacts/ under the stored names once it exits. + csv_prefix = work_dir / "locust" + stats_csv = artifacts / "stats.csv" + stats_history_csv = artifacts / "stats_history.csv" + jsonl_path = artifacts / "stats.jsonl" + logs_path = artifacts / "logs.txt" + traces_path = artifacts / "traces.txt" + status_path = artifacts / "status.json" + server_summary_json = artifacts / "server_summary.json" + with open(logs_path, "w") as logs, open(traces_path, "w") as traces: traces.write("\t".join(TRACE_COLUMNS) + "\n") traces.flush() log_run_config(args, prefix, work_dir, logs) + judge = prepare_evaluations(args, artifacts, prefix, work_dir / "evaluate", logs) # Worker pods around the run, for OOMKilled restarts and evictions. pods_before = read_worker_pods(args, logs) exit_code = run_test(args, csv_prefix, logs, traces) + for csv_path in work_dir.glob(f"{csv_prefix.name}_*.csv"): + csv_path.replace(artifacts / csv_path.name.removeprefix(f"{csv_prefix.name}_")) run_end_ts = int(datetime.now(timezone.utc).timestamp()) pods_after = read_worker_pods(args, logs) # Right after the run, as Evicted events expire after about 1h. - evicted_uids = read_evictions(args, run_ts, logs) + evicted_uids = read_evictions(args, start_ts, logs) stats_generated = False if stats_csv.exists(): @@ -613,7 +726,6 @@ def main() -> None: # Density frontiers and server-side telemetry are additive. They are # kept out of the block above so that a failure here cannot discard # the measurements the trial actually came for. - stats_history_csv = work_dir / f"{args.name}_stats_history.csv" # Seeded up front so that a discovery failure still leaves a usable # value for the frontier summary below. facts = dict(EMPTY_FACTS) @@ -633,7 +745,7 @@ def main() -> None: data_ts, facts, logs, - run_start=run_ts, + run_start=start_ts, run_end=run_end_ts, ) except Exception as e: @@ -641,7 +753,7 @@ def main() -> None: # A turnover run is measured from the end of its fill, past the # registration of its fleet: the server telemetry's steady window and - # the turnover_window row start there. Other runs have no such line. + # the turnover_ rows start there. Other runs have no such line. turnover_start = None try: with open(logs_path, errors="replace") as f: @@ -657,7 +769,7 @@ def main() -> None: try: extract_and_record_server_telemetry( prom_url=args.prometheus_url, - start_ts=run_ts, + start_ts=start_ts, end_ts=run_end_ts, stats_history_csv=stats_history_csv, output_json_path=server_summary_json, @@ -692,7 +804,7 @@ def main() -> None: jsonl_path, turnover_start, stats_history_csv, data_ts, args.tag, args.name, logs, ): - tee(logs, f"Appended the turnover_window row to {jsonl_path}") + tee(logs, f"Appended the turnover rows to {jsonl_path}") except Exception as e: tee(logs, f"Warning: Failed to summarize the turnover window: {e}") @@ -716,28 +828,25 @@ def main() -> None: elif stats_generated: tee(logs, "Skipping phase breakdown (--no-phase-breakdown)") + # Evaluations come last: their sources read the finished logs.txt and + # stats.jsonl, so they run once logs.txt is closed, and append their own + # lines to it. Additive like the steps above: a failure here costs no + # measurement, and the rows are appended only to a run's stats. + if judge is not None: + with open(logs_path, "a") as logs: + try: + run_evaluations(judge, artifacts, stats_generated, data_ts, logs) + except Exception as e: + tee(logs, f"Warning: Failed to run the evaluations: {e}") + status_path.write_text( json.dumps( {"locust_exit_code": exit_code, "stats_generated": stats_generated} ) ) - files: list[tuple[Path, str]] = [ - (status_path, "status.json"), - (logs_path, "logs.txt"), - (traces_path, "traces.txt"), - (jsonl_path, "stats.jsonl"), - (stats_csv, "stats.csv"), - (work_dir / f"{args.name}_exceptions.csv", "exceptions.csv"), - (work_dir / f"{args.name}_failures.csv", "failures.csv"), - (work_dir / f"{args.name}_stats_history.csv", "stats_history.csv"), - (server_summary_json, "server_summary.json"), - ] - for src, basename in files: - if not src.exists(): - print(f"Skipping {src}: not produced", flush=True) - continue - dest = f"{prefix}/{basename}" + for src in sorted(p for p in artifacts.rglob("*") if p.is_file()): + dest = f"{prefix}/{src.relative_to(artifacts).as_posix()}" upload(src, dest) print(f"Uploaded {src} -> {dest}", flush=True) diff --git a/benchmarking/locust/server_telemetry.py b/benchmarking/locust/server_telemetry.py index 0bbd074da1..faa3996ad2 100644 --- a/benchmarking/locust/server_telemetry.py +++ b/benchmarking/locust/server_telemetry.py @@ -15,13 +15,15 @@ """Harvests server-side Prometheus ground-truth timeseries during benchmark trials. Queries Prometheus over [T_start, T_end] and the steady-state window inside it -to capture cluster packing, node and pod PSI stalls, snapshot sizes, latencies -and throughput, running actors, memory working set and OOM kills. +to capture cluster packing, node and pod PSI stalls, node disk throughput, +snapshot sizes, latencies and throughput, running actors, memory working set, +CPU cores used and OOM kills. """ import csv import json import math +import re import sys import time import urllib.parse @@ -280,6 +282,19 @@ def _node_psi_query(resource: str) -> str: ) +def _node_disk_query(counter: str) -> str: + """Disk MiB/s per node and device, kept to nodes hosting a live worker pod. + + cAdvisor counts the whole node's I/O on its root cgroup. Workers are found + by CPU rate, as for the node working set, so this works without PSI. + """ + return ( + f"sum by (instance, device) (rate(container_fs_{counter}_bytes_total" + f'{{container="node"}}[1m])) / {2**20}' + f" and on (instance) count by (instance) ({WORKER_PODS})" + ) + + def _steady_values( results: list[dict[str, Any]], steady_start_ts: int, steady_end_ts: int ) -> list[float]: @@ -426,6 +441,31 @@ def _harvest_pod_psi( return out +def _harvest_node_disk( + prom_url: str, start_ts: int, end_ts: int, steady_start_ts: int, + steady_end_ts: int, +) -> dict[str, Any]: + """Worker node disk MiB/s, every node's steady samples pooled per device.""" + out: dict[str, Any] = {} + nodes: set[str] = set() + for key, counter in (("read", "reads"), ("write", "writes")): + res = query_prometheus_range( + prom_url, _node_disk_query(counter), start_ts, end_ts, step="10s" + ) + nodes.update(s.get("metric", {}).get("instance", "") for s in res) + devices: dict[str, list[dict[str, Any]]] = {} + for s in res: + devices.setdefault(s.get("metric", {}).get("device", ""), []).append(s) + out[f"{key}_mb_s"] = { + device: compute_percentiles( + _steady_values(series, steady_start_ts, steady_end_ts) + ) + for device, series in sorted(devices.items()) + } + out["nodes"] = len(nodes - {""}) + return out + + def _ratio( num: float | None, den: float | None, scale: float = 1.0 ) -> float | None: @@ -617,6 +657,32 @@ def _count_active_actors( ACTOR_COUNT = "sum by (instance, exported_instance) (ate_actor_stats_sampled_actors)" WORKING_SET_KEYS = (*WORKING_SET_QUERIES, "actor", "per_actor") +# CPU cores used, by the same owners as the working set. A rate, so the two +# series of a restarted pod add up to that pod's use. +CPU_QUERIES = { + "node": ( + "sum by (instance) (rate(container_cpu_usage_seconds_total" + '{container="node"}[1m]))' + f" and on (instance) count by (instance) ({WORKER_PODS})" + ), + "worker": ( + "sum by (pod) (rate(container_cpu_usage_seconds_total" + '{namespace="benchmark-workloads", container="worker"}[1m]))' + ), + "atelet": ( + "sum by (pod, instance) (rate(container_cpu_usage_seconds_total" + '{namespace="ate-system", container="atelet"}[1m]))' + f" and on (instance) count by (instance) ({WORKER_PODS})" + ), +} +# The atelet adds each activation's CPU time about once a minute, so the rate +# window spans a few samples. +ACTOR_CPU = ( + "sum by (instance, exported_instance) " + "(rate(ate_actor_stats_cpu_time_seconds_total[3m]))" +) +CPU_KEYS = (*CPU_QUERIES, "actor") + BYTES_PER_GIB = 2**30 @@ -647,32 +713,37 @@ def _read_series( return out -def _summarize_gb( +def _summarize( series: dict[Any, dict[int, float]], steady_start_ts: int, steady_end_ts: int, + unit: str, + divisor: float = 1, ) -> dict[str, Any]: - """Steady percentiles, series seen in steady, and a 10s sum/max timeseries.""" + """Steady percentiles, series seen in steady, and a 10s sum/max timeseries. + + Samples are divided by `divisor`; `unit` names the timeseries fields. + """ by_ts: dict[int, list[float]] = {} - steady_gb: list[float] = [] + steady: list[float] = [] steady_series = 0 for samples in series.values(): in_steady = False for t, val in samples.items(): - gb = val / BYTES_PER_GIB - by_ts.setdefault(t, []).append(gb) + scaled = val / divisor + by_ts.setdefault(t, []).append(scaled) if steady_start_ts <= t <= steady_end_ts: - steady_gb.append(gb) + steady.append(scaled) in_steady = True steady_series += in_steady return { - "summary": compute_percentiles(steady_gb), + "summary": compute_percentiles(steady), "count": steady_series if by_ts else None, "timeseries": [ { "timestamp": t, - "total_gb": round(sum(v), 4), - "max_gb": round(max(v), 4), + f"total_{unit}": round(sum(v), 4), + f"max_{unit}": round(max(v), 4), } for t, v in sorted(by_ts.items()) ], @@ -695,7 +766,9 @@ def _measure_working_set( both are read `lag_s // 2` late and moved back onto the run's 10s grid. """ def summarize(series: dict[Any, dict[int, float]]) -> dict[str, Any]: - return _summarize_gb(series, steady_start_ts, steady_end_ts) + return _summarize( + series, steady_start_ts, steady_end_ts, "gb", BYTES_PER_GIB + ) out: dict[str, Any] = { key: summarize(_read_series(prom_url, query, start_ts, end_ts)) @@ -718,6 +791,33 @@ def summarize(series: dict[Any, dict[int, float]]) -> dict[str, Any]: return out +def _measure_cpu( + prom_url: str, + start_ts: int, + end_ts: int, + steady_start_ts: int, + steady_end_ts: int, + lag_s: int = 0, +) -> dict[str, Any]: + """CPU cores used per node, worker, atelet and actor; null, not 0, with no series. + + `worker` is the whole worker pod: the actors on it and the suspend, restore + and sandbox work done for them. `actor` is the atelet's sum over the actors + it measured, per atelet, read `lag_s // 2` late like the actor working set. + """ + def summarize(series: dict[Any, dict[int, float]]) -> dict[str, Any]: + return _summarize(series, steady_start_ts, steady_end_ts, "cores") + + out: dict[str, Any] = { + key: summarize(_read_series(prom_url, query, start_ts, end_ts)) + for key, query in CPU_QUERIES.items() + } + out["actor"] = summarize(_read_series( + prom_url, ACTOR_CPU, start_ts, end_ts, lag_s // 2, key=_process_key + )) + return out + + # A global OOM logs no oom_memcg, so cAdvisor counts it on `/` (container="node"). OOM_NODE = 'container="node"' # Kills in a worker pod: nested actor sandbox cgroups, then the worker container's. @@ -782,9 +882,10 @@ def harvest_server_telemetry( ) -> dict[str, Any]: """Harvests the ground truth metric streams from Prometheus. - Only the atelet-exported snapshot, active actor and actor working set - blocks are read late, by `lag_s // 2`; packing, PSI, the cAdvisor working - set and OOM counts aren't shifted and are read over the run window as is. + Only the atelet-exported snapshot, active actor, actor working set and + actor CPU blocks are read late, by `lag_s // 2`; packing, PSI, node disk, + the cAdvisor working set and CPU, and OOM counts aren't shifted and are + read over the run window as is. """ steady_end = end_ts if steady_end_ts is None else steady_end_ts return { @@ -797,6 +898,9 @@ def harvest_server_telemetry( "pod_psi": _harvest_pod_psi( prom_url, start_ts, end_ts, steady_start_ts, steady_end ), + "node_disk": _harvest_node_disk( + prom_url, start_ts, end_ts, steady_start_ts, steady_end + ), "snapshots": _harvest_snapshots( prom_url, steady_start_ts, steady_end, lag_s ), @@ -806,6 +910,9 @@ def harvest_server_telemetry( "working_set": _measure_working_set( prom_url, start_ts, end_ts, steady_start_ts, steady_end, lag_s ), + "cpu": _measure_cpu( + prom_url, start_ts, end_ts, steady_start_ts, steady_end, lag_s + ), "oom_events": _count_oom_events(prom_url, start_ts, end_ts), } @@ -886,6 +993,7 @@ def log(msg: str) -> None: packing_s = telemetry.get("cluster_packing", {}).get("summary", {}) psi = telemetry.get("node_psi", {}) pod_psi = telemetry.get("pod_psi", {}) + disk = telemetry.get("node_disk", {}) snaps = telemetry.get("snapshots", {}) ps = ("p50", "p90", "p95", "p99") @@ -900,6 +1008,14 @@ def log(msg: str) -> None: measurements[f"pod_psi_{res}_stall_{p}"] = ( pod_psi.get(f"{res}_stall_pct", {}).get(p) ) + # Keyed by device name, so /dev/nvme0n1 gives node_disk_nvme0n1_*. + for key in ("read", "write"): + for device, mb_s in disk.get(f"{key}_mb_s", {}).items(): + name = re.sub( + r"[^a-z0-9]+", "_", device.removeprefix("/dev/").lower() + ).strip("_") + for p in ps: + measurements[f"node_disk_{name}_{key}_{p}_mb_s"] = mb_s.get(p) for p in ps: measurements[f"snapshot_size_{p}_mb"] = snaps.get(f"size_{p}_mb") measurements["snapshot_size_avg_mb"] = snaps.get("size_avg_mb") @@ -917,6 +1033,11 @@ def log(msg: str) -> None: ws = working_set.get(block, {}).get("summary", {}) for p in (*ps, "max"): measurements[f"working_set_{block}_{p}_gb"] = ws.get(p) + cpu = telemetry.get("cpu", {}) + for block in CPU_KEYS: + cores = cpu.get(block, {}).get("summary", {}) + for p in (*ps, "max"): + measurements[f"cpu_{block}_{p}_cores"] = cores.get(p) oom = telemetry.get("oom_events", {}) for key in ("node", "pod", *WORKER_POD_FIELDS): measurements[f"oom_events_{key}"] = oom.get(key) diff --git a/benchmarking/locust/tests/agentsession.py b/benchmarking/locust/tests/agentsession.py index 19742cb534..d89d4a701a 100644 --- a/benchmarking/locust/tests/agentsession.py +++ b/benchmarking/locust/tests/agentsession.py @@ -26,7 +26,14 @@ import os -if os.environ.get("LOCUST_NO_AGENTSESSION_USER") != "1": + +def workloads(test): + """deploy.sh's default workloads, sized from the test's tests.yaml entry.""" + return [("deploy_sh", test)] + + +# The orchestrator sets LOCUST_NO_USERS=1 to call workloads() without locust. +if os.environ.get("LOCUST_NO_AGENTSESSION_USER") != "1" and os.environ.get("LOCUST_NO_USERS") != "1": from locust import User, task from common.boomer_config import init_boomer_config diff --git a/benchmarking/locust/tests/ate_env.py b/benchmarking/locust/tests/ate_env.py index a127a08a03..15add2d612 100644 --- a/benchmarking/locust/tests/ate_env.py +++ b/benchmarking/locust/tests/ate_env.py @@ -23,7 +23,14 @@ import os -if os.environ.get("LOCUST_NO_ATE_ENV_USER") != "1": + +def workloads(test): + """deploy.sh's default workloads, sized from the test's tests.yaml entry.""" + return [("deploy_sh", test)] + + +# The orchestrator sets LOCUST_NO_USERS=1 to call workloads() without locust. +if os.environ.get("LOCUST_NO_ATE_ENV_USER") != "1" and os.environ.get("LOCUST_NO_USERS") != "1": from locust import User, task from common.boomer_config import init_boomer_config diff --git a/benchmarking/locust/tests/durdir.py b/benchmarking/locust/tests/durdir.py index 4e503aec09..55f5e54f90 100644 --- a/benchmarking/locust/tests/durdir.py +++ b/benchmarking/locust/tests/durdir.py @@ -25,7 +25,14 @@ import os -if os.environ.get("LOCUST_NO_DURDIR_USER") != "1": + +def workloads(test): + """deploy.sh's default workloads, sized from the test's tests.yaml entry.""" + return [("deploy_sh", test)] + + +# The orchestrator sets LOCUST_NO_USERS=1 to call workloads() without locust. +if os.environ.get("LOCUST_NO_DURDIR_USER") != "1" and os.environ.get("LOCUST_NO_USERS") != "1": from locust import User, task from common.boomer_config import init_boomer_config diff --git a/benchmarking/locust/tests/glutton.py b/benchmarking/locust/tests/glutton.py index 77671b696b..ea7bf12618 100644 --- a/benchmarking/locust/tests/glutton.py +++ b/benchmarking/locust/tests/glutton.py @@ -23,7 +23,14 @@ import os -if os.environ.get("LOCUST_NO_GLUTTON_USER") != "1": + +def workloads(test): + """deploy.sh's default workloads, sized from the test's tests.yaml entry.""" + return [("deploy_sh", test)] + + +# The orchestrator sets LOCUST_NO_USERS=1 to call workloads() without locust. +if os.environ.get("LOCUST_NO_GLUTTON_USER") != "1" and os.environ.get("LOCUST_NO_USERS") != "1": from locust import User, task from common.boomer_config import init_boomer_config diff --git a/benchmarking/locust/tests/resumepaused.py b/benchmarking/locust/tests/resumepaused.py index 89a9c1506a..d5d1c9b9a1 100644 --- a/benchmarking/locust/tests/resumepaused.py +++ b/benchmarking/locust/tests/resumepaused.py @@ -28,7 +28,14 @@ import os -if os.environ.get("LOCUST_NO_RESUMEPAUSED_USER") != "1": + +def workloads(test): + """deploy.sh's default workloads, sized from the test's tests.yaml entry.""" + return [("deploy_sh", test)] + + +# The orchestrator sets LOCUST_NO_USERS=1 to call workloads() without locust. +if os.environ.get("LOCUST_NO_RESUMEPAUSED_USER") != "1" and os.environ.get("LOCUST_NO_USERS") != "1": from locust import User, task from common.boomer_config import init_boomer_config diff --git a/benchmarking/locust/tests/spawn.py b/benchmarking/locust/tests/spawn.py index 027c14e1a1..850f453a7a 100644 --- a/benchmarking/locust/tests/spawn.py +++ b/benchmarking/locust/tests/spawn.py @@ -21,7 +21,14 @@ import os -if os.environ.get("LOCUST_NO_SPAWN_USER") != "1": + +def workloads(test): + """deploy.sh's default workloads, sized from the test's tests.yaml entry.""" + return [("deploy_sh", test)] + + +# The orchestrator sets LOCUST_NO_USERS=1 to call workloads() without locust. +if os.environ.get("LOCUST_NO_SPAWN_USER") != "1" and os.environ.get("LOCUST_NO_USERS") != "1": from locust import User, task from common.boomer_config import init_boomer_config diff --git a/benchmarking/locust/tests/sweperf.py b/benchmarking/locust/tests/sweperf.py index 68c88caf79..27fc9f8bbb 100644 --- a/benchmarking/locust/tests/sweperf.py +++ b/benchmarking/locust/tests/sweperf.py @@ -26,7 +26,14 @@ import os -if os.environ.get("LOCUST_NO_SWEPERF_USER") != "1": + +def workloads(test): + """deploy.sh's default workloads, sized from the test's tests.yaml entry.""" + return [("deploy_sh", test)] + + +# The orchestrator sets LOCUST_NO_USERS=1 to call workloads() without locust. +if os.environ.get("LOCUST_NO_SWEPERF_USER") != "1" and os.environ.get("LOCUST_NO_USERS") != "1": from locust import User, task from common.boomer_config import init_boomer_config diff --git a/benchmarking/locust/turnover_window.py b/benchmarking/locust/turnover_window.py index dfee030d16..2cbff2b826 100644 --- a/benchmarking/locust/turnover_window.py +++ b/benchmarking/locust/turnover_window.py @@ -19,8 +19,8 @@ then wakes the awake sessions, and only after that fill does it swap at --target-rps. stats.jsonl's other rows cover the whole run, so their rates divide by the time spent registering. This finds the end of the fill in the -line boomer logs then, and writes one `turnover_window` row with each -request's count, failures and rate from there to the end of the run, read +line boomer logs then, and writes a `turnover_` row for each request +with its count, failures and rate from there to the end of the run, read from stats_history.csv. runner.py also starts the server telemetry's steady-state window there. @@ -109,30 +109,41 @@ def window_counts( } -def window_record( +def window_records( start: int, end: int, counts: dict[str, tuple[int, int]], timestamp: str, tag: str, test_name: str, -) -> dict[str, Any]: - """The window as a stats.jsonl row: each request's count, failures and - rate. The rate counts every request, failed or not, like locust's - Requests/s.""" +) -> list[dict[str, Any]]: + """The window as stats.jsonl rows, one turnover_ row per request. + Each uses the measurement keys of the whole-run rows, so tools that read + those rows read these too. requests_per_s counts every request, failed + or not, like locust's Requests/s.""" secs = end - start - m: dict[str, Any] = {"window_start": start, "window_end": end, "window_s": secs} - for name, (requests, failures) in sorted(counts.items()): - m[f"requests_{name}"] = requests - m[f"failures_{name}"] = failures - m[f"rps_{name}"] = round(requests / secs, 4) if secs > 0 else None - return { - "timestamp": timestamp, - "tag": tag, - "test_name": test_name, - "metric": "turnover_window", - "measurements": m, - } + + def rate(n: int) -> float | None: + return round(n / secs, 4) if secs > 0 else None + + return [ + { + "timestamp": timestamp, + "tag": tag, + "test_name": test_name, + "metric": f"turnover_{name}", + "measurements": { + "window_start": start, + "window_end": end, + "window_s": secs, + "request_count": requests, + "failure_count": failures, + "requests_per_s": rate(requests), + "failures_per_s": rate(failures), + }, + } + for name, (requests, failures) in sorted(counts.items()) + ] def append_turnover_window( @@ -144,19 +155,19 @@ def append_turnover_window( test_name: str, logs: TextIO, ) -> bool: - """Append the turnover_window row of a run whose fill ended at start to - jsonl_path, and return whether there was one to append.""" + """Append the turnover rows of a run whose fill ended at start to + jsonl_path, and return whether there were any to append.""" if not stats_history_csv.exists(): - _log(logs, f"No {stats_history_csv}; no turnover_window row") + _log(logs, f"No {stats_history_csv}; no turnover rows") return False counts = window_counts(stats_history_csv, start) if counts is None: - _log(logs, f"No stats_history sample after the turnover start {start}; no turnover_window row") + _log(logs, f"No stats_history sample after the turnover start {start}; no turnover rows") return False end, per_request = counts - row = window_record(start, end, per_request, timestamp, tag, test_name) with open(jsonl_path, "a", encoding="utf-8") as f: - f.write(json.dumps(row) + "\n") + for row in window_records(start, end, per_request, timestamp, tag, test_name): + f.write(json.dumps(row) + "\n") return True diff --git a/benchmarking/locust/unit_tests/test_boomer_config.py b/benchmarking/locust/unit_tests/test_boomer_config.py index 282edd4291..556aac6ded 100644 --- a/benchmarking/locust/unit_tests/test_boomer_config.py +++ b/benchmarking/locust/unit_tests/test_boomer_config.py @@ -71,6 +71,17 @@ def test_build_config_json_turnover(self): self.assertEqual(parsed["agentsession_awake"], 650) self.assertEqual(parsed["target_rps"], 2.5) + def test_build_config_json_burst_size(self): + raw = boomer_config.build_config_json([ + "--target-rps", + "200", + "--burst-size", + "50", + ]) + parsed = json.loads(raw) + self.assertEqual(parsed["target_rps"], 200.0) + self.assertEqual(parsed["burst_size"], 50) + if __name__ == "__main__": unittest.main() diff --git a/benchmarking/locust/unit_tests/test_runner_evaluations.py b/benchmarking/locust/unit_tests/test_runner_evaluations.py new file mode 100644 index 0000000000..7c8b965d65 --- /dev/null +++ b/benchmarking/locust/unit_tests/test_runner_evaluations.py @@ -0,0 +1,157 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for runner.py's evaluations (the --test-entry's evaluations).""" + +import argparse +import io +import json +import sys +import tempfile +import unittest +import unittest.mock +from datetime import datetime, timezone +from pathlib import Path + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +# The evaluate package is /app/evaluate in the image; here it is +# benchmarking/evaluate. Appended, so nothing else on the path is shadowed. +sys.path.append(str(Path(__file__).resolve().parents[2])) + +import runner # noqa: E402 + +RUN_TS = 1791701190 # 2026-10-11T07:26:30Z +RECORD_SELECT = "has(line.msg) && line.msg == 'sweperf task record' && has(line.v) && line.v == 1.0" +EVALUATIONS = [{ + "name": "goodput_strict", + "variables": [{"name": "goodput", "source": "cel", "source_cfg": { + "inputs": [ + {"name": "records", "reader": "json_lines", + "reader_cfg": {"file": "logs.txt", "prefix": "[boomer] ", "select": RECORD_SELECT}}, + {"name": "one_user", "from_test": "t1", "reader": "json_lines", + "reader_cfg": {"file": "logs.txt", "prefix": "[boomer] ", "select": RECORD_SELECT}}, + ], + "locals": [ + {"name": "ref_wall_ms", "cel": "percentile(one_user.lines.filter(t, !t.failed).map(t, t.wall_ms), 50.0)"}, + {"name": "good", + "cel": "records.lines.filter(t, !t.failed && t.resume_max_ms <= 1500.0 && t.wall_ms <= 1.5 * ref_wall_ms)"}, + ], + "values": [ + {"name": "good_ratio_pct", "cel": "round(100.0 * double(size(good)) / double(size(records.lines)), 2)"}, + {"name": "ref_wall_ms", "cel": "ref_wall_ms"}, + {"name": "one_user_run", "cel": "one_user.uri"}, + ], + }}], + "conditions": [{"name": "good_ratio", "cel": "goodput.good_ratio_pct >= 90"}], +}] + + +def boomer(ts: int, msg: str, **kw) -> str: + t = datetime.fromtimestamp(ts, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + return "[boomer] " + json.dumps({"time": t, "msg": msg, **kw}) + + +def write_run(logs: Path, stats: Path, run_ts: int, wall_ms: float) -> None: + """What a run of runner.py leaves: one sweperf task record, and a trial_summary row.""" + end = datetime.fromtimestamp(run_ts + 30, tz=timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + logs.parent.mkdir(parents=True, exist_ok=True) + logs.write_text("\n".join([ + boomer(run_ts + 30, "sweperf task record", v=1, actor="a1", end=end, cel_ms=6000.0, wall_ms=wall_ms, + resume_max_ms=200.0, failed=False), + boomer(run_ts + 60, "sweperf shutdown started")]) + "\n") + trial = {"timestamp": "", "tag": "abc", "test_name": "t", "metric": "trial_summary", + "measurements": {"allocatable_cores": "100", "run_start": str(run_ts), "run_end": str(run_ts + 60)}} + stats.write_text(json.dumps(trial) + "\n") + + +def args(evaluations: object, dest: str) -> argparse.Namespace: + return argparse.Namespace(test_entry={"name": "t150", "type": "locust", "evaluations": evaluations}, tag="abc", + name="t150", dest=dest) + + +class RunEvaluationsTest(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.dest = Path(tmp.name) / "dest" + self.work = Path(tmp.name) / "work" + self.artifacts = self.work / "artifacts" + self.uri = f"{self.dest}/runs/t150/run_date=2026-10-11/run_ts={RUN_TS}/run_tag=abc" + + def prepare(self, a: argparse.Namespace, logs: io.StringIO): + return runner.prepare_evaluations(a, self.artifacts, self.uri, self.work / "evaluate", logs) + + def run_step(self, a: argparse.Namespace, stats_generated: bool = True) -> tuple[dict, list[str], str]: + """prepare_evaluations at the start of the run, then the run, then run_evaluations.""" + logs = io.StringIO() + judge = self.prepare(a, logs) + write_run(self.artifacts / "logs.txt", self.artifacts / "stats.jsonl", RUN_TS, wall_ms=8000.0) + if not stats_generated: + (self.artifacts / "stats.jsonl").unlink() + runner.run_evaluations(judge, self.artifacts, stats_generated, "ts", logs) + stats = self.artifacts / "stats.jsonl" + metrics = [json.loads(line)["metric"] for line in stats.read_text().splitlines()] if stats.exists() else [] + return json.loads((self.artifacts / "evaluation.json").read_text()), metrics, logs.getvalue() + + def store(self, test: str, run_ts: int, wall_ms: float) -> Path: + """A run of test stored under --dest at run_ts.""" + run = self.dest / f"runs/{test}/run_date=2026-10-11/run_ts={run_ts}/run_tag=abc" + write_run(run / "logs.txt", run / "stats.jsonl", run_ts, wall_ms) + return run + + def test_judges_the_run_and_appends_rows(self): + report, metrics, log = self.run_step(args(EVALUATIONS, str(self.dest))) + self.assertEqual(report["run"], {"test_name": "t150", "tag": "abc", "run_date": "2026-10-11", + "run_ts": str(RUN_TS), "uri": self.uri}) + variable = report["evaluations"][0]["variables"][0] + self.assertEqual((report["summary"]["status"], variable["values"]), ("invalid", {})) + # No run of t1 in this invocation: the input can't be read, and the reason says where it looked. + self.assertEqual(variable["invalid_reason"], f"input 'one_user': no run of t1 at " + f"{self.dest}/runs/t1/run_date=2026-10-11/run_ts={RUN_TS}/run_tag=abc") + self.assertEqual(metrics, ["trial_summary", "evaluation_goodput_strict", "evaluations"]) + self.assertIn("evaluation goodput_strict: invalid (invalid: good_ratio; " + "variable goodput is invalid: input 'one_user'", log) + + def test_reads_the_run_of_another_test_from_the_same_invocation(self): + one_user = self.store("t1", RUN_TS, wall_ms=4000.0) + self.store("t1", RUN_TS - 600, wall_ms=1000.0) # another invocation's run of t1 + report, _, log = self.run_step(args(EVALUATIONS, str(self.dest))) + values = report["evaluations"][0]["variables"][0]["values"] + self.assertEqual((values["one_user_run"], values["ref_wall_ms"]), (str(one_user), 4000.0)) + # 8000 ms against 1.5 x the 1-user run's 4000 ms. + self.assertEqual((values["good_ratio_pct"], report["summary"]["status"]), (0.0, "fail")) + self.assertIn("evaluation goodput_strict: fail (failed: good_ratio)", log) + + def test_a_run_without_stats_gets_only_evaluation_json(self): + """Like the other steps that append rows, the evaluations don't create a stats.jsonl.""" + report, metrics, _ = self.run_step(args(EVALUATIONS, str(self.dest)), stats_generated=False) + self.assertEqual((report["summary"]["status"], metrics), ("invalid", [])) + + def test_prepare_never_raises(self): + logs = io.StringIO() + with unittest.mock.patch("evaluate.prepare", side_effect=TypeError("unhashable type: 'list'")): + report = self.prepare(args([], str(self.dest)), logs)() + self.assertEqual(report.error, "evaluate failed to load or prepare the evaluations: TypeError: unhashable type: 'list'") + self.assertIn("Warning: evaluations will not be judged", logs.getvalue()) + + def test_config_error_is_found_before_the_run_and_recorded(self): + report, metrics, log = self.run_step(args([{"name": "Bad"}], str(self.dest))) + self.assertTrue(report["error"].startswith("config: evaluations: 0.name: String should match pattern")) + self.assertEqual((report["summary"]["status"], report["evaluations"]), ("invalid", [])) + self.assertEqual(metrics, ["trial_summary", "evaluations"]) + self.assertIn("Warning: evaluations will not be judged: config: ", log) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/locust/unit_tests/test_runner_test_entry.py b/benchmarking/locust/unit_tests/test_runner_test_entry.py new file mode 100644 index 0000000000..0ce5f23799 --- /dev/null +++ b/benchmarking/locust/unit_tests/test_runner_test_entry.py @@ -0,0 +1,78 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for runner.py's --test-entry and --run-ts, and the artifacts it stores.""" + +import argparse +import contextlib +import io +import sys +import unittest +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) + +import runner # noqa: E402 + + +class TestEntryTest(unittest.TestCase): + def test_json_object(self): + self.assertEqual(runner.json_object('{"name": "t", "observers": []}'), {"name": "t", "observers": []}) + for bad in ("{oops", "[]"): + with self.subTest(bad=bad), self.assertRaises(argparse.ArgumentTypeError): + runner.json_object(bad) + + def test_the_run_config_shows_the_whole_entry(self): + a = argparse.Namespace(name="t", tag="c", file="tests/glutton.py", duration="1m", users=1, + allow_empty_stats=False, locust_extra=[], + test_entry={"name": "t", "evaluations": [{"name": "e"}]}) + logs = io.StringIO() + with contextlib.redirect_stdout(io.StringIO()): + runner.log_run_config(a, "d", Path("w"), logs) + self.assertIn(' test entry:\n {\n "name": "t",\n "evaluations": [\n', logs.getvalue()) + + +class StoredArtifactsTest(unittest.TestCase): + ARGV = ["runner.py", "-f", "tests/glutton.py", "-t", "1m", "-u", "10", "--tag", "unit", "--name", "unit-run", + "--no-cluster-facts", "--no-phase-breakdown", "--allow-empty-stats"] + + @staticmethod + def locust(_args, csv_prefix, _logs, _traces): + """What locust leaves: its CSVs, named after the --csv prefix.""" + Path(f"{csv_prefix}_stats.csv").write_text("Type,Name,Request Count\nPOST,CreateActor,3\n") + Path(f"{csv_prefix}_failures.csv").write_text("Method,Name,Error,Occurrences\n") + return 0 + + def stored(self, *flags: str) -> list[str]: + uploaded = [] + with mock.patch.object(runner, "run_test", self.locust), \ + mock.patch.object(runner, "upload", lambda src, dest: uploaded.append(dest)), \ + mock.patch.object(runner, "append_trial_summary"), \ + mock.patch.object(runner, "extract_and_record_server_telemetry"), \ + mock.patch.object(runner, "append_ladder_steps", return_value=0), \ + mock.patch.object(sys, "argv", self.ARGV + list(flags)), \ + contextlib.redirect_stdout(io.StringIO()): + runner.main() + return uploaded + + def test_artifacts_are_stored_by_name_under_the_run_ts(self): + prefix = "/dest/runs/unit-run/run_date=2026-10-11/run_ts=1791701190/run_tag=unit" + self.assertEqual(self.stored("--dest", "/dest", "--run-ts", "1791701190"), [ + f"{prefix}/{name}" for name in + ("failures.csv", "logs.txt", "stats.csv", "stats.jsonl", "status.json", "traces.txt")]) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/locust/unit_tests/test_server_telemetry.py b/benchmarking/locust/unit_tests/test_server_telemetry.py index e1517292f2..c615c9a23d 100644 --- a/benchmarking/locust/unit_tests/test_server_telemetry.py +++ b/benchmarking/locust/unit_tests/test_server_telemetry.py @@ -40,16 +40,19 @@ "end_ts": 105, "steady_start_ts": 100} -def ranges(packing, node=(), pod=(), active=(), ws=(), actor_ws=()): - """A query_prometheus_range fake: packing, PSI, active actors, working set. +def ranges(packing, node=(), pod=(), active=(), ws=(), actor_ws=(), disk=((), ()), + cpu=(), actor_cpu=()): + """A query_prometheus_range fake: packing, PSI, active actors, working set, disk, CPU. Pod PSI only answers the pod-slice selector, so a query that loses the id regex (and would also sum the pause container) gets nothing back. Node PSI - only answers when kept to nodes hosting a worker pod. + only answers when kept to nodes hosting a worker pod, and node disk, given + as (reads, writes), only when kept to nodes with a live worker. """ pod_slice = ('{pod=~"benchmark-worker.*", container="", ' 'id=~".*[/-]pod[^/]+(\\\\.slice)?"}') worker_nodes = "and on (instance) sum by (instance) (rate(" + live_workers = "and on (instance) count by (instance) (rate(" def fake(_url, query, *_args, **_kwargs): if "ate_workerpool_workers" in query: @@ -58,9 +61,17 @@ def fake(_url, query, *_args, **_kwargs): return list(active) if "ate_actor_stats_memory_working_set_bytes" in query: return list(actor_ws) - # Before the PSI branch: the node working set query has container="node". + if "ate_actor_stats_cpu_time_seconds_total" in query: + return list(actor_cpu) + # The CPU blocks lead with the rate; elsewhere it only filters live workers. + if "(rate(container_cpu_usage_seconds_total" in query.split(" and on ")[0]: + return list(cpu) + # Before PSI: the node working set and disk queries have container="node". if "container_memory_working_set_bytes" in query: return list(ws) + if "container_fs_" in query: + series = disk[0] if "container_fs_reads_" in query else disk[1] + return list(series) if live_workers in query else [] if 'container="node"' in query: return list(node) if worker_nodes in query and pod_slice in query else [] return list(pod) if pod_slice in query else [] @@ -251,13 +262,20 @@ def test_packing_and_checkpoint_math(self, mock_instant, mock_range): "values": [[100, "0.0"], [105, "0.0"]]} for n in "ab"] pods = [{"metric": {"pod": f"benchmark-worker-{p}"}, "values": [[100, "0.5"], [105, "0.5"]]} for p in "ab"] + boot = [{"metric": {"instance": "node-a", "device": "/dev/nvme0n1"}, + "values": [[100, "300.0"], [105, "300.0"]]}] mock_range.side_effect = ranges( [partial, full, idle], node=quiet, pod=pods, active=[{"metric": {"instance": "atelet-a"}, "values": [[135, "3"]]}], ws=[{"metric": {"instance": "node-a"}, "values": [[100, str(2**30)], [105, str(2**30)]]}], actor_ws=[{"metric": {"instance": "atelet-a"}, - "values": [[135, str(6 * 2**30)]]}]) + "values": [[135, str(6 * 2**30)]]}], + disk=(boot, boot), + cpu=[{"metric": {"pod": "benchmark-worker-a"}, + "values": [[100, "7.5"], [105, "7.5"]]}], + actor_cpu=[{"metric": {"instance": "atelet-a"}, + "values": [[135, "4.5"]]}]) # The default 70s lag reads the snapshot window at 135 and 140. mock_instant.side_effect = snapshot_prom( "11.5", @@ -299,8 +317,8 @@ def test_packing_and_checkpoint_math(self, mock_instant, mock_range): self.assertEqual(windows, {(False, (100, 105)), (True, (135, 140))}) self.assertEqual( set(summary), - {"metadata", "cluster_packing", "node_psi", "pod_psi", "snapshots", - "active_actors", "working_set", "oom_events"}, + {"metadata", "cluster_packing", "node_psi", "pod_psi", "node_disk", + "snapshots", "active_actors", "working_set", "cpu", "oom_events"}, ) packing = summary["cluster_packing"] self.assertEqual(packing["summary"]["p50"], 0.8) # 3 + 1 busy / 5 workers @@ -312,6 +330,7 @@ def test_packing_and_checkpoint_math(self, mock_instant, mock_range): self.assertEqual(summary["pod_psi"]["cpu_stall_pct"]["p99"], 0.5) self.assertEqual(summary["node_psi"]["nodes"], 2) self.assertEqual(summary["node_psi"]["cpu_stall_pct"]["p99"], 0.0) + self.assertEqual(summary["node_disk"]["nodes"], 1) snapshots = summary["snapshots"] self.assertEqual(snapshots["checkpoints_in_window"], 50) # 150 - 100 @@ -320,13 +339,14 @@ def test_packing_and_checkpoint_math(self, mock_instant, mock_range): self.assertEqual(row["metric"], "server_summary") m = row["measurements"] # Every source answered, so a key wired to a wrong name would read None. - self.assertEqual(len(m), 80) + self.assertEqual(len(m), 108) self.assertEqual([k for k, v in m.items() if v is None], []) # Every value a string, so one row's types match every other row's. self.assertTrue(all(isinstance(v, str) for v in m.values())) self.assertEqual(m["checkpoint_mb_s"], "2.0") self.assertEqual(m["pod_psi_cpu_stall_p99"], "0.5") self.assertEqual(m["psi_cpu_stall_p90"], "0.0") + self.assertEqual(m["node_disk_nvme0n1_write_p99_mb_s"], "300.0") self.assertEqual(m["cluster_packing_p95"], "0.8") self.assertEqual(m["snapshot_size_p95_mb"], "11.5") self.assertEqual(m["restore_mean_s"], "0.5") @@ -337,6 +357,10 @@ def test_packing_and_checkpoint_math(self, mock_instant, mock_range): self.assertEqual(actor["timeseries"][0]["timestamp"], 100) self.assertEqual(m["working_set_actor_p50_gb"], "6.0") self.assertEqual(m["working_set_per_actor_p50_gb"], "2.0") + # Worker CPU is read on the run window, actor CPU late like its working set. + self.assertEqual(m["cpu_worker_p50_cores"], "7.5") + self.assertEqual(m["cpu_actor_p50_cores"], "4.5") + self.assertEqual(summary["cpu"]["actor"]["timeseries"][0]["timestamp"], 100) @mock.patch("server_telemetry.query_prometheus_range") @mock.patch("server_telemetry.query_prometheus_instant") @@ -486,6 +510,47 @@ def test_steady_window_bounds_packing_and_psi(self, mock_instant, mock_range): self.assertEqual(out["node_psi"]["cpu_stall_pct"]["max"], 0.5) self.assertEqual(out["pod_psi"]["cpu_stall_pct"]["max"], 0.5) + @mock.patch("server_telemetry.query_prometheus_range") + def test_node_disk_pools_nodes_per_device(self, mock_range): + def disk(node, device, *values): + return {"metric": {"instance": node, "device": device}, + "values": [[100 + 10 * i, v] for i, v in enumerate(values)]} + # The boot disk pools across nodes; the sample at 120 is teardown. + writes = [disk("node-a", "/dev/nvme0n1", "300", "280", "9"), + disk("node-b", "/dev/nvme0n1", "100"), + disk("node-a", "/dev/nvme0n3", "40"), + disk("node-a", "/dev/root", "0")] + reads = [disk("node-a", "/dev/nvme0n1", "2")] + mock_range.side_effect = ranges([], disk=(reads, writes)) + out = server_telemetry._harvest_node_disk("http://p", 100, 120, 100, 110) + boot = out["write_mb_s"]["/dev/nvme0n1"] + self.assertEqual((boot["min"], boot["max"]), (100.0, 300.0)) + self.assertEqual(out["write_mb_s"]["/dev/nvme0n3"]["max"], 40.0) + # Every device is kept: /dev/root reads a measured 0, not null. + self.assertEqual(out["write_mb_s"]["/dev/root"]["max"], 0.0) + self.assertEqual(list(out["read_mb_s"]), ["/dev/nvme0n1"]) + self.assertEqual(out["read_mb_s"]["/dev/nvme0n1"]["max"], 2.0) + self.assertEqual(out["nodes"], 2) + # cAdvisor's root cgroup, summed per node and device, in MiB/s. + query = mock_range.call_args.args[1] + self.assertIn('container_fs_writes_bytes_total{container="node"}', query) + self.assertIn("sum by (instance, device)", query) + self.assertIn("/ 1048576", query) + + @mock.patch("server_telemetry.query_prometheus_range") + def test_node_disk_null_not_zero(self, mock_range): + # Never seen (not scraped, or the read failed): no device reads 0. + mock_range.side_effect = ranges([]) + self.assertEqual( + server_telemetry._harvest_node_disk("http://p", 100, 120, 100, 110), + {"read_mb_s": {}, "write_mb_s": {}, "nodes": 0}) + # A device seen only outside the steady window is null, not 0. + late = [{"metric": {"instance": "node-a", "device": "/dev/nvme0n1"}, + "values": [[120, "50"]]}] + mock_range.side_effect = ranges([], disk=(late, late)) + out = server_telemetry._harvest_node_disk("http://p", 100, 120, 100, 110) + self.assertEqual(out["write_mb_s"], {"/dev/nvme0n1": NO_PERCENTILES}) + @mock.patch("server_telemetry.query_prometheus_instant") def test_oom_pod_needs_both_reads(self, mock_instant): leaf, worker = 'pod=""', 'namespace="benchmark-workloads"' @@ -545,6 +610,48 @@ def test_working_set_actor_keys_like_active_actors(self, mock_range): # cAdvisor keeps the label key: 2 worker pods are still 2. self.assertEqual(out["worker"]["count"], 2) + @mock.patch("server_telemetry.query_prometheus_range") + def test_cpu_cores_and_steady_window(self, mock_range): + meter = [{"exported_instance": "a", "instance": f"meter-{i}"} for i in "01"] + mock_range.side_effect = ranges( + [], + cpu=[{"metric": {"pod": "w-0"}, + "values": [[90, "9"], [100, "2.5"], [110, "4"]]}, + {"metric": {"pod": "w-1"}, "values": [[110, "1.5"]]}], + actor_cpu=[{"metric": m, "values": [[100, v]]} + for m, v in zip(meter, ("1", "3"))]) + out = server_telemetry._measure_cpu("http://p", 90, 110, 100, 110) + worker = out["worker"] + # The 9 cores at 90 are ramp-up: in the timeseries, not the summary. + self.assertEqual((worker["summary"]["p50"], worker["summary"]["max"]), (2.5, 4.0)) + self.assertEqual(worker["count"], 2) + self.assertEqual(worker["timeseries"], [ + {"timestamp": 90, "total_cores": 9.0, "max_cores": 9.0}, + {"timestamp": 100, "total_cores": 2.5, "max_cores": 2.5}, + {"timestamp": 110, "total_cores": 5.5, "max_cores": 4.0}, + ]) + # One atelet through 2 meter pods is one series, the larger read. + self.assertEqual((out["actor"]["count"], out["actor"]["summary"]["max"]), (1, 3.0)) + self.assertEqual(set(out), {"node", "worker", "atelet", "actor"}) + + @mock.patch("server_telemetry.query_prometheus_range") + def test_cpu_null_not_zero(self, mock_range): + mock_range.side_effect = ranges([]) + out = server_telemetry._measure_cpu("http://p", 90, 110, 100, 110) + for block in out.values(): + self.assertEqual(block, {"summary": NO_PERCENTILES, "count": None, + "timeseries": []}) + + def test_cpu_queries(self): + q = server_telemetry.CPU_QUERIES + for block in q.values(): + self.assertTrue(block.startswith("sum by (")) # a restart's 2 series add up + self.assertIn('container="node"', q["node"]) + self.assertIn('container="worker"', q["worker"]) + # Every template on the atelet, and a window of a few atelet samples. + self.assertIn("sum by (instance, exported_instance)", server_telemetry.ACTOR_CPU) + self.assertIn("[3m]", server_telemetry.ACTOR_CPU) + def test_working_set_queries_keep_live_workers(self): q = server_telemetry.WORKING_SET_QUERIES live = "rate(container_cpu_usage_seconds_total" @@ -804,12 +911,12 @@ def ladder(jsonl_path, log_path, prom_url, *_): "--prometheus-url", "http://x:9090"]), \ contextlib.redirect_stdout(out): runner.main() - self.assertEqual(calls, ["telemetry", ("ladder", "unit-run_logs.txt", "http://x:9090")]) + self.assertEqual(calls, ["telemetry", ("ladder", "logs.txt", "http://x:9090")]) self.assertIn("Failed to summarize ladder steps: prometheus down", out.getvalue()) self.assertTrue(upload.called) # The fill-done line of a turnover run starts the telemetry's steady - # window and the turnover_window row; a run without one gets neither. + # window and the turnover rows; a run without one gets neither. @mock.patch.object(runner, "upload") def test_turnover_start_reaches_telemetry_and_window(self, _up): for line, start in ( diff --git a/benchmarking/locust/unit_tests/test_turnover_window.py b/benchmarking/locust/unit_tests/test_turnover_window.py index 5c2c07dada..f2ef7a2ece 100644 --- a/benchmarking/locust/unit_tests/test_turnover_window.py +++ b/benchmarking/locust/unit_tests/test_turnover_window.py @@ -121,29 +121,31 @@ def append(self, body, start): jsonl, start, d / "stats_history.csv", "ts", "tag", "test", io.StringIO()) return ok, [json.loads(line) for line in jsonl.read_text().splitlines()] - def test_appends_the_window_row(self): + def test_appends_a_row_per_request(self): ok, rows = self.append(HISTORY, T0 + 250) self.assertTrue(ok) - self.assertEqual(rows[1], { - "timestamp": "ts", - "tag": "tag", - "test_name": "test", - "metric": "turnover_window", - "measurements": { - "window_start": T0 + 250, - "window_end": T0 + 350, - "window_s": 100, - "requests_ResumeActor": 500, - "failures_ResumeActor": 2, - "rps_ResumeActor": 5.0, - "requests_SuspendActorAsync": 500, - "failures_SuspendActorAsync": 1, - "rps_SuspendActorAsync": 5.0, - "requests_SuspendActorAsync_Register": 0, - "failures_SuspendActorAsync_Register": 0, - "rps_SuspendActorAsync_Register": 0.0, - }, - }) + self.assertEqual(rows[1:], [ + { + "timestamp": "ts", + "tag": "tag", + "test_name": "test", + "metric": f"turnover_{name}", + "measurements": { + "window_start": T0 + 250, + "window_end": T0 + 350, + "window_s": 100, + "request_count": requests, + "failure_count": failures, + "requests_per_s": rps, + "failures_per_s": fps, + }, + } + for name, requests, failures, rps, fps in ( + ("ResumeActor", 500, 2, 5.0, 0.02), + ("SuspendActorAsync", 500, 1, 5.0, 0.01), + ("SuspendActorAsync_Register", 0, 0, 0.0, 0.0), + ) + ]) def test_appends_nothing_without_a_history(self): self.assertEqual(self.append(None, T0 + 250), (False, [{"metric": "locust"}])) diff --git a/benchmarking/nighthawk-egress/Dockerfile b/benchmarking/nighthawk-egress/Dockerfile new file mode 100644 index 0000000000..452a61fc5a --- /dev/null +++ b/benchmarking/nighthawk-egress/Dockerfile @@ -0,0 +1,75 @@ +# Copyright 2026 The Agent Substrate 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. + +# Nighthawk egress-capacity benchmark runner image. Build context is the +# repo root. Always build with --platform linux/amd64 +# (envoyproxy/nighthawk-dev publishes no arm64 images): +# docker build --platform linux/amd64 -f benchmarking/nighthawk-egress/Dockerfile . + +# The three pins move together, as in benchmarking/nighthawk-ingress/Dockerfile. +# NIGHTHAWK_IMAGE_DIGEST is also the nighthawk_service image in +# traffic-driver-template.yaml.tmpl: the adaptive client here calls that service. +ARG NIGHTHAWK_COMMIT=21f3f100b86b11e5211e5672ade956c87baaa75c +ARG ENVOY_COMMIT=ad01ae36a702169140334ebadb2d0fc3be56327e +ARG NIGHTHAWK_IMAGE_DIGEST=sha256:7729902afea9d83f593b240690ba7d6e8fff04f6215ada538cfb4c1452b2553e + +# --- Stage 1: proto descriptor set ----------------------------------------- +FROM python:3.12-slim@sha256:b18b261e1b4974b4f321451ad5251ded85abb22c2b8b262da527dda1d031ab30 AS protogen +ARG NIGHTHAWK_COMMIT +ARG ENVOY_COMMIT +COPY benchmarking/locust/codegen/requirements.txt /tmp/codegen-requirements.txt +RUN apt-get update && apt-get install -y --no-install-recommends git ca-certificates \ + && rm -rf /var/lib/apt/lists/* \ + && pip install --no-cache-dir -r /tmp/codegen-requirements.txt + +RUN git clone --depth 1 https://github.com/cncf/xds /src/xds \ + && git clone --depth 1 https://github.com/bufbuild/protoc-gen-validate /src/pgv \ + && git clone --depth 1 https://github.com/googleapis/googleapis /src/googleapis +RUN git init /src/nighthawk \ + && git -C /src/nighthawk fetch --depth 1 https://github.com/envoyproxy/nighthawk "${NIGHTHAWK_COMMIT}" \ + && git -C /src/nighthawk checkout FETCH_HEAD +RUN git init /src/envoy \ + && git -C /src/envoy fetch --depth 1 https://github.com/envoyproxy/envoy "${ENVOY_COMMIT}" \ + && git -C /src/envoy checkout FETCH_HEAD + +COPY benchmarking/nighthawk_common/protogen/generate_descriptor.sh /gen.sh +RUN bash /gen.sh /out/nighthawk.desc + +# --- Stage 2: runtime ------------------------------------------------------- +FROM envoyproxy/nighthawk-dev@${NIGHTHAWK_IMAGE_DIGEST} + +COPY benchmarking/nighthawk-egress/requirements.txt /tmp/requirements.txt +RUN apt-get update \ + && apt-get install -y --no-install-recommends python3 python3-pip ca-certificates \ + && python3 -m pip install --no-cache-dir --break-system-packages \ + --target=/app/deps -r /tmp/requirements.txt \ + && apt-get purge -y python3-pip \ + && apt-get autoremove -y \ + && rm -rf /var/lib/apt/lists/* /tmp/requirements.txt + +WORKDIR /app +COPY --from=protogen /out/nighthawk.desc /app/nighthawk.desc +COPY benchmarking/nighthawk_common /app/nighthawk_common +COPY benchmarking/nighthawk-egress/runner.py \ + benchmarking/nighthawk-egress/spec.py \ + /app/ +COPY benchmarking/nighthawk-egress/tests/check_descriptor.py /app/tests/check_descriptor.py + +ENV PYTHONPATH=/app:/app/deps +ENV PYTHONUNBUFFERED=1 +ENV NIGHTHAWK_DESC=/app/nighthawk.desc + +RUN python3 /app/tests/check_descriptor.py +USER 65532:65532 +ENTRYPOINT ["python3", "/app/runner.py"] diff --git a/benchmarking/nighthawk-egress/README.md b/benchmarking/nighthawk-egress/README.md index 3377329c26..3abd91a3f0 100644 --- a/benchmarking/nighthawk-egress/README.md +++ b/benchmarking/nighthawk-egress/README.md @@ -2,13 +2,23 @@ Benchmarks the Agent Substrate egress dataplane (`atunnel` -> `atenet-egress`) using [Nighthawk](https://github.com/envoyproxy/nighthawk). -## Architecture +## Objective + +For `http` / `mitm` egress mode, the benchmark finds the highest request rate that one `atenet-egress` replica carries with 1 CPU allocated for each of its `envoy` and `ext-proc` containers under 3 thresholds: + +- `success-rate`: at least 99.8% of the sent requests get a 2xx response. +- `send-rate`: the client sends at least 90% of the scheduled requests. +- `latency-ns-mean-plus-2stdev`: the latency mean plus two standard deviations is at most 25 ms. + +## What it measures ```mermaid flowchart LR - client["nighthawk_client
(host)"] - invoker["traffic-driver-invoker
(:19980, adds ate-target-actor)"] - router["atenet-router
(:443)"] + subgraph job["Runner Job"] + client["Nighthawk client"] + invoker["invoker sidecar
(:19980, adds ate-target-actor)"] + end + router["atenet-router"] subgraph worker["WorkerPod (ateworker-gvisor)"] atunnel-ingress["ingress atunnel"] @@ -28,71 +38,179 @@ flowchart LR egress ==> server ``` -## Prerequisites +The test traffic follows the thick arrows: + +- `nighthawk_service` inside the actor sends it. +- The egress `atunnel` of the worker pod and `atenet-egress` carry it. +- `nighthawk-server`: a `nighthawk_test_server` that answers each request with a 10-byte body. + +The runner Job only starts each stage of the search. + +Each suite uses one egress mode, `http` or `mitm`. [Target URLs and Default Egress Policy](#target-urls-and-default-egress-policy) lists the target URL of each mode. + +A stage passes only when each of the three thresholds holds. + +| Threshold | Purpose | +|---|---| +| `success-rate`: at least 99.8% of the sent requests get a 2xx response. | Detects fast errors, such as 503 and 504. | +| `send-rate`: the client sends at least 90% of the scheduled requests. | Detects scheduled requests that the client skips. | +| `latency-ns-mean-plus-2stdev`: the latency mean plus two standard deviations is at most 25 ms. | Detects a slow egress path. This threshold is the SLO. | + +In the runs so far, the stages directly above the highest rate fail the latency threshold. + +## How it works + +One Kubernetes Job per `type: nighthawk-egress` tests.yaml entry, driven by [`../automation/orchestrator.py`](../automation/orchestrator.py). For each suite the orchestrator deploys Substrate with the `ateArgs` of the entry, then: + +1. **Pin the gateway.** The orchestrator pins `deployment/atenet-egress` to 1 replica with `envoy` and `ext-proc` at 1 CPU each, and waits for the rollout. +2. **Deploy the rig.** `hack/setup-e2e-egress-tls-kind.sh` provisions the CA bundle so `atenet-egress` trusts the certificate of `nighthawk-server`. `deploy.sh` and `deploy-traffic-driver.sh` deploy `nighthawk-server`, the worker pool, the actor template, and the `nighthawk/tester` actor with its egress policy. +3. **Adaptive search.** The orchestrator submits one Job from `nighthawk-egress-runner-job.yaml.tmpl`. In the Job, `runner.py` builds the load spec for the mode (`spec.py`) and runs `nighthawk_adaptive_load_client` against `nighthawk_service` in the `nighthawk/tester` actor, through the `invoker` sidecar of the Job. The sidecar is an Envoy that adds the `ate-target-actor: nighthawk/tester` header and connects to `atenet-router` as `benchmarking/benchmark-runner`. The search doubles the rate until a stage fails a threshold, then narrows the range, and ends with one testing stage. [Search values](#search-values) gives the rates and the durations. +4. **Upload results** (see [Reading the results](#reading-the-results)). The runner uploads the files that exist before it exits. The Job fails in each of these cases: + - The adaptive client exits non-zero, with no output. It does so when a stage ends with an error, the first stage fails a threshold, or the search passes its deadline. + - The output of the client has no testing stage. + - The runner raises an error. + - An upload fails. + +## How to run it + +### In CI + +The scheduled job in [benchmarking/automation](../automation/README.md) runs the two `type: nighthawk-egress` suites of [`benchmarking/automation/tests.yaml`](../automation/tests.yaml): + +| Suite | `mode` | +|---|---| +| `egress_gatewaycap_http_1cpu` | `http` | +| `egress_gatewaycap_mitm_1cpu` | `mitm` | + +The suites support gVisor only. Each suite passes `--cordon-system-infra-components` in `ateArgs`, so the cluster needs the node pools of [Sizing the rig](#sizing-the-rig). The entry of the `http` suite: + +```yaml +- name: egress_gatewaycap_http_1cpu + type: nighthawk-egress + targetCluster: dev + duration: 30m + ateArgs: + - "--cordon-system-infra-components" + nighthawk-egress: + mode: http +``` + +### Reading the results + +The runner uploads these files to `/runs//run_date=/run_ts=/run_tag=/`: + +| File | Content | +|---|---| +| `capacity.json` | The verdict. `slo_max_rps` is the achieved rate of the highest stage that passed every threshold, and `slo_max_stage` names that stage. `binding_threshold` lists the thresholds that failed in any stage. The other keys are those of the [nighthawk-ingress](../nighthawk-ingress/README.md) summary, plus `mode`. The runner writes this file only when the search succeeds. | +| `status.json` | `adaptive_client_exit_code`, `slo_max_rps`, and `failures`, the reasons why the run does not count. A failed upload of `status.json` itself is in the Job log only. | +| `stats.jsonl`, `results.json` | One record for each stage, and the Nighthawk output as JSON. | +| `spec.textproto`, `output.textproto`, `logs.txt` | The load spec, the raw Nighthawk output, and the client log. | + +#### Limitations -To measure single CPU performance characteristics of Envoy dataplane set E2E_ATE_ENVOY_CONCURRENCY=1 environment -variable when deploying ATE. +Nighthawk starts its latency clock when it sends a request, so the latency does not count the wait for a free connection. A run does not record the CPU use of the gateway, so a result that `send-rate` sets does not show by itself that the gateway was the limit. -1. **Cluster with Agent Substrate deployed**: +## Tuning + +### Configuration knobs (the `nighthawk-egress:` block) + +A `type: nighthawk-egress` entry in [`benchmarking/automation/tests.yaml`](../automation/tests.yaml) sets one knob in its `nighthawk-egress:` block: + +| Knob | Default | Meaning | +|---|---|---| +| `mode` | required | `http`, `mitm`, or `passthrough`. | + +The gateway size is not a knob. The orchestrator gives `envoy` and `ext-proc` of `deployment/atenet-egress` a CPU request and limit of 1 each and starts Envoy with `--concurrency 1`. [Sizing the rig](#sizing-the-rig) sizes the load for that gateway. + +### Search values + +The thresholds of [What it measures](#what-it-measures) and these search values are constants in [`spec.py`](spec.py): + +| Constant | Value | Meaning | +|---|---|---| +| `DEFAULT_CONCURRENCY` | 16 | Nighthawk event loops of `nighthawk_service` in the actor. | +| `DEFAULT_CONNECTIONS` | 16 | Client connections of each event loop, 256 in total. | +| `DEFAULT_MAX_PENDING` | 32 | Requests of each event loop that can wait for a free connection. The client does not send a request beyond this number and counts it in `pool_overflow`, which lowers `send-rate`. | +| `DEFAULT_INITIAL_RPS` | 500 | Start rate in requests per second in total. Nighthawk rounds it down to 31 for each event loop, 496 in total. | +| `DEFAULT_EXP_FACTOR` | 2 | Multiplies the rate after each stage that passes, until a stage fails. | +| `DEFAULT_MEASURING_PERIOD_S` | 20 | Length in seconds of each stage before the testing stage. | +| `DEFAULT_CONVERGENCE_DEADLINE_S` | 600 | Total time in seconds of the stages before the testing stage. | +| `DEFAULT_TESTING_STAGE_S` | 60 | Length in seconds of the last stage, at the rate where the search converged. | + +### Sizing the rig + +The actor, the worker pool, and `nighthawk-server` are sized to outscale `atenet-egress` with one Envoy worker thread, so a run measures the gateway and not the load generator or the origin server. `--cordon-system-infra-components` keeps the gateway off the nodes that run the load. The cluster needs the two tainted node pools of [System Infra Isolation](../../docs/concepts/architecture.md#system-infra-isolation) and a default pool: + +| Node pool | Example size | Runs | Kept there by | +|---|---|---|---| +| `ate-system-infra` | 1 x `c3-standard-22` | `atenet-egress`, the system under test, beside the other system infra components, which carry no test traffic | the node selector and toleration that `--cordon-system-infra-components` adds | +| `ate-postgres` | 1 x `c3-standard-4` | Postgres | the same flag | +| default | 2 x `c3-standard-22` (22 vCPUs and 88 GiB each) | the worker pod with the `nighthawk/tester` actor, `nighthawk-server`, and the runner Job | the `NoSchedule` taints of the other two pools, which these pods do not tolerate | + +The sizes: + +- `traffic-driver-template.yaml.tmpl` gives the `nighthawk/tester` sandbox 16 vCPUs and 8 GiB, so `nighthawk_service` runs its 16 event loops without CPU throttling. The suites and the manual example command both use 16. +- `traffic-driver.yaml.tmpl` requests 12 vCPUs and 8 GiB for the worker pod and sets no limits, so only the actor's own limits cap the load generator. The request fits a `c3-standard-22` node beside the system DaemonSets. The worker pod and `nighthawk-server` request 18 vCPUs together, so the scheduler may place them on the same node; this benchmark accepts that. +- `nighthawk-server.yaml` runs `nighthawk_test_server` with `--concurrency 8` and requests 6 vCPUs, so upstream HTTP and TLS on `:80`, `:443`, and `:8443` do not saturate before the gateway. + +## Manual runs + +The rig also takes a fixed-rate run from a host, with no runner Job. `nighthawk_client` reaches `nighthawk_service` in the actor through `kubectl-ate proxy actor`. + +### Prerequisites + +1. **Multi-node benchmark cluster with Agent Substrate deployed**: - **Existing cluster** (with `.ate-dev-env.sh` configured): ```bash - go run ./cmd/ate-setup deploy ate-system \ + E2E_ATE_ENVOY_CONCURRENCY=1 go run ./cmd/ate-setup deploy ate-system \ + --cordon-system-infra-components \ --credential-provider='{"name":"k8s.io"}' \ - --ingress-allowed-spiffe-ids=spiffe://cluster.local/ns/nighthawk/sa/default + --ingress-allowed-spiffe-ids=spiffe://cluster.local/ns/ate-system/sa/atenet-client ``` - - **Local `kind` cluster**: + - `E2E_ATE_ENVOY_CONCURRENCY` sets the `atenet-egress` Envoy worker thread count (`--concurrency`). `E2E_ATE_ENVOY_CONCURRENCY=1` measures a single Envoy core, which the sizes above are for. + - Provision the CA bundle in `ate-system` so `atenet-egress` trusts `nighthawk-server`'s `servicedns` certificate on `:443`. The script defaults to a kind context, so name the cluster's context: ```bash - go run ./cmd/ate-setup --kind deploy ate-system \ - --credential-provider='{"enabled":false}' \ - --ingress-allowed-spiffe-ids=spiffe://cluster.local/ns/nighthawk/sa/default + KUBECTL_CONTEXT= hack/setup-e2e-egress-tls-kind.sh ``` - - To set the `atenet-egress` Envoy worker thread count (`--concurrency`), set `E2E_ATE_ENVOY_CONCURRENCY` when deploying: - ```bash - E2E_ATE_ENVOY_CONCURRENCY=1 go run ./cmd/ate-setup --kind deploy ate-system --credential-provider='{"name":"k8s.io"}' --ingress-allowed-spiffe-ids=spiffe://cluster.local/ns/nighthawk/sa/default - ``` - - Provision CA bundle which includes cluster's trust bundle, so that egress gateway can trust nighhawk's test server cert, run: - ```bash - hack/setup-e2e-egress-tls-kind.sh - ``` -2. **`kubectl-ate` installed in `PATH`**: - ```bash - go install ./cmd/kubectl-ate - ``` + - To run on a smaller cluster, lower `requests.cpu` and `requests.memory` in `traffic-driver.yaml.tmpl` and `nighthawk-server.yaml` before deploying. A worker pod without limits offers its node's allocatable CPU and memory to actors, so on nodes with fewer than 16 allocatable vCPUs also lower `cpuMillicores` in `traffic-driver-template.yaml.tmpl`. On a cluster without the two tainted pools, leave out `--cordon-system-infra-components`; the gateway then shares nodes with the load. +2. **`kubectl-ate`**: `deploy-traffic-driver.sh` builds it from `./cmd/kubectl-ate` into a temporary directory. 3. **Docker** running locally (used to run `nighthawk_client`). -## Setup +### Setup -### 1. Deploy `nighthawk-server` and `traffic-driver-invoker` +#### 1. Deploy `nighthawk-server` ```bash ./benchmarking/nighthawk-egress/deploy.sh ``` -### 2. Deploy the worker pool, actor template, and `nighthawk/tester` actor +#### 2. Deploy the worker pool, actor template, and `nighthawk/tester` actor ```bash ./benchmarking/nighthawk-egress/deploy-traffic-driver.sh ``` -### 3. Port-forward `traffic-driver-invoker` +#### 3. Forward a port to the actor -In a separate terminal, forward local port `19980` to the `traffic-driver-invoker` service: +In a separate terminal, forward local port `19980` to `nighthawk_service` in the `nighthawk/tester` actor. `kubectl-ate proxy actor` connects as `spiffe://cluster.local/ns/ate-system/sa/atenet-client`, which is the ID in the deploy command above: ```bash -kubectl -n nighthawk port-forward svc/traffic-driver-invoker 19980:19980 +go run ./cmd/kubectl-ate proxy actor tester -a nighthawk 19980:80 ``` -## Running the Benchmark +### Running the benchmark -Run `nighthawk_client` against the port-forwarded `traffic-driver-invoker` endpoint (`grpc://127.0.0.1:19980`), which routes the gRPC request to `nighthawk_service` inside the `nighthawk/tester` actor: +Run `nighthawk_client` against the forwarded port (`grpc://127.0.0.1:19980`), which reaches `nighthawk_service` inside the `nighthawk/tester` actor: ```bash -docker run --rm --network=host --entrypoint /usr/local/bin/nighthawk_client envoyproxy/nighthawk-dev:latest --nighthawk-service grpc://127.0.0.1:19980 --rps 1000 --concurrency 1 --protocol http1 --duration 60 http://nighthawk-server.nighthawk.svc:80 +docker run --rm --network=host --entrypoint /usr/local/bin/nighthawk_client envoyproxy/nighthawk-dev:latest --nighthawk-service grpc://127.0.0.1:19980 --rps 1000 --concurrency 16 --protocol http1 --duration 60 http://nighthawk-server.nighthawk.svc:80 ``` +Nighthawk multiplies `--rps` by `--concurrency`, so this command targets 16,000 requests per second in total. One Envoy worker thread holds less than that, so the gateway saturates and the output shows the rate it reached. + See [Nighthawk CLI help](https://github.com/envoyproxy/nighthawk#using-the-nighthawk-client-cli) for all command line options. -### Target URLs and Default Egress Policy +#### Target URLs and Default Egress Policy | Egress Mode | Target URL | Port | |---|---|---| @@ -100,7 +218,7 @@ See [Nighthawk CLI help](https://github.com/envoyproxy/nighthawk#using-the-night | HTTPS (TLS MITM) | `https://nighthawk-server.nighthawk.svc:443` | `443` | | TLS Passthrough | `https://nighthawk-server.nighthawk.svc:8443` | `8443` | -## Cleanup +### Cleanup Delete the `nighthawk/tester` actor, actor template, atespace, and worker pool: @@ -108,7 +226,7 @@ Delete the `nighthawk/tester` actor, actor template, atespace, and worker pool: ./benchmarking/nighthawk-egress/deploy-traffic-driver.sh --delete ``` -Delete `nighthawk-server` and `traffic-driver-invoker` from `nighthawk`: +Delete `nighthawk-server` from `nighthawk`: ```bash ./benchmarking/nighthawk-egress/deploy.sh --delete diff --git a/benchmarking/nighthawk-egress/deploy-traffic-driver.sh b/benchmarking/nighthawk-egress/deploy-traffic-driver.sh index 1f10a52867..e56bc8a8b4 100755 --- a/benchmarking/nighthawk-egress/deploy-traffic-driver.sh +++ b/benchmarking/nighthawk-egress/deploy-traffic-driver.sh @@ -25,6 +25,9 @@ if [[ -f "${REPO_ROOT}/.ate-dev-env.sh" ]] && [[ -z "${NO_DEV_ENV:-}" ]]; then source "${REPO_ROOT}/.ate-dev-env.sh" fi +# shellcheck source=benchmarking/lib/kubectl-ate.sh +source "${REPO_ROOT}/benchmarking/lib/kubectl-ate.sh" + ATESPACE="nighthawk" TEMPLATE_NAME="traffic-driver" ACTOR_NAME="tester" @@ -32,7 +35,6 @@ POOL_MANIFEST="${SCRIPT_DIR}/traffic-driver.yaml.tmpl" NAMESPACE_MANIFEST="${SCRIPT_DIR}/namespace.yaml" MANIFEST="${SCRIPT_DIR}/traffic-driver-template.yaml.tmpl" EGRESS_POLICY_MANIFEST="${SCRIPT_DIR}/egress-policy.yaml" -KUBECTL_ATE_BIN="kubectl-ate" WAIT_TIMEOUT_SECS=300 CONTEXT="${KUBECTL_CONTEXT:-}" KO_DOCKER_REPO="${KO_DOCKER_REPO:-localhost:5001}" @@ -97,12 +99,14 @@ if ! [[ "${WAIT_TIMEOUT_SECS}" =~ ^[0-9]+$ ]]; then exit 1 fi +# bash 3.2 treats an empty array as unset under nounset, so args expands +# only when it has elements. run_kubectl() { local args=() if [[ -n "${CONTEXT}" ]]; then args+=(--context "${CONTEXT}") fi - kubectl "${args[@]}" "$@" + kubectl ${args[@]+"${args[@]}"} "$@" } run_kubectl_ate() { @@ -110,7 +114,7 @@ run_kubectl_ate() { if [[ -n "${CONTEXT}" ]]; then args+=(--context "${CONTEXT}") fi - "${KUBECTL_ATE_BIN}" "${args[@]}" "$@" + "${KUBECTL_ATE_BIN}" ${args[@]+"${args[@]}"} "$@" } wait_template_ready() { @@ -146,6 +150,7 @@ deploy() { exit 1 fi export KO_DOCKER_REPO + build_kubectl_ate echo "Deploying namespace from ${NAMESPACE_MANIFEST}..." run_kubectl apply -f "${NAMESPACE_MANIFEST}" @@ -183,6 +188,7 @@ deploy() { } delete() { + build_kubectl_ate echo "Suspending and deleting actor ${ATESPACE}/${ACTOR_NAME}..." run_kubectl_ate suspend actor "${ACTOR_NAME}" -a "${ATESPACE}" >/dev/null 2>&1 || true run_kubectl_ate delete actor "${ACTOR_NAME}" -a "${ATESPACE}" >/dev/null 2>&1 || true diff --git a/benchmarking/nighthawk-egress/deploy.sh b/benchmarking/nighthawk-egress/deploy.sh index 4f04668665..3da886c5ac 100755 --- a/benchmarking/nighthawk-egress/deploy.sh +++ b/benchmarking/nighthawk-egress/deploy.sh @@ -19,7 +19,6 @@ set -o errexit -o nounset -o pipefail SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" NAMESPACE_MANIFEST="${SCRIPT_DIR}/namespace.yaml" SERVER_MANIFEST="${SCRIPT_DIR}/nighthawk-server.yaml" -INVOKER_MANIFEST="${SCRIPT_DIR}/traffic-driver-invoker.yaml" WAIT_TIMEOUT_SECS=120 CONTEXT="${KUBECTL_CONTEXT:-}" @@ -27,8 +26,8 @@ usage() { echo "Usage: $0 [options]" echo "" echo "Options:" - echo " --deploy Deploy nighthawk-server and traffic-driver-invoker in nighthawk (default)" - echo " --delete Delete nighthawk-server and traffic-driver-invoker from nighthawk" + echo " --deploy Deploy nighthawk-server in nighthawk (default)" + echo " --delete Delete nighthawk-server from nighthawk" echo " --context CONTEXT kubectl context to use (default: \$KUBECTL_CONTEXT or current context)" echo " --wait-timeout SECONDS Rollout wait timeout in seconds (default: ${WAIT_TIMEOUT_SECS})" echo " -h, --help Show this help message" @@ -85,13 +84,9 @@ if [[ "${action}" == "deploy" ]]; then "${kubectl_cmd[@]}" apply -f "${NAMESPACE_MANIFEST}" echo "Deploying Nighthawk server from ${SERVER_MANIFEST}..." "${kubectl_cmd[@]}" apply -f "${SERVER_MANIFEST}" - echo "Deploying traffic-driver-invoker from ${INVOKER_MANIFEST}..." - "${kubectl_cmd[@]}" apply -f "${INVOKER_MANIFEST}" echo "Waiting for deployment/nighthawk-server in nighthawk to be ready (timeout: ${WAIT_TIMEOUT_SECS}s)..." "${kubectl_cmd[@]}" -n nighthawk rollout status deployment/nighthawk-server --timeout="${WAIT_TIMEOUT_SECS}s" - echo "Waiting for deployment/traffic-driver-invoker in nighthawk to be ready (timeout: ${WAIT_TIMEOUT_SECS}s)..." - "${kubectl_cmd[@]}" -n nighthawk rollout status deployment/traffic-driver-invoker --timeout="${WAIT_TIMEOUT_SECS}s" elif [[ "${action}" == "delete" ]]; then - echo "Deleting Nighthawk server and traffic-driver-invoker..." - "${kubectl_cmd[@]}" delete --ignore-not-found -f "${INVOKER_MANIFEST}" -f "${SERVER_MANIFEST}" + echo "Deleting Nighthawk server..." + "${kubectl_cmd[@]}" delete --ignore-not-found -f "${SERVER_MANIFEST}" fi diff --git a/benchmarking/nighthawk-egress/nighthawk-server.yaml b/benchmarking/nighthawk-egress/nighthawk-server.yaml index 00bfb57c23..d46a40f5b1 100644 --- a/benchmarking/nighthawk-egress/nighthawk-server.yaml +++ b/benchmarking/nighthawk-egress/nighthawk-server.yaml @@ -248,6 +248,12 @@ spec: args: - -c - /etc/nighthawk/nighthawk.yaml + - --concurrency + - "8" + resources: + requests: + cpu: "6" + memory: "2Gi" securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true diff --git a/benchmarking/nighthawk-egress/requirements.txt b/benchmarking/nighthawk-egress/requirements.txt new file mode 100644 index 0000000000..4b032998c4 --- /dev/null +++ b/benchmarking/nighthawk-egress/requirements.txt @@ -0,0 +1,16 @@ +# Copyright 2026 The Agent Substrate 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. + +protobuf>=7.35.1 +google-cloud-storage>=2.10.0 diff --git a/benchmarking/nighthawk-egress/runner.py b/benchmarking/nighthawk-egress/runner.py new file mode 100644 index 0000000000..8bf9ce9e67 --- /dev/null +++ b/benchmarking/nighthawk-egress/runner.py @@ -0,0 +1,205 @@ +#!/usr/bin/env python3 +# Copyright 2026 The Agent Substrate 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. + +"""Nighthawk adaptive egress-gateway capacity benchmark runner. + +One Kubernetes Job per tests.yaml entry, submitted by +benchmarking/automation/orchestrator.py: + 1. Build the AdaptiveLoadSessionSpec for the mode (spec.py). + 2. Run nighthawk_adaptive_load_client against the nighthawk_service in the + nighthawk/tester actor, through the invoker sidecar of the Job. + 3. Convert the output (nighthawk_common/output.py) and upload it to + /runs//..., the layout of the nighthawk-ingress runner. + +Exit 0 only when the adaptive client exits 0, its output has a testing stage, +the runner raises no error, and every upload works. +""" + +import argparse +from datetime import datetime, timezone +import json +import os +from pathlib import Path +import socket +import subprocess +import sys +import time +import traceback + +from nighthawk_common.output import upload_files, write_artifacts +from nighthawk_common.spec import spec_dict_to_textproto +from spec import ( + DEFAULT_CONCURRENCY, + DEFAULT_TAIL_LATENCY_SLO_MS, + MODE_URIS, + build_egress_session_spec, +) + +ADAPTIVE_CLIENT = "nighthawk_adaptive_load_client" +INVOKER_ADDR = "127.0.0.1:19980" +SERVICEDNS_CA_CERT = "/run/servicedns-ca/ca.crt" +DESC_PATH = os.environ.get("NIGHTHAWK_DESC", "/app/nighthawk.desc") + + +def load_servicedns_ca_pem(path: str | os.PathLike[str]) -> str: + if not os.path.isfile(path): + raise ValueError(f"servicedns CA bundle not found at {path}") + with open(path, encoding="utf-8") as f: + pem = f.read() + if not pem.strip(): + raise ValueError(f"servicedns CA bundle at {path} is empty") + return pem + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + p = argparse.ArgumentParser(description=__doc__) + p.add_argument("--name", required=True) + p.add_argument("--tag", required=True) + p.add_argument("--dest", required=True) + p.add_argument( + "--run-ts", + type=int, + default=None, + help="Unix seconds that name where the run is stored, shared by every run of one invocation. Default: now", + ) + p.add_argument("--mode", required=True, choices=sorted(MODE_URIS)) + p.add_argument("--envoy-cpu", required=True, type=int, dest="envoy_cpu") + return p.parse_args(argv) + + +def wait_for_tcp(host: str, port: int, timeout_s: float) -> None: + deadline = time.monotonic() + timeout_s + last_err: Exception | None = None + while time.monotonic() < deadline: + try: + with socket.create_connection((host, port), timeout=1.0): + return + except OSError as exc: + last_err = exc + time.sleep(0.25) + raise RuntimeError(f"Timed out waiting for {host}:{port}: {last_err}") + + +def run_adaptive_client(spec_path: Path, output_path: Path, logs_path: Path) -> int: + """Runs the adaptive session through the invoker sidecar and returns the client's exit code.""" + host, port = INVOKER_ADDR.rsplit(":", 1) + with open(logs_path, "w") as logs: + wait_for_tcp(host, int(port), timeout_s=30.0) + cmd = [ + ADAPTIVE_CLIENT, + "--nighthawk-service-address", + INVOKER_ADDR, + "--spec-file", + str(spec_path), + "--output-file", + str(output_path), + ] + proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True, bufsize=1) + for line in proc.stdout or (): + sys.stdout.write(line) + sys.stdout.flush() + logs.write(line) + return proc.wait() + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + now = datetime.now(timezone.utc) + work_dir = Path(f"/tmp/{now.strftime('%Y%m%dT%H%M%SZ')}-nighthawk-egress-{args.mode}") + work_dir.mkdir(parents=True, exist_ok=True) + stored_at = now if args.run_ts is None else datetime.fromtimestamp(args.run_ts, timezone.utc) + prefix = ( + f"{args.dest.rstrip('/')}/runs/{args.name}" + f"/run_date={stored_at.strftime('%Y-%m-%d')}/run_ts={int(stored_at.timestamp())}/run_tag={args.tag}" + ) + print(f"Uploading to {prefix}", flush=True) + logs_path = work_dir / "logs.txt" + spec_path = work_dir / "spec.textproto" + output_path = work_dir / "output.textproto" + results_path = work_dir / "results.json" + stats_path = work_dir / "stats.jsonl" + capacity_path = work_dir / "capacity.json" + status_path = work_dir / "status.json" + + # Each entry is one reason the run does not count. The exit code derives + # from this list alone. + failures: list[str] = [] + adaptive_exit = None + slo_max_rps = None + try: + servicedns_ca_pem = ( + load_servicedns_ca_pem(SERVICEDNS_CA_CERT) if args.mode == "passthrough" else None + ) + spec_dict = build_egress_session_spec(args.mode, servicedns_ca_pem=servicedns_ca_pem) + spec_path.write_text(spec_dict_to_textproto(spec_dict, DESC_PATH)) + adaptive_exit = run_adaptive_client(spec_path, output_path, logs_path) + if adaptive_exit != 0: + failures.append(f"{ADAPTIVE_CLIENT} exited with code {adaptive_exit}") + else: + # The client writes its output only when the session succeeds. + summary, has_testing_stage = write_artifacts( + output_path, + DESC_PATH, + tag=args.tag, + name=args.name, + envoy_cpu=args.envoy_cpu, + # The rig runs one actor, nighthawk/tester. + actors=1, + client_concurrency=DEFAULT_CONCURRENCY, + tail_latency_slo_ms=DEFAULT_TAIL_LATENCY_SLO_MS, + extra={"mode": args.mode}, + ) + slo_max_rps = summary["slo_max_rps"] + print(f"Capacity summary: {json.dumps(summary)}", flush=True) + # No testing stage means that the search did not finish, as in the nighthawk-ingress runner. + if not has_testing_stage: + failures.append(f"the output of {ADAPTIVE_CLIENT} has no testing stage") + except Exception as exc: + traceback.print_exc() + failures.append(f"{type(exc).__name__}: {exc}") + + # Upload before the exit decision, so a failed run keeps its artifacts. + failures += upload_files( + [ + logs_path, + spec_path, + output_path, + results_path, + stats_path, + capacity_path, + ], + prefix, + ) + # status.json is last, so it names the uploads that failed before it. + status_path.write_text( + json.dumps( + { + "adaptive_client_exit_code": adaptive_exit, + "slo_max_rps": slo_max_rps, + "failures": failures, + }, + indent=2, + ) + + "\n" + ) + failures += upload_files([status_path], prefix) + + for reason in failures: + print(f"Run failed: {reason}", flush=True) + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/benchmarking/nighthawk-egress/spec.py b/benchmarking/nighthawk-egress/spec.py new file mode 100644 index 0000000000..bd33926dcf --- /dev/null +++ b/benchmarking/nighthawk-egress/spec.py @@ -0,0 +1,97 @@ +# Copyright 2026 The Agent Substrate 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. + +"""AdaptiveLoadSessionSpec builder for the Nighthawk egress gateway benchmark.""" + +from typing import Any + +from nighthawk_common.spec import ( + PERMISSIVE_FAILURE_PREDICATES, + build_session_spec, +) + +UPSTREAM_SNI = "nighthawk-server.nighthawk.svc" +ACTOR_TRUST_BUNDLE = "/run/ate/egress-trust-bundle/trust-bundle.pem" +UPSTREAM_TLS_TYPE_URL = ( + "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext" +) +MODE_URIS: dict[str, str] = { + "http": f"http://{UPSTREAM_SNI}:80/", + "mitm": f"https://{UPSTREAM_SNI}:443/", + "passthrough": f"https://{UPSTREAM_SNI}:8443/", +} + +DEFAULT_CONCURRENCY = 16 +DEFAULT_CONNECTIONS = 16 +DEFAULT_MAX_PENDING = 32 +DEFAULT_INITIAL_RPS = 500 +DEFAULT_EXP_FACTOR = 2.0 +DEFAULT_MEASURING_PERIOD_S = 20 +DEFAULT_CONVERGENCE_DEADLINE_S = 600 +DEFAULT_TESTING_STAGE_S = 60 +DEFAULT_SUCCESS_RATE_THRESHOLD = 0.998 +DEFAULT_SEND_RATE_THRESHOLD = 0.9 +DEFAULT_TAIL_LATENCY_SLO_MS = 25.0 + + +def build_egress_session_spec(mode: str, *, servicedns_ca_pem: str | None = None) -> dict[str, Any]: + target_uri = MODE_URIS[mode] + traffic_template: dict[str, Any] = { + "uri": target_uri, + "concurrency": str(DEFAULT_CONCURRENCY), + "connections": DEFAULT_CONNECTIONS, + "max_pending_requests": DEFAULT_MAX_PENDING, + "open_loop": True, + "request_options": {"request_method": "GET", "request_headers": []}, + "failure_predicates": dict(PERMISSIVE_FAILURE_PREDICATES), + } + if target_uri.startswith("https://"): + if mode == "mitm": + trusted_ca: dict[str, str] = {"filename": ACTOR_TRUST_BUNDLE} + else: + if not servicedns_ca_pem or not servicedns_ca_pem.strip(): + raise ValueError("passthrough mode requires non-empty servicedns_ca_pem") + trusted_ca = {"inline_string": servicedns_ca_pem} + traffic_template["transport_socket"] = { + "name": "envoy.transport_sockets.tls", + "typed_config": { + "@type": UPSTREAM_TLS_TYPE_URL, + "sni": UPSTREAM_SNI, + "common_tls_context": { + "alpn_protocols": ["http/1.1"], + "validation_context": { + "trusted_ca": trusted_ca, + "match_typed_subject_alt_names": [ + { + "san_type": "DNS", + "matcher": {"exact": UPSTREAM_SNI}, + }, + ], + }, + }, + }, + } + + return build_session_spec( + traffic_template, + client_concurrency=DEFAULT_CONCURRENCY, + initial_total_rps=DEFAULT_INITIAL_RPS, + exponential_factor=DEFAULT_EXP_FACTOR, + measuring_period_s=DEFAULT_MEASURING_PERIOD_S, + convergence_deadline_s=DEFAULT_CONVERGENCE_DEADLINE_S, + testing_stage_duration_s=DEFAULT_TESTING_STAGE_S, + success_rate_threshold=DEFAULT_SUCCESS_RATE_THRESHOLD, + send_rate_threshold=DEFAULT_SEND_RATE_THRESHOLD, + tail_latency_slo_ms=DEFAULT_TAIL_LATENCY_SLO_MS, + ) diff --git a/benchmarking/nighthawk-egress/tests/check_descriptor.py b/benchmarking/nighthawk-egress/tests/check_descriptor.py new file mode 100644 index 0000000000..76b67e6c5b --- /dev/null +++ b/benchmarking/nighthawk-egress/tests/check_descriptor.py @@ -0,0 +1,34 @@ +# Copyright 2026 The Agent Substrate 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. + +import os + +from nighthawk_common.spec import spec_dict_to_textproto +import spec as egress_spec + + +def main(): + desc = os.environ.get("NIGHTHAWK_DESC", "/app/nighthawk.desc") + fake_ca = "-----BEGIN CERTIFICATE-----\nMIIBfake\n-----END CERTIFICATE-----\n" + for mode in egress_spec.MODE_URIS: + s = egress_spec.build_egress_session_spec( + mode, + servicedns_ca_pem=fake_ca if mode == "passthrough" else None, + ) + spec_dict_to_textproto(s, desc) + print("The spec of each mode converts with the Nighthawk protos") + + +if __name__ == "__main__": + main() diff --git a/benchmarking/nighthawk-egress/tests/test_runner.py b/benchmarking/nighthawk-egress/tests/test_runner.py new file mode 100644 index 0000000000..cfa190fd28 --- /dev/null +++ b/benchmarking/nighthawk-egress/tests/test_runner.py @@ -0,0 +1,240 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for benchmarking/nighthawk-egress/runner.py.""" + +import json +from pathlib import Path +import re +import socket +import sys +import tempfile +import unittest +from unittest.mock import MagicMock, patch + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) +import runner + +ARGS = ["--name", "test", "--tag", "tag1", "--dest", "gs://b/p", "--envoy-cpu", "1"] +DEST_RE = re.compile(r"gs://b/p/runs/test/run_date=\d{4}-\d{2}-\d{2}/run_ts=\d+/run_tag=tag1/(.+)") +CLIENT_LINE = "[adaptive] stage done\n" + + +def _stage(attempted_rps: float, achieved_rps: float, failed: str | None = None) -> dict: + evals = [ + {"metric_id": "nighthawk.builtin/attempted-rps", "metric_value": attempted_rps}, + {"metric_id": "nighthawk.builtin/achieved-rps", "metric_value": achieved_rps}, + ] + if failed: + evals.append({"metric_id": f"nighthawk.builtin/{failed}", "metric_value": 1.0, "threshold_score": -1.0}) + # Nighthawk reports the request counter with every evaluation. + result = { + "name": "global", + "execution_duration": "20s", + "counters": [{"name": "upstream_rq_total", "value": str(int(achieved_rps * 20))}], + } + return {"metric_evaluations": evals, "nighthawk_service_output": {"results": [result]}} + + +SAMPLE_OUTPUT = { + "session_status": {"code": 0}, + "adjusting_stage_results": [_stage(400.0, 399.0), _stage(800.0, 750.0), _stage(1600.0, 900.0, failed="send-rate")], + "testing_stage_result": _stage(800.0, 760.0), +} + + +def _run_main(work_dir: Path, mode: str, *, output=None, client_exit=0, failed_uploads=(), wait_error=None, parse_error=None): + """Runs runner.main with Nighthawk mocked out. The client writes its + output file only when output is given. Returns the exit code and the mocks. + sent holds the text of each file at its upload.""" + proc = MagicMock(stdout=[CLIENT_LINE]) + proc.wait.return_value = client_exit + if output is not None: + (work_dir / "output.textproto").write_text("fake output textproto") + sent = {} + + def fake_upload(src, dest): + sent[src.name] = src.read_text() + if src.name in failed_uploads: + raise OSError("bucket gone") + + with ( + patch("runner.Path", return_value=work_dir), + patch("nighthawk_common.output.upload", side_effect=fake_upload) as upload, + patch("subprocess.Popen", return_value=proc) as popen, + patch("runner.wait_for_tcp", side_effect=wait_error) as wait, + patch("nighthawk_common.output.parse_output_textproto", return_value=output, side_effect=parse_error), + patch("runner.spec_dict_to_textproto", return_value="fake textproto") as spec, + ): + got = runner.main([*ARGS, "--mode", mode]) + return got, {"upload": upload, "popen": popen, "wait": wait, "spec": spec, "sent": sent} + + +class TestRunner(unittest.TestCase): + def test_main_exit_code_and_artifacts(self): + run_files = {"logs.txt", "spec.textproto", "status.json"} + all_files = run_files | {"output.textproto", "results.json", "stats.jsonl", "capacity.json"} + cases = [ + # label, _run_main arguments, want exit code, want failures in status.json, want uploaded files + ("clean run", {"output": SAMPLE_OUTPUT}, 0, [], all_files), + ( + "client fails", + {"client_exit": 3}, + 1, + ["nighthawk_adaptive_load_client exited with code 3"], + run_files, + ), + ( + "invoker never listens", + {"wait_error": RuntimeError("Timed out waiting for 127.0.0.1:19980")}, + 1, + ["RuntimeError: Timed out waiting for 127.0.0.1:19980"], + run_files, + ), + ( + "output does not parse", + {"output": SAMPLE_OUTPUT, "parse_error": ValueError("bad textproto")}, + 1, + ["ValueError: bad textproto"], + run_files | {"output.textproto"}, + ), + ( + "output has no testing stage", + {"output": {k: v for k, v in SAMPLE_OUTPUT.items() if k != "testing_stage_result"}}, + 1, + ["the output of nighthawk_adaptive_load_client has no testing stage"], + all_files, + ), + ( + "one upload fails", + {"output": SAMPLE_OUTPUT, "failed_uploads": {"results.json"}}, + 1, + ["upload of results.json failed: bucket gone"], + all_files, + ), + # status.json is the last upload, so it cannot name its own failure. + ("status.json upload fails", {"output": SAMPLE_OUTPUT, "failed_uploads": {"status.json"}}, 1, [], all_files), + ] + for label, kwargs, want, want_failures, want_uploaded in cases: + with self.subTest(label=label), tempfile.TemporaryDirectory() as tmp: + work_dir = Path(tmp) + got, mocks = _run_main(work_dir, "mitm", **kwargs) + self.assertEqual(got, want) + + uploaded = {} + for call in mocks["upload"].call_args_list: + src, dest = call.args + uploaded[src.name] = DEST_RE.fullmatch(dest).group(1) + self.assertEqual(set(uploaded), want_uploaded) + self.assertEqual(set(uploaded.values()), want_uploaded) + + status = json.loads(mocks["sent"]["status.json"]) + self.assertEqual(status["failures"], want_failures) + if "capacity.json" in want_uploaded: + cap = json.loads((work_dir / "capacity.json").read_text()) + self.assertEqual(status["slo_max_rps"], cap["slo_max_rps"]) + else: + self.assertFalse((work_dir / "capacity.json").exists()) + self.assertIsNone(status["slo_max_rps"]) + + def test_main_runs_the_client_through_the_invoker(self): + with tempfile.TemporaryDirectory() as tmp: + work_dir = Path(tmp) + _, mocks = _run_main(work_dir, "http", output=SAMPLE_OUTPUT, client_exit=0) + logs = (work_dir / "logs.txt").read_text() + status = json.loads((work_dir / "status.json").read_text()) + mocks["wait"].assert_called_once_with("127.0.0.1", 19980, timeout_s=30.0) + self.assertEqual( + mocks["popen"].call_args.args[0], + [ + "nighthawk_adaptive_load_client", + "--nighthawk-service-address", + "127.0.0.1:19980", + "--spec-file", + str(work_dir / "spec.textproto"), + "--output-file", + str(work_dir / "output.textproto"), + ], + ) + self.assertEqual(logs, CLIENT_LINE) + self.assertEqual(status["adaptive_client_exit_code"], 0) + + def test_capacity_json_fields(self): + with tempfile.TemporaryDirectory() as tmp: + _run_main(Path(tmp), "http", output=SAMPLE_OUTPUT) + cap = json.loads((Path(tmp) / "capacity.json").read_text()) + want = { + "mode": "http", + "envoy_cpu": 1, + "actors": 1, + "client_concurrency": 16, + "tail_latency_slo_ms": 25.0, + "slo_max_rps": 750.0, + "slo_max_stage": "adjusting_001", + "binding_threshold": ["send-rate"], + "converged": True, + } + self.assertEqual({k: cap.get(k) for k in want}, want) + + def test_main_passthrough_servicedns_ca(self): + pem = "-----BEGIN CERTIFICATE-----\nMIIBfake\n-----END CERTIFICATE-----\n" + cases = [ + # label, content of the CA file (None: no file), want failure + ("bundle mounted", pem, None), + ("no bundle", None, "ValueError: servicedns CA bundle not found at "), + ("empty bundle", " \n", "ValueError: servicedns CA bundle at "), + ] + for label, content, want_failure in cases: + with self.subTest(label=label), tempfile.TemporaryDirectory() as tmp: + ca = Path(tmp) / "ca.crt" + if content is not None: + ca.write_text(content) + with patch("runner.SERVICEDNS_CA_CERT", str(ca)): + got, mocks = _run_main(Path(tmp), "passthrough", output=SAMPLE_OUTPUT) + status = json.loads((Path(tmp) / "status.json").read_text()) + if want_failure: + self.assertEqual(got, 1) + self.assertTrue(status["failures"][0].startswith(want_failure), status["failures"]) + mocks["popen"].assert_not_called() + continue + self.assertEqual(got, 0) + tpl = mocks["spec"].call_args[0][0]["nighthawk_traffic_template"] + tls = tpl["transport_socket"]["typed_config"]["common_tls_context"] + self.assertEqual(tls["validation_context"]["trusted_ca"], {"inline_string": pem}) + + def test_wait_for_tcp_returns_when_the_port_listens(self): + with socket.socket() as server: + server.bind(("127.0.0.1", 0)) + server.listen(1) + runner.wait_for_tcp("127.0.0.1", server.getsockname()[1], timeout_s=30.0) + + def test_wait_for_tcp_raises_after_the_limit(self): + clock = [0.0] + + def sleep(seconds): + clock[0] += seconds + + with ( + patch("runner.socket.create_connection", side_effect=OSError("refused")), + patch("runner.time.monotonic", side_effect=lambda: clock[0]), + patch("runner.time.sleep", side_effect=sleep), + self.assertRaisesRegex(RuntimeError, "Timed out waiting for 127.0.0.1:19980: refused"), + ): + runner.wait_for_tcp("127.0.0.1", 19980, timeout_s=30.0) + self.assertGreaterEqual(clock[0], 30.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/nighthawk-egress/tests/test_spec.py b/benchmarking/nighthawk-egress/tests/test_spec.py new file mode 100644 index 0000000000..507c03465d --- /dev/null +++ b/benchmarking/nighthawk-egress/tests/test_spec.py @@ -0,0 +1,82 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for benchmarking/nighthawk-egress/spec.py.""" + +from pathlib import Path +import sys +import unittest + +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +import spec as egress_spec + +FAKE_SERVICEDNS_CA = "-----BEGIN CERTIFICATE-----\nMIIBfake\n-----END CERTIFICATE-----\n" + + +class TestEgressSpec(unittest.TestCase): + def test_modes_uris_and_tls_contexts(self): + tpls = {} + for mode, uri in ( + ("http", "http://nighthawk-server.nighthawk.svc:80/"), + ("mitm", "https://nighthawk-server.nighthawk.svc:443/"), + ("passthrough", "https://nighthawk-server.nighthawk.svc:8443/"), + ): + with self.subTest(mode=mode): + tpl = egress_spec.build_egress_session_spec(mode, servicedns_ca_pem=FAKE_SERVICEDNS_CA)[ + "nighthawk_traffic_template" + ] + self.assertEqual(tpl["uri"], uri) + self.assertEqual(tpl["concurrency"], "16") + self.assertEqual(tpl["connections"], 16) + self.assertEqual(tpl["max_pending_requests"], 32) + self.assertTrue(tpl["open_loop"]) + tpls[mode] = tpl + self.assertNotIn("transport_socket", tpls["http"]) + self.assertEqual(tpls["mitm"]["transport_socket"], { + "name": "envoy.transport_sockets.tls", + "typed_config": { + "@type": "type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext", + "sni": "nighthawk-server.nighthawk.svc", + "common_tls_context": { + "alpn_protocols": ["http/1.1"], + "validation_context": { + "trusted_ca": {"filename": egress_spec.ACTOR_TRUST_BUNDLE}, + "match_typed_subject_alt_names": [ + {"san_type": "DNS", "matcher": {"exact": "nighthawk-server.nighthawk.svc"}}, + ], + }, + }, + }, + }) + passthrough_ctx = tpls["passthrough"]["transport_socket"]["typed_config"]["common_tls_context"] + self.assertEqual(passthrough_ctx["validation_context"]["trusted_ca"], {"inline_string": FAKE_SERVICEDNS_CA}) + + def test_passthrough_needs_the_servicedns_ca(self): + for pem in (None, "", " \n"): + with self.subTest(pem=pem), self.assertRaises(ValueError): + egress_spec.build_egress_session_spec("passthrough", servicedns_ca_pem=pem) + + def test_thresholds_and_step_controller(self): + s = egress_spec.build_egress_session_spec("mitm") + sc = s["step_controller_config"]["typed_config"] + self.assertAlmostEqual(sc["initial_value"], 31.25) + by_name = {t["metric_spec"]["metric_name"]: t["threshold_spec"]["scoring_function"]["typed_config"] for t in s["metric_thresholds"]} + self.assertEqual(set(by_name), {"success-rate", "send-rate", "latency-ns-mean-plus-2stdev"}) + self.assertAlmostEqual(by_name["latency-ns-mean-plus-2stdev"]["upper_threshold"], 25_000_000.0) + + +if __name__ == "__main__": + unittest.main() diff --git a/benchmarking/nighthawk-egress/traffic-driver-invoker.yaml b/benchmarking/nighthawk-egress/traffic-driver-invoker.yaml deleted file mode 100644 index 437f64cdfa..0000000000 --- a/benchmarking/nighthawk-egress/traffic-driver-invoker.yaml +++ /dev/null @@ -1,227 +0,0 @@ -# Copyright 2026 The Agent Substrate 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. - -# In-cluster Envoy proxy that listens for plaintext HTTP/1.1 and HTTP/2 -# (h2c/gRPC) on :19980, injects `ate-target-actor: nighthawk/tester` on every -# request, and forwards upstream over mTLS to -# atenet-router.ate-system.svc.cluster.local:443 using a SPIFFE client -# certificate issued by podidentity.podcert.ate.dev/identity. -# -# TODO(yanavlasov): this is a temporary workaround for nighthawk's cli's inability -# to add headers when invoking traffic driver gRPC service. So this Envoy adds the -# `ate-target-actor: nighthawk/tester` header so that cli can reach the traffic driver. -apiVersion: v1 -kind: ConfigMap -metadata: - name: traffic-driver-invoker - namespace: nighthawk -data: - envoy.yaml: | - # SDS requires a node id and cluster. - node: - id: traffic-driver-invoker - cluster: traffic-driver-invoker - - static_resources: - listeners: - - name: listener_http_19980 - address: - socket_address: - address: "::" - ipv4_compat: true - port_value: 19980 - listener_filters: - - name: envoy.filters.listener.http_inspector - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.listener.http_inspector.v3.HttpInspector - filter_chains: - - filters: - - name: envoy.filters.network.http_connection_manager - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager - stat_prefix: ingress_http_19980 - codec_type: AUTO - route_config: - name: local_route - request_headers_to_add: - - header: - key: ate-target-actor - value: nighthawk/tester - append_action: OVERWRITE_IF_EXISTS_OR_ADD - virtual_hosts: - - name: backend - domains: ["*"] - routes: - - match: - prefix: "/" - route: - cluster: atenet_router - timeout: 0s - http_filters: - - name: envoy.filters.http.router - typed_config: - "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router - - clusters: - - name: atenet_router - type: STRICT_DNS - connect_timeout: 5s - typed_extension_protocol_options: - envoy.extensions.upstreams.http.v3.HttpProtocolOptions: - "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions - use_downstream_protocol_config: - http_protocol_options: {} - http2_protocol_options: {} - transport_socket: - name: envoy.transport_sockets.tls - typed_config: - "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext - sni: atenet-router.ate-system.svc - common_tls_context: - tls_certificate_sds_secret_configs: - - name: podidentity_client_cert - sds_config: - resource_api_version: V3 - path_config_source: - path: /etc/envoy/sds-podidentity-cert.yaml - combined_validation_context: - default_validation_context: - match_typed_subject_alt_names: - - san_type: DNS - matcher: - exact: atenet-router.ate-system.svc - validation_context_sds_secret_config: - name: servicedns_validation_context - sds_config: - resource_api_version: V3 - path_config_source: - path: /etc/envoy/sds-servicedns-validation.yaml - load_assignment: - cluster_name: atenet_router - endpoints: - - lb_endpoints: - - endpoint: - address: - socket_address: - address: atenet-router.ate-system.svc.cluster.local - port_value: 443 - sds-podidentity-cert.yaml: | - resources: - - "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.Secret - name: podidentity_client_cert - tls_certificate: - certificate_chain: { filename: /run/podidentity.podcert.ate.dev/credential-bundle.pem } - private_key: { filename: /run/podidentity.podcert.ate.dev/credential-bundle.pem } - watched_directory: { path: /run/podidentity.podcert.ate.dev } - sds-servicedns-validation.yaml: | - resources: - - "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.Secret - name: servicedns_validation_context - validation_context: - trusted_ca: { filename: /run/servicedns.podcert.ate.dev/trust-bundle.pem } - watched_directory: { path: /run/servicedns.podcert.ate.dev } ---- -apiVersion: apps/v1 -kind: Deployment -metadata: - name: traffic-driver-invoker - namespace: nighthawk - labels: - app: traffic-driver-invoker -spec: - replicas: 1 - selector: - matchLabels: - app: traffic-driver-invoker - template: - metadata: - labels: - app: traffic-driver-invoker - spec: - securityContext: - runAsUser: 65532 - runAsGroup: 65532 - runAsNonRoot: true - fsGroup: 65532 - containers: - - name: envoy - # Same envoyproxy/envoy digest as cmd/dataplane/envoy/Dockerfile. - image: envoyproxy/envoy:v1.39.5@sha256:8fc594a5d85eb76dca24155cfb9208882406873932b20cf33649a0a611194c43 - command: - - /usr/local/bin/envoy - args: - - -c - - /etc/envoy/envoy.yaml - - --concurrency - - "1" - securityContext: - allowPrivilegeEscalation: false - readOnlyRootFilesystem: true - capabilities: - drop: - - ALL - ports: - - name: http - containerPort: 19980 - protocol: TCP - readinessProbe: - tcpSocket: - port: http - periodSeconds: 5 - volumeMounts: - - name: config - mountPath: /etc/envoy - readOnly: true - - name: podidentity - mountPath: /run/podidentity.podcert.ate.dev - readOnly: true - - name: servicedns-ca - mountPath: /run/servicedns.podcert.ate.dev - readOnly: true - volumes: - - name: config - configMap: - name: traffic-driver-invoker - - name: podidentity - projected: - sources: - - podCertificate: - signerName: podidentity.podcert.ate.dev/identity - keyType: ECDSAP256 - credentialBundlePath: credential-bundle.pem - - name: servicedns-ca - projected: - sources: - - clusterTrustBundle: - signerName: servicedns.podcert.ate.dev/identity - labelSelector: - matchLabels: - podcert.ate.dev/canarying: live - path: trust-bundle.pem ---- -apiVersion: v1 -kind: Service -metadata: - name: traffic-driver-invoker - namespace: nighthawk -spec: - type: ClusterIP - ipFamilyPolicy: PreferDualStack - selector: - app: traffic-driver-invoker - ports: - - name: http - port: 19980 - targetPort: http - protocol: TCP diff --git a/benchmarking/nighthawk-egress/traffic-driver-template.yaml.tmpl b/benchmarking/nighthawk-egress/traffic-driver-template.yaml.tmpl index 3df14b17bc..59dac5990c 100644 --- a/benchmarking/nighthawk-egress/traffic-driver-template.yaml.tmpl +++ b/benchmarking/nighthawk-egress/traffic-driver-template.yaml.tmpl @@ -61,7 +61,7 @@ volumes: # Sandbox size: headroom so the load generator is not the bottleneck. resources: limits: - cpuMillicores: 2000 - memoryBytes: 1073741824 # 1Gi + cpuMillicores: 16000 + memoryBytes: 8589934592 # 8Gi snapshotConfig: preferredFidelity: SNAPSHOT_FIDELITY_MEMORY diff --git a/benchmarking/nighthawk-egress/traffic-driver.yaml.tmpl b/benchmarking/nighthawk-egress/traffic-driver.yaml.tmpl index 67750489e2..f396bf1661 100644 --- a/benchmarking/nighthawk-egress/traffic-driver.yaml.tmpl +++ b/benchmarking/nighthawk-egress/traffic-driver.yaml.tmpl @@ -29,3 +29,8 @@ spec: workerImage: ko://go.ate.dev/substrate/cmd/ateworker-gvisor sandboxClasses: - name: gvisor + template: + resources: + requests: + cpu: "12" + memory: "8Gi" diff --git a/benchmarking/nighthawk-ingress/Dockerfile b/benchmarking/nighthawk-ingress/Dockerfile index 9cfbb836a8..6da41c14fd 100644 --- a/benchmarking/nighthawk-ingress/Dockerfile +++ b/benchmarking/nighthawk-ingress/Dockerfile @@ -52,7 +52,7 @@ RUN git init /src/envoy \ && git -C /src/envoy fetch --depth 1 https://github.com/envoyproxy/envoy "${ENVOY_COMMIT}" \ && git -C /src/envoy checkout FETCH_HEAD -COPY benchmarking/nighthawk-ingress/protogen/generate_descriptor.sh /gen.sh +COPY benchmarking/nighthawk_common/protogen/generate_descriptor.sh /gen.sh RUN bash /gen.sh /out/nighthawk.desc # --- Stage 2: ateapi Python clients ------------------------------------------ @@ -91,10 +91,10 @@ COPY --from=protogen /out/nighthawk.desc /app/nighthawk.desc COPY benchmarking/locust/common/__init__.py /app/common/__init__.py COPY benchmarking/locust/common/ateapi_channel.py /app/common/ateapi_channel.py COPY --from=ateprotos /out/ /app/common/ +COPY benchmarking/nighthawk_common /app/nighthawk_common COPY benchmarking/nighthawk-ingress/runner.py \ benchmarking/nighthawk-ingress/spec.py \ - benchmarking/nighthawk-ingress/output.py \ benchmarking/nighthawk-ingress/actors.py \ /app/ COPY benchmarking/nighthawk-ingress/tests /app/tests diff --git a/benchmarking/nighthawk-ingress/actors.py b/benchmarking/nighthawk-ingress/actors.py index 22398e8d24..7a16b0c890 100644 --- a/benchmarking/nighthawk-ingress/actors.py +++ b/benchmarking/nighthawk-ingress/actors.py @@ -30,7 +30,6 @@ from common import ateapi_pb2_grpc from common.ateapi_channel import CA_FILE, CRED_BUNDLE, SERVER_NAME, ateapi_channel -import spec as spec_mod ATEAPI_HOST = "api.ate-system.svc.cluster.local:443" TOKEN_FILE = "/run/ateapi-token/token" diff --git a/benchmarking/nighthawk-ingress/runner.py b/benchmarking/nighthawk-ingress/runner.py index c746f6933b..f5bf310f20 100644 --- a/benchmarking/nighthawk-ingress/runner.py +++ b/benchmarking/nighthawk-ingress/runner.py @@ -30,7 +30,6 @@ import json import os import re -import shutil import socket import subprocess import sys @@ -41,8 +40,9 @@ from typing import IO, TextIO import actors -import output as output_mod +from nighthawk_common import output as output_mod import spec as spec_mod +from nighthawk_common import spec as common_spec NIGHTHAWK_SERVICE = "nighthawk_service" ADAPTIVE_CLIENT = "nighthawk_adaptive_load_client" @@ -69,6 +69,12 @@ def parse_args() -> argparse.Namespace: required=True, help="Root destination (gs://bucket/path or local path)", ) + p.add_argument( + "--run-ts", + type=int, + default=None, + help="Unix seconds that name where the run is stored, shared by every run of one invocation. Default: now", + ) p.add_argument("--envoy-cpu", required=True, type=int, dest="envoy_cpu") p.add_argument("--actors", type=int, default=100) # Event loops and per-loop pools are sized so the client never binds @@ -179,25 +185,6 @@ def run_adaptive_client( return proc.wait() -def upload_to_gcs(local_path: Path, gcs_uri: str) -> None: - # Imported here so non-GCS use doesn't require google-cloud-storage. - from google.cloud import storage - - bucket_name, _, blob_path = gcs_uri[len("gs://"):].partition("/") - storage.Client().bucket(bucket_name).blob(blob_path).upload_from_filename( - str(local_path) - ) - - -def upload(src: Path, dest: str) -> None: - if dest.startswith("gs://"): - upload_to_gcs(src, dest) - else: - dest_path = Path(dest) - dest_path.parent.mkdir(parents=True, exist_ok=True) - shutil.copy(src, dest_path) - - def log_run_config(args: argparse.Namespace, prefix: str, logs: TextIO) -> None: lines = [ "==== Run config ====", @@ -232,9 +219,10 @@ def main() -> None: work_dir = Path(f"/tmp/{now.strftime('%Y%m%dT%H%M%SZ')}-nighthawk-runner") work_dir.mkdir(parents=True, exist_ok=True) + stored_at = now if args.run_ts is None else datetime.fromtimestamp(args.run_ts, timezone.utc) prefix = ( f"{args.dest.rstrip('/')}/runs/{args.name}" - f"/run_date={now.strftime('%Y-%m-%d')}/run_ts={int(now.timestamp())}" + f"/run_date={stored_at.strftime('%Y-%m-%d')}/run_ts={int(stored_at.timestamp())}" f"/run_tag={args.tag}" ) @@ -293,7 +281,7 @@ def main() -> None: ), ) spec_path.write_text( - spec_mod.spec_dict_to_textproto(spec_dict, DESC_PATH) + common_spec.spec_dict_to_textproto(spec_dict, DESC_PATH) ) tee(logs, f"Wrote spec to {spec_path}") @@ -302,17 +290,11 @@ def main() -> None: tee(logs, f"{ADAPTIVE_CLIENT} exited with code {adaptive_exit}") if output_path.exists(): - output_dict = output_mod.parse_output_textproto( - output_path.read_text(), DESC_PATH - ) - results_path.write_text(json.dumps(output_dict, indent=2)) - rows = output_mod.stage_rows(output_dict) - output_mod.write_jsonl( - output_mod.stats_records(rows, args.tag, args.name), - stats_path, - ) - summary = output_mod.capacity_summary( - output_dict, + summary, testing_stage_parsed = output_mod.write_artifacts( + output_path, + DESC_PATH, + tag=args.tag, + name=args.name, envoy_cpu=args.envoy_cpu, actors=args.actors, client_concurrency=args.client_concurrency, @@ -322,10 +304,6 @@ def main() -> None: else None ), ) - capacity_path.write_text(json.dumps(summary, indent=2)) - testing_stage_parsed = any( - r["stage"] == "testing" for r in rows - ) tee(logs, f"Capacity summary: {json.dumps(summary)}") else: tee(logs, f"No output file at {output_path}") @@ -358,29 +336,20 @@ def main() -> None: ) ) - upload_ok = True - files = [ - (status_path, "status.json"), - (logs_path, "logs.txt"), - (spec_path, "spec.textproto"), - (output_path, "output.textproto"), - (results_path, "results.json"), - (stats_path, "stats.jsonl"), - (capacity_path, "capacity.json"), - ] - for src, basename in files: - if not src.exists(): - print(f"Skipping {src}: not produced", flush=True) - continue - dest = f"{prefix}/{basename}" - try: - upload(src, dest) - print(f"Uploaded {src} -> {dest}", flush=True) - except Exception as e: - print(f"Upload of {src} failed: {e}", flush=True) - upload_ok = False + upload_failures = output_mod.upload_files( + [ + status_path, + logs_path, + spec_path, + output_path, + results_path, + stats_path, + capacity_path, + ], + prefix, + ) - sys.exit(0 if (converged and upload_ok) else 1) + sys.exit(0 if (converged and not upload_failures) else 1) if __name__ == "__main__": diff --git a/benchmarking/nighthawk-ingress/spec.py b/benchmarking/nighthawk-ingress/spec.py index 3bf435ae3d..32cac09100 100644 --- a/benchmarking/nighthawk-ingress/spec.py +++ b/benchmarking/nighthawk-ingress/spec.py @@ -12,80 +12,24 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""AdaptiveLoadSessionSpec builder. +"""AdaptiveLoadSessionSpec builder for the ingress router capacity benchmark. Specs are plain dicts, validated and rendered to textproto through the -FileDescriptorSet built by protogen/generate_descriptor.sh — field names -are checked against the real Nighthawk protos at spec-build time. +FileDescriptorSet built by nighthawk_common/protogen/generate_descriptor.sh — +field names are checked against the real Nighthawk protos at spec-build time. """ -SPEC_MESSAGE = "nighthawk.adaptive_load.AdaptiveLoadSessionSpec" -OUTPUT_MESSAGE = "nighthawk.adaptive_load.AdaptiveLoadSessionOutput" - -# Registered plugin names: adaptive-load plugins use underscores upstream, -# request-source plugins use hyphens. -STEP_CONTROLLER_PLUGIN = "nighthawk.exponential_search" -STEP_CONTROLLER_TYPE_URL = ( - "type.googleapis.com/nighthawk.adaptive_load.ExponentialSearchStepControllerConfig" -) -BINARY_SCORING_PLUGIN = "nighthawk.binary_scoring" -BINARY_SCORING_TYPE_URL = ( - "type.googleapis.com/nighthawk.adaptive_load.BinaryScoringFunctionConfig" -) -BUILTIN_METRICS_PLUGIN = "nighthawk.builtin" -REQUEST_SOURCE_PLUGIN = "nighthawk.in-line-options-list-request-source-plugin" -REQUEST_SOURCE_TYPE_URL = ( - "type.googleapis.com/nighthawk.request_source.InLineOptionsListRequestSourceConfig" +from nighthawk_common.spec import ( + PERMISSIVE_FAILURE_PREDICATES, + REQUEST_SOURCE_PLUGIN, + REQUEST_SOURCE_TYPE_URL, + build_session_spec, ) ROUTER_SNI = "atenet-router.ate-system.svc" CA_FILE = "/run/servicedns-ca/ca.crt" CRED_BUNDLE = "/run/podidentity.podcert.ate.dev/credential-bundle.pem" -# The default failure predicates (all 0) abort an execution on the first -# 4xx/5xx; measuring periods must instead run to completion so overload -# scores as degraded success-rate. All five defaults overridden. -PERMISSIVE_FAILURE_PREDICATES = { - "benchmark.http_4xx": "1000000000", - "benchmark.http_5xx": "1000000000", - "benchmark.pool_connection_failure": "1000000000", - "benchmark.stream_resets": "1000000000", - "requestsource.upstream_rq_5xx": "1000000000", -} - -INFORMATIONAL_METRICS = ( - "attempted-rps", - "achieved-rps", - "send-rate", - "latency-ns-mean", - "latency-ns-mean-plus-2stdev", -) - - -def _metric_spec(name: str) -> dict: - return {"metric_name": name, "metrics_plugin_name": BUILTIN_METRICS_PLUGIN} - - -def _binary_threshold( - metric_name: str, - lower_threshold: float | None = None, - upper_threshold: float | None = None, -) -> dict: - config: dict = {"@type": BINARY_SCORING_TYPE_URL} - if lower_threshold is not None: - config["lower_threshold"] = lower_threshold - if upper_threshold is not None: - config["upper_threshold"] = upper_threshold - return { - "metric_spec": _metric_spec(metric_name), - "threshold_spec": { - "scoring_function": { - "name": BINARY_SCORING_PLUGIN, - "typed_config": config, - }, - }, - } - def build_spec_dict( *, @@ -105,13 +49,10 @@ def build_spec_dict( tail_latency_slo_ms: float | None = None, benchmark_cooldown_s: int = 5, ) -> dict: - """Assemble the AdaptiveLoadSessionSpec as a JSON-shaped dict. + """Assemble the AdaptiveLoadSessionSpec as a JSON-shaped dict.""" + if not uri.startswith("https://"): + raise ValueError(f"router URI must use https://, got {uri!r}") - The controller varies the *per-worker* requests_per_second, so - initial_value = initial_total_rps / client_concurrency. The template - must not set duration (the controller rejects it); open_loop is forced - true by the controller. - """ request_variants = [ { "request_method": "POST", @@ -127,28 +68,6 @@ def build_spec_dict( } for actor_name in actor_names ] - # Threshold roles: tail latency (mean+2stdev, ~p95 proxy — no true - # percentiles in the builtin adaptive metrics) is the SLO bound; - # success-rate catches fast-error saturation (503/504) that latency and - # send-rate miss; send-rate is the open-loop backstop — skipped - # requests are neither failures nor latency samples, so without it the - # search ramps unboundedly. - thresholds = [ - _binary_threshold("success-rate", lower_threshold=success_rate_threshold) - ] - if send_rate_threshold is not None: - thresholds.append( - _binary_threshold("send-rate", lower_threshold=send_rate_threshold) - ) - if tail_latency_slo_ms is not None: - thresholds.append( - _binary_threshold( - "latency-ns-mean-plus-2stdev", - upper_threshold=tail_latency_slo_ms * 1_000_000.0, - ) - ) - if not uri.startswith("https://"): - raise ValueError(f"router URI must use https://, got {uri!r}") traffic_template: dict = { "uri": uri, @@ -189,61 +108,16 @@ def build_spec_dict( }, }, } - return { - "nighthawk_traffic_template": traffic_template, - "metric_thresholds": thresholds, - "informational_metric_specs": [ - _metric_spec(m) for m in INFORMATIONAL_METRICS - ], - "step_controller_config": { - "name": STEP_CONTROLLER_PLUGIN, - "typed_config": { - "@type": STEP_CONTROLLER_TYPE_URL, - "initial_value": max(1.0, initial_total_rps / client_concurrency), - "exponential_factor": exponential_factor, - }, - }, - "measuring_period": f"{measuring_period_s}s", - "convergence_deadline": f"{convergence_deadline_s}s", - "testing_stage_duration": f"{testing_stage_duration_s}s", - "benchmark_cooldown_duration": f"{benchmark_cooldown_s}s", - } - - -# protobuf imports are deferred: the dict builder above must work without -# protobuf installed. - - -def load_pool(desc_path: str): - from google.protobuf import descriptor_pb2 - from google.protobuf import descriptor_pool - - pool = descriptor_pool.DescriptorPool() - fds = descriptor_pb2.FileDescriptorSet() - with open(desc_path, "rb") as f: - fds.ParseFromString(f.read()) - for file_proto in fds.file: - pool.Add(file_proto) - return pool - - -def message_class(pool, full_name: str): - from google.protobuf import message_factory - - return message_factory.GetMessageClass(pool.FindMessageTypeByName(full_name)) - - -def spec_dict_to_textproto(spec_dict: dict, desc_path: str) -> str: - """Validate the dict against the real protos and render textproto. - - No descriptor_pool for MessageToString: expanded-form Any is not - parseable by nighthawk_adaptive_load_client for plugin types it does - not link (the request-source config); raw type_url/value form is. - """ - from google.protobuf import json_format - from google.protobuf import text_format - - pool = load_pool(desc_path) - msg = message_class(pool, SPEC_MESSAGE)() - json_format.ParseDict(spec_dict, msg, descriptor_pool=pool) - return text_format.MessageToString(msg) + return build_session_spec( + traffic_template, + client_concurrency=client_concurrency, + initial_total_rps=initial_total_rps, + exponential_factor=exponential_factor, + measuring_period_s=measuring_period_s, + convergence_deadline_s=convergence_deadline_s, + testing_stage_duration_s=testing_stage_duration_s, + success_rate_threshold=success_rate_threshold, + send_rate_threshold=send_rate_threshold, + tail_latency_slo_ms=tail_latency_slo_ms, + benchmark_cooldown_s=benchmark_cooldown_s, + ) diff --git a/benchmarking/nighthawk-ingress/tests/test_output.py b/benchmarking/nighthawk-ingress/tests/test_output.py index 24709e7c54..236e0e6b8b 100644 --- a/benchmarking/nighthawk-ingress/tests/test_output.py +++ b/benchmarking/nighthawk-ingress/tests/test_output.py @@ -18,12 +18,15 @@ preserving_proto_field_name=True) produces from a real session output (uint64 counters as strings, Durations as '30s' strings).""" +import json import sys from pathlib import Path -sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +import pytest -import output as output_mod +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from nighthawk_common import output as output_mod def benchmark_result( @@ -196,8 +199,43 @@ def test_capacity_summary_no_testing_stage(): assert "max_total_rps" not in summary +@pytest.mark.parametrize("testing_stage", [True, False]) +def test_write_artifacts(tmp_path, monkeypatch, testing_stage): + session = dict(SESSION) + if not testing_stage: + del session["testing_stage_result"] + monkeypatch.setattr(output_mod, "parse_output_textproto", lambda text, desc_path: session) + output_path = tmp_path / "output.textproto" + output_path.write_text("textproto") + + # The keyword set of the nighthawk-ingress runner, plus extra. + summary, got_testing_stage = output_mod.write_artifacts( + output_path, + "nighthawk.desc", + tag="abc123", + name="cap2", + envoy_cpu=4, + actors=100, + client_concurrency=16, + tail_latency_slo_ms=None, + extra={"mode": "http"}, + ) + + assert got_testing_stage is testing_stage + assert summary["mode"] == "http" + results = (tmp_path / "results.json").read_text() + assert results.endswith("}\n") + assert json.loads(results) == session + capacity = (tmp_path / "capacity.json").read_text() + assert capacity.endswith("}\n") + assert json.loads(capacity) == summary + stats = [json.loads(line) for line in (tmp_path / "stats.jsonl").read_text().splitlines()] + assert [rec["metric"] for rec in stats] == [ + "nighthawk_adjusting_000", + "nighthawk_adjusting_001", + ] + (["nighthawk_testing"] if testing_stage else []) + assert {(rec["tag"], rec["test_name"]) for rec in stats} == {("abc123", "cap2")} + + if __name__ == "__main__": - for fn_name, fn in sorted(dict(globals()).items()): - if fn_name.startswith("test_") and callable(fn): - fn() - print(f"PASS {fn_name}") + sys.exit(pytest.main([__file__])) diff --git a/benchmarking/nighthawk-ingress/tests/test_spec.py b/benchmarking/nighthawk-ingress/tests/test_spec.py index ef58b1151d..036437bcff 100644 --- a/benchmarking/nighthawk-ingress/tests/test_spec.py +++ b/benchmarking/nighthawk-ingress/tests/test_spec.py @@ -26,8 +26,10 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) import spec as spec_mod +from nighthawk_common import spec as common_spec def build(**overrides): @@ -103,7 +105,7 @@ def test_actor_reference_rotation_covers_all_actors(): actor_names = [f"sb-{i}" for i in range(5)] spec = build(actor_names=actor_names) plugin = spec["nighthawk_traffic_template"]["request_source_plugin_config"] - assert plugin["name"] == spec_mod.REQUEST_SOURCE_PLUGIN + assert plugin["name"] == common_spec.REQUEST_SOURCE_PLUGIN options = plugin["typed_config"]["options_list"]["options"] got = [ {header["header"]["key"]: header["header"]["value"] for header in o["request_headers"]} @@ -123,7 +125,7 @@ def test_actor_reference_rotation_covers_all_actors(): def test_initial_rps_is_per_worker(): spec = build(initial_total_rps=1000, client_concurrency=4) controller = spec["step_controller_config"] - assert controller["name"] == spec_mod.STEP_CONTROLLER_PLUGIN + assert controller["name"] == common_spec.STEP_CONTROLLER_PLUGIN assert controller["typed_config"]["initial_value"] == 250.0 @@ -136,7 +138,7 @@ def test_thresholds_and_durations(): ] assert names == ["success-rate", "send-rate"] scoring = spec["metric_thresholds"][0]["threshold_spec"]["scoring_function"] - assert scoring["name"] == spec_mod.BINARY_SCORING_PLUGIN + assert scoring["name"] == common_spec.BINARY_SCORING_PLUGIN assert scoring["typed_config"]["lower_threshold"] == 0.999 assert spec["measuring_period"] == "10s" assert spec["convergence_deadline"] == "600s" @@ -165,9 +167,9 @@ def test_spec_round_trips_through_real_protos(): return from google.protobuf import text_format - text = spec_mod.spec_dict_to_textproto(build(tail_latency_slo_ms=25), desc) - pool = spec_mod.load_pool(desc) - msg = spec_mod.message_class(pool, spec_mod.SPEC_MESSAGE)() + text = common_spec.spec_dict_to_textproto(build(tail_latency_slo_ms=25), desc) + pool = common_spec.load_pool(desc) + msg = common_spec.message_class(pool, common_spec.SPEC_MESSAGE)() text_format.Parse(text, msg, descriptor_pool=pool) assert msg.nighthawk_traffic_template.concurrency.value == "4" assert msg.measuring_period.seconds == 10 diff --git a/benchmarking/nighthawk-ingress/tests/test_upload.py b/benchmarking/nighthawk-ingress/tests/test_upload.py new file mode 100644 index 0000000000..fc4a9ad75a --- /dev/null +++ b/benchmarking/nighthawk-ingress/tests/test_upload.py @@ -0,0 +1,69 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Unit tests for upload() and upload_files() of nighthawk_common/output.py. They use pytest fixtures.""" + +import sys +from pathlib import Path +from unittest import mock + +sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + +from nighthawk_common.output import upload, upload_files + + +def test_upload_copies_to_a_local_path(tmp_path): + src = tmp_path / "capacity.json" + src.write_text("{}") + dest = tmp_path / "runs" / "name" / "capacity.json" + upload(src, str(dest)) + assert dest.read_text() == "{}" + + +def test_upload_sends_a_gs_uri_to_its_bucket(tmp_path): + src = tmp_path / "capacity.json" + src.write_text("{}") + with mock.patch("google.cloud.storage.Client") as client: + upload(src, "gs://bucket/path/runs/name/capacity.json") + bucket = client.return_value.bucket + bucket.assert_called_once_with("bucket") + bucket.return_value.blob.assert_called_once_with("path/runs/name/capacity.json") + bucket.return_value.blob.return_value.upload_from_filename.assert_called_once_with(str(src)) + + +def test_upload_files_goes_on_after_a_missing_file_and_a_failure(tmp_path, capsys): + first, failing, last = (tmp_path / name for name in ("status.json", "results.json", "capacity.json")) + for src in (first, failing, last): + src.write_text("{}") + missing = tmp_path / "output.textproto" + + def fake_upload(src, dest): + if src == failing: + raise OSError("bucket gone") + + with mock.patch("nighthawk_common.output.upload", side_effect=fake_upload) as fake: + failures = upload_files([first, missing, failing, last], "gs://bucket/run") + + assert failures == ["upload of results.json failed: bucket gone"] + assert [call.args for call in fake.call_args_list] == [ + (first, "gs://bucket/run/status.json"), + (failing, "gs://bucket/run/results.json"), + (last, "gs://bucket/run/capacity.json"), + ] + assert capsys.readouterr().out.splitlines() == [ + f"Uploaded {first} -> gs://bucket/run/status.json", + f"Skipping {missing}: not produced", + f"Upload of {failing} failed: bucket gone", + f"Uploaded {last} -> gs://bucket/run/capacity.json", + ] diff --git a/benchmarking/nighthawk_common/__init__.py b/benchmarking/nighthawk_common/__init__.py new file mode 100644 index 0000000000..7cb8bca5cd --- /dev/null +++ b/benchmarking/nighthawk_common/__init__.py @@ -0,0 +1,13 @@ +# Copyright 2026 The Agent Substrate 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. diff --git a/benchmarking/nighthawk-ingress/output.py b/benchmarking/nighthawk_common/output.py similarity index 79% rename from benchmarking/nighthawk-ingress/output.py rename to benchmarking/nighthawk_common/output.py index 46bee72949..087eaec8c8 100644 --- a/benchmarking/nighthawk-ingress/output.py +++ b/benchmarking/nighthawk_common/output.py @@ -13,7 +13,7 @@ # limitations under the License. """Transforms Nighthawk's AdaptiveLoadSessionOutput textproto into the run -artifacts runner.py uploads: +artifacts with write_artifacts(), and uploads them with upload_files(): results.json parse_output_textproto() — the session as JSON, 1:1. stats.jsonl stage_rows() -> stats_records() — one record per stage, @@ -29,6 +29,10 @@ import json import re +import shutil +from pathlib import Path + +from nighthawk_common import spec as spec_mod # Statistic carrying client-measured end-to-end request latency. LATENCY_STAT_ID = "benchmark_http_client.request_to_response" @@ -70,8 +74,6 @@ def parse_output_textproto(text: str, desc_path: str) -> dict: from google.protobuf import json_format from google.protobuf import text_format - import spec as spec_mod - # Drop the client's leading "goo.gle/debugproto" marker line(s). lines = text.splitlines() start = 0 @@ -260,3 +262,72 @@ def write_jsonl(records: list[dict], path) -> None: with open(path, "w") as f: for record in records: f.write(json.dumps(record) + "\n") + + +def write_artifacts( + output_path: Path, + desc_path: str, + *, + tag: str, + name: str, + envoy_cpu: int, + actors: int, + client_concurrency: int | None, + tail_latency_slo_ms: float | None, + extra: dict | None = None, +) -> tuple[dict, bool]: + """Writes results.json, stats.jsonl and capacity.json next to the client + output at output_path, with extra merged into the capacity summary. + Returns the summary and whether the output has a testing stage.""" + work_dir = output_path.parent + output_dict = parse_output_textproto(output_path.read_text(), desc_path) + (work_dir / "results.json").write_text(json.dumps(output_dict, indent=2) + "\n") + rows = stage_rows(output_dict) + write_jsonl(stats_records(rows, tag, name), work_dir / "stats.jsonl") + summary = capacity_summary( + output_dict, + envoy_cpu=envoy_cpu, + actors=actors, + client_concurrency=client_concurrency, + tail_latency_slo_ms=tail_latency_slo_ms, + ) + summary.update(extra or {}) + (work_dir / "capacity.json").write_text(json.dumps(summary, indent=2) + "\n") + return summary, any(row["stage"] == "testing" for row in rows) + + +def upload_to_gcs(local_path: Path, gcs_uri: str) -> None: + # Imported here so non-GCS use doesn't require google-cloud-storage. + from google.cloud import storage + + bucket_name, _, blob_path = gcs_uri[len("gs://"):].partition("/") + storage.Client().bucket(bucket_name).blob(blob_path).upload_from_filename( + str(local_path) + ) + + +def upload(src: Path, dest: str) -> None: + if dest.startswith("gs://"): + upload_to_gcs(src, dest) + else: + dest_path = Path(dest) + dest_path.parent.mkdir(parents=True, exist_ok=True) + shutil.copy(src, dest_path) + + +def upload_files(paths: list[Path], prefix: str) -> list[str]: + """Uploads each path that exists to / and prints one line + per path. Returns one line per failed upload.""" + failures = [] + for src in paths: + if not src.exists(): + print(f"Skipping {src}: not produced", flush=True) + continue + dest = f"{prefix}/{src.name}" + try: + upload(src, dest) + print(f"Uploaded {src} -> {dest}", flush=True) + except Exception as e: + print(f"Upload of {src} failed: {e}", flush=True) + failures.append(f"upload of {src.name} failed: {e}") + return failures diff --git a/benchmarking/nighthawk-ingress/protogen/generate_descriptor.sh b/benchmarking/nighthawk_common/protogen/generate_descriptor.sh similarity index 100% rename from benchmarking/nighthawk-ingress/protogen/generate_descriptor.sh rename to benchmarking/nighthawk_common/protogen/generate_descriptor.sh diff --git a/benchmarking/nighthawk_common/spec.py b/benchmarking/nighthawk_common/spec.py new file mode 100644 index 0000000000..14584a0560 --- /dev/null +++ b/benchmarking/nighthawk_common/spec.py @@ -0,0 +1,180 @@ +# Copyright 2026 The Agent Substrate 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. + +"""Shared AdaptiveLoadSessionSpec builder and descriptor-pool textproto serializer.""" + + +SPEC_MESSAGE = "nighthawk.adaptive_load.AdaptiveLoadSessionSpec" +OUTPUT_MESSAGE = "nighthawk.adaptive_load.AdaptiveLoadSessionOutput" + +# Registered plugin names: adaptive-load plugins use underscores upstream, +# request-source plugins use hyphens. +STEP_CONTROLLER_PLUGIN = "nighthawk.exponential_search" +STEP_CONTROLLER_TYPE_URL = ( + "type.googleapis.com/nighthawk.adaptive_load.ExponentialSearchStepControllerConfig" +) +BINARY_SCORING_PLUGIN = "nighthawk.binary_scoring" +BINARY_SCORING_TYPE_URL = ( + "type.googleapis.com/nighthawk.adaptive_load.BinaryScoringFunctionConfig" +) +BUILTIN_METRICS_PLUGIN = "nighthawk.builtin" +REQUEST_SOURCE_PLUGIN = "nighthawk.in-line-options-list-request-source-plugin" +REQUEST_SOURCE_TYPE_URL = ( + "type.googleapis.com/nighthawk.request_source.InLineOptionsListRequestSourceConfig" +) + +# The default failure predicates (all 0) abort an execution on the first +# 4xx/5xx; measuring periods must instead run to completion so overload +# scores as degraded success-rate. All five defaults overridden. +PERMISSIVE_FAILURE_PREDICATES = { + "benchmark.http_4xx": "1000000000", + "benchmark.http_5xx": "1000000000", + "benchmark.pool_connection_failure": "1000000000", + "benchmark.stream_resets": "1000000000", + "requestsource.upstream_rq_5xx": "1000000000", +} + +INFORMATIONAL_METRICS = ( + "attempted-rps", + "achieved-rps", + "send-rate", + "latency-ns-mean", + "latency-ns-mean-plus-2stdev", +) + + +def _metric_spec(name: str) -> dict: + return {"metric_name": name, "metrics_plugin_name": BUILTIN_METRICS_PLUGIN} + + +def _binary_threshold( + metric_name: str, + lower_threshold: float | None = None, + upper_threshold: float | None = None, +) -> dict: + config: dict = {"@type": BINARY_SCORING_TYPE_URL} + if lower_threshold is not None: + config["lower_threshold"] = lower_threshold + if upper_threshold is not None: + config["upper_threshold"] = upper_threshold + return { + "metric_spec": _metric_spec(metric_name), + "threshold_spec": { + "scoring_function": { + "name": BINARY_SCORING_PLUGIN, + "typed_config": config, + }, + }, + } + + +def build_session_spec( + traffic_template: dict, + *, + client_concurrency: int, + initial_total_rps: int, + exponential_factor: float, + measuring_period_s: int, + convergence_deadline_s: int, + testing_stage_duration_s: int, + success_rate_threshold: float, + send_rate_threshold: float | None = 0.9, + tail_latency_slo_ms: float | None = None, + benchmark_cooldown_s: int = 5, +) -> dict: + """Wrap a traffic_template dict in an AdaptiveLoadSessionSpec dict. + + The controller varies the per-worker requests_per_second, so + initial_value = initial_total_rps / client_concurrency. The template + must not set duration (the controller rejects it); open_loop is forced + true by the controller. + """ + # Threshold roles: tail latency (mean+2stdev, ~p95 proxy — no true + # percentiles in the builtin adaptive metrics) is the SLO bound; + # success-rate catches fast-error saturation (503/504) that latency and + # send-rate miss; send-rate is the open-loop backstop — skipped + # requests are neither failures nor latency samples, so without it the + # search ramps unboundedly. + thresholds = [ + _binary_threshold("success-rate", lower_threshold=success_rate_threshold) + ] + if send_rate_threshold is not None: + thresholds.append( + _binary_threshold("send-rate", lower_threshold=send_rate_threshold) + ) + if tail_latency_slo_ms is not None: + thresholds.append( + _binary_threshold( + "latency-ns-mean-plus-2stdev", + upper_threshold=tail_latency_slo_ms * 1_000_000.0, + ) + ) + return { + "nighthawk_traffic_template": traffic_template, + "metric_thresholds": thresholds, + "informational_metric_specs": [ + _metric_spec(m) for m in INFORMATIONAL_METRICS + ], + "step_controller_config": { + "name": STEP_CONTROLLER_PLUGIN, + "typed_config": { + "@type": STEP_CONTROLLER_TYPE_URL, + "initial_value": max(1.0, initial_total_rps / client_concurrency), + "exponential_factor": exponential_factor, + }, + }, + "measuring_period": f"{measuring_period_s}s", + "convergence_deadline": f"{convergence_deadline_s}s", + "testing_stage_duration": f"{testing_stage_duration_s}s", + "benchmark_cooldown_duration": f"{benchmark_cooldown_s}s", + } + + +# protobuf imports are deferred: the dict builder above must work without +# protobuf installed. + + +def load_pool(desc_path: str): + from google.protobuf import descriptor_pb2 + from google.protobuf import descriptor_pool + + pool = descriptor_pool.DescriptorPool() + fds = descriptor_pb2.FileDescriptorSet() + with open(desc_path, "rb") as f: + fds.ParseFromString(f.read()) + for file_proto in fds.file: + pool.Add(file_proto) + return pool + + +def message_class(pool, full_name: str): + from google.protobuf import message_factory + + return message_factory.GetMessageClass(pool.FindMessageTypeByName(full_name)) + + +def spec_dict_to_textproto(spec_dict: dict, desc_path: str) -> str: + """Validate the dict against the real protos and render textproto. + + No descriptor_pool for MessageToString: expanded-form Any is not + parseable by nighthawk_adaptive_load_client for plugin types it does + not link (the request-source config); raw type_url/value form is. + """ + from google.protobuf import json_format + from google.protobuf import text_format + + pool = load_pool(desc_path) + msg = message_class(pool, SPEC_MESSAGE)() + json_format.ParseDict(spec_dict, msg, descriptor_pool=pool) + return text_format.MessageToString(msg) diff --git a/benchmarking/telemetry/README.md b/benchmarking/telemetry/README.md index c8492c712c..89f18b9e32 100644 --- a/benchmarking/telemetry/README.md +++ b/benchmarking/telemetry/README.md @@ -46,9 +46,9 @@ go run ./cmd/ate-setup deploy ate-system \ `--otlp-endpoint` patches the `ate-otel-config` ConfigMap and restarts the workloads that read it. One patch is sufficient for `ateapi`, `ate-controller`, -`atelet`, `atenet-router`, and `atenet-egress`, because each one reads the -ConfigMap through `envFrom`. `ate-controller` also copies the values to the -worker pods that it creates. +`atelet`, `atenet-router`, `atenet-egress`, and `k8s-credential-provider`, +because each one reads the ConfigMap through `envFrom`. `ate-controller` also +copies the values to the worker pods that it creates. The actor containers are different. Substrate puts no OTLP configuration in them, thus they use the `env` of the ActorTemplate: diff --git a/benchmarking/workloads/deploy.sh b/benchmarking/workloads/deploy.sh index 74b41ed589..04ee7d2a2e 100755 --- a/benchmarking/workloads/deploy.sh +++ b/benchmarking/workloads/deploy.sh @@ -18,8 +18,9 @@ set -o errexit -o nounset -o pipefail ROOT="$(git rev-parse --show-toplevel)" cd "${ROOT}" -# Source the environment variables if configured -if [[ -f .ate-dev-env.sh ]]; then +# Source the environment variables if configured, like the hack/ scripts; +# set NO_DEV_ENV to skip this and take every setting from the caller. +if [[ -f .ate-dev-env.sh ]] && [[ -z "${NO_DEV_ENV:-}" ]]; then source .ate-dev-env.sh fi @@ -130,15 +131,8 @@ resolve_otlp_endpoint() { # kubectl-ate runs once per poll while waiting for the golden snapshots; # build_kubectl_ate builds it once up front instead of paying the `go run` # toolchain startup on every call. -KUBECTL_ATE_BIN="" - -build_kubectl_ate() { - local dir - dir="$(mktemp -d)" - trap 'rm -rf '"${dir}" EXIT - KUBECTL_ATE_BIN="${dir}/kubectl-ate" - go build -o "${KUBECTL_ATE_BIN}" ./cmd/kubectl-ate -} +# shellcheck source=benchmarking/lib/kubectl-ate.sh +source "${ROOT}/benchmarking/lib/kubectl-ate.sh" run_kubectl_ate() { "${KUBECTL_ATE_BIN}" "$@" @@ -239,6 +233,10 @@ wait_templates_ready() { for template in "${TEMPLATES[@]}"; do echo "Waiting for the benchmark-workloads/${template} golden snapshot..." wait_actortemplate_ready benchmark-workloads "${template}" "${WAIT_TIMEOUT_SECS}" + # Announce success explicitly: without this the last line of a completed + # deploy is identical to the last line of one that is still blocked, which + # makes a finished run indistinguishable from a hung one in a log. + echo "Golden snapshot ready for benchmark-workloads/${template}." done } @@ -300,8 +298,6 @@ deploy() { echo "Error: --fake-atelet-env needs substrate installed with --fake-data-plane" >&2 exit 1 fi - ACTOR_CPU_MILLICORES="$(cpu_millicores "${ACTOR_CPU}")" - ACTOR_MEMORY_BYTES="$(memory_bytes "${ACTOR_MEMORY}")" echo "Deploying workloads (worker_count=${WORKER_COUNT}, actor_memory=${ACTOR_MEMORY}, actor_cpu=${ACTOR_CPU}, worker_memory=${WORKER_MEMORY:-unset}, storage_class=${STORAGE_CLASS_NAME:-none}, otlp_endpoint=${OTLP_ENDPOINT})..." substitute "${POOL_MANIFEST}" | hack/run-tool.sh ko apply -f - echo "Waiting for worker pool to be ready (timeout: ${WAIT_TIMEOUT_SECS}s)..." @@ -491,6 +487,11 @@ for entry in "${FAKE_ATELET_ENV[@]}"; do fi done +# substitute fills these into every manifest, the pool's included, so delete +# needs them too. +ACTOR_CPU_MILLICORES="$(cpu_millicores "${ACTOR_CPU}")" +ACTOR_MEMORY_BYTES="$(memory_bytes "${ACTOR_MEMORY}")" + if [[ "${action}" == "deploy" ]]; then build_kubectl_ate deploy diff --git a/buf.yaml b/buf.yaml index 52a90e393d..a1fe14f84a 100644 --- a/buf.yaml +++ b/buf.yaml @@ -25,3 +25,22 @@ modules: breaking: use: - PACKAGE + # TODO(#4323): remove ignore_only once proto-breaking.sh can exempt single + # findings. + ignore_only: + # ExternalVolumeStatus is renamed to ActorExternalVolumeStatus. + PACKAGE_MESSAGE_NO_DELETE: + - api/ateapi/v1/ateapi.proto + FIELD_SAME_TYPE: + - api/ateapi/v1/ateapi.proto + # The ExternalVolume resource's status reuses the name + # ExternalVolumeStatus from v1.0.1, but has since been + # renamed to ActorExternalVolumeStatus. + FIELD_NO_DELETE: + - api/ateapi/v1/ateapi.proto + FIELD_SAME_NAME: + - api/ateapi/v1/ateapi.proto + FIELD_SAME_JSON_NAME: + - api/ateapi/v1/ateapi.proto + FIELD_SAME_CARDINALITY: + - api/ateapi/v1/ateapi.proto \ No newline at end of file diff --git a/charts/substrate-atelet/templates/atelet.yaml b/charts/substrate-atelet/templates/atelet.yaml index 66c8e3a4ce..79189efca3 100644 --- a/charts/substrate-atelet/templates/atelet.yaml +++ b/charts/substrate-atelet/templates/atelet.yaml @@ -139,6 +139,8 @@ spec: prometheus.io/port: "9090" spec: serviceAccountName: {{ include "substrate.fullname" (list "atelet" .) }} + # Only atelet calls the Kubernetes API, so only it mounts the token. + automountServiceAccountToken: false priorityClassName: system-cluster-critical {{- with .Values.atelet.nodeSelector }} nodeSelector: @@ -310,6 +312,9 @@ spec: {{- end }} readOnly: true {{- end }} + - name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true volumes: - name: objectstore-plugin emptyDir: {} @@ -369,3 +374,18 @@ spec: matchLabels: podcert.ate.dev/canarying: live path: trust-bundle.pem + - name: kube-api-access + projected: + sources: + - serviceAccountToken: + path: token + - configMap: + name: kube-root-ca.crt + items: + - key: ca.crt + path: ca.crt + - downwardAPI: + items: + - path: namespace + fieldRef: + fieldPath: metadata.namespace diff --git a/charts/substrate-atelet/tests/service_account_token_test.yaml b/charts/substrate-atelet/tests/service_account_token_test.yaml new file mode 100644 index 0000000000..9a4dd9dddb --- /dev/null +++ b/charts/substrate-atelet/tests/service_account_token_test.yaml @@ -0,0 +1,39 @@ +# Copyright 2026 The Agent Substrate 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. + +suite: Service account tokens +templates: +- atelet.yaml +tests: +- it: mounts the atelet token only into atelet + template: atelet.yaml + documentSelector: + path: kind + value: DaemonSet + asserts: + - equal: + path: spec.template.spec.automountServiceAccountToken + value: false + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: + name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true + - notContains: + path: spec.template.spec.initContainers[0].volumeMounts + content: + name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true diff --git a/charts/substrate-crds/templates/ate.dev_csidriverconfigs.yaml b/charts/substrate-crds/templates/ate.dev_csidriverconfigs.yaml index 28a88a38a1..4fef7fc735 100644 --- a/charts/substrate-crds/templates/ate.dev_csidriverconfigs.yaml +++ b/charts/substrate-crds/templates/ate.dev_csidriverconfigs.yaml @@ -73,7 +73,7 @@ spec: Matches the StorageClass referenced in ActorTemplate volume definitions. maxLength: 63 minLength: 1 - pattern: ^(substrate\.io/)?([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)$ + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string nodeSocketOverride: description: |- diff --git a/charts/substrate-crds/templates/ate.dev_workerpools.yaml b/charts/substrate-crds/templates/ate.dev_workerpools.yaml index e8ac92720f..a17682c6c5 100644 --- a/charts/substrate-crds/templates/ate.dev_workerpools.yaml +++ b/charts/substrate-crds/templates/ate.dev_workerpools.yaml @@ -167,7 +167,7 @@ spec: properties: preferredDuringSchedulingIgnoredDuringExecution: description: |- - The scheduler will prefer to schedule pods to nodes that satisfy + preferredDuringSchedulingIgnoredDuringExecution specifies that the scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. @@ -182,29 +182,29 @@ spec: (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op). properties: preference: - description: A node selector term, associated with the - corresponding weight. + description: preference is a node selector term, associated + with the corresponding weight. properties: matchExpressions: - description: A list of node selector requirements - by node's labels. + description: matchExpressions is a list of node + selector requirements by node's labels. items: description: |- A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: key: - description: The label key that the selector - applies to. + description: key is the label key that the + selector applies to. type: string operator: description: |- - Represents a key's relationship to a set of values. + operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. type: string values: description: |- - An array of string values. If the operator is In or NotIn, + values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. @@ -220,25 +220,25 @@ spec: type: array x-kubernetes-list-type: atomic matchFields: - description: A list of node selector requirements - by node's fields. + description: matchFields is a list of node selector + requirements by node's fields. items: description: |- A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: key: - description: The label key that the selector - applies to. + description: key is the label key that the + selector applies to. type: string operator: description: |- - Represents a key's relationship to a set of values. + operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. type: string values: description: |- - An array of string values. If the operator is In or NotIn, + values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. @@ -256,8 +256,8 @@ spec: type: object x-kubernetes-map-type: atomic weight: - description: Weight associated with matching the corresponding - nodeSelectorTerm, in the range 1-100. + description: weight is the weight associated with matching + the corresponding nodeSelectorTerm, in the range 1-100. format: int32 type: integer required: @@ -268,15 +268,16 @@ spec: x-kubernetes-list-type: atomic requiredDuringSchedulingIgnoredDuringExecution: description: |- - If the affinity requirements specified by this field are not met at + requiredDuringSchedulingIgnoredDuringExecution specifies that if the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node. properties: nodeSelectorTerms: - description: Required. A list of node selector terms. - The terms are ORed. + description: |- + nodeSelectorTerms is a list of node selector terms. The terms are ORed. + Required. A list of node selector terms. The terms are ORed. items: description: |- A null or empty node selector term matches no objects. The requirements of @@ -284,25 +285,25 @@ spec: The TopologySelectorTerm type implements a subset of the NodeSelectorTerm. properties: matchExpressions: - description: A list of node selector requirements - by node's labels. + description: matchExpressions is a list of node + selector requirements by node's labels. items: description: |- A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: key: - description: The label key that the selector - applies to. + description: key is the label key that the + selector applies to. type: string operator: description: |- - Represents a key's relationship to a set of values. + operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. type: string values: description: |- - An array of string values. If the operator is In or NotIn, + values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. @@ -318,25 +319,25 @@ spec: type: array x-kubernetes-list-type: atomic matchFields: - description: A list of node selector requirements - by node's fields. + description: matchFields is a list of node selector + requirements by node's fields. items: description: |- A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: key: - description: The label key that the selector - applies to. + description: key is the label key that the + selector applies to. type: string operator: description: |- - Represents a key's relationship to a set of values. + operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. type: string values: description: |- - An array of string values. If the operator is In or NotIn, + values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. @@ -375,25 +376,22 @@ spec: properties: claims: description: |- - Claims lists the names of resources, defined in spec.resourceClaims, + claims lists the names of resources, defined in spec.resourceClaims, that are used by this container. - This field depends on the - DynamicResourceAllocation feature gate. - This field is immutable. It can only be set for containers. items: description: ResourceClaim references one entry in PodSpec.ResourceClaims. properties: name: description: |- - Name must match the name of one entry in pod.spec.resourceClaims of + name must match the name of one entry in pod.spec.resourceClaims of the Pod where this field is used. It makes that resource available inside a container. type: string request: description: |- - Request is the name chosen for a request in the referenced claim. + request is the name chosen for a request in the referenced claim. If empty, everything from the claim is made available, otherwise only the result of this request. type: string @@ -412,8 +410,12 @@ spec: pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true description: |- - Limits describes the maximum amount of compute resources allowed. - More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ + limits describes the maximum amount of compute resources allowed. + For kubelet cgroup enforcement: + - cpu and memory: a limit of 0 is treated the same as an unspecified limit. If + neither the container nor the pod specifies a limit, the resource is not limited. + - hugepages: an unspecified limit is treated the same as a limit of 0. + More details: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ type: object requests: additionalProperties: @@ -423,7 +425,7 @@ spec: pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true description: |- - Requests describes the minimum amount of compute resources required. + requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ @@ -433,7 +435,8 @@ spec: description: |- serviceAccountName for the worker pods. The ServiceAccount must exist in the WorkerPool's namespace. When omitted, the pods run as the - "ateworker" ServiceAccount, which the controller creates. + "ateworker" ServiceAccount, which the controller creates. Worker pods + never get a ServiceAccount token, whichever ServiceAccount they use. minLength: 1 type: string tolerations: @@ -445,17 +448,17 @@ spec: properties: effect: description: |- - Effect indicates the taint effect to match. Empty means match all taint effects. + effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. type: string key: description: |- - Key is the taint key that the toleration applies to. Empty means match all taint keys. + key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys. type: string operator: description: |- - Operator represents a key's relationship to the value. + operator represents a key's relationship to the value. Valid operators are Exists, Equal, Lt, and Gt. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category. @@ -463,7 +466,7 @@ spec: type: string tolerationSeconds: description: |- - TolerationSeconds represents the period of time the toleration (which must be + tolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system. @@ -471,7 +474,7 @@ spec: type: integer value: description: |- - Value is the taint value the toleration matches to. + value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string. type: string type: object diff --git a/charts/substrate/templates/ate-api-server.yaml b/charts/substrate/templates/ate-api-server.yaml index dc1ea0263d..8a77f9d5c5 100644 --- a/charts/substrate/templates/ate-api-server.yaml +++ b/charts/substrate/templates/ate-api-server.yaml @@ -85,6 +85,8 @@ spec: prometheus.io/port: "9090" spec: serviceAccountName: {{ include "substrate.fullname" (list "ate-api-server" .) }} + # Only ate-api-server calls the Kubernetes API, so only it mounts the token. + automountServiceAccountToken: false terminationGracePeriodSeconds: 40 {{- with include "substrate.imagePullSecrets" . }}{{- . | nindent 6 }}{{- end }} initContainers: @@ -225,6 +227,9 @@ spec: {{- end }} - { name: api-config, mountPath: /run/apiconfig.ate.dev, readOnly: true } - { name: authentication-config, mountPath: /etc/ateapi/authentication, readOnly: true } + - name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true ports: - containerPort: 443 - name: prometheus @@ -299,6 +304,21 @@ spec: matchLabels: podcert.ate.dev/canarying: live path: trust-bundle.pem + - name: kube-api-access + projected: + sources: + - serviceAccountToken: + path: token + - configMap: + name: kube-root-ca.crt + items: + - key: ca.crt + path: ca.crt + - downwardAPI: + items: + - path: namespace + fieldRef: + fieldPath: metadata.namespace {{- if .Values.postgres.clientCertificates.enabled }} - name: postgres projected: diff --git a/charts/substrate/templates/atelet.yaml b/charts/substrate/templates/atelet.yaml index 6c55ffa5ed..28fd85ba86 100644 --- a/charts/substrate/templates/atelet.yaml +++ b/charts/substrate/templates/atelet.yaml @@ -140,6 +140,8 @@ spec: prometheus.io/port: "9090" spec: serviceAccountName: {{ include "substrate.fullname" (list "atelet" .) }} + # Only atelet calls the Kubernetes API, so only it mounts the token. + automountServiceAccountToken: false priorityClassName: system-cluster-critical {{- with .Values.atelet.nodeSelector }} nodeSelector: @@ -311,6 +313,9 @@ spec: {{- end }} readOnly: true {{- end }} + - name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true volumes: - name: objectstore-plugin emptyDir: {} @@ -370,4 +375,19 @@ spec: matchLabels: podcert.ate.dev/canarying: live path: trust-bundle.pem + - name: kube-api-access + projected: + sources: + - serviceAccountToken: + path: token + - configMap: + name: kube-root-ca.crt + items: + - key: ca.crt + path: ca.crt + - downwardAPI: + items: + - path: namespace + fieldRef: + fieldPath: metadata.namespace {{- end }} diff --git a/charts/substrate/templates/sandboxconfig-gvisor.yaml b/charts/substrate/templates/sandboxconfig-gvisor.yaml index 080e408628..cf5b45466c 100644 --- a/charts/substrate/templates/sandboxconfig-gvisor.yaml +++ b/charts/substrate/templates/sandboxconfig-gvisor.yaml @@ -33,7 +33,7 @@ metadata: sandboxconfig.ate.dev/is-class-default: "true" spec: sandboxClass: gvisor - defaultVersion: v7 + defaultVersion: v8 versions: # gVisor release 20261026.0. ateworker-gvisor saves container rootfs overlays # (rootfs/) and durable-dir volumes (fs/) as separate checkpoint bundles. That @@ -64,3 +64,17 @@ spec: gvisor: url: "gs://gvisor/releases/release/20261102.0/aarch64/gvisor.tar.zstd" sha256: "f702ae92ad7a0c4134be34ca23f52966dbb696db0c0f5b8ec439210ab2cd7c6a" + # gVisor nightly 2026-12-02 (google/gvisor@ce0884fa5472), which includes + # google/gvisor@61d3a87e5a4f (fixing sub-container start in a restoring + # sandbox). + - name: v8 + state: Enabled + assets: + amd64: + gvisor: + url: "gs://gvisor/releases/nightly/2026-12-02/x86_64/gvisor.tar.zstd" + sha256: "e4bb791370872192ea91211a5d9f0e7b3cb6d55248c1168ce82dd76ffef73e64" + arm64: + gvisor: + url: "gs://gvisor/releases/nightly/2026-12-02/aarch64/gvisor.tar.zstd" + sha256: "54c4357298d1f12122b6cc18078ecf7b5cc1ac2ee1ef7032f170cb6e7c5ef75d" diff --git a/charts/substrate/tests/service_account_token_test.yaml b/charts/substrate/tests/service_account_token_test.yaml new file mode 100644 index 0000000000..bbca970595 --- /dev/null +++ b/charts/substrate/tests/service_account_token_test.yaml @@ -0,0 +1,63 @@ +# Copyright 2026 The Agent Substrate 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. + +suite: Service account tokens +templates: +- ate-api-server.yaml +- ate-api-server-envvars.yaml +- atelet.yaml +tests: +- it: mounts the ate-api-server token only into ate-api-server + template: ate-api-server.yaml + documentSelector: + path: kind + value: Deployment + asserts: + - equal: + path: spec.template.spec.automountServiceAccountToken + value: false + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: + name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true + - notContains: + path: spec.template.spec.initContainers[0].volumeMounts + content: + name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true + +- it: mounts the atelet token only into atelet + template: atelet.yaml + documentSelector: + path: kind + value: DaemonSet + asserts: + - equal: + path: spec.template.spec.automountServiceAccountToken + value: false + - contains: + path: spec.template.spec.containers[0].volumeMounts + content: + name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true + - notContains: + path: spec.template.spec.initContainers[0].volumeMounts + content: + name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true diff --git a/cmd/ate-idp-server/main.go b/cmd/ate-idp-server/main.go index c9224e2eb1..7c6b2b5c84 100644 --- a/cmd/ate-idp-server/main.go +++ b/cmd/ate-idp-server/main.go @@ -58,7 +58,7 @@ func main() { if err := serverboot.SetLogLevel(*logLevel); err != nil { serverboot.Fatal(ctx, "invalid --log-level", err) } - if err := preview.Init(*previewFlags...); err != nil { + if _, err := preview.New(*previewFlags...); err != nil { serverboot.Fatal(ctx, "invalid --preview", err) } slog.InfoContext(ctx, "starting ate-idp-server", slog.String("version", version.String())) diff --git a/cmd/ate-setup/commands.md b/cmd/ate-setup/commands.md index 07efcf411c..bbd0150f36 100644 --- a/cmd/ate-setup/commands.md +++ b/cmd/ate-setup/commands.md @@ -26,9 +26,12 @@ every setting with its environment variable. | `--ateapi-postgres-storage-class NAME` | StorageClass for the bundled PostgreSQL volume instead of the cluster default, such as `dynamic-rwo` on GKE so C4 and N4 nodes can attach it. An existing install must delete the postgres StatefulSet and its claim first. `ATE_API_POSTGRES_STORAGE_CLASS` when the flag is absent | | `--cordon-system-infra-components` | Keep the system infra components, such as ate-api-server, atenet-router, atenet-egress and postgres, off the worker nodes. Assumes a small shared pool labeled and tainted `ate.dev/workloadType=ate-system-infra:NoSchedule`, across which each workload's replicas are spread, and a one-node pool labeled and tainted `ate.dev/workloadType=ate-postgres:NoSchedule` for postgres alone. `ATE_INSTALL_CORDON_SYSTEM_INFRA_COMPONENTS=true` when the flag is absent | | `--fake-data-plane` | Install the fake data plane for control-plane benchmarks: fake-atelet takes atelet's place in its DaemonSet, taking its objectstore-plugin's storage settings, ate-controller is scaled to zero, and fake-workersync honors every WorkerPool with fake Workers on the fake-atelet nodes. Reaches `deploy ate-system`, `deploy atelet`, and `deploy ate-controller`; only `deploy ate-system` switches a cluster between the real and fake data planes, and the other two refuse a data plane other than the installed one. `deploy ate-system --fake-data-plane` refuses a cluster whose WorkerPools have worker pods. fake-atelet runs with its defaults; a benchmark tunes it through the optional `fake-atelet-tuning` ConfigMap, whose `FAKE_ATELET_*` variables set its flags, and which no install creates or resets. Actors do not exist; never use it on a cluster that serves real actors. `ATE_INSTALL_FAKE_DATA_PLANE=true` when the flag is absent | +| `--pprof off\|on\|contention` | Enable `:6060` Go `pprof` servers on `ate-api-server`, `ate-controller`, `atelet`, `atenet-router`, `atenet-egress` (`ext-proc`), and worker pods through `ate-controller`, skipping `agentgateway` and `fake-atelet` (default `off`). `contention` also samples 1 in 10 mutex contention events and about one blocking event per 1ms spent blocked. Never use it on a cluster that serves real actors. `ATE_INSTALL_PPROF` when the flag is absent | | `--ingress-allowed-spiffe-ids IDS` | Comma-separated SPIFFE IDs (exact match) of the clients the ingress router lets reach actors; any listed client may reach any actor. Unset, no client may reach actors through the router. Both dataplanes require a Pod Identity CA client certificate on HTTPS and TLS CONNECT. The SPIFFE URI SAN allowlist may be checked during or after TLS, including after CONNECT acceptance, but unlisted clients must be denied before actor routing. The podidentity signer issues `spiffe://cluster.local/ns//sa/`. `ATE_INGRESS_ALLOWED_SPIFFE_IDS` when the flag is absent | | `--egress-gateway-extra-spiffe-ids IDS` | Comma-separated SPIFFE IDs that hold ate-api-server's `egress_gateway` role next to atenet-egress, such as a credential provider that mints actor JWTs. ate-setup passes atenet-egress's ID and then each listed ID as repeated `--egress-gateway-spiffe-id` flags; unset passes none, leaving ate-api-server's default. `ATE_EGRESS_GATEWAY_EXTRA_SPIFFE_IDS` when the flag is absent | +| `--default-egress-gateway-address HOST:PORT` | Address of the egress gateway that each actor's atunnel dials (default `atenet-egress.ate-system.svc:443`). `deploy ate-system` and `deploy apiserver` pass it to ate-api-server as `--default-egress-gateway-address`. `ATE_DEFAULT_EGRESS_GATEWAY_ADDRESS` when the flag is absent | | `--experimental-additional-egress-extproc-service NS/SVC:PORT` | External processor authorization filter | +| `--egress-upstream-ca-bundle-configmap NAME[/KEY]` | ConfigMap in `ate-system` whose key (default `ca.crt`) replaces the roots atenet-egress trusts for HTTPS origins, for origins signed by a private CA. See [`docs/guides/egress-credential-injection.md`](../../docs/guides/egress-credential-injection.md#origins-signed-by-a-private-ca). `ATE_EGRESS_UPSTREAM_CA_BUNDLE_CONFIGMAP` when the flag is absent | | `--credential-provider JSON` | Required by `deploy ate-system` and `deploy atenet`. A JSON object: `{"name":"k8s.io"}` deploys and uses the bundled Kubernetes Secrets provider, with a NetworkPolicy that admits only the egress gateway; `{"enabled":false}` turns egress credential injection off; `{"name":"","address":":"}` uses a provider you deploy yourself. A JSON array of provider objects selects several, each serving the `ate-secret://` URIs its name is the host of. See [`docs/guides/egress-credential-injection.md`](../../docs/guides/egress-credential-injection.md). `ATE_CREDENTIAL_PROVIDER` when the flag is absent | | `--ateapi-log-level LEVEL` | ate-api-server log level: `debug`, `info`, `warn`, or `error`. Written to the `ate-api-config` ConfigMap on every deploy when set; unset keeps the installed level (`info` on a new install). Changing the level updates the env-hash annotation and rolls `ate-api-server`. `ATE_API_LOG_LEVEL` when the flag is absent | | `--otlp-endpoint URL` | Send control plane telemetry to `URL` instead of the cluster default (see [`benchmarking/telemetry/README.md`](../../benchmarking/telemetry/README.md)). `ATE_OTLP_ENDPOINT` when the flag is absent | diff --git a/cmd/ate-setup/internal/cmd/record_test.go b/cmd/ate-setup/internal/cmd/record_test.go index 5c17005bbb..33c8d0e23b 100644 --- a/cmd/ate-setup/internal/cmd/record_test.go +++ b/cmd/ate-setup/internal/cmd/record_test.go @@ -16,6 +16,7 @@ package cmd import ( "errors" + "fmt" "os" "path/filepath" "strings" @@ -120,9 +121,11 @@ func TestRecordRunWritesAParseableFile(t *testing.T) { cfg := &config.Config{} cfg.SetResolved(r) - prevEnv, prevResolved := env, resolved - env, resolved = &steps.Env{Cfg: cfg}, r - t.Cleanup(func() { env, resolved = prevEnv, prevResolved }) + prevEnv, prevResolved, prevInputVersion := env, resolved, inputSubstrateVersion + env, resolved, inputSubstrateVersion = &steps.Env{Cfg: cfg}, r, "" + t.Cleanup(func() { + env, resolved, inputSubstrateVersion = prevEnv, prevResolved, prevInputVersion + }) target, _, err := rootCmd.Find([]string{"deploy", "atenet"}) if err != nil { @@ -182,6 +185,47 @@ func TestRecordRunWritesAFailureArtifact(t *testing.T) { } } +func TestFailedRunKeepsRecordedSource(t *testing.T) { + t.Setenv("VERSION", "v1.3.0") + for _, hasEnv := range []bool{false, true} { + t.Run(fmt.Sprintf("environment=%t", hasEnv), func(t *testing.T) { + dir := t.TempDir() + r, err := config.Resolve(nil, config.ResolveOptions{Env: map[string]string{ + "ATE_RECORD_DIR": dir, + "KUBECTL_CONTEXT": "prod", + }}) + if err != nil { + t.Fatalf("Resolve: %v", err) + } + + var runEnv *steps.Env + if hasEnv { + runEnv = &steps.Env{Cfg: &config.Config{}} + } + prevEnv, prevResolved, prevInputVersion := env, resolved, inputSubstrateVersion + env, resolved, inputSubstrateVersion = runEnv, r, "v1.2.3" + t.Cleanup(func() { + env, resolved, inputSubstrateVersion = prevEnv, prevResolved, prevInputVersion + }) + + target, _, _ := rootCmd.Find([]string{"deploy", "atenet"}) + recordRun(target, errors.New("the install failed")) + + failed, _ := filepath.Glob(filepath.Join(dir, "failed", "prod-*.yaml")) + if len(failed) != 1 { + t.Fatalf("%d failure artifacts, want 1", len(failed)) + } + f, err := config.ParseFile(failed[0]) + if err != nil { + t.Fatalf("ParseFile: %v", err) + } + if got := f.SubstrateVersion; got != "v1.2.3" { + t.Errorf("SubstrateVersion = %q, want v1.2.3", got) + } + }) + } +} + // The record names the release the run installed, so a later reader can tell // what the cluster runs without asking the cluster. func TestRecordNamesTheInstalledVersion(t *testing.T) { diff --git a/cmd/ate-setup/internal/cmd/root.go b/cmd/ate-setup/internal/cmd/root.go index 608028a1ce..076d67a50b 100644 --- a/cmd/ate-setup/internal/cmd/root.go +++ b/cmd/ate-setup/internal/cmd/root.go @@ -25,6 +25,7 @@ import ( "go.ate.dev/substrate/cmd/ate-setup/internal/config" "go.ate.dev/substrate/cmd/ate-setup/internal/log" "go.ate.dev/substrate/cmd/ate-setup/internal/steps" + "go.ate.dev/substrate/cmd/ate-setup/internal/upgradepolicy" "go.ate.dev/substrate/internal/version" ) @@ -50,6 +51,10 @@ var env *steps.Env // from Execute, which cobra's PersistentPostRunE does not reach. var resolved *config.Resolved +// inputSubstrateVersion is the source release from an input record. A failure +// before env exists retains it so the retry is checked against the same source. +var inputSubstrateVersion string + // recordAnnotation says whether a command's runs are recorded: "yes" or "no". // The nearest command that carries it, the command itself or an ancestor, // decides, so the deploy subtree opts in once and a component added later @@ -109,6 +114,12 @@ is present (skipped for --kind, and by NO_DEV_ENV=1).`, // the two copies sandwich anything written in between. SilenceErrors: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + // The command tree is reusable in tests. A failed invocation must not + // leave recordable state for the next one. + env = nil + resolved = nil + inputSubstrateVersion = "" + // Commands that touch neither config nor cluster (help, version, // completion) opt out by way of not being run through this path. // cmd.Flags() rather than the root's persistent set: cobra parses a @@ -121,11 +132,22 @@ is present (skipped for --kind, and by NO_DEV_ENV=1).`, if err != nil { return err } - resolved = cfg.Resolved() + if cfg.HasInstallRecord { + inputSubstrateVersion = cfg.RecordedSubstrateVersion + } + runResolved := cfg.Resolved() // Reported before the cluster is touched, so the settings are on // screen even when connecting fails. - resolved.Report(log.Writer(), config.ReportOptions{OmitDefaults: noReportDefaults}) + runResolved.Report(log.Writer(), config.ReportOptions{OmitDefaults: noReportDefaults}) + if isDeployCommand(cmd) && recordsRun(cmd) { + if err := checkDeployUpgrade(cfg); err != nil { + return err + } + } + // A rejected transition should not write a retry artifact that loses + // the source release and can bypass the same check on retry. + resolved = runResolved if !needsCluster(cmd) { env = steps.NewLocalEnv(cfg) @@ -169,6 +191,22 @@ func isDeployCommand(cmd *cobra.Command) bool { return false } +func checkDeployUpgrade(cfg *config.Config) error { + if !cfg.HasInstallRecord || !cfg.Images.IsPrebuilt() { + return nil + } + // A fresh install can fail before an environment exists to identify its + // target release. Its failure artifact must remain usable for the retry + // command recordRun prints. + if cfg.FailedInstallRecord && cfg.RecordedSubstrateVersion == "" { + return nil + } + if err := upgradepolicy.CheckUpgrade(cfg.RecordedSubstrateVersion, cfg.Images.TagWithoutDigest()); err != nil { + return fmt.Errorf("checking release transition: %w", err) + } + return nil +} + // recordRun writes what this run used, so the next one can reproduce it by // pointing --config at the file. Recording is best effort: an install that // worked must not be reported as failed because a directory was read-only. @@ -185,10 +223,10 @@ func recordRun(cmd *cobra.Command, runErr error) { } context := resolved.ClusterKey() - // Recorded so the file says what the cluster runs. Left out when the run - // failed before it had an environment to ask. - var version string - if env != nil { + // A successful run records its target. A failed run keeps the input source: + // a partial deploy cannot prove that the cluster reached the target. + version := inputSubstrateVersion + if runErr == nil && env != nil { version = env.SubstrateVersion() } diff --git a/cmd/ate-setup/internal/cmd/upgrade_test.go b/cmd/ate-setup/internal/cmd/upgrade_test.go new file mode 100644 index 0000000000..789da7a00e --- /dev/null +++ b/cmd/ate-setup/internal/cmd/upgrade_test.go @@ -0,0 +1,97 @@ +// Copyright 2026 The Agent Substrate 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 ( + "os" + "path/filepath" + "strings" + "testing" + + "go.ate.dev/substrate/cmd/ate-setup/internal/config" + "go.ate.dev/substrate/cmd/ate-setup/internal/images" +) + +func TestDeployChecksPrebuiltUpgradeBeforeConnecting(t *testing.T) { + path := filepath.Join(t.TempDir(), "install.yaml") + body := "apiVersion: " + config.FileAPIVersion + "\nkind: " + config.FileKind + "\n" + + "cluster:\n substrateVersion: v1.2.3-4-gabcdef\n" + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + + resetCommandFlags(t, rootCmd.PersistentFlags()) + resetCommandFlags(t, deployAteSystemCmd.Flags()) + previousEnv, previousResolved, previousInputVersion := env, resolved, inputSubstrateVersion + env, resolved, inputSubstrateVersion = nil, nil, "" + t.Cleanup(func() { + env, resolved, inputSubstrateVersion = previousEnv, previousResolved, previousInputVersion + }) + + err := runRoot(t, "deploy", "ate-system", "--no-dev-env", "--config", path, + "--image-repo", "registry.example/substrate", "--image-tag", "v1.3.0") + if err == nil || !strings.Contains(err.Error(), "source release") { + t.Fatalf("deploy error = %v, want invalid source release", err) + } + if env != nil { + t.Error("deploy connected to the cluster before checking the release transition") + } + if resolved != nil { + t.Error("rejected transition is recordable as a failed run") + } +} + +func TestCheckDeployUpgrade(t *testing.T) { + tests := []struct { + name string + record bool + failed bool + from string + images images.Source + wantError string + }{ + {name: "fresh prebuilt install", images: images.Source{Repo: "registry.example/substrate", Tag: "v1.2.3"}}, + {name: "source build", record: true, from: "v1.2.3-4-gabcdef", images: images.Source{}}, + {name: "same prebuilt release", record: true, from: "v1.2.3", images: images.Source{Repo: "registry.example/substrate", Tag: "v1.2.3"}}, + {name: "prebuilt upgrade", record: true, from: "v1.2.3", images: images.Source{Repo: "registry.example/substrate", Tag: "v1.3.0"}}, + {name: "prebuilt upgrade pinned by digest", record: true, from: "v1.2.3", images: images.Source{Repo: "registry.example/substrate", Tag: "v1.3.0@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}}, + {name: "prebuilt release candidate pinned by digest", record: true, from: "v1.2.3", images: images.Source{Repo: "registry.example/substrate", Tag: "v1.3.0-rc.1@sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef"}}, + {name: "prebuilt after source build", record: true, from: "v1.2.3-4-gabcdef", images: images.Source{Repo: "registry.example/substrate", Tag: "v1.3.0"}, wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + {name: "successful prebuilt record with missing source", record: true, images: images.Source{Repo: "registry.example/substrate", Tag: "v1.3.0"}, wantError: "source release is empty"}, + {name: "fresh prebuilt retry", record: true, failed: true, images: images.Source{Repo: "registry.example/substrate", Tag: "v1.3.0"}}, + {name: "failed prebuilt record with development source", record: true, failed: true, from: "v1.2.3-4-gabcdef", images: images.Source{Repo: "registry.example/substrate", Tag: "v1.3.0"}, wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + cfg := &config.Config{ + HasInstallRecord: test.record, + FailedInstallRecord: test.failed, + RecordedSubstrateVersion: test.from, + Images: test.images, + } + err := checkDeployUpgrade(cfg) + if test.wantError == "" { + if err != nil { + t.Fatalf("checkDeployUpgrade() error = %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), test.wantError) { + t.Fatalf("checkDeployUpgrade() error = %v, want %q", err, test.wantError) + } + }) + } +} diff --git a/cmd/ate-setup/internal/config/config.go b/cmd/ate-setup/internal/config/config.go index 30bcd18aad..a46eaf4707 100644 --- a/cmd/ate-setup/internal/config/config.go +++ b/cmd/ate-setup/internal/config/config.go @@ -51,6 +51,11 @@ const ( // the podcertificate controller's API rate limits to match. ClusterSizeSize0 = "size0" ClusterSizeSize10 = "size10" + + // Pprof profiling modes for ATE_INSTALL_PPROF (--pprof). + PprofOff = "off" + PprofOn = "on" + PprofContention = "contention" ) // DefaultRolloutTimeout is the default wait timeout for workload rollouts. @@ -126,6 +131,10 @@ type Config struct { // next to atenet-egress (ATE_EGRESS_GATEWAY_EXTRA_SPIFFE_IDS). EgressGatewayExtraSPIFFEIDs []string + // DefaultEgressGatewayAddress is ate-api-server's + // --default-egress-gateway-address. + DefaultEgressGatewayAddress string + // ActorJWTAlgorithm is the signing algorithm of the key in a new actor JWT // pool (ACTOR_JWT_ALGORITHM): ES256 or RS256. ActorJWTAlgorithm string @@ -164,9 +173,19 @@ type Config struct { // Images selects where container images come from. Its zero value builds // them from source with ko, which is what a developer install does. Images images.Source + // HasInstallRecord reports whether --config names an ate-setup record. + HasInstallRecord bool + // FailedInstallRecord reports whether that record came from a failed run. + FailedInstallRecord bool + // RecordedSubstrateVersion is the release stored in that record. + RecordedSubstrateVersion string // Router selects the atenet router dataplane. Router string + // NoAtenetRouter and NoAtenetEgress leave that built-in gateway out of the + // install (ATE_INSTALL_NO_ATENET_ROUTER, ATE_INSTALL_NO_ATENET_EGRESS). + NoAtenetRouter bool + NoAtenetEgress bool // The read/write and owner connections can use different login identities. // With one configured connection, both pools use it. Both empty selects // bundled PostgreSQL. @@ -230,6 +249,10 @@ type Config struct { // data plane applies (ATE_INSTALL_E2E_TUNING). E2ETuning bool + // Pprof selects the opt-in Go pprof kustomize components (ATE_INSTALL_PPROF): + // off, on, or contention. Never enable it on a cluster that serves real actors. + Pprof string + // IngressAllowedSPIFFEIDs are the SPIFFE IDs the ingress router lets // reach actors over its TLS listeners (ATE_INGRESS_ALLOWED_SPIFFE_IDS). // Empty means no client may reach actors through the router. @@ -238,6 +261,11 @@ type Config struct { // AdditionalEgressExtprocService is the optional NS/SVC:PORT external processor filter. AdditionalEgressExtprocService string + // EgressUpstreamCABundle is the ConfigMap key in ate-system that replaces + // the roots the Envoy egress gateway trusts when it opens TLS to an + // origin. The zero value keeps the roots in the gateway image. + EgressUpstreamCABundle EgressUpstreamCABundle + // CredentialProviderJSON is the --credential-provider value; see // CredentialProviders for its schema. CredentialProviderJSON string @@ -361,6 +389,28 @@ type CloudSQLConfig struct { IPType string } +// EgressUpstreamCABundle names a ConfigMap key that holds a PEM bundle. +type EgressUpstreamCABundle struct { + ConfigMap string + Key string +} + +// defaultEgressUpstreamCABundleKey is the key read when the setting names +// only a ConfigMap. +const defaultEgressUpstreamCABundleKey = "ca.crt" + +// parseEgressUpstreamCABundle splits the setting's NAME or NAME/KEY value. +func parseEgressUpstreamCABundle(raw string) EgressUpstreamCABundle { + if raw == "" { + return EgressUpstreamCABundle{} + } + name, key, found := strings.Cut(raw, "/") + if !found { + key = defaultEgressUpstreamCABundleKey + } + return EgressUpstreamCABundle{ConfigMap: name, Key: key} +} + // extprocServiceForm and extprocServicePort describe the accepted value, for // the two ways it can be wrong. const ( @@ -522,6 +572,10 @@ func (c *Config) ScriptEnv() []string { if c.E2ETuning { merged["ATE_INSTALL_E2E_TUNING"] = "true" } + delete(merged, "ATE_INSTALL_PPROF") + if c.Pprof != "" && c.Pprof != PprofOff { + merged["ATE_INSTALL_PPROF"] = c.Pprof + } delete(merged, "ATE_INGRESS_ALLOWED_SPIFFE_IDS") if len(c.IngressAllowedSPIFFEIDs) > 0 { merged["ATE_INGRESS_ALLOWED_SPIFFE_IDS"] = strings.Join(c.IngressAllowedSPIFFEIDs, ",") @@ -533,6 +587,9 @@ func (c *Config) ScriptEnv() []string { if c.AdditionalEgressExtprocService != "" { merged["ATE_ADDITIONAL_EGRESS_EXTPROC_SERVICE"] = c.AdditionalEgressExtprocService } + if b := c.EgressUpstreamCABundle; b.ConfigMap != "" { + merged["ATE_EGRESS_UPSTREAM_CA_BUNDLE_CONFIGMAP"] = b.ConfigMap + "/" + b.Key + } if c.CredentialProviderJSON != "" { merged["ATE_CREDENTIAL_PROVIDER"] = c.CredentialProviderJSON } @@ -576,6 +633,10 @@ const ( K8sCredentialProviderAddress = "k8s-credential-provider." + installdefaults.SystemNamespace + ".svc:50051" ) +// atenetEgressAddress is the atenet-egress Service in +// manifests/ate-install/atenet-egress.yaml. +const atenetEgressAddress = "atenet-egress." + installdefaults.SystemNamespace + ".svc:443" + // credentialProviderKey is the setting the provider JSON arrives on. const credentialProviderKey = "atenet.egress.credentialProvider" diff --git a/cmd/ate-setup/internal/config/config_test.go b/cmd/ate-setup/internal/config/config_test.go index 18e95e41be..b6ebb41c60 100644 --- a/cmd/ate-setup/internal/config/config_test.go +++ b/cmd/ate-setup/internal/config/config_test.go @@ -16,6 +16,7 @@ package config import ( "errors" + "fmt" "os" "path/filepath" "runtime" @@ -61,7 +62,9 @@ func loadEnv(t *testing.T) { "ATE_API_POSTGRES_SERVER_CA_FILE", "ATE_ATENET_DATAPLANE", "ATE_CREDENTIAL_PROVIDER", + "ATE_DEFAULT_EGRESS_GATEWAY_ADDRESS", "ATE_EGRESS_GATEWAY_EXTRA_SPIFFE_IDS", + "ATE_EGRESS_UPSTREAM_CA_BUNDLE_CONFIGMAP", "ATE_IMAGE_REPO", "ATE_IMAGE_TAG", "ATE_INGRESS_ALLOWED_SPIFFE_IDS", @@ -70,7 +73,10 @@ func loadEnv(t *testing.T) { "ATE_INSTALL_E2E_TUNING", "ATE_INSTALL_FAKE_DATA_PLANE", "ATE_INSTALL_KIND", + "ATE_INSTALL_NO_ATENET_EGRESS", + "ATE_INSTALL_NO_ATENET_ROUTER", "ATE_INSTALL_PODCERT_WORKERS_PER_SIGNER", + "ATE_INSTALL_PPROF", "ATE_INSTALL_ROLLOUT_TIMEOUT", "ATE_OTLP_ENDPOINT", "ATE_PREVIEW", @@ -134,6 +140,9 @@ func TestLoadDefaults(t *testing.T) { if cfg.CordonSystemInfraComponents { t.Error("CordonSystemInfraComponents = true, want false") } + if cfg.Pprof != PprofOff { + t.Errorf("Pprof = %q, want %q", cfg.Pprof, PprofOff) + } } func TestLoadClusterSize(t *testing.T) { @@ -278,6 +287,63 @@ func TestLoadE2ETuning(t *testing.T) { } } +func TestLoadPprof(t *testing.T) { + for _, tc := range []struct { + name string + opts Options + env string + wantPprof string + }{ + { + name: "default", + wantPprof: PprofOff, + }, + { + name: "flag on", + opts: Options{Pprof: PprofOn}, + wantPprof: PprofOn, + }, + { + name: "flag contention", + opts: Options{Pprof: PprofContention}, + wantPprof: PprofContention, + }, + { + name: "environment", + env: PprofContention, + wantPprof: PprofContention, + }, + { + name: "flag beats the environment", + opts: Options{Pprof: PprofOff}, + env: PprofOn, + wantPprof: PprofOff, + }, + } { + t.Run(tc.name, func(t *testing.T) { + loadEnv(t) + if tc.env != "" { + t.Setenv("ATE_INSTALL_PPROF", tc.env) + } + cfg, err := Load(tc.opts) + if err != nil { + t.Fatalf("Load() error = %v", err) + } + if cfg.Pprof != tc.wantPprof { + t.Errorf("Pprof = %q, want %q", cfg.Pprof, tc.wantPprof) + } + env := scriptEnvMap(t, cfg) + if tc.wantPprof != PprofOff { + if env["ATE_INSTALL_PPROF"] != tc.wantPprof { + t.Errorf("ScriptEnv()[ATE_INSTALL_PPROF] = %q, want %q", env["ATE_INSTALL_PPROF"], tc.wantPprof) + } + } else if _, ok := env["ATE_INSTALL_PPROF"]; ok { + t.Errorf("ScriptEnv() exports ATE_INSTALL_PPROF = %q for off, want it absent", env["ATE_INSTALL_PPROF"]) + } + }) + } +} + func TestLoadIngressAllowedSPIFFEIDs(t *testing.T) { const a, b = "spiffe://cluster.local/ns/a/sa/a", "spiffe://cluster.local/ns/b/sa/b" for _, tc := range []struct { @@ -355,6 +421,60 @@ func TestLoadEgressGatewayExtraSPIFFEIDs(t *testing.T) { } } +func TestLoadDefaultEgressGatewayAddress(t *testing.T) { + for _, tc := range []struct { + name string + set bool + env string + want string + wantErr string + }{ + {name: "unset", want: "atenet-egress.ate-system.svc:443"}, + {name: "set is used as given", set: true, env: "egress.example.svc:8443", want: "egress.example.svc:8443"}, + {name: "set to empty stays empty", set: true, want: ""}, + {name: "no port", set: true, env: "egress.example.svc", wantErr: `ateapi.defaultEgressGatewayAddress: Invalid value: "egress.example.svc": must be host:port (from ATE_DEFAULT_EGRESS_GATEWAY_ADDRESS)`}, + {name: "port out of range", set: true, env: "egress.example.svc:99999", wantErr: "port must be a number between 1 and 65535"}, + } { + t.Run(tc.name, func(t *testing.T) { + loadEnv(t) + if tc.set { + t.Setenv("ATE_DEFAULT_EGRESS_GATEWAY_ADDRESS", tc.env) + } + cfg, err := Load(Options{}) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("Load() error = %v, want one containing %q", err, tc.wantErr) + } + return + } + if err != nil { + t.Fatalf("Load() error = %v", err) + } + if cfg.DefaultEgressGatewayAddress != tc.want { + t.Errorf("DefaultEgressGatewayAddress = %q, want %q", cfg.DefaultEgressGatewayAddress, tc.want) + } + }) + } +} + +// ate-setup replaces the address in the manifest with its default, so both +// must name the same Service. +func TestDefaultEgressGatewayAddressMatchesManifest(t *testing.T) { + loadEnv(t) + cfg, err := Load(Options{}) + if err != nil { + t.Fatalf("Load() error = %v", err) + } + manifest, err := os.ReadFile(cfg.Manifest("ate-api-server.yaml")) + if err != nil { + t.Fatalf("reading the ate-api-server manifest: %v", err) + } + want := fmt.Sprintf("--default-egress-gateway-address=%s\n", cfg.DefaultEgressGatewayAddress) + if !strings.Contains(string(manifest), want) { + t.Errorf("ate-api-server.yaml does not carry %q", strings.TrimSpace(want)) + } +} + // The credential exchange impersonates the transfer account only on GCS, so // only a GKE deploy needs one, and its email needs both the name and the // project. @@ -429,10 +549,20 @@ func TestLoadDockerBuildFlags(t *testing.T) { } } +func firstRealPreviewGate(t *testing.T) string { + t.Helper() + gates := preview.NewForTest(t, "ALL").Enabled() + if len(gates) == 0 { + t.Fatal("need a real gate to test parsing") + } + return gates[0] +} + // The preview gates arrive from any channel as one comma-separated value. An // explicitly empty one turns every gate off, even over a lower channel's. func TestLoadPreviewGates(t *testing.T) { - preview.InitForTestFake(t, []preview.Gate{"A", "B"}) + // Real gate names, so the test survives gates graduating. + a, b := firstRealPreviewGate(t), preview.All // nil leaves the channel out; a pointer to "" supplies it, empty. val := func(s string) *string { return &s } @@ -443,12 +573,12 @@ func TestLoadPreviewGates(t *testing.T) { }{ {name: "default"}, {name: "flag all", flag: val("ALL"), want: []string{"ALL"}}, - {name: "flag list", flag: val("A,B"), want: []string{"A", "B"}}, - {name: "file", file: val("A, B"), want: []string{"A", "B"}}, + {name: "flag list", flag: val(a + "," + b), want: []string{a, b}}, + {name: "file", file: val(a + ", " + b), want: []string{a, b}}, {name: "environment", env: val("ALL"), want: []string{"ALL"}}, - {name: "empty items dropped", env: val(",A,,"), want: []string{"A"}}, - {name: "file beats environment", file: val("A"), env: val("ALL"), want: []string{"A"}}, - {name: "flag beats file", flag: val("B"), file: val("A"), want: []string{"B"}}, + {name: "empty items dropped", env: val("," + a + ",,"), want: []string{a}}, + {name: "file beats environment", file: val(a), env: val("ALL"), want: []string{a}}, + {name: "flag beats file", flag: val(b), file: val(a), want: []string{b}}, {name: "empty flag beats environment", flag: val(""), env: val("ALL")}, {name: "empty file beats environment", file: val(""), env: val("ALL")}, } { @@ -488,15 +618,56 @@ func TestLoadPreviewGates(t *testing.T) { } } +// The bundle setting takes NAME or NAME/KEY, and needs the Envoy dataplane. +func TestLoadEgressUpstreamCABundle(t *testing.T) { + for _, tc := range []struct { + name string + opts Options + want EgressUpstreamCABundle + wantErr bool + }{ + {name: "name takes the default key", opts: Options{EgressUpstreamCABundle: "egress-roots"}, + want: EgressUpstreamCABundle{ConfigMap: "egress-roots", Key: "ca.crt"}}, + {name: "name and key", opts: Options{EgressUpstreamCABundle: "egress-roots/bundle.pem"}, + want: EgressUpstreamCABundle{ConfigMap: "egress-roots", Key: "bundle.pem"}}, + {name: "not a ConfigMap name", opts: Options{EgressUpstreamCABundle: "Egress_Roots"}, wantErr: true}, + {name: "no name", opts: Options{EgressUpstreamCABundle: "/ca.crt"}, wantErr: true}, + {name: "empty key", opts: Options{EgressUpstreamCABundle: "egress-roots/"}, wantErr: true}, + {name: "key with a slash", opts: Options{EgressUpstreamCABundle: "egress-roots/certs/ca.crt"}, wantErr: true}, + {name: "agentgateway", opts: Options{Router: RouterAgentgateway, EgressUpstreamCABundle: "egress-roots"}, wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + loadEnv(t) + cfg, err := Load(tc.opts) + if tc.wantErr { + if err == nil { + t.Fatal("Load() succeeded, want an error") + } + return + } + if err != nil { + t.Fatalf("Load() error = %v", err) + } + if cfg.EgressUpstreamCABundle != tc.want { + t.Errorf("EgressUpstreamCABundle = %+v, want %+v", cfg.EgressUpstreamCABundle, tc.want) + } + wantEnv := tc.want.ConfigMap + "/" + tc.want.Key + if got := scriptEnvMap(t, cfg)["ATE_EGRESS_UPSTREAM_CA_BUNDLE_CONFIGMAP"]; got != wantEnv { + t.Errorf("ScriptEnv() ATE_EGRESS_UPSTREAM_CA_BUNDLE_CONFIGMAP = %q, want %q", got, wantEnv) + } + }) + } +} + func TestLoadRejectsUnknownPreviewGates(t *testing.T) { - preview.InitForTestFake(t, []preview.Gate{"Fake"}) + known := firstRealPreviewGate(t) for _, tc := range []struct { name string env string wantErr string }{ {name: "all", env: "ALL"}, - {name: "known gate", env: "Fake"}, + {name: "known gate", env: known}, {name: "unknown gate", env: "NoSuchGate", wantErr: "ATE_PREVIEW"}, {name: "unknown among known", env: "ALL,NoSuchGate", wantErr: "ATE_PREVIEW"}, } { @@ -1040,6 +1211,7 @@ func TestLoadRejectsInvalidValues(t *testing.T) { {"negative rollout timeout", Options{RolloutTimeout: "-30s"}}, {"podcert workers", Options{PodcertWorkersPerSigner: -1}}, {"cluster size", Options{ClusterSize: "size5"}}, + {"pprof", Options{Pprof: "invalid"}}, {"extproc invalid format", Options{AdditionalEgressExtprocService: "extproc:50051"}}, {"extproc agentgateway", Options{Router: RouterAgentgateway, AdditionalEgressExtprocService: "ate-system/extproc:50051"}}, {"provider not JSON", Options{CredentialProvider: "k8s.io"}}, diff --git a/cmd/ate-setup/internal/config/coverage_test.go b/cmd/ate-setup/internal/config/coverage_test.go index cbbfa73201..0977502ef3 100644 --- a/cmd/ate-setup/internal/config/coverage_test.go +++ b/cmd/ate-setup/internal/config/coverage_test.go @@ -29,10 +29,18 @@ var notFromASetting = map[string]bool{ "CloudSQL": true, // assembled from the ateapi.postgres.cloudsql.* settings "PostgresOwnerRoleSet": true, "PostgresReadWriteRoleSet": true, + "HasInstallRecord": true, // derived from the --config document shape + "FailedInstallRecord": true, // derived from cluster.outcome in --config + "RecordedSubstrateVersion": true, // read from --config record metadata // kindCluster.enabled feeds Kind, but the fixture sets it false to reach // the cloud path, so its zero value here says nothing. "Kind": true, + + // buildConfig rejects the two skip settings, so the fixture sets them + // false and these zero values say nothing. + "NoAtenetRouter": true, + "NoAtenetEgress": true, } // A Config field that no setting feeds stays at its zero value however the @@ -48,7 +56,9 @@ func TestEveryConfigFieldIsFedBySomeSetting(t *testing.T) { case KindBool: // A Kind install clears the GCP coordinates by design, so the // cloud path is the one that exercises every field. - env[s.Env] = strconv.FormatBool(s.Key != "kindCluster.enabled") + // buildConfig rejects the two skip settings. + off := s.Key == "kindCluster.enabled" || s.Key == "atenet.router.skip" || s.Key == "atenet.egress.skip" + env[s.Env] = strconv.FormatBool(!off) case KindInt: env[s.Env] = "7" case KindDuration: @@ -90,12 +100,16 @@ func valueFor(key string) string { return RouterEnvoy case "clusterSize": return ClusterSizeSize0 + case "pprof": + return PprofOn case "ingressAllowedSPIFFEIDs", "ateapi.authz.egressGatewayExtraSPIFFEIDs": return "spiffe://cluster.local/ns/a/sa/b" case "ateapi.postgres.cloudsql.ipType": return CloudSQLIPTypePSC case "atenet.egress.additionalExtprocService": return "ns/svc:8080" + case "ateapi.defaultEgressGatewayAddress": + return "egress.example.svc:443" case "atenet.egress.credentialProvider": return `{"name":"k8s.io"}` case "actorJWT.algorithm": diff --git a/cmd/ate-setup/internal/config/document.go b/cmd/ate-setup/internal/config/document.go index 1a5ccb54ad..9020442177 100644 --- a/cmd/ate-setup/internal/config/document.go +++ b/cmd/ate-setup/internal/config/document.go @@ -47,9 +47,8 @@ type DocumentMetadata struct { Outcome Outcome `json:"outcome,omitempty"` // FailedAt is the command that returned an error, for a failed run. FailedAt string `json:"failedAt,omitempty"` - // SubstrateVersion is the Substrate release the run installed: the - // version stamped into the binaries it built, or the image tag of a - // prebuilt install. + // SubstrateVersion is the Substrate release the run installed, or the + // recorded source when a retry fails before its target can be established. SubstrateVersion string `json:"substrateVersion,omitempty"` // WrittenAt and WrittenBy identify the run for a reader comparing two // documents. diff --git a/cmd/ate-setup/internal/config/errors_test.go b/cmd/ate-setup/internal/config/errors_test.go index 87169d6be8..58625239d8 100644 --- a/cmd/ate-setup/internal/config/errors_test.go +++ b/cmd/ate-setup/internal/config/errors_test.go @@ -219,6 +219,16 @@ func TestValidationErrorsNameTheSupplyingChannel(t *testing.T) { env: map[string]string{"ATE_IMAGE_REPO": "example.com/substrate"}, wantIn: []string{"images.repo", "ATE_IMAGE_REPO", "images.tag", "needs a tag"}, }, + { + name: "skipping atenet-router is not implemented", + env: map[string]string{"ATE_INSTALL_NO_ATENET_ROUTER": "true"}, + wantIn: []string{"atenet.router.skip", "cannot skip a gateway yet", "ATE_INSTALL_NO_ATENET_ROUTER"}, + }, + { + name: "skipping atenet-egress is not implemented", + env: map[string]string{"ATE_INSTALL_NO_ATENET_EGRESS": "true"}, + wantIn: []string{"atenet.egress.skip", "cannot skip a gateway yet", "ATE_INSTALL_NO_ATENET_EGRESS"}, + }, } { t.Run(tc.name, func(t *testing.T) { loadEnv(t) diff --git a/cmd/ate-setup/internal/config/file.go b/cmd/ate-setup/internal/config/file.go index 9ab166add3..30a0dfc571 100644 --- a/cmd/ate-setup/internal/config/file.go +++ b/cmd/ate-setup/internal/config/file.go @@ -39,8 +39,13 @@ const ( type File struct { // Path is where the document was read from, for error messages. Path string + // SubstrateVersion is the release recorded in cluster metadata. It is + // empty in a configuration that is not an install record. + SubstrateVersion string - values map[string]string + failedInstall bool + hasMetadata bool + values map[string]string } // reserved names the top-level keys that are not settings: the two header @@ -97,6 +102,11 @@ func ParseFile(path string) (*File, error) { if err := flatten("", doc, flat); err != nil { return nil, fmt.Errorf("%s: %w", path, err) } + metadataNode := mappingField(doc, documentMetadataKey) + metadata := make(map[string]string) + if err := flatten(documentMetadataKey, metadataNode, metadata); err != nil { + return nil, fmt.Errorf("%s: %w", path, err) + } var unknown []string for k := range flat { @@ -110,7 +120,13 @@ func ParseFile(path string) (*File, error) { plural(len(unknown)), strings.Join(quoteAll(unknown), ", ")) } - return &File{Path: path, values: flat}, nil + return &File{ + Path: path, + SubstrateVersion: metadata[documentMetadataKey+".substrateVersion"], + failedInstall: metadata[documentMetadataKey+".outcome"] == string(Failed), + hasMetadata: metadataNode != nil, + values: flat, + }, nil } // Get returns the raw value for a canonical key. @@ -143,6 +159,20 @@ func headerField(doc *yaml.Node, name string) string { return "" } +// mappingField reads a top-level mapping. A field of another kind is absent +// to readers here; ParseFile still skips reserved metadata as configuration. +func mappingField(doc *yaml.Node, name string) *yaml.Node { + if doc == nil { + return nil + } + for i := 0; i+1 < len(doc.Content); i += 2 { + if doc.Content[i].Value == name && doc.Content[i+1].Kind == yaml.MappingNode { + return doc.Content[i+1] + } + } + return nil +} + // flatten walks the document into dotted keys, carrying each scalar's text // through unchanged so the file and the environment feed the resolver // identical input. @@ -159,9 +189,6 @@ func flatten(prefix string, node *yaml.Node, out map[string]string) error { seen := make(map[string]bool, len(node.Content)/2) for i := 0; i+1 < len(node.Content); i += 2 { name, value := node.Content[i].Value, node.Content[i+1] - if prefix == "" && reserved[name] { - continue - } key := name if prefix != "" { key = prefix + "." + name @@ -170,6 +197,9 @@ func flatten(prefix string, node *yaml.Node, out map[string]string) error { return fmt.Errorf("setting %q is set twice", key) } seen[name] = true + if prefix == "" && reserved[name] { + continue + } switch value.Kind { case yaml.MappingNode: diff --git a/cmd/ate-setup/internal/config/file_test.go b/cmd/ate-setup/internal/config/file_test.go index aed80d3b1b..46a69e37f6 100644 --- a/cmd/ate-setup/internal/config/file_test.go +++ b/cmd/ate-setup/internal/config/file_test.go @@ -67,6 +67,23 @@ fixture: } } +func TestParseFileReadsSubstrateVersion(t *testing.T) { + path := writeConfig(t, validHeader+`cluster: + context: prod + substrateVersion: v1.2.3 +`) + f, err := ParseFile(path) + if err != nil { + t.Fatalf("ParseFile() error = %v", err) + } + if got := f.SubstrateVersion; got != "v1.2.3" { + t.Errorf("SubstrateVersion = %q, want %q", got, "v1.2.3") + } + if got := f.Keys(); len(got) != 0 { + t.Errorf("Keys() = %v, want cluster metadata excluded", got) + } +} + // An integer must not arrive as "6e+06" or "6.0", which is what resolving the // scalar to a float before flattening would produce. func TestParseFileNumbersAreNotFloatFormatted(t *testing.T) { @@ -119,17 +136,19 @@ func TestParseFileRejectsDuplicateKeys(t *testing.T) { Kind: KindString, Usage: "a string", }) - for _, tc := range []struct{ name, body string }{ - {name: "repeated in one map", body: "scratch:\n str: a\n str: b\n"}, - {name: "dotted beside nested", body: "scratch.str: a\nscratch:\n str: b\n"}, + for _, tc := range []struct{ name, body, wantKey string }{ + {name: "repeated in one map", body: "scratch:\n str: a\n str: b\n", wantKey: "scratch.str"}, + {name: "dotted beside nested", body: "scratch.str: a\nscratch:\n str: b\n", wantKey: "scratch.str"}, + {name: "repeated cluster metadata", body: "cluster:\n substrateVersion: v1.2.3\n substrateVersion: v1.2.4\n", wantKey: "cluster.substrateVersion"}, + {name: "repeated cluster block", body: "cluster:\n substrateVersion: v1.2.3\ncluster:\n substrateVersion: v1.2.4\n", wantKey: "cluster"}, } { t.Run(tc.name, func(t *testing.T) { _, err := ParseFile(writeConfig(t, validHeader+tc.body)) if err == nil { t.Fatal("ParseFile() = nil error, want the duplicate key reported") } - if !strings.Contains(err.Error(), "scratch.str") { - t.Errorf("ParseFile() = %q, want it to name the duplicated key", err) + if !strings.Contains(err.Error(), "set twice") || !strings.Contains(err.Error(), tc.wantKey) { + t.Errorf("ParseFile() = %q, want it to report the duplicated key", err) } }) } diff --git a/cmd/ate-setup/internal/config/load.go b/cmd/ate-setup/internal/config/load.go index c9410fab3a..bf621a8517 100644 --- a/cmd/ate-setup/internal/config/load.go +++ b/cmd/ate-setup/internal/config/load.go @@ -23,11 +23,14 @@ import ( "github.com/spf13/pflag" "github.com/spiffe/go-spiffe/v2/spiffeid" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/util/validation/field" "go.ate.dev/substrate/cmd/ate-setup/internal/images" "go.ate.dev/substrate/internal/actoridjwt" "go.ate.dev/substrate/internal/installdefaults" "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/internal/resources" ) // ConfigPathEnv names the configuration document when --config is not given. @@ -76,7 +79,16 @@ func LoadFlags(fs *pflag.FlagSet, o LoadOptions) (*Config, error) { if err != nil { return nil, err } - return buildConfig(root, env, res) + cfg, err := buildConfig(root, env, res) + if err != nil { + return nil, err + } + if file != nil { + cfg.HasInstallRecord = file.hasMetadata + cfg.FailedInstallRecord = file.failedInstall + cfg.RecordedSubstrateVersion = file.SubstrateVersion + } + return cfg, nil } // configPathFrom picks the configuration document, flag over environment. @@ -225,6 +237,7 @@ func buildConfig(root string, env map[string]string, r *Resolved) (*Config, erro APIAuthzBootstrapOwners: bootstrapOwners, EgressGatewayExtraSPIFFEIDs: splitList(r.String("ateapi.authz.egressGatewayExtraSPIFFEIDs")), + DefaultEgressGatewayAddress: r.String("ateapi.defaultEgressGatewayAddress"), BucketName: r.String("storage.bucketName"), SnapshotLocation: r.String("storage.snapshotLocation"), @@ -239,6 +252,8 @@ func buildConfig(root string, env map[string]string, r *Resolved) (*Config, erro Tag: r.String("images.tag"), }, Router: r.String("atenet.dataplane"), + NoAtenetRouter: r.Bool("atenet.router.skip"), + NoAtenetEgress: r.Bool("atenet.egress.skip"), PostgresSchema: r.String("ateapi.postgres.schema"), PostgresPoolMaxConns: r.String("ateapi.postgres.poolMaxConns"), PostgresServerCAFile: r.String("ateapi.postgres.serverCAFile"), @@ -270,8 +285,10 @@ func buildConfig(root string, env map[string]string, r *Resolved) (*Config, erro CordonSystemInfraComponents: r.Bool("cordonSystemInfraComponents"), FakeDataPlane: r.Bool("fakeDataPlane.enabled"), E2ETuning: r.Bool("e2e.tuning"), + Pprof: r.String("pprof"), IngressAllowedSPIFFEIDs: splitList(r.String("ingressAllowedSPIFFEIDs")), AdditionalEgressExtprocService: r.String("atenet.egress.additionalExtprocService"), + EgressUpstreamCABundle: parseEgressUpstreamCABundle(r.String("atenet.egress.upstreamCABundleConfigMap")), CredentialProviderJSON: r.String("atenet.egress.credentialProvider"), AnthropicAPIKey: r.String("demo.anthropicAPIKey"), OtlpEndpoint: r.String("otlpEndpoint"), @@ -393,6 +410,12 @@ func validateResolved(cfg *Config, r *Resolved) error { default: return &InvalidError{Value: dataplane, Want: RouterEnvoy + " or " + RouterAgentgateway} } + for _, key := range []string{"atenet.router.skip", "atenet.egress.skip"} { + if r.Bool(key) { + skip, _ := r.Value(key) + return &InvalidError{Value: skip, Want: "false, because ate-setup cannot skip a gateway yet"} + } + } if ipType, _ := r.Value("ateapi.postgres.cloudsql.ipType"); ipType.Raw != "" { switch ipType.Raw { @@ -407,6 +430,10 @@ func validateResolved(cfg *Config, r *Resolved) error { return &InvalidError{Value: size, Want: ClusterSizeSize0 + " or " + ClusterSizeSize10} } + if pprofVal, _ := r.Value("pprof"); cfg.Pprof != PprofOff && cfg.Pprof != PprofOn && cfg.Pprof != PprofContention { + return &InvalidError{Value: pprofVal, Want: PprofOff + ", " + PprofOn + " or " + PprofContention} + } + // The router and ate-api-server reject a malformed ID at startup; catch it // before the rollout does. for _, id := range cfg.IngressAllowedSPIFFEIDs { @@ -421,6 +448,11 @@ func validateResolved(cfg *Config, r *Resolved) error { return &InvalidError{Value: ids, Want: fmt.Sprintf("a comma-separated list of SPIFFE IDs (%q: %v)", id, err)} } } + // ate-api-server applies the same rule at startup. + if errs := resources.ValidateHostPort(field.NewPath("ateapi.defaultEgressGatewayAddress"), cfg.DefaultEgressGatewayAddress); len(errs) > 0 { + address, _ := r.Value("ateapi.defaultEgressGatewayAddress") + return fmt.Errorf("%w (from %s)", errs.ToAggregate(), address.From.Describe(address.Setting)) + } switch cfg.APILogLevel { case "", "debug", "info", "warn", "error": @@ -449,6 +481,20 @@ func validateResolved(cfg *Config, r *Resolved) error { Why: "an additional ext_proc filter requires dataplane " + RouterEnvoy} } } + // Check the raw value. A value with no name, such as "/ca.crt", parses to + // an empty ConfigMap, which cfg cannot tell from unset. + if r.String("atenet.egress.upstreamCABundleConfigMap") != "" { + bundle, _ := r.Value("atenet.egress.upstreamCABundleConfigMap") + ref := cfg.EgressUpstreamCABundle + if len(validation.IsDNS1123Subdomain(ref.ConfigMap)) > 0 || len(validation.IsConfigMapKey(ref.Key)) > 0 { + return &InvalidError{Value: bundle, Want: "a ConfigMap name, or NAME/KEY"} + } + // TODO: remove when the flag is also supported in agentgateway. + if cfg.Router != RouterEnvoy { + return &ConflictError{A: bundle, B: dataplane, + Why: "an egress upstream CA bundle requires dataplane " + RouterEnvoy} + } + } // A gate the components do not know makes each of them refuse to start, so // catch it here rather than as a failed rollout. if err := preview.Verify(cfg.PreviewGates...); err != nil { diff --git a/cmd/ate-setup/internal/config/load_test.go b/cmd/ate-setup/internal/config/load_test.go index f9a620985b..9209730d3c 100644 --- a/cmd/ate-setup/internal/config/load_test.go +++ b/cmd/ate-setup/internal/config/load_test.go @@ -99,6 +99,43 @@ func TestLoadFlagsFileOutranksEnvironment(t *testing.T) { } } +func TestLoadFlagsCarriesInstallRecordMetadata(t *testing.T) { + loadEnv(t) + for _, test := range []struct { + name, metadata, version string + failed bool + }{ + {name: "success", metadata: "outcome: succeeded\n substrateVersion: v1.2.3\n", version: "v1.2.3"}, + {name: "failure before environment", metadata: "outcome: failed\n", failed: true}, + } { + t.Run(test.name, func(t *testing.T) { + path := filepath.Join(t.TempDir(), "install.yaml") + body := "apiVersion: " + FileAPIVersion + "\nkind: " + FileKind + "\n" + + "cluster:\n " + test.metadata + if err := os.WriteFile(path, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + fs, err := optionsFlagSet(Options{}) + if err != nil { + t.Fatal(err) + } + cfg, err := LoadFlags(fs, LoadOptions{ConfigPath: path}) + if err != nil { + t.Fatalf("LoadFlags() error = %v", err) + } + if !cfg.HasInstallRecord { + t.Error("HasInstallRecord = false, want true") + } + if cfg.FailedInstallRecord != test.failed { + t.Errorf("FailedInstallRecord = %v, want %v", cfg.FailedInstallRecord, test.failed) + } + if got := cfg.RecordedSubstrateVersion; got != test.version { + t.Errorf("RecordedSubstrateVersion = %q, want %q", got, test.version) + } + }) + } +} + // A validation failure names the channel the offending value came from. func TestLoadFlagsErrorsNameTheSupplyingChannel(t *testing.T) { loadEnv(t) diff --git a/cmd/ate-setup/internal/config/options_test.go b/cmd/ate-setup/internal/config/options_test.go index a6d03c514d..6e1d90c245 100644 --- a/cmd/ate-setup/internal/config/options_test.go +++ b/cmd/ate-setup/internal/config/options_test.go @@ -41,7 +41,9 @@ type Options struct { CordonSystemInfraComponents bool FakeDataPlane bool E2ETuning bool + Pprof string AdditionalEgressExtprocService string + EgressUpstreamCABundle string CredentialProvider string OtlpEndpoint string @@ -89,7 +91,9 @@ func optionsFlagSet(opts Options) (*pflag.FlagSet, error) { {"atenet-dataplane", opts.Router}, {"rollout-timeout", opts.RolloutTimeout}, {"cluster-size", opts.ClusterSize}, + {"pprof", opts.Pprof}, {"experimental-additional-egress-extproc-service", opts.AdditionalEgressExtprocService}, + {"egress-upstream-ca-bundle-configmap", opts.EgressUpstreamCABundle}, {"credential-provider", opts.CredentialProvider}, {"otlp-endpoint", opts.OtlpEndpoint}, {"image-repo", opts.ImageRepo}, diff --git a/cmd/ate-setup/internal/config/setting.go b/cmd/ate-setup/internal/config/setting.go index cb3dfd15c8..10d0519875 100644 --- a/cmd/ate-setup/internal/config/setting.go +++ b/cmd/ate-setup/internal/config/setting.go @@ -169,6 +169,22 @@ var Registry = []Setting{ Usage: "Run an additional ext_proc authorization filter served by NS/SVC:PORT " + "(requires --atenet-dataplane=envoy)", }, + { + Key: "atenet.router.skip", Env: "ATE_INSTALL_NO_ATENET_ROUTER", Flag: "no-atenet-router", + Kind: KindBool, Default: "false", + Usage: "Do not install atenet-router. Not implemented yet: ate-setup rejects it", + }, + { + Key: "atenet.egress.skip", Env: "ATE_INSTALL_NO_ATENET_EGRESS", Flag: "no-atenet-egress", + Kind: KindBool, Default: "false", + Usage: "Do not install atenet-egress. Not implemented yet: ate-setup rejects it", + }, + { + Key: "atenet.egress.upstreamCABundleConfigMap", Env: "ATE_EGRESS_UPSTREAM_CA_BUNDLE_CONFIGMAP", + Flag: "egress-upstream-ca-bundle-configmap", Kind: KindString, + Usage: "ConfigMap in ate-system, as NAME or NAME/KEY, whose key (default " + defaultEgressUpstreamCABundleKey + + ") replaces the roots atenet-egress trusts for HTTPS origins (requires --atenet-dataplane=envoy)", + }, { // No default: an unset level keeps the one an existing install has, @@ -194,6 +210,12 @@ var Registry = []Setting{ "such as a credential provider that mints actor JWTs. The role also reads actors and mints actor " + "certificates. The podidentity signer issues spiffe://cluster.local/ns//sa/", }, + { + Key: "ateapi.defaultEgressGatewayAddress", Env: "ATE_DEFAULT_EGRESS_GATEWAY_ADDRESS", + Flag: "default-egress-gateway-address", Kind: KindString, + Default: atenetEgressAddress, + Usage: "Address (host:port) of the egress gateway that each actor's atunnel dials", + }, { // The egress gateway's credential providers: one JSON object, or a JSON array // of them for several. A repeated flag would be ideal, but a Setting holds one @@ -311,6 +333,12 @@ var Registry = []Setting{ "atelet, and fake-workersync in place of ate-controller. Actors do not exist; never " + "use it on a cluster that serves real actors", }, + { + Key: "pprof", Env: "ATE_INSTALL_PPROF", Flag: "pprof", Kind: KindString, + Default: PprofOff, + Usage: "Enable opt-in Go pprof servers via components/pprof " + + "(off, on, contention; never use on a cluster that serves real actors)", + }, { // Comma-separated, as the router's own flag is. The registry has no // list kind, so the value is carried as written and split where it is diff --git a/cmd/ate-setup/internal/images/images.go b/cmd/ate-setup/internal/images/images.go index 79ab3f9a05..1f874d5bcf 100644 --- a/cmd/ate-setup/internal/images/images.go +++ b/cmd/ate-setup/internal/images/images.go @@ -25,6 +25,7 @@ import ( "fmt" "path" "slices" + "strings" ) // ModulePath is this repository's module path. A ko:// reference is it joined @@ -137,6 +138,12 @@ type Source struct { // IsPrebuilt reports whether images should be pulled rather than built. func (s Source) IsPrebuilt() bool { return s.Repo != "" } +// TagWithoutDigest returns Tag without its optional @sha256 digest. +func (s Source) TagWithoutDigest() string { + tag, _, _ := strings.Cut(s.Tag, "@") + return tag +} + // Describe renders the source for the install log. func (s Source) Describe() string { if !s.IsPrebuilt() { diff --git a/cmd/ate-setup/internal/kube/apply.go b/cmd/ate-setup/internal/kube/apply.go index 7e797f7c13..64bfc8e492 100644 --- a/cmd/ate-setup/internal/kube/apply.go +++ b/cmd/ate-setup/internal/kube/apply.go @@ -19,6 +19,7 @@ import ( "errors" "fmt" "io/fs" + "slices" "time" apierrors "k8s.io/apimachinery/pkg/api/errors" @@ -185,13 +186,65 @@ func (c *Client) DeleteOne(ctx context.Context, obj *unstructured.Unstructured) } return err } - err = ri.Delete(ctx, obj.GetName(), metav1.DeleteOptions{}) + // An object read from the cluster carries its UID. The precondition then + // keeps a same-named object that replaced it after the read. + var opts metav1.DeleteOptions + if uid := obj.GetUID(); uid != "" { + opts.Preconditions = metav1.NewUIDPreconditions(string(uid)) + } + err = ri.Delete(ctx, obj.GetName(), opts) if err != nil && !apierrors.IsNotFound(err) { return fmt.Errorf("while deleting %s: %w", Describe(obj), err) } return nil } +// DeleteApplied deletes the objects of objs that this tool applied. An object +// with no managedFields goes with them, and stays when this tool applied none. +func (c *Client) DeleteApplied(ctx context.Context, objs []*unstructured.Unstructured) error { + var applied, unmanaged []*unstructured.Unstructured + for _, obj := range objs { + ri, err := c.resourceFor(obj) + if err != nil { + return err + } + live, err := ri.Get(ctx, obj.GetName(), metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + continue + } + if err != nil { + return fmt.Errorf("while getting %s: %w", Describe(obj), err) + } + managed := live.GetManagedFields() + switch { + case len(managed) == 0: + // The API server records no manager for an object that sets no + // field, such as a ServiceAccount with only a name. + unmanaged = append(unmanaged, live) + case slices.ContainsFunc(managed, func(entry metav1.ManagedFieldsEntry) bool { + // A patch by this tool does not count: it also reaches objects of others. + return entry.Manager == FieldManager && entry.Operation == metav1.ManagedFieldsOperationApply + }): + applied = append(applied, live) + default: + logKept(live) + } + } + if len(applied) == 0 { + for _, obj := range unmanaged { + logKept(obj) + } + return nil + } + // The objects without a manager go first. After a failure, the next run + // then still finds an applied object beside them. + return c.Delete(ctx, append(unmanaged, applied...)) +} + +func logKept(obj *unstructured.Unstructured) { + log.Infof("Keeping %s: its managedFields hold no apply by %s", Describe(obj), FieldManager) +} + // DeletePath deletes the objects described by a manifest file or directory. // // A path that does not exist is not an error. Teardown runs over a fixed list diff --git a/cmd/ate-setup/internal/kube/apply_test.go b/cmd/ate-setup/internal/kube/apply_test.go index 711f84ba4b..f69884aff3 100644 --- a/cmd/ate-setup/internal/kube/apply_test.go +++ b/cmd/ate-setup/internal/kube/apply_test.go @@ -22,11 +22,18 @@ import ( "testing" "time" + "github.com/google/go-cmp/cmp" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/apimachinery/pkg/types" "k8s.io/apimachinery/pkg/util/wait" + dynamicfake "k8s.io/client-go/dynamic/fake" + "k8s.io/client-go/kubernetes/fake" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + ktesting "k8s.io/client-go/testing" ) // Teardown walks a fixed list of manifests covering every install shape, so a @@ -158,3 +165,102 @@ func TestApplyWithRetryStopsOnCancellation(t *testing.T) { t.Errorf("apply attempted %d times, want 1", ri.attempts) } } + +// DeleteApplied deletes the objects that this tool applied, each by the UID +// that it read. An object with no manager goes first, and only beside an +// object that this tool applied. +func TestDeleteApplied(t *testing.T) { + var ( + applied = metav1.ManagedFieldsEntry{Manager: FieldManager, Operation: metav1.ManagedFieldsOperationApply} + patched = metav1.ManagedFieldsEntry{Manager: FieldManager, Operation: metav1.ManagedFieldsOperationUpdate} + otherTool = metav1.ManagedFieldsEntry{Manager: "kubectl", Operation: metav1.ManagedFieldsOperationApply} + controller = metav1.ManagedFieldsEntry{Manager: "kube-controller-manager", Operation: metav1.ManagedFieldsOperationUpdate} + ) + type managers = []metav1.ManagedFieldsEntry + // DeleteApplied gets ConfigMaps a, b and c, in that order. + for _, tc := range []struct { + name string + // cluster holds the managedFields of each ConfigMap that exists. + cluster map[string]managers + failDelete bool + // want lists the deleted ConfigMaps, in the order of the deletes. + want []string + wantErr bool + }{ + {name: "applied", cluster: map[string]managers{"a": {applied}}, want: []string{"a"}}, + { + name: "applied, with other managers", + cluster: map[string]managers{"a": {otherTool, applied, controller}}, + want: []string{"a"}, + }, + {name: "applied by another tool", cluster: map[string]managers{"a": {otherTool, controller}}}, + {name: "only patched by this tool", cluster: map[string]managers{"a": {patched}}}, + { + name: "kept, missing and applied", + cluster: map[string]managers{"a": {otherTool}, "c": {applied}}, + want: []string{"c"}, + }, + { + name: "no manager, with an applied object", + cluster: map[string]managers{"a": {applied}, "b": nil}, + want: []string{"b", "a"}, + }, + {name: "no manager, with an object of another tool", cluster: map[string]managers{"a": {otherTool}, "b": nil}}, + {name: "no manager, alone", cluster: map[string]managers{"b": nil}}, + {name: "nothing exists"}, + {name: "a delete fails", cluster: map[string]managers{"a": {applied}}, failDelete: true, wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var objs []*unstructured.Unstructured + var existing []runtime.Object + for _, name := range []string{"a", "b", "c"} { + obj := &unstructured.Unstructured{} + obj.SetAPIVersion("v1") + obj.SetKind("ConfigMap") + obj.SetNamespace("ns") + obj.SetName(name) + objs = append(objs, obj) + if managed, ok := tc.cluster[name]; ok { + live := obj.DeepCopy() + live.SetUID(types.UID("uid-" + name)) + live.SetManagedFields(managed) + existing = append(existing, live) + } + } + cs := fake.NewClientset() + cs.Fake.Resources = []*metav1.APIResourceList{ + {GroupVersion: "v1", APIResources: []metav1.APIResource{{Name: "configmaps", Kind: "ConfigMap", Namespaced: true}}}, + } + dc := dynamicfake.NewSimpleDynamicClient(clientgoscheme.Scheme, existing...) + if tc.failDelete { + dc.PrependReactor("delete", "configmaps", func(ktesting.Action) (bool, runtime.Object, error) { + return true, nil, errors.New("delete refused") + }) + } + c := NewFromClients(nil, cs, dc, cs.Discovery()) + + err := c.DeleteApplied(context.Background(), objs) + if (err != nil) != tc.wantErr { + t.Fatalf("DeleteApplied() error = %v, want error %v", err, tc.wantErr) + } + if tc.wantErr { + return + } + var deleted []string + for _, action := range dc.Actions() { + del, ok := action.(ktesting.DeleteActionImpl) + if !ok { + continue + } + pre := del.DeleteOptions.Preconditions + if pre == nil || pre.UID == nil || *pre.UID != types.UID("uid-"+del.Name) { + t.Errorf("delete of %s has preconditions %+v, want UID uid-%s", del.Name, pre, del.Name) + } + deleted = append(deleted, del.Name) + } + if diff := cmp.Diff(tc.want, deleted); diff != "" { + t.Errorf("deleted ConfigMaps (-want +got):\n%s", diff) + } + }) + } +} diff --git a/cmd/ate-setup/internal/steps/apienv.go b/cmd/ate-setup/internal/steps/apienv.go index b9320eaaac..c44b8ba955 100644 --- a/cmd/ate-setup/internal/steps/apienv.go +++ b/cmd/ate-setup/internal/steps/apienv.go @@ -360,6 +360,9 @@ func (e *Env) applyWithAPIServerEnvHash(ctx context.Context, manifest []byte) er if err := setAPIServerEgressGatewayArgs(objs, e.Namespace(), e.Cfg.EgressGatewayExtraSPIFFEIDs); err != nil { return err } + if err := setAPIServerEgressAddressArg(objs, e.Cfg.DefaultEgressGatewayAddress); err != nil { + return err + } if msg := sharedBootstrapOwnerWarning(e.Cfg.APIAuthzBootstrapOwners, e.Namespace()); msg != "" { log.Warnf("%s", msg) } @@ -400,6 +403,22 @@ func setAPIServerEgressGatewayArgs(objs []*unstructured.Unstructured, namespace return setAPIServerFlag(objs, apiServerEgressGatewayFlag, ids) } +// apiServerEgressAddressFlag is the ate-api-server flag +// setAPIServerEgressAddressArg owns. +const apiServerEgressAddressFlag = "--default-egress-gateway-address" + +// setAPIServerEgressAddressArg sets ate-api-server's default egress gateway +// address on its container in objs, replacing the one the manifest carries. +// An empty address drops the flag, which leaves actors with no egress: besides +// DNS, the sandbox lets out only TCP, and TCP goes through the gateway. +func setAPIServerEgressAddressArg(objs []*unstructured.Unstructured, address string) error { + var values []string + if address != "" { + values = []string{address} + } + return setAPIServerFlag(objs, apiServerEgressAddressFlag, values) +} + // setAPIServerFlag replaces every flag arg on ate-api-server's container in // objs with one flag=value arg per value, in order. A changed flag changes the // pod template, so it rolls the Deployment. diff --git a/cmd/ate-setup/internal/steps/apienv_test.go b/cmd/ate-setup/internal/steps/apienv_test.go index 72790fe140..f88691ca74 100644 --- a/cmd/ate-setup/internal/steps/apienv_test.go +++ b/cmd/ate-setup/internal/steps/apienv_test.go @@ -23,6 +23,8 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + ktesting "k8s.io/client-go/testing" "go.ate.dev/substrate/cmd/ate-setup/internal/config" "go.ate.dev/substrate/cmd/ate-setup/internal/kube" @@ -764,6 +766,68 @@ spec: } } +// Both deploys of ate-api-server apply through applyWithAPIServerEnvHash, so +// the configured address has to reach the Deployment there. +func TestApplyWithAPIServerEnvHashSetsEgressAddress(t *testing.T) { + const manifest = `apiVersion: apps/v1 +kind: Deployment +metadata: + name: ate-api-server + namespace: ate-system +spec: + template: + spec: + containers: + - name: ate-api-server + args: + - --default-egress-gateway-address=atenet-egress.ate-system.svc:443 +` + const owners = "system:serviceaccount:ate-system:ate-client" + for _, tc := range []struct { + name string + address string + want []string + }{ + { + name: "a set address replaces the manifest's", + address: "egress.example.svc:8443", + want: []string{ + "--authz-bootstrap-owners=" + owners, + "--default-egress-gateway-address=egress.example.svc:8443", + }, + }, + { + name: "an empty address drops the flag", + want: []string{"--authz-bootstrap-owners=" + owners}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + kc, dc := fakeDeleteKube(t, nil, nil) + // The fake dynamic client has no server-side apply, so read the + // object off the apply request. + dep := &unstructured.Unstructured{} + dc.PrependReactor("patch", "deployments", func(action ktesting.Action) (bool, runtime.Object, error) { + if err := dep.UnmarshalJSON(action.(ktesting.PatchAction).GetPatch()); err != nil { + return true, nil, err + } + return true, dep, nil + }) + e := &Env{Kube: kc, Cfg: &config.Config{ + APIAuthzBootstrapOwners: owners, + DefaultEgressGatewayAddress: tc.address, + }} + if err := e.applyWithAPIServerEnvHash(t.Context(), []byte(manifest)); err != nil { + t.Fatalf("applyWithAPIServerEnvHash() error = %v", err) + } + containers, _, _ := unstructured.NestedSlice(dep.Object, "spec", "template", "spec", "containers") + args, _, _ := unstructured.NestedStringSlice(containers[0].(map[string]any), "args") + if diff := cmp.Diff(tc.want, args); diff != "" { + t.Errorf("ate-api-server args (-want +got):\n%s", diff) + } + }) + } +} + func TestCreateAPIServerEnvVarsOmitsAuthz(t *testing.T) { e := &Env{Cfg: &config.Config{ TransferGSAName: testTransferGSAName, ProjectID: testProjectID, diff --git a/cmd/ate-setup/internal/steps/credprovider_test.go b/cmd/ate-setup/internal/steps/credprovider_test.go index 06edc380a7..83b96b47c7 100644 --- a/cmd/ate-setup/internal/steps/credprovider_test.go +++ b/cmd/ate-setup/internal/steps/credprovider_test.go @@ -15,6 +15,7 @@ package steps import ( + "slices" "testing" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" @@ -46,6 +47,16 @@ func TestK8sCredentialProviderManifestsAgree(t *testing.T) { if got := mountedConfigMaps(dep); len(got) != 1 || got[0] != k8sCredentialProviderPolicyConfigMap { t.Errorf("deployment/%s mounts ConfigMaps %v, want only %q", k8sCredentialProviderDeployment, got, k8sCredentialProviderPolicyConfigMap) } + // The provider's NetworkPolicy admits no scraper, so the OTLP push is the + // only way its metrics leave the pod, and the push needs the endpoint. + if !slices.Contains(envFromConfigMaps(dep), otelConfigMap) { + t.Errorf("deployment/%s does not load configmap/%s through envFrom, so its metrics go to localhost:4317", k8sCredentialProviderDeployment, otelConfigMap) + } + // applyOtelEndpointOverride must restart every Deployment that reads the + // ConfigMap, or the pod keeps the old endpoint in its environment. + if !slices.Contains(otelOverrideDeployments, k8sCredentialProviderDeployment) { + t.Errorf("deployment/%s reads configmap/%s but is not in otelOverrideDeployments, so --otlp-endpoint does not restart it", k8sCredentialProviderDeployment, otelConfigMap) + } svc := findObject(provider, "Service", k8sCredentialProviderDeployment) if svc == nil { t.Fatalf("provider manifest has no service/%s", k8sCredentialProviderDeployment) @@ -202,3 +213,20 @@ func mountedConfigMaps(dep *unstructured.Unstructured) []string { } return names } + +// envFromConfigMaps returns the names of the ConfigMaps a Deployment's +// containers load through envFrom. +func envFromConfigMaps(dep *unstructured.Unstructured) []string { + containers, _, _ := unstructured.NestedSlice(dep.Object, "spec", "template", "spec", "containers") + var names []string + for _, c := range containers { + sources, _, _ := unstructured.NestedSlice(c.(map[string]any), "envFrom") + for _, src := range sources { + name, found, _ := unstructured.NestedString(src.(map[string]any), "configMapRef", "name") + if found { + names = append(names, name) + } + } + } + return names +} diff --git a/cmd/ate-setup/internal/steps/csi.go b/cmd/ate-setup/internal/steps/csi.go index 0a2d9e0e24..d4459b3c47 100644 --- a/cmd/ate-setup/internal/steps/csi.go +++ b/cmd/ate-setup/internal/steps/csi.go @@ -326,7 +326,7 @@ data: listeners: - name: csi_tls_listener address: - socket_address: { address: 0.0.0.0, port_value: 10000 } + socket_address: { address: "::", ipv4_compat: true, port_value: 10000 } filter_chains: - transport_socket: name: envoy.transport_sockets.tls @@ -398,7 +398,7 @@ spec: - $patch: delete name: socat - name: envoy - image: envoyproxy/envoy:v1.39.5@sha256:8fc594a5d85eb76dca24155cfb9208882406873932b20cf33649a0a611194c43 + image: envoyproxy/envoy:v1.40.0@sha256:459f2a6404c340fe6afccd69d85527012d47f3c036765493e6f8f3113fa384de command: - /usr/local/bin/envoy args: diff --git a/cmd/ate-setup/internal/steps/csi_test.go b/cmd/ate-setup/internal/steps/csi_test.go index b8f83ea8b7..5393d8efc3 100644 --- a/cmd/ate-setup/internal/steps/csi_test.go +++ b/cmd/ate-setup/internal/steps/csi_test.go @@ -229,6 +229,15 @@ func TestTheNFSDriverConfigEnablesTLSAgainstTheControllerService(t *testing.T) { } } +func TestTheNFSControllerListensOnIPv4AndIPv6(t *testing.T) { + var configMap corev1.ConfigMap + decodeYAML(t, "csiNFSEnvoyConfigMap", csiNFSEnvoyConfigMap("spiffe://test"), &configMap) + want := `socket_address: { address: "::", ipv4_compat: true, port_value: 10000 }` + if !strings.Contains(configMap.Data["envoy.yaml"], want) { + t.Errorf("Envoy listener does not contain %q", want) + } +} + // hack/setup-csi-nfs-kind.sh is the same install by hand and must keep the same security decisions. func TestTheNFSShellSetupMatchesTheGoSetup(t *testing.T) { script, err := os.ReadFile(filepath.Join(repoRoot(t), "hack", "setup-csi-nfs-kind.sh")) @@ -243,6 +252,7 @@ func TestTheNFSShellSetupMatchesTheGoSetup(t *testing.T) { } } for _, required := range []string{ + `socket_address: { address: "::", ipv4_compat: true, port_value: 10000 }`, "require_client_certificate: true", "serverName: csi-nfs-controller.kube-system.svc\n", "usePodIdentity: true", diff --git a/cmd/ate-setup/internal/steps/delete.go b/cmd/ate-setup/internal/steps/delete.go index 3e52e7ec7a..8ca2bfcc14 100644 --- a/cmd/ate-setup/internal/steps/delete.go +++ b/cmd/ate-setup/internal/steps/delete.go @@ -187,11 +187,7 @@ func (e *Env) DeleteAtenet(ctx context.Context) error { return err } - for _, path := range [][]string{ - {"atenet-router.yaml"}, - {"components", "agentgateway", "configmap.yaml"}, - {"atenet-egress.yaml"}, - } { + for _, path := range atenetManifests { if err := e.Kube.DeletePath(ctx, e.Cfg.Manifest(path...)); err != nil { return err } diff --git a/cmd/ate-setup/internal/steps/deploy.go b/cmd/ate-setup/internal/steps/deploy.go index b1f9c4fe7a..de28dfd839 100644 --- a/cmd/ate-setup/internal/steps/deploy.go +++ b/cmd/ate-setup/internal/steps/deploy.go @@ -71,7 +71,7 @@ func (e *Env) DeployAteSystem(ctx context.Context, opts DeployOptions) error { } // Fail fast on an unusable credential provider selection before touching // the cluster. - providers, err := e.Cfg.CredentialProviders() + providers, err := e.credentialProviders() if err != nil { return err } @@ -94,6 +94,11 @@ func (e *Env) DeployAteSystem(ctx context.Context, opts DeployOptions) error { if _, err := clusterSnapshotLocation(e.Cfg.SnapshotLocation, e.Cfg.PreviewGates); err != nil { return err } + // Likewise the egress upstream CA bundle. The gateway that mounts it is + // applied last. + if err := e.checkEgressUpstreamCABundle(ctx); err != nil { + return err + } if err := e.requireNoWorkerPods(ctx); err != nil { return err } @@ -170,22 +175,27 @@ func (e *Env) DeployAteSystem(ctx context.Context, opts DeployOptions) error { return err } - // Deploy egress gateway explicitly so kind and experimental modes are applied. - if err := e.EnsureEgressMITMCAPoolSecret(ctx); err != nil { - return err - } - // After the podcertificate controller: the provider serves with a - // projected pod certificate. - if config.HasKubernetesProvider(providers) { - err = e.deployK8sCredentialProvider(ctx) - } else { - err = e.removeK8sCredentialProvider(ctx) - } - if err != nil { + if err := e.removeSkippedGateways(ctx); err != nil { return err } - if err := e.applyAtenetEgress(ctx, providers); err != nil { - return err + if !e.Cfg.NoAtenetEgress { + // Deploy egress gateway explicitly so kind and experimental modes are applied. + if err := e.EnsureEgressMITMCAPoolSecret(ctx); err != nil { + return err + } + // After the podcertificate controller: the provider serves with a + // projected pod certificate. + if config.HasKubernetesProvider(providers) { + err = e.deployK8sCredentialProvider(ctx) + } else { + err = e.removeK8sCredentialProvider(ctx) + } + if err != nil { + return err + } + if err := e.applyAtenetEgress(ctx, providers); err != nil { + return err + } } if microvmPrep != nil { if err := e.applyMicroVMSandboxConfig(ctx, microvmPrep); err != nil { @@ -200,12 +210,10 @@ func (e *Env) DeployAteSystem(ctx context.Context, opts DeployOptions) error { rollout{kube.KindDeployment, "ate-api-server"}, rollout{kube.KindDeployment, "ate-idp-server"}, rollout{kube.KindDeployment, "ate-controller"}, - rollout{kube.KindDeployment, "atenet-router"}, - rollout{kube.KindDeployment, "atenet-egress"}, rollout{kube.KindDaemonSet, "atelet"}, ) - if config.HasKubernetesProvider(providers) { - waits = append(waits, rollout{kube.KindDeployment, k8sCredentialProviderDeployment}) + for _, name := range e.gatewayDeployments(providers) { + waits = append(waits, rollout{kube.KindDeployment, name}) } for _, w := range waits { if err := e.Kube.RolloutStatus(ctx, w.kind, e.Namespace(), w.name, e.Cfg.RolloutTimeout); err != nil { @@ -218,6 +226,93 @@ func (e *Env) DeployAteSystem(ctx context.Context, opts DeployOptions) error { return e.applyOtelEndpointOverride(ctx) } +// credentialProviders is the provider selection for atenet-egress, the only +// caller of a provider. An install without atenet-egress needs none. +func (e *Env) credentialProviders() ([]config.CredentialProvider, error) { + if e.Cfg.NoAtenetEgress { + return nil, nil + } + return e.Cfg.CredentialProviders() +} + +// gatewayDeployments names the Deployments of the built-in gateways this +// install has, and with atenet-egress the bundled credential provider when +// providers selects it. +func (e *Env) gatewayDeployments(providers []config.CredentialProvider) []string { + var names []string + if !e.Cfg.NoAtenetRouter { + names = append(names, "atenet-router") + } + if !e.Cfg.NoAtenetEgress { + names = append(names, "atenet-egress") + if config.HasKubernetesProvider(providers) { + names = append(names, k8sCredentialProviderDeployment) + } + } + return names +} + +// removeSkippedGateways deletes the workload objects that ate-setup applied +// for each skipped gateway. Without atenet-egress, it first deletes the +// bundled credential provider. +func (e *Env) removeSkippedGateways(ctx context.Context) error { + skipped := e.skippedGateways() + if len(skipped) == 0 { + return nil + } + log.Step("remove_skipped_gateways") + if e.Cfg.NoAtenetEgress { + // The provider goes first, so that a later failure cannot leave its + // cluster-wide Secret read behind. + provider, err := kube.LoadPath(e.k8sCredentialProviderPath(k8sCredentialProviderManifest)) + if err != nil { + return err + } + if err := e.Kube.DeleteApplied(ctx, provider); err != nil { + return err + } + } + for _, gateway := range skipped { + objs, err := e.gatewayObjects(gateway) + if err != nil { + return err + } + if err := e.Kube.DeleteApplied(ctx, objs); err != nil { + return err + } + } + return nil +} + +// atenetManifests are the files that hold the workload objects of the two +// gateways, for both dataplanes. +var atenetManifests = [][]string{ + {"atenet-router.yaml"}, + {"components", "agentgateway", "configmap.yaml"}, + {"atenet-egress.yaml"}, +} + +// gatewayObjects returns the workload objects of gateway. It reads +// atenetManifests and not a render, so it holds the ConfigMaps of both +// dataplanes, whichever one the install selects now. The files hold no +// NetworkPolicy and no PodMonitoring. deploy atenet applies neither, so a +// gateway that it installs again needs the NetworkPolicy in place. +func (e *Env) gatewayObjects(gateway string) ([]*unstructured.Unstructured, error) { + var objs []*unstructured.Unstructured + for _, file := range atenetManifests { + defined, err := kube.LoadPath(e.Cfg.Manifest(file...)) + if err != nil { + return nil, err + } + for _, obj := range defined { + if ofGateway(obj.GetName(), gateway) { + objs = append(objs, obj) + } + } + } + return objs, nil +} + // DeployPodCertificateController creates any missing signer CA pools, applies // the podcertificate controller, and waits until it is rolling and has // published its trust bundles. @@ -552,10 +647,15 @@ func (e *Env) ateletManifestPath() string { func (e *Env) DeployAtenet(ctx context.Context) error { log.Step("deploy_atenet") - providers, err := e.Cfg.CredentialProviders() + providers, err := e.credentialProviders() if err != nil { return err } + // The router and the credential provider are applied ahead of the egress + // gateway, so check its upstream CA bundle before any of them. + if err := e.checkEgressUpstreamCABundle(ctx); err != nil { + return err + } if err := e.EnsureCRDs(ctx); err != nil { return err } @@ -569,33 +669,36 @@ func (e *Env) DeployAtenet(ctx context.Context) error { return err } - routerManifest, err := e.renderAtenetRouterManifest(ctx) - if err != nil { - return err - } - if err := e.Kube.ApplyBytes(ctx, routerManifest); err != nil { - return err - } - if err := e.EnsureEgressMITMCAPoolSecret(ctx); err != nil { + if err := e.removeSkippedGateways(ctx); err != nil { return err } - if config.HasKubernetesProvider(providers) { - err = e.deployK8sCredentialProvider(ctx) - } else { - err = e.removeK8sCredentialProvider(ctx) - } - if err != nil { - return err + if !e.Cfg.NoAtenetRouter { + routerManifest, err := e.renderAtenetRouterManifest(ctx) + if err != nil { + return err + } + if err := e.Kube.ApplyBytes(ctx, routerManifest); err != nil { + return err + } } - if err := e.applyAtenetEgress(ctx, providers); err != nil { - return err + if !e.Cfg.NoAtenetEgress { + if err := e.EnsureEgressMITMCAPoolSecret(ctx); err != nil { + return err + } + if config.HasKubernetesProvider(providers) { + err = e.deployK8sCredentialProvider(ctx) + } else { + err = e.removeK8sCredentialProvider(ctx) + } + if err != nil { + return err + } + if err := e.applyAtenetEgress(ctx, providers); err != nil { + return err + } } - deployments := []string{"atenet-router", "atenet-egress"} - if config.HasKubernetesProvider(providers) { - deployments = append(deployments, k8sCredentialProviderDeployment) - } - for _, name := range deployments { + for _, name := range e.gatewayDeployments(providers) { if err := e.Kube.RolloutStatus(ctx, kube.KindDeployment, e.Namespace(), name, e.Cfg.RolloutTimeout); err != nil { return err } diff --git a/cmd/ate-setup/internal/steps/deploy_test.go b/cmd/ate-setup/internal/steps/deploy_test.go index 2cb7e0e310..25ab15fefd 100644 --- a/cmd/ate-setup/internal/steps/deploy_test.go +++ b/cmd/ate-setup/internal/steps/deploy_test.go @@ -15,15 +15,22 @@ package steps import ( + "context" "errors" "io/fs" "path/filepath" + "slices" + "strings" "testing" "github.com/google/go-cmp/cmp" corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/api/meta" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/client-go/kubernetes/fake" + ktesting "k8s.io/client-go/testing" "go.ate.dev/substrate/cmd/ate-setup/internal/config" "go.ate.dev/substrate/cmd/ate-setup/internal/kube" @@ -229,3 +236,416 @@ func TestComponentManifestsMatchSystemBundle(t *testing.T) { } } } + +// A deploy drops every object of a skipped gateway from what it applies, and +// nothing else. With agentgateway, the manifest of each gateway carries the +// ConfigMaps of both. +func TestWithoutSkippedGateways(t *testing.T) { + const ( + egressPolicy = "NetworkPolicy/atenet-egress" + routerAGConfig = "ConfigMap/atenet-router-agentgateway-config" + egressAGConfig = "ConfigMap/atenet-egress-agentgateway-substrate-config" + ) + routerObjects := []string{ + "Deployment/atenet-router", "NetworkPolicy/atenet-router", "Role/atenet-router-endpointslices", + "RoleBinding/atenet-router-endpointslices", "Service/atenet-router", "ServiceAccount/atenet-router", + } + system := func(e *Env) string { return e.Cfg.Path(SystemOverlay(e.Cfg)) } + file := func(name string) func(*Env) string { + return func(e *Env) string { return e.Cfg.Manifest(name) } + } + dir := func(name string) func(*Env) string { + return func(e *Env) string { return e.Cfg.Path(installDir + "/" + name) } + } + kindNames := func(objs []*unstructured.Unstructured) []string { + var out []string + for _, obj := range objs { + out = append(out, obj.GetKind()+"/"+obj.GetName()) + } + slices.Sort(out) + return out + } + for _, tc := range []struct { + name string + dataplane string + kind bool + path func(*Env) string + noRouter, noEgress bool + wantDropped []string + // wantNoneKept is for a gateway's own manifest: a new object in it has + // to carry the gateway's name too. + wantNoneKept bool + }{ + {name: "system bundle, both gateways", dataplane: config.RouterEnvoy, path: system}, + { + name: "system bundle, no router", dataplane: config.RouterEnvoy, path: system, noRouter: true, + wantDropped: append(slices.Clone(routerObjects), "ConfigMap/atenet-router-envoy-config", "PodMonitoring/atenet-router-envoy"), + }, + { + name: "system bundle, no egress", dataplane: config.RouterEnvoy, path: system, noEgress: true, + wantDropped: []string{egressPolicy}, + }, + { + name: "agentgateway system bundle on kind, neither gateway", dataplane: config.RouterAgentgateway, kind: true, path: system, + noRouter: true, noEgress: true, + wantDropped: append(slices.Clone(routerObjects), egressPolicy, routerAGConfig, egressAGConfig), + }, + { + name: "agentgateway egress manifest, no router", dataplane: config.RouterAgentgateway, path: dir("agentgateway-egress"), + noRouter: true, wantDropped: []string{routerAGConfig}, + }, + { + name: "agentgateway router manifest, no egress", dataplane: config.RouterAgentgateway, path: dir("agentgateway-router"), + noEgress: true, wantDropped: []string{egressAGConfig}, + }, + {name: "envoy router manifest, no router", dataplane: config.RouterEnvoy, path: file("atenet-router.yaml"), noRouter: true, wantNoneKept: true}, + {name: "router monitoring, no router", dataplane: config.RouterEnvoy, path: file("atenet-router-monitoring.yaml"), noRouter: true, wantNoneKept: true}, + {name: "envoy egress manifest, no egress", dataplane: config.RouterEnvoy, path: file("atenet-egress.yaml"), noEgress: true, wantNoneKept: true}, + } { + t.Run(tc.name, func(t *testing.T) { + e := &Env{Cfg: &config.Config{ + Root: repoRoot(t), Router: tc.dataplane, Kind: tc.kind, + NoAtenetRouter: tc.noRouter, NoAtenetEgress: tc.noEgress, + }} + manifest, err := e.render(tc.path(e)) + if err != nil { + t.Fatalf("render: %v", err) + } + objs, err := kube.DecodeManifestBytes(manifest) + if err != nil { + t.Fatalf("DecodeManifestBytes() error = %v", err) + } + stripped, err := e.withoutSkippedGateways(manifest) + if err != nil { + t.Fatalf("withoutSkippedGateways() error = %v", err) + } + keptObjs, err := kube.DecodeManifestBytes(stripped) + if err != nil { + t.Fatalf("DecodeManifestBytes() error = %v", err) + } + all := kindNames(objs) + kept := kindNames(keptObjs) + // An existing installation keeps a dropped object unless + // removeSkippedGateways deletes it. Only a NetworkPolicy and a + // PodMonitoring stay on purpose. + var deleted []string + for _, gateway := range e.skippedGateways() { + objs, err := e.gatewayObjects(gateway) + if err != nil { + t.Fatalf("gatewayObjects(%s) error = %v", gateway, err) + } + deleted = append(deleted, kindNames(objs)...) + } + for _, obj := range all { + stays := strings.HasPrefix(obj, "NetworkPolicy/") || strings.HasPrefix(obj, "PodMonitoring/") + if !slices.Contains(kept, obj) && !slices.Contains(deleted, obj) && !stays { + t.Errorf("a deploy drops %s from the apply, but does not delete it from an existing installation", obj) + } + } + if tc.wantNoneKept { + if len(all) == 0 || len(kept) != 0 { + t.Errorf("kept %v of %d objects, want none of at least one", kept, len(all)) + } + return + } + var dropped []string + for _, obj := range all { + if !slices.Contains(kept, obj) { + dropped = append(dropped, obj) + } + } + slices.Sort(tc.wantDropped) + if diff := cmp.Diff(tc.wantDropped, dropped); diff != "" { + t.Errorf("dropped objects (-want +got):\n%s", diff) + } + }) + } +} + +// appliedBy returns objs as the API server holds them after manager applied +// each one. +func appliedBy(t *testing.T, manager string, objs []*unstructured.Unstructured) []*unstructured.Unstructured { + t.Helper() + tracker := fake.NewClientset().Tracker() + force := true + var out []*unstructured.Unstructured + for _, obj := range objs { + gvr, _ := meta.UnsafeGuessKindToResource(obj.GroupVersionKind()) + opts := metav1.PatchOptions{FieldManager: manager, Force: &force} + if err := tracker.Apply(gvr, obj.DeepCopy(), obj.GetNamespace(), opts); err != nil { + t.Fatalf("apply of %s by %s: %v", kube.Describe(obj), manager, err) + } + live, err := tracker.Get(gvr, obj.GetNamespace(), obj.GetName()) + if err != nil { + t.Fatalf("get of %s: %v", kube.Describe(obj), err) + } + accessor, err := meta.Accessor(live) + if err != nil { + t.Fatalf("accessor of %s: %v", kube.Describe(obj), err) + } + obj = obj.DeepCopy() + obj.SetManagedFields(accessor.GetManagedFields()) + out = append(out, obj) + } + return out +} + +// A deploy with a skip setting deletes what ate-setup applied for the skipped +// gateways, and nothing else. +func TestRemoveSkippedGateways(t *testing.T) { + router := []string{ + "ConfigMap/atenet-router-agentgateway-config", "ConfigMap/atenet-router-envoy-config", + "Deployment/atenet-router", "Role/atenet-router-endpointslices", + "RoleBinding/atenet-router-endpointslices", "Service/atenet-router", "ServiceAccount/atenet-router", + } + egress := []string{ + "ConfigMap/atenet-egress", "ConfigMap/atenet-egress-agentgateway-substrate-config", + "Deployment/atenet-egress", "Service/atenet-egress", "ServiceAccount/atenet-egress", + } + bundledProvider := []string{ + "ClusterRole/k8s-credential-provider-secret-reader", "ClusterRoleBinding/k8s-credential-provider-secret-reader", + "Deployment/k8s-credential-provider", "NetworkPolicy/k8s-credential-provider", + "Service/k8s-credential-provider", "ServiceAccount/k8s-credential-provider", + } + + // What an install with both gateways and the bundled provider holds. + cfg := &config.Config{Root: repoRoot(t)} + provider := (&Env{Cfg: cfg}).k8sCredentialProviderPath + var installed []*unstructured.Unstructured + for _, path := range []string{ + cfg.Manifest("atenet-router.yaml"), + cfg.Manifest("atenet-egress.yaml"), + cfg.Manifest("components", "agentgateway", "configmap.yaml"), + cfg.Manifest("ate-system-networkpolicies.yaml"), + provider(k8sCredentialProviderManifest), + provider(k8sCredentialProviderPolicyManifest), + } { + objs, err := kube.LoadPath(path) + if err != nil { + t.Fatalf("LoadPath(%s) error = %v", path, err) + } + installed = append(installed, objs...) + } + pool := &unstructured.Unstructured{} + pool.SetAPIVersion("v1") + pool.SetKind("Secret") + pool.SetNamespace(NamespaceAteSystem) + pool.SetName(SecretEgressMITMCAPool) + installed = append(installed, pool) + + ours := appliedBy(t, kube.FieldManager, installed) + theirs := appliedBy(t, "kubectl", installed) + // The router of ate-setup, beside an egress gateway and a provider of + // another tool. + var onlyRouterOurs []*unstructured.Unstructured + for i, obj := range installed { + if ofGateway(obj.GetName(), "atenet-router") { + onlyRouterOurs = append(onlyRouterOurs, ours[i]) + } else { + onlyRouterOurs = append(onlyRouterOurs, theirs[i]) + } + } + + for _, tc := range []struct { + name string + noRouter, noEgress bool + cluster []*unstructured.Unstructured + want []string + }{ + {name: "both gateways", cluster: ours}, + {name: "no router", noRouter: true, cluster: ours, want: router}, + {name: "no egress", noEgress: true, cluster: ours, want: slices.Concat(egress, bundledProvider)}, + { + name: "neither gateway", noRouter: true, noEgress: true, cluster: ours, + want: slices.Concat(router, egress, bundledProvider), + }, + {name: "neither gateway, installed by another tool", noRouter: true, noEgress: true, cluster: theirs}, + { + name: "neither gateway, only the router installed by ate-setup", noRouter: true, noEgress: true, + cluster: onlyRouterOurs, want: router, + }, + {name: "neither gateway, nothing installed", noRouter: true, noEgress: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var dyn []runtime.Object + for _, obj := range tc.cluster { + dyn = append(dyn, obj.DeepCopy()) + } + k, dc := fakeDeleteKube(t, nil, dyn) + e := &Env{ + Cfg: &config.Config{Root: cfg.Root, NoAtenetRouter: tc.noRouter, NoAtenetEgress: tc.noEgress}, + Kube: k, + } + if err := e.removeSkippedGateways(context.Background()); err != nil { + t.Fatalf("removeSkippedGateways() error = %v", err) + } + var gone []string + for _, obj := range tc.cluster { + exists, err := k.Exists(context.Background(), obj.GroupVersionKind(), obj.GetNamespace(), obj.GetName()) + if err != nil { + t.Fatalf("Exists(%s) error = %v", kube.Describe(obj), err) + } + if !exists { + gone = append(gone, obj.GetKind()+"/"+obj.GetName()) + } + } + slices.Sort(gone) + if diff := cmp.Diff(slices.Sorted(slices.Values(tc.want)), gone); diff != "" { + t.Errorf("objects gone after removeSkippedGateways() (-want +got):\n%s", diff) + } + + gatewayGone := false + for _, action := range dc.Actions() { + del, ok := action.(ktesting.DeleteActionImpl) + if !ok { + continue + } + if !strings.HasPrefix(del.Name, "k8s-credential-provider") { + gatewayGone = true + } else if gatewayGone { + t.Errorf("provider object %s deleted after a gateway object, want the provider first", del.Name) + } + } + }) + } +} + +// deploy atenet with both gateways skipped deletes the gateways that ate-setup +// applied. +func TestDeployAtenetRemovesSkippedGateways(t *testing.T) { + cfg := &config.Config{Root: repoRoot(t), NoAtenetRouter: true, NoAtenetEgress: true} + e := &Env{Cfg: cfg} + var gateways []*unstructured.Unstructured + for _, file := range []string{"atenet-router.yaml", "atenet-egress.yaml"} { + objs, err := kube.LoadPath(cfg.Manifest(file)) + if err != nil { + t.Fatalf("LoadPath(%s) error = %v", file, err) + } + gateways = append(gateways, objs...) + } + gateways = appliedBy(t, kube.FieldManager, gateways) + // EnsureCRDs applies a CRD that the cluster lacks, and waits for it. + crds, err := e.generatedCRDs() + if err != nil { + t.Fatalf("generatedCRDs() error = %v", err) + } + var dyn []runtime.Object + for _, obj := range slices.Concat(crds, gateways) { + dyn = append(dyn, obj.DeepCopy()) + } + namespace := &corev1.Namespace{ + ObjectMeta: metav1.ObjectMeta{Name: NamespaceAteSystem}, + Status: corev1.NamespaceStatus{Phase: corev1.NamespaceActive}, + } + k, dc := fakeDeleteKube(t, []runtime.Object{namespace}, dyn) + // The fake dynamic client cannot apply, so accept each apply of the steps + // before the delete. + dc.PrependReactor("patch", "*", func(ktesting.Action) (bool, runtime.Object, error) { return true, nil, nil }) + e.Kube = k + + if err := e.DeployAtenet(t.Context()); err != nil { + t.Fatalf("DeployAtenet() error = %v", err) + } + for _, obj := range gateways { + exists, err := k.Exists(t.Context(), obj.GroupVersionKind(), obj.GetNamespace(), obj.GetName()) + if err != nil { + t.Fatalf("Exists(%s) error = %v", kube.Describe(obj), err) + } + if exists { + t.Errorf("%s exists after DeployAtenet(), want it deleted", kube.Describe(obj)) + } + } +} + +// Only atenet-egress calls a credential provider, so an install without it +// needs no provider selection and uses none. +func TestCredentialProvidersWithoutEgress(t *testing.T) { + const bundled = `{"name":"k8s.io"}` + for _, tc := range []struct { + name string + selected string + noEgress bool + want int + wantErr bool + }{ + {name: "atenet-egress requires a selection", wantErr: true}, + {name: "atenet-egress uses the selection", selected: bundled, want: 1}, + {name: "no atenet-egress requires no selection", noEgress: true}, + {name: "no atenet-egress uses no provider", selected: bundled, noEgress: true}, + } { + t.Run(tc.name, func(t *testing.T) { + e := &Env{Cfg: &config.Config{CredentialProviderJSON: tc.selected, NoAtenetEgress: tc.noEgress}} + providers, err := e.credentialProviders() + if (err != nil) != tc.wantErr || len(providers) != tc.want { + t.Errorf("credentialProviders() = %v, %v, want %d providers and wantErr %v", providers, err, tc.want, tc.wantErr) + } + }) + } +} + +// A deploy waits only for the gateways it installs. +func TestGatewayDeployments(t *testing.T) { + bundled, err := (&config.Config{CredentialProviderJSON: `{"name":"k8s.io"}`}).CredentialProviders() + if err != nil { + t.Fatalf("CredentialProviders() error = %v", err) + } + for _, tc := range []struct { + name string + noRouter, noEgress bool + providers []config.CredentialProvider + want []string + }{ + {name: "both gateways", want: []string{"atenet-router", "atenet-egress"}}, + { + name: "both gateways and the bundled provider", providers: bundled, + want: []string{"atenet-router", "atenet-egress", k8sCredentialProviderDeployment}, + }, + {name: "no router", noRouter: true, want: []string{"atenet-egress"}}, + {name: "no egress", noEgress: true, want: []string{"atenet-router"}}, + {name: "no egress and the bundled provider", noEgress: true, providers: bundled, want: []string{"atenet-router"}}, + {name: "neither gateway", noRouter: true, noEgress: true}, + } { + t.Run(tc.name, func(t *testing.T) { + e := &Env{Cfg: &config.Config{NoAtenetRouter: tc.noRouter, NoAtenetEgress: tc.noEgress}} + if diff := cmp.Diff(tc.want, e.gatewayDeployments(tc.providers)); diff != "" { + t.Errorf("gatewayDeployments() (-want +got):\n%s", diff) + } + }) + } +} + +// A missing bundle stops a deploy before it writes anything. The egress +// gateway is applied after the router and the credential provider, which would +// otherwise already have rolled. +func TestDeployChecksEgressUpstreamCABundleFirst(t *testing.T) { + for _, tc := range []struct { + name string + deploy func(*Env) error + }{ + {"deploy atenet", func(e *Env) error { return e.DeployAtenet(t.Context()) }}, + {"deploy ate-system", func(e *Env) error { return e.DeployAteSystem(t.Context(), DeployOptions{SetupCSI: "none"}) }}, + } { + t.Run(tc.name, func(t *testing.T) { + typed := fake.NewSimpleClientset() + e := &Env{ + Cfg: &config.Config{ + Root: repoRoot(t), + Kind: true, + SnapshotLocation: "gs://bucket/", + CredentialProviderJSON: `{"enabled":false}`, + EgressUpstreamCABundle: config.EgressUpstreamCABundle{ConfigMap: "egress-roots", Key: "ca.crt"}, + }, + Kube: &kube.Client{Typed: typed}, + } + err := tc.deploy(e) + if err == nil || !strings.Contains(err.Error(), "configmap ate-system/egress-roots not found") { + t.Fatalf("error = %v, want the missing bundle", err) + } + for _, a := range typed.Actions() { + if a.GetVerb() != "get" { + t.Errorf("%s %s ran before the bundle check", a.GetVerb(), a.GetResource().Resource) + } + } + }) + } +} diff --git a/cmd/ate-setup/internal/steps/egress_dns_test.go b/cmd/ate-setup/internal/steps/egress_dns_test.go index 31a1f9760f..c6701dfc65 100644 --- a/cmd/ate-setup/internal/steps/egress_dns_test.go +++ b/cmd/ate-setup/internal/steps/egress_dns_test.go @@ -18,6 +18,7 @@ import ( "bufio" "bytes" "errors" + "fmt" "io" "io/fs" "os" @@ -33,41 +34,42 @@ import ( "go.ate.dev/substrate/cmd/ate-setup/internal/kustomize" ) -// TestEgressDNSLookupFamily requires ALL on every dynamic forward proxy DNS -// cache in the install tree, so a new egress manifest is checked the day it is -// added rather than the day it is installed. atenet-egress.yaml says why ALL. -func TestEgressDNSLookupFamily(t *testing.T) { +// TestEgressDNSCacheSettings requires ALL and the resolved address filter on +// every dynamic forward proxy DNS cache in the install tree, so a new egress +// manifest is checked the day it is added rather than the day it is installed. +// atenet-egress.yaml says why. +func TestEgressDNSCacheSettings(t *testing.T) { for _, path := range manifestPaths(t) { caches := dnsCacheConfigs(t, path) if len(caches) == 0 { continue } t.Run(filepath.Base(path), func(t *testing.T) { - requireLookupFamilyALL(t, caches) + requireDNSCacheSettings(t, caches) }) } } -// TestRenderedOverlaysDNSLookupFamily repeats the check against the output of +// TestRenderedOverlaysDNSCacheSettings repeats the check against the output of // every overlay, because a manifest is not what gets applied: a patch or a // configMapGenerator can put back a pin that no file in the tree contains. -func TestRenderedOverlaysDNSLookupFamily(t *testing.T) { +func TestRenderedOverlaysDNSCacheSettings(t *testing.T) { for _, dir := range overlayDirs(t) { t.Run(filepath.Base(dir), func(t *testing.T) { rendered, err := kustomize.Build(dir) if err != nil { t.Fatalf("rendering %s: %v", dir, err) } - requireLookupFamilyALL(t, dnsCacheConfigsIn(t, dir, bytes.NewReader(rendered))) + requireDNSCacheSettings(t, dnsCacheConfigsIn(t, dir, bytes.NewReader(rendered))) }) } } // TestEgressManifestsCarryDNSCaches pins the cache count of the envoy egress // manifest the installer selects, so a walk that quietly stopped matching -// fails here instead of passing TestEgressDNSLookupFamily vacuously. +// fails here instead of passing TestEgressDNSCacheSettings vacuously. func TestEgressManifestsCarryDNSCaches(t *testing.T) { - const want = 7 + const want = 8 env := &Env{Cfg: &config.Config{Root: repoRoot(t)}} path := env.atenetEgressManifestPath() if got := len(dnsCacheConfigs(t, path)); got != want { @@ -101,12 +103,29 @@ func TestOverlayDiscoveryCoversTheInstaller(t *testing.T) { } } -func requireLookupFamilyALL(t *testing.T, caches []map[string]any) { +func requireDNSCacheSettings(t *testing.T, caches []map[string]any) { t.Helper() + // A sample of the denied ranges: loopback and link-local in both families. + mustDeny := []string{"127.0.0.0/8", "169.254.0.0/16", "::1/128", "fe80::/10"} for _, cache := range caches { if got := cache["dns_lookup_family"]; got != "ALL" { t.Errorf("dns_cache_config %v: dns_lookup_family = %v, want ALL", cache["name"], got) } + var denied []string + filter, _ := cache["resolved_address_filter"].(map[string]any) + ranges, _ := filter["ranges"].([]any) + for _, r := range ranges { + r, _ := r.(map[string]any) + denied = append(denied, fmt.Sprintf("%v/%v", r["address_prefix"], r["prefix_len"])) + } + if filter["invert_match"] == true { + t.Errorf("dns_cache_config %v: resolved_address_filter is inverted", cache["name"]) + } + for _, cidr := range mustDeny { + if !slices.Contains(denied, cidr) { + t.Errorf("dns_cache_config %v: resolved_address_filter does not deny %s", cache["name"], cidr) + } + } } } diff --git a/cmd/ate-setup/internal/steps/overlay.go b/cmd/ate-setup/internal/steps/overlay.go index 2fbaf8ca66..94692aa5bd 100644 --- a/cmd/ate-setup/internal/steps/overlay.go +++ b/cmd/ate-setup/internal/steps/overlay.go @@ -17,14 +17,21 @@ package steps import ( "bytes" "context" + "crypto/x509" "encoding/json" + "encoding/pem" + "errors" "fmt" "os" "path/filepath" + "slices" "strconv" "strings" "time" + "sigs.k8s.io/kustomize/kyaml/kio" + "sigs.k8s.io/kustomize/kyaml/yaml" + "go.ate.dev/substrate/cmd/ate-setup/internal/config" "go.ate.dev/substrate/cmd/ate-setup/internal/images" "go.ate.dev/substrate/cmd/ate-setup/internal/kustomize" @@ -53,6 +60,17 @@ const fakeDataPlaneComponent = installDir + "/components/fake-data-plane" const agentgatewayStaticMTLSComponent = installDir + "/components/agentgateway-static-mtls" +// pprofComponent is the kustomize component that exposes :6060 pprof servers +// on the instrumented ate-system workloads and propagates worker pprof through +// ate-controller, layered over every control plane apply under --pprof=on or +// --pprof=contention. +const pprofComponent = installDir + "/components/pprof" + +// pprofContentionComponent is the kustomize component that enables Go mutex +// and block contention sampling alongside pprofComponent, layered over every +// control plane apply under --pprof=contention. +const pprofContentionComponent = installDir + "/components/pprof-contention" + // components lists the kustomize components every control plane apply is // composed with. Each patch targets its workloads by name, and kustomize leaves // a stream alone when nothing in it matches, so composing a manifest that @@ -73,6 +91,12 @@ func (e *Env) components() []string { if e.Cfg.CordonSystemInfraComponents { components = append(components, e.Cfg.Path(cordonSystemInfraComponent)) } + if e.Cfg.Pprof == config.PprofOn || e.Cfg.Pprof == config.PprofContention { + components = append(components, e.Cfg.Path(pprofComponent)) + } + if e.Cfg.Pprof == config.PprofContention { + components = append(components, e.Cfg.Path(pprofContentionComponent)) + } return components } @@ -158,7 +182,12 @@ func (e *Env) renderSystemManifests(ctx context.Context) ([]byte, error) { if manifest, err = e.setAgentgatewayIngressAllowedSPIFFEIDs(manifest); err != nil { return nil, err } - if e.Cfg.Router != config.RouterAgentgateway { + // Drop a skipped gateway before the image steps below, so that the + // deploy builds no image for it. + if manifest, err = e.withoutSkippedGateways(manifest); err != nil { + return nil, err + } + if e.Cfg.Router != config.RouterAgentgateway && !e.Cfg.NoAtenetRouter { manifest, err = e.patchAtenetRouterAllowedSPIFFEIDs(manifest) if err != nil { return nil, err @@ -172,6 +201,50 @@ func (e *Env) renderSystemManifests(ctx context.Context) ([]byte, error) { return e.ResolveManifestBytes(ctx, manifest) } +// withoutSkippedGateways drops the objects of each built-in gateway that the +// install leaves out. Every object of a gateway carries the gateway's name, +// alone or as a prefix. +func (e *Env) withoutSkippedGateways(manifest []byte) ([]byte, error) { + skipped := e.skippedGateways() + if len(skipped) == 0 { + return manifest, nil + } + nodes, err := (&kio.ByteReader{ + Reader: bytes.NewReader(manifest), + OmitReaderAnnotations: true, + }).Read() + if err != nil { + return nil, fmt.Errorf("while parsing manifest: %w", err) + } + nodes = slices.DeleteFunc(nodes, func(node *yaml.RNode) bool { + return slices.ContainsFunc(skipped, func(gateway string) bool { + return ofGateway(node.GetName(), gateway) + }) + }) + var out bytes.Buffer + if err := (kio.ByteWriter{Writer: &out}).Write(nodes); err != nil { + return nil, fmt.Errorf("while writing manifest: %w", err) + } + return out.Bytes(), nil +} + +// skippedGateways names the built-in gateways that the install leaves out. +func (e *Env) skippedGateways() []string { + var skipped []string + if e.Cfg.NoAtenetRouter { + skipped = append(skipped, "atenet-router") + } + if e.Cfg.NoAtenetEgress { + skipped = append(skipped, "atenet-egress") + } + return skipped +} + +// ofGateway reports whether name is the name of an object of gateway. +func ofGateway(name, gateway string) bool { + return name == gateway || strings.HasPrefix(name, gateway+"-") +} + // renderAtenetRouterManifest produces the atenet router manifest for the // selected dataplane. func (e *Env) renderAtenetRouterManifest(ctx context.Context) ([]byte, error) { @@ -184,6 +257,10 @@ func (e *Env) renderAtenetRouterManifest(ctx context.Context) ([]byte, error) { if err != nil { return nil, err } + manifest, err = e.withoutSkippedGateways(manifest) + if err != nil { + return nil, err + } return e.ResolveManifestBytes(ctx, manifest) } manifest, err := e.render(e.Cfg.Manifest("atenet-router.yaml")) @@ -250,6 +327,10 @@ func (e *Env) renderAtenetEgressManifest(ctx context.Context, providers []config if err != nil { return nil, err } + raw, err = e.withoutSkippedGateways(raw) + if err != nil { + return nil, err + } return e.ResolveManifestBytes(ctx, raw) } @@ -276,6 +357,12 @@ func (e *Env) renderAtenetEgressManifest(ctx context.Context, providers []config return nil, err } raw = e.patchEnvoyDataplaneImage(raw, imageReference) + if e.Cfg.EgressUpstreamCABundle.ConfigMap != "" { + raw, err = patchAtenetEgressUpstreamCABundle(raw, e.Cfg.EgressUpstreamCABundle) + if err != nil { + return nil, err + } + } if e.Cfg.EnvoyConcurrency > 0 { raw, err = patchAtenetEgressEnvoyConcurrency(raw, e.Cfg.EnvoyConcurrency) if err != nil { @@ -312,6 +399,30 @@ func (e *Env) patchAtenetRouterAllowedSPIFFEIDs(raw []byte) ([]byte, error) { // tests that the first container is the one named, so a reordered manifest // fails the render instead of patching the wrong container. func appendContainerArgs(raw []byte, deployment, container string, args ...string) ([]byte, error) { + var patches strings.Builder + fmt.Fprintf(&patches, ` - target: + group: apps + version: v1 + kind: Deployment + name: %s + namespace: ate-system + patch: |- + - op: test + path: /spec/template/spec/containers/0/name + value: %q +`, deployment, container) + for _, arg := range args { + fmt.Fprintf(&patches, ` - op: add + path: /spec/template/spec/containers/0/args/- + value: %q +`, arg) + } + return kustomizePatches(raw, patches.String()) +} + +// kustomizePatches builds raw through a scratch kustomization whose patches +// list holds the given entries. +func kustomizePatches(raw []byte, patches string) ([]byte, error) { dir, err := os.MkdirTemp("", "ate-setup-kustomize-") if err != nil { return nil, fmt.Errorf("while creating a scratch kustomization: %w", err) @@ -321,33 +432,73 @@ func appendContainerArgs(raw []byte, deployment, container string, args ...strin if err := os.WriteFile(filepath.Join(dir, "manifest.yaml"), raw, 0o600); err != nil { return nil, fmt.Errorf("while staging a manifest for kustomize: %w", err) } - var kustomization strings.Builder - fmt.Fprintf(&kustomization, `apiVersion: kustomize.config.k8s.io/v1beta1 + kustomization := `apiVersion: kustomize.config.k8s.io/v1beta1 kind: Kustomization resources: - manifest.yaml patches: +` + patches + if err := os.WriteFile(filepath.Join(dir, "kustomization.yaml"), []byte(kustomization), 0o600); err != nil { + return nil, fmt.Errorf("while writing a scratch kustomization: %w", err) + } + return kustomize.Build(dir) +} + +// The envoy container mounts the EgressUpstreamCABundle ConfigMap at +// egressUpstreamCABundleDir, with its key as egressUpstreamCABundleFile. +const ( + egressUpstreamCABundleDir = "/run/egress-upstream-ca" + egressUpstreamCABundleFile = "ca-bundle.pem" +) + +// patchAtenetEgressUpstreamCABundle makes the bundle the roots the forward +// proxy clusters trust. It mounts the ConfigMap key on the envoy container as +// a directory, because a subPath mount never sees an update, and replaces the +// SDS resource with one that watches that directory, so Envoy reloads the +// bundle when kubelet swaps it. The volume names the key, so a ConfigMap +// without it fails the mount. +func patchAtenetEgressUpstreamCABundle(raw []byte, bundle config.EgressUpstreamCABundle) ([]byte, error) { + return kustomizePatches(raw, fmt.Sprintf(` - target: + version: v1 + kind: ConfigMap + name: atenet-egress + namespace: ate-system + patch: | + - op: replace + path: /data/sds-egress-upstream-validation.yaml + value: | + resources: + - "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.Secret + name: egress_upstream_validation_context + validation_context: + trusted_ca: { filename: %[1]s/%[2]s } + watched_directory: { path: %[1]s } - target: group: apps version: v1 kind: Deployment - name: %s + name: atenet-egress namespace: ate-system patch: |- - op: test path: /spec/template/spec/containers/0/name - value: %q -`, deployment, container) - for _, arg := range args { - fmt.Fprintf(&kustomization, ` - op: add - path: /spec/template/spec/containers/0/args/- - value: %q -`, arg) - } - if err := os.WriteFile(filepath.Join(dir, "kustomization.yaml"), []byte(kustomization.String()), 0o600); err != nil { - return nil, fmt.Errorf("while writing a scratch kustomization: %w", err) - } - return kustomize.Build(dir) + value: envoy + - op: add + path: /spec/template/spec/containers/0/volumeMounts/- + value: + name: egress-upstream-ca + mountPath: %[1]s + readOnly: true + - op: add + path: /spec/template/spec/volumes/- + value: + name: egress-upstream-ca + configMap: + name: %[3]q + items: + - key: %[4]q + path: %[2]s +`, egressUpstreamCABundleDir, egressUpstreamCABundleFile, bundle.ConfigMap, bundle.Key)) } // patchEnvoyDataplaneImage replaces the ${ENVOY_DATAPLANE_IMAGE} placeholder in @@ -560,6 +711,72 @@ func emitAdditionalEgressExtprocCluster(address, port, serverName string) string port_value: %s`, additionalEgressExtprocCluster, serverName, serverName, additionalEgressExtprocCluster, address, port) } +// checkEgressUpstreamCABundle refuses a bundle that is missing or is not a +// PEM bundle of X.509 certificates. The gateway pod cannot start without the +// ConfigMap key, and Envoy fails every HTTPS origin when it cannot load the +// bundle. The deploys that apply the egress gateway call it before they apply +// anything. +func (e *Env) checkEgressUpstreamCABundle(ctx context.Context) error { + bundle := e.Cfg.EgressUpstreamCABundle + if bundle.ConfigMap == "" { + return nil + } + cm, err := e.Kube.GetConfigMap(ctx, e.Namespace(), bundle.ConfigMap) + if err != nil { + return err + } + if cm == nil { + return fmt.Errorf("egress upstream CA bundle: configmap %s/%s not found", e.Namespace(), bundle.ConfigMap) + } + // kubectl stores a file that is not valid UTF-8 under binaryData, and + // kubelet mounts a key from either map. + data, ok := cm.BinaryData[bundle.Key] + if text, found := cm.Data[bundle.Key]; found { + data, ok = []byte(text), true + } + if !ok { + return fmt.Errorf("egress upstream CA bundle: configmap %s/%s has no key %s", e.Namespace(), bundle.ConfigMap, bundle.Key) + } + if err := validateCertificateBundle(data); err != nil { + return fmt.Errorf("egress upstream CA bundle: configmap %s/%s key %s: %w", e.Namespace(), bundle.ConfigMap, bundle.Key, err) + } + return nil +} + +// validateCertificateBundle checks that data is one or more PEM blocks, each +// an X.509 certificate without PEM headers. It parses with crypto/x509, which +// refuses some certificates Envoy loads, such as one with a negative serial +// number. +func validateCertificateBundle(data []byte) error { + // pem.Decode skips a block it cannot read, such as two certificates + // joined without a newline, so count the markers it should have found. + want := bytes.Count(data, []byte("-----BEGIN ")) + if want == 0 { + return errors.New("holds no PEM certificate") + } + rest := data + for n := 1; ; n++ { + var block *pem.Block + block, rest = pem.Decode(rest) + if block == nil { + if read := n - 1; read < want { + return fmt.Errorf("%d of %d PEM blocks are malformed", want-read, want) + } + return nil + } + if block.Type != "CERTIFICATE" { + return fmt.Errorf("PEM block %d is a %s, want only certificates", n, block.Type) + } + // Envoy loads nothing from a bundle in which a block has headers. + if len(block.Headers) != 0 { + return fmt.Errorf("PEM block %d has headers, which Envoy rejects", n) + } + if _, err := x509.ParseCertificate(block.Bytes); err != nil { + return fmt.Errorf("PEM block %d is not an X.509 certificate: %w", n, err) + } + } +} + func (e *Env) applyAtenetEgress(ctx context.Context, providers []config.CredentialProvider) error { manifests, err := e.renderAtenetEgressManifest(ctx, providers) if err != nil { @@ -611,8 +828,10 @@ const otelEndpointKey = "OTEL_EXPORTER_OTLP_ENDPOINT" // otelOverrideDeployments are the control plane Deployments that read // ate-otel-config. ate-controller additionally copies the values onto the -// worker pods it creates, so one patch reaches the whole system. -var otelOverrideDeployments = []string{"ate-api-server", "ate-controller", "atenet-router", "atenet-egress"} +// worker pods it creates, so one patch reaches the whole system. The bundled +// credential provider is present only when the k8s.io provider is selected; +// the restart skips a Deployment that does not exist. +var otelOverrideDeployments = []string{"ate-api-server", "ate-controller", "atenet-router", "atenet-egress", k8sCredentialProviderDeployment} // applyOtelEndpointOverride points all control plane telemetry at a different // collector for the duration of a measurement. See diff --git a/cmd/ate-setup/internal/steps/overlay_test.go b/cmd/ate-setup/internal/steps/overlay_test.go index 634b1e36a0..75176a4b4e 100644 --- a/cmd/ate-setup/internal/steps/overlay_test.go +++ b/cmd/ate-setup/internal/steps/overlay_test.go @@ -16,7 +16,13 @@ package steps import ( "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "encoding/pem" "fmt" + "math/big" "os" "reflect" "slices" @@ -1438,9 +1444,15 @@ func TestApplyOtelEndpointOverride(t *testing.T) { Name: "atenet-egress", }, } + provider := &appsv1.Deployment{ + ObjectMeta: metav1.ObjectMeta{ + Namespace: NamespaceAteSystem, + Name: k8sCredentialProviderDeployment, + }, + } e := &Env{ Cfg: &config.Config{OtlpEndpoint: endpoint}, - Kube: fakeKube(t, otelConfig("http://default:4317"), apiServerDeployment(), egress, atelet), + Kube: fakeKube(t, otelConfig("http://default:4317"), apiServerDeployment(), egress, atelet, provider), } if err := e.applyOtelEndpointOverride(t.Context()); err != nil { @@ -1459,6 +1471,9 @@ func TestApplyOtelEndpointOverride(t *testing.T) { if !restartedAt(t, e, "deployment", "atenet-egress") { t.Error("atenet-egress was not restarted") } + if !restartedAt(t, e, "deployment", k8sCredentialProviderDeployment) { + t.Errorf("%s was not restarted", k8sCredentialProviderDeployment) + } if !restartedAt(t, e, "daemonset", "atelet") { t.Error("the atelet DaemonSet was not restarted") } @@ -1520,6 +1535,80 @@ func TestRenderAtenetEgressManifestPrebuilt(t *testing.T) { } } +// Each render drops a skipped gateway itself, before it resolves images, so +// the deploy applies no object of that gateway and asks for no image of it. +func TestRenderSkippedGateways(t *testing.T) { + src := images.Source{Repo: "example.com/substrate", Tag: "v1.2.3"} + system := func(e *Env) ([]byte, error) { return e.renderSystemManifests(t.Context()) } + for _, tc := range []struct { + name string + dataplane string + noRouter bool + noEgress bool + render func(*Env) ([]byte, error) + wantNoLookup []string + }{ + { + name: "envoy system bundle, no router", + dataplane: config.RouterEnvoy, + noRouter: true, + render: system, + wantNoLookup: []string{"envoy-dataplane", "atenet"}, + }, + { + name: "agentgateway system bundle, no router", + dataplane: config.RouterAgentgateway, + noRouter: true, + render: system, + }, + { + name: "agentgateway egress manifest, no router", + dataplane: config.RouterAgentgateway, + noRouter: true, + render: func(e *Env) ([]byte, error) { return e.renderAtenetEgressManifest(t.Context(), nil) }, + }, + { + name: "agentgateway router manifest, no egress", + dataplane: config.RouterAgentgateway, + noEgress: true, + render: func(e *Env) ([]byte, error) { return e.renderAtenetRouterManifest(t.Context()) }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + var looked []string + e := &Env{ + Cfg: &config.Config{ + Root: repoRoot(t), Router: tc.dataplane, Images: src, + NoAtenetRouter: tc.noRouter, NoAtenetEgress: tc.noEgress, + }, + resolver: images.NewPrebuilt(src, func(_ context.Context, ref string) (string, error) { + looked = append(looked, ref) + return "sha256:" + strings.Repeat("2", 64), nil + }), + } + out, err := tc.render(e) + if err != nil { + t.Fatalf("render() error = %v", err) + } + objs, err := kube.DecodeManifestBytes(out) + if err != nil { + t.Fatalf("DecodeManifestBytes() error = %v", err) + } + for _, obj := range objs { + name := obj.GetName() + if tc.noRouter && strings.HasPrefix(name, "atenet-router") || tc.noEgress && strings.HasPrefix(name, "atenet-egress") { + t.Errorf("render holds %s/%s of a skipped gateway", obj.GetKind(), name) + } + } + for _, image := range tc.wantNoLookup { + if ref := src.Repo + "/" + image + ":" + src.Tag; slices.Contains(looked, ref) { + t.Errorf("registry lookups = %v, want none for %s", looked, image) + } + } + }) + } +} + // An install from an image repository without a readable envoy-dataplane fails // with a message saying how to proceed, rather than a bare registry error. func TestDockerfileImagePrebuiltNotPublished(t *testing.T) { @@ -1628,6 +1717,200 @@ func TestRenderAtenetEgressManifestEnvoyConcurrency(t *testing.T) { }) } +// The forward proxy clusters read their roots through one SDS resource. The +// bundle setting has to move that resource and mount the ConfigMap key behind +// it as a directory: Envoy reloads on kubelet's swap of the directory, which a +// subPath mount never sees. +func TestRenderAtenetEgressManifestUpstreamCABundle(t *testing.T) { + const digest = "sha256:3333333333333333333333333333333333333333333333333333333333333333" + src := images.Source{Repo: "example.com/substrate", Tag: "v1.2.3"} + + type validation struct { + TrustedCA struct{ Filename string } `json:"trusted_ca"` + WatchedDirectory struct{ Path string } `json:"watched_directory"` + } + for _, tc := range []struct { + name string + bundle config.EgressUpstreamCABundle + wantRoots string + wantWatch string + wantVolume *corev1.ConfigMapVolumeSource + }{ + { + name: "unset trusts the image roots", + wantRoots: "/etc/ssl/certs/ca-certificates.crt", + }, + { + name: "set mounts the key as ca-bundle.pem", + bundle: config.EgressUpstreamCABundle{ConfigMap: "egress-roots", Key: "roots.crt"}, + wantRoots: "/run/egress-upstream-ca/ca-bundle.pem", + wantWatch: "/run/egress-upstream-ca", + wantVolume: &corev1.ConfigMapVolumeSource{ + LocalObjectReference: corev1.LocalObjectReference{Name: "egress-roots"}, + Items: []corev1.KeyToPath{{Key: "roots.crt", Path: "ca-bundle.pem"}}, + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + e := &Env{ + Cfg: &config.Config{Root: repoRoot(t), Router: config.RouterEnvoy, Images: src, EgressUpstreamCABundle: tc.bundle}, + resolver: images.NewPrebuilt(src, func(context.Context, string) (string, error) { + return digest, nil + }), + } + out, err := e.renderAtenetEgressManifest(t.Context(), nil) + if err != nil { + t.Fatalf("renderAtenetEgressManifest() error = %v", err) + } + + var sds string + var dep appsv1.Deployment + for _, doc := range strings.Split(string(out), "\n---\n") { + var cm corev1.ConfigMap + if err := yaml.Unmarshal([]byte(doc), &cm); err == nil && cm.Kind == "ConfigMap" && cm.Name == "atenet-egress" { + sds = cm.Data["sds-egress-upstream-validation.yaml"] + } + var d appsv1.Deployment + if err := yaml.Unmarshal([]byte(doc), &d); err == nil && d.Kind == "Deployment" && d.Name == "atenet-egress" { + dep = d + } + } + + var resource struct { + Resources []struct { + Name string `json:"name"` + ValidationContext validation `json:"validation_context"` + } `json:"resources"` + } + if err := yaml.Unmarshal([]byte(sds), &resource); err != nil || len(resource.Resources) != 1 { + t.Fatalf("sds-egress-upstream-validation.yaml does not hold one resource (err %v):\n%s", err, sds) + } + got := resource.Resources[0] + if got.Name != "egress_upstream_validation_context" { + t.Errorf("SDS resource name = %q, want the one the forward proxy clusters reference", got.Name) + } + if got.ValidationContext.TrustedCA.Filename != tc.wantRoots { + t.Errorf("trusted_ca = %q, want %q", got.ValidationContext.TrustedCA.Filename, tc.wantRoots) + } + if got.ValidationContext.WatchedDirectory.Path != tc.wantWatch { + t.Errorf("watched_directory = %q, want %q", got.ValidationContext.WatchedDirectory.Path, tc.wantWatch) + } + + var volume *corev1.ConfigMapVolumeSource + for _, v := range dep.Spec.Template.Spec.Volumes { + if v.Name == "egress-upstream-ca" { + volume = v.ConfigMap + } + } + if !reflect.DeepEqual(volume, tc.wantVolume) { + t.Errorf("egress-upstream-ca volume = %+v, want %+v", volume, tc.wantVolume) + } + var mounts []corev1.VolumeMount + for _, c := range dep.Spec.Template.Spec.Containers { + for _, m := range c.VolumeMounts { + if m.Name == "egress-upstream-ca" { + if c.Name != "envoy" { + t.Errorf("container %q mounts the bundle, want only envoy", c.Name) + } + mounts = append(mounts, m) + } + } + } + var wantMounts []corev1.VolumeMount + if tc.wantVolume != nil { + wantMounts = []corev1.VolumeMount{{Name: "egress-upstream-ca", MountPath: tc.wantWatch, ReadOnly: true}} + } + if !reflect.DeepEqual(mounts, wantMounts) { + t.Errorf("bundle mounts = %+v, want %+v", mounts, wantMounts) + } + }) + } +} + +func TestCheckEgressUpstreamCABundle(t *testing.T) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatal(err) + } + template := &x509.Certificate{SerialNumber: big.NewInt(1), NotAfter: time.Now().Add(time.Hour)} + der, err := x509.CreateCertificate(rand.Reader, template, template, &key.PublicKey, key) + if err != nil { + t.Fatal(err) + } + cert := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der})) + keyDER, err := x509.MarshalPKCS8PrivateKey(key) + if err != nil { + t.Fatal(err) + } + privateKey := string(pem.EncodeToMemory(&pem.Block{Type: "PRIVATE KEY", Bytes: keyDER})) + notACert := string(pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: []byte("not DER")})) + withHeader := string(pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE", + Headers: map[string]string{"Comment": "private CA"}, + Bytes: der, + })) + + setting := config.EgressUpstreamCABundle{ConfigMap: "egress-roots", Key: "ca.crt"} + bundle := func(data map[string]string) []runtime.Object { + return []runtime.Object{&corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: NamespaceAteSystem, Name: "egress-roots"}, + Data: data, + }} + } + for _, tc := range []struct { + name string + setting config.EgressUpstreamCABundle + objects []runtime.Object + wantErr string + }{ + {name: "unset checks nothing"}, + {name: "configmap missing", setting: setting, wantErr: "configmap ate-system/egress-roots not found"}, + {name: "key missing", setting: setting, objects: bundle(map[string]string{"other.crt": cert}), wantErr: "has no key ca.crt"}, + {name: "empty", setting: setting, objects: bundle(map[string]string{"ca.crt": ""}), wantErr: "holds no PEM certificate"}, + {name: "not PEM", setting: setting, objects: bundle(map[string]string{"ca.crt": "not a certificate"}), wantErr: "holds no PEM certificate"}, + {name: "private key", setting: setting, objects: bundle(map[string]string{"ca.crt": cert + privateKey}), wantErr: "PEM block 2 is a PRIVATE KEY"}, + {name: "not X.509", setting: setting, objects: bundle(map[string]string{"ca.crt": cert + notACert}), wantErr: "PEM block 2 is not an X.509 certificate"}, + {name: "PEM header", setting: setting, objects: bundle(map[string]string{"ca.crt": cert + withHeader}), wantErr: "PEM block 2 has headers"}, + { + // cat of two files where the first has no final newline. + name: "certificates joined without a newline", + setting: setting, + objects: bundle(map[string]string{"ca.crt": strings.TrimSuffix(cert, "\n") + cert}), + wantErr: "of 2 PEM blocks are malformed", + }, + {name: "one certificate", setting: setting, objects: bundle(map[string]string{"ca.crt": cert})}, + {name: "two certificates", setting: setting, objects: bundle(map[string]string{"ca.crt": cert + cert})}, + { + name: "another key", + setting: config.EgressUpstreamCABundle{ConfigMap: "egress-roots", Key: "roots.pem"}, + objects: bundle(map[string]string{"roots.pem": cert}), + }, + { + // kubectl stores a file that is not valid UTF-8 under binaryData. + name: "key under binaryData", + setting: setting, + objects: []runtime.Object{&corev1.ConfigMap{ + ObjectMeta: metav1.ObjectMeta{Namespace: NamespaceAteSystem, Name: "egress-roots"}, + BinaryData: map[string][]byte{"ca.crt": []byte("# caf\xe9\n" + cert)}, + }}, + }, + } { + t.Run(tc.name, func(t *testing.T) { + e := &Env{Cfg: &config.Config{EgressUpstreamCABundle: tc.setting}, Kube: fakeKube(t, tc.objects...)} + err := e.checkEgressUpstreamCABundle(t.Context()) + if tc.wantErr == "" { + if err != nil { + t.Fatalf("checkEgressUpstreamCABundle() error = %v", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("checkEgressUpstreamCABundle() error = %v, want it to contain %q", err, tc.wantErr) + } + }) + } +} + // Without --fake-data-plane there is no fake-workersync rollout to wait for. func TestWaitFakeWorkersyncWithoutTheFlagIsANoOp(t *testing.T) { e := &Env{Cfg: &config.Config{Root: repoRoot(t)}, Kube: fakeKube(t)} @@ -1771,8 +2054,15 @@ func fakeDeleteKube(t *testing.T, typed []runtime.Object, dyn []runtime.Object) t.Helper() cs := fake.NewClientset(typed...) cs.Fake.Resources = []*metav1.APIResourceList{ - {GroupVersion: "v1", APIResources: []metav1.APIResource{{Name: "serviceaccounts", Kind: "ServiceAccount", Namespaced: true}}}, + {GroupVersion: "v1", APIResources: []metav1.APIResource{ + {Name: "namespaces", Kind: "Namespace"}, + {Name: "serviceaccounts", Kind: "ServiceAccount", Namespaced: true}, + {Name: "configmaps", Kind: "ConfigMap", Namespaced: true}, + {Name: "services", Kind: "Service", Namespaced: true}, + {Name: "secrets", Kind: "Secret", Namespaced: true}, + }}, {GroupVersion: "apps/v1", APIResources: []metav1.APIResource{{Name: "deployments", Kind: "Deployment", Namespaced: true}}}, + {GroupVersion: "apiextensions.k8s.io/v1", APIResources: []metav1.APIResource{{Name: "customresourcedefinitions", Kind: "CustomResourceDefinition"}}}, {GroupVersion: "networking.k8s.io/v1", APIResources: []metav1.APIResource{{Name: "networkpolicies", Kind: "NetworkPolicy", Namespaced: true}}}, {GroupVersion: "rbac.authorization.k8s.io/v1", APIResources: []metav1.APIResource{ {Name: "clusterroles", Kind: "ClusterRole"}, diff --git a/cmd/ate-setup/internal/steps/pprof_component_test.go b/cmd/ate-setup/internal/steps/pprof_component_test.go new file mode 100644 index 0000000000..3004b23e79 --- /dev/null +++ b/cmd/ate-setup/internal/steps/pprof_component_test.go @@ -0,0 +1,208 @@ +// Copyright 2026 The Agent Substrate 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 steps + +import ( + "reflect" + "slices" + "strings" + "testing" + + corev1 "k8s.io/api/core/v1" + networkingv1 "k8s.io/api/networking/v1" + "k8s.io/apimachinery/pkg/labels" + + "go.ate.dev/substrate/cmd/ate-setup/internal/config" +) + +func loadWorkloads(t *testing.T, cfg config.Config) (systemInstall, map[string][]corev1.Container) { + t.Helper() + in := loadSystemInstall(t, &cfg) + workloads := make(map[string][]corev1.Container, len(in.pods)) + for _, pod := range in.pods { + workloads[pod.workload] = pod.spec.Containers + } + return in, workloads +} + +func findPolicyByName(t *testing.T, policies []networkingv1.NetworkPolicy, name string) networkingv1.NetworkPolicy { + t.Helper() + idx := slices.IndexFunc(policies, func(np networkingv1.NetworkPolicy) bool { return np.Name == name }) + if idx < 0 { + t.Fatalf("NetworkPolicy/%s not found", name) + } + return policies[idx] +} + +func findContainerByName(t *testing.T, workloads map[string][]corev1.Container, workload, container string) corev1.Container { + t.Helper() + cs, ok := workloads[workload] + if !ok { + t.Fatalf("workload %s not found", workload) + } + idx := slices.IndexFunc(cs, func(c corev1.Container) bool { return c.Name == container }) + if idx < 0 { + t.Fatalf("container %q not found in %s", container, workload) + } + return cs[idx] +} + +// checkPprofContainer asserts whether c exposes TCP port pprof:6060 and the +// expected pprof/contention environment variables without duplicates or extras. +func checkPprofContainer(t *testing.T, workload string, c corev1.Container, wantPort bool, wantEnv map[string]string) { + t.Helper() + hasPort := slices.ContainsFunc(c.Ports, func(p corev1.ContainerPort) bool { + return p.Name == "pprof" && p.ContainerPort == 6060 && (p.Protocol == "" || p.Protocol == corev1.ProtocolTCP) + }) + if wantPort && !hasPort { + t.Errorf("%s container %q missing TCP port pprof:6060 (got %+v)", workload, c.Name, c.Ports) + } + if !wantPort { + for _, p := range c.Ports { + if p.Name == "pprof" || p.ContainerPort == 6060 { + t.Errorf("%s container %q unexpectedly exposes port %+v", workload, c.Name, p) + } + } + } + + envs := make(map[string]string, len(c.Env)) + for _, e := range c.Env { + if _, dup := envs[e.Name]; dup { + t.Errorf("%s container %q has duplicate env var %q", workload, c.Name, e.Name) + } + envs[e.Name] = e.Value + isPprof := strings.HasPrefix(e.Name, "ATE_PPROF_") || + strings.HasPrefix(e.Name, "ATE_WORKER_PPROF") || + e.Name == "GRPC_GO_SERVER_GOROUTINE_LABELS" + if _, expected := wantEnv[e.Name]; isPprof && !expected { + t.Errorf("%s container %q has unexpected env var %s=%q", workload, c.Name, e.Name, e.Value) + } + } + for k, want := range wantEnv { + if got, ok := envs[k]; !ok { + t.Errorf("%s container %q missing env var %s (want %q)", workload, c.Name, k, want) + } else if got != want { + t.Errorf("%s container %q env %s = %q, want %q", workload, c.Name, k, got, want) + } + } +} + +func checkPprofTargets(t *testing.T, in systemInstall, workloads map[string][]corev1.Container, cfg config.Config) { + t.Helper() + wantPprof := cfg.Pprof == config.PprofOn || cfg.Pprof == config.PprofContention + wantContention := cfg.Pprof == config.PprofContention + obs := findPolicyByName(t, in.policies, "ate-system-observability") + credPod := in.pod(t, "k8s-credential-provider") + if mustSelector(t, &obs.Spec.PodSelector).Matches(labels.Set(credPod.labels)) { + t.Errorf("ate-system-observability selects k8s-credential-provider") + } + for _, c := range credPod.spec.Containers { + checkPprofContainer(t, credPod.workload, c, false, nil) + } + + grpcEnv := map[string]string{} + ctrlEnv := map[string]string{} + if wantPprof { + grpcEnv["ATE_PPROF_LISTEN_ADDR"] = ":6060" + grpcEnv["GRPC_GO_SERVER_GOROUTINE_LABELS"] = "grpc.method=true" + ctrlEnv["ATE_PPROF_LISTEN_ADDR"] = ":6060" + ctrlEnv["ATE_WORKER_PPROF"] = "true" + } + if wantContention { + grpcEnv["ATE_PPROF_MUTEX_FRACTION"] = "10" + grpcEnv["ATE_PPROF_BLOCK_RATE"] = "1000000" + ctrlEnv["ATE_PPROF_MUTEX_FRACTION"] = "10" + ctrlEnv["ATE_PPROF_BLOCK_RATE"] = "1000000" + ctrlEnv["ATE_WORKER_PPROF_MUTEX_FRACTION"] = "10" + ctrlEnv["ATE_WORKER_PPROF_BLOCK_RATE"] = "1000000" + } + + targets := []struct { + workload, container string + wantEnv map[string]string + skip bool + }{ + {"Deployment/ate-api-server", "ate-api-server", grpcEnv, false}, + {"Deployment/ate-controller", "ate-controller", ctrlEnv, false}, + {"DaemonSet/atelet", "atelet", grpcEnv, cfg.FakeDataPlane}, + {"Deployment/atenet-router", "atenet-router", grpcEnv, cfg.Router == config.RouterAgentgateway}, + {"Deployment/atenet-egress", "ext-proc", grpcEnv, cfg.Router == config.RouterAgentgateway}, + } + for _, tgt := range targets { + if tgt.skip { + cs := workloads[tgt.workload] + if len(cs) == 0 { + t.Errorf("workload %s has 0 containers, want >= 1", tgt.workload) + continue + } + if strings.HasPrefix(tgt.workload, "Deployment/atenet-") && (len(cs) != 1 || cs[0].Name != "agentgateway") { + t.Errorf("%s containers = %+v, want single agentgateway container", tgt.workload, cs) + } + for _, c := range cs { + checkPprofContainer(t, tgt.workload, c, false, nil) + } + continue + } + checkPprofContainer(t, tgt.workload, findContainerByName(t, workloads, tgt.workload, tgt.container), wantPprof, tgt.wantEnv) + } +} + +func checkPprofBaselinePreserved(t *testing.T, got, baseline map[string][]corev1.Container) { + t.Helper() + for workload, baseContainers := range baseline { + for _, bc := range baseContainers { + gc := findContainerByName(t, got, workload, bc.Name) + for _, bp := range bc.Ports { + if !slices.Contains(gc.Ports, bp) { + t.Errorf("%s container %q dropped baseline port %+v", workload, bc.Name, bp) + } + } + for _, be := range bc.Env { + if !slices.ContainsFunc(gc.Env, func(ge corev1.EnvVar) bool { return reflect.DeepEqual(ge, be) }) { + t.Errorf("%s container %q dropped baseline env var %q", workload, bc.Name, be.Name) + } + } + } + } +} + +// TestPprofComponents verifies pprof and pprof-contention port/env placement, +// excluded workloads, and baseline port/env preservation under --pprof. +func TestPprofComponents(t *testing.T) { + cases := []struct { + name string + cfg config.Config + checkBaseline bool + }{ + {"gke-envoy", config.Config{Router: config.RouterEnvoy, Pprof: config.PprofOn}, true}, + {"gke-envoy-contention", config.Config{Router: config.RouterEnvoy, Pprof: config.PprofContention}, false}, + {"gke-agentgateway-contention", config.Config{Router: config.RouterAgentgateway, Pprof: config.PprofContention}, false}, + {"gke-envoy-fake-contention", config.Config{Router: config.RouterEnvoy, FakeDataPlane: true, Pprof: config.PprofContention}, false}, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + in, workloads := loadWorkloads(t, tc.cfg) + checkPprofTargets(t, in, workloads, tc.cfg) + if tc.checkBaseline { + baseCfg := tc.cfg + baseCfg.Pprof = config.PprofOff + baseIn, baseline := loadWorkloads(t, baseCfg) + checkPprofTargets(t, baseIn, baseline, baseCfg) + checkPprofBaselinePreserved(t, workloads, baseline) + } + }) + } +} diff --git a/cmd/ate-setup/internal/steps/serviceaccounttoken_test.go b/cmd/ate-setup/internal/steps/serviceaccounttoken_test.go new file mode 100644 index 0000000000..2f1c917ebc --- /dev/null +++ b/cmd/ate-setup/internal/steps/serviceaccounttoken_test.go @@ -0,0 +1,172 @@ +// Copyright 2026 The Agent Substrate 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 steps + +import ( + "slices" + "testing" + + corev1 "k8s.io/api/core/v1" +) + +// kubeAPIClients maps each ate-system workload that calls the Kubernetes API +// to the one container in it that does. Only that container may get a +// ServiceAccount token. +var kubeAPIClients = map[string]string{ + "Deployment/ate-api-server": "ate-api-server", + "Deployment/ate-controller": "ate-controller", + "DaemonSet/atelet": "atelet", + "Deployment/atenet-router": "atenet-router", + "Deployment/k8s-credential-provider": "k8s-credential-provider", + "Deployment/fake-workersync": "fake-workersync", +} + +// tokenDir is where client-go's in-cluster config reads the token, CA and +// namespace. +const tokenDir = "/var/run/secrets/kubernetes.io/serviceaccount" + +// automountsToken reports whether the kubelet mounts a ServiceAccount token +// into pod, following the pod field and then its ServiceAccount's. +func (in systemInstall) automountsToken(pod systemPod) bool { + if pod.spec.AutomountServiceAccountToken != nil { + return *pod.spec.AutomountServiceAccountToken + } + name := pod.spec.ServiceAccountName + if name == "" { + name = "default" + } + if sa, ok := in.serviceAccounts[name]; ok && sa.AutomountServiceAccountToken != nil { + return *sa.AutomountServiceAccountToken + } + return true +} + +// tokenVolumes returns pod's projected volumes that carry a ServiceAccount +// token, by name. +func tokenVolumes(pod systemPod) map[string]*corev1.ProjectedVolumeSource { + out := map[string]*corev1.ProjectedVolumeSource{} + for _, volume := range pod.spec.Volumes { + if volume.Projected == nil { + continue + } + for _, source := range volume.Projected.Sources { + if source.ServiceAccountToken != nil { + out[volume.Name] = volume.Projected + } + } + } + return out +} + +// tokenMount returns the container's mount of one of the pod's token volumes, +// if it has one. +func tokenMount(pod systemPod, container corev1.Container) (corev1.VolumeMount, bool) { + volumes := tokenVolumes(pod) + for _, mount := range container.VolumeMounts { + if volumes[mount.Name] != nil { + return mount, true + } + } + return corev1.VolumeMount{}, false +} + +// containerGetsToken reports whether the container can read a ServiceAccount +// token, through automount or a token volume it mounts. +func (in systemInstall) containerGetsToken(pod systemPod, container corev1.Container) bool { + _, mounted := tokenMount(pod, container) + return in.automountsToken(pod) || mounted +} + +// projectedPaths returns the names of the files a projected volume puts in its +// mount. +func projectedPaths(projected *corev1.ProjectedVolumeSource) []string { + var out []string + for _, source := range projected.Sources { + switch { + case source.ServiceAccountToken != nil: + out = append(out, source.ServiceAccountToken.Path) + case source.ConfigMap != nil: + for _, item := range source.ConfigMap.Items { + out = append(out, item.Path) + } + case source.DownwardAPI != nil: + for _, item := range source.DownwardAPI.Items { + out = append(out, item.Path) + } + } + } + return out +} + +// clientContainerName returns the name of the pod's container that calls the +// Kubernetes API, or "" if none does. The fake data plane's atelet keeps the +// atelet name but never calls the API. +func clientContainerName(pod systemPod) string { + if pod.labels["ate.dev/fake-atelet"] == "true" { + return "" + } + return kubeAPIClients[pod.workload] +} + +// checkClientToken checks that the client container gets a token at the path +// client-go reads, with the token, CA and namespace files. Automount always +// provides these, so only a hand-mounted token is checked. +func checkClientToken(t *testing.T, install systemInstall, pod systemPod, client corev1.Container) { + t.Helper() + if install.automountsToken(pod) { + return + } + mount, ok := tokenMount(pod, client) + if !ok { + t.Errorf("%s: container %s calls the Kubernetes API but gets no ServiceAccount token; mount one at %s", pod.workload, client.Name, tokenDir) + return + } + if mount.MountPath != tokenDir { + t.Errorf("%s: container %s mounts its ServiceAccount token at %s, want %s", pod.workload, client.Name, mount.MountPath, tokenDir) + } + files := projectedPaths(tokenVolumes(pod)[mount.Name]) + for _, want := range []string{corev1.ServiceAccountTokenKey, corev1.ServiceAccountRootCAKey, corev1.ServiceAccountNamespaceKey} { + if !slices.Contains(files, want) { + t.Errorf("%s: token volume %s has no %s file, which client-go needs", pod.workload, mount.Name, want) + } + } +} + +func TestSystemPodsMountTokenOnlyForKubeAPIClients(t *testing.T) { + clientsFound := map[string]bool{} + for _, cfg := range installConfigs() { + t.Run(installName(cfg), func(t *testing.T) { + install := loadSystemInstall(t, cfg) + for _, pod := range install.pods { + clientName := clientContainerName(pod) + for _, container := range slices.Concat(pod.spec.InitContainers, pod.spec.Containers) { + if container.Name == clientName { + clientsFound[pod.workload] = true + checkClientToken(t, install, pod, container) + continue + } + if install.containerGetsToken(pod, container) { + t.Errorf("%s: container %s gets a ServiceAccount token but does not call the Kubernetes API; set automountServiceAccountToken: false and mount the token only into the client container", pod.workload, container.Name) + } + } + } + }) + } + for workload, clientName := range kubeAPIClients { + if !clientsFound[workload] { + t.Errorf("kubeAPIClients lists container %s of %s, which no install config deploys in ate-system; fix or remove it", clientName, workload) + } + } +} diff --git a/cmd/ate-setup/internal/steps/systemnetworkpolicy_test.go b/cmd/ate-setup/internal/steps/systemnetworkpolicy_test.go index 1471c398e4..3b2bc91568 100644 --- a/cmd/ate-setup/internal/steps/systemnetworkpolicy_test.go +++ b/cmd/ate-setup/internal/steps/systemnetworkpolicy_test.go @@ -29,23 +29,23 @@ import ( "go.ate.dev/substrate/cmd/ate-setup/internal/config" "go.ate.dev/substrate/cmd/ate-setup/internal/kube" - "go.ate.dev/substrate/cmd/ate-setup/internal/kustomize" ) -// systemPod is one ate-system workload's pod template, as the NetworkPolicies -// see it. +// systemPod is one ate-system workload's pod template. type systemPod struct { workload string // kind/name, for messages labels map[string]string ports []corev1.ContainerPort + spec corev1.PodSpec } // systemInstall is everything an install of one configuration puts in // ate-system: the system overlay plus the manifests the installer applies on // their own (postgres, the egress gateway, the bundled credential provider). type systemInstall struct { - pods []systemPod - policies []networkingv1.NetworkPolicy + pods []systemPod + policies []networkingv1.NetworkPolicy + serviceAccounts map[string]corev1.ServiceAccount } // unadmittedPorts are the container ports no NetworkPolicy may admit, keyed @@ -69,7 +69,7 @@ var unadmittedPorts = map[string][]string{ // installConfigs are the configurations whose ate-system the policies must // cover: both dataplanes, on GKE and on kind, each with the real and the fake -// data plane. +// data plane, plus --pprof=on on GKE Envoy. func installConfigs() []*config.Config { var out []*config.Config for _, kind := range []bool{false, true} { @@ -79,6 +79,7 @@ func installConfigs() []*config.Config { } } } + out = append(out, &config.Config{Router: config.RouterEnvoy, Pprof: config.PprofOn}) return out } @@ -91,6 +92,9 @@ func installName(cfg *config.Config) string { if cfg.FakeDataPlane { name += "-fake" } + if cfg.Pprof != "" && cfg.Pprof != config.PprofOff { + name += "-pprof" + } return name } @@ -119,22 +123,18 @@ func loadSystemInstall(t *testing.T, cfg *config.Config) systemInstall { add(e.postgresManifestPath(), rendered, err) if cfg.Router == config.RouterAgentgateway { egress := filepath.Join(root, installDir, "agentgateway-egress") - rendered, err = kustomize.Build(egress) + rendered, err = e.render(egress) add(egress, rendered, err) } else { - loaded, err := kube.LoadPath(e.atenetEgressManifestPath()) - if err != nil { - t.Fatalf("loading %s: %v", e.atenetEgressManifestPath(), err) - } - objs = append(objs, loaded...) - } - provider, err := kube.LoadPath(e.k8sCredentialProviderPath(k8sCredentialProviderManifest)) - if err != nil { - t.Fatalf("loading the credential provider manifest: %v", err) + egress := e.atenetEgressManifestPath() + rendered, err = e.render(egress) + add(egress, rendered, err) } - objs = append(objs, provider...) + provider := e.k8sCredentialProviderPath(k8sCredentialProviderManifest) + rendered, err = e.render(provider) + add(provider, rendered, err) - var install systemInstall + install := systemInstall{serviceAccounts: map[string]corev1.ServiceAccount{}} for _, obj := range objs { if obj.GetNamespace() != NamespaceAteSystem { continue @@ -146,6 +146,12 @@ func loadSystemInstall(t *testing.T, cfg *config.Config) systemInstall { t.Fatalf("converting networkpolicy/%s: %v", obj.GetName(), err) } install.policies = append(install.policies, np) + case "ServiceAccount": + var sa corev1.ServiceAccount + if err := runtime.DefaultUnstructuredConverter.FromUnstructured(obj.Object, &sa); err != nil { + t.Fatalf("converting serviceaccount/%s: %v", obj.GetName(), err) + } + install.serviceAccounts[sa.Name] = sa case "Deployment", "DaemonSet", "StatefulSet", "Job": raw, ok, _ := unstructured.NestedMap(obj.Object, "spec", "template") if !ok { @@ -155,7 +161,7 @@ func loadSystemInstall(t *testing.T, cfg *config.Config) systemInstall { if err := runtime.DefaultUnstructuredConverter.FromUnstructured(raw, &tmpl); err != nil { t.Fatalf("converting the pod template of %s/%s: %v", obj.GetKind(), obj.GetName(), err) } - pod := systemPod{workload: obj.GetKind() + "/" + obj.GetName(), labels: tmpl.Labels} + pod := systemPod{workload: obj.GetKind() + "/" + obj.GetName(), labels: tmpl.Labels, spec: tmpl.Spec} if obj.GetKind() == "Job" { // The Job controller adds this label to its pods. pod.labels = map[string]string{"batch.kubernetes.io/job-name": obj.GetName()} @@ -488,6 +494,48 @@ func TestSystemNetworkPoliciesLeastPrivilege(t *testing.T) { } } + pprofPods := 0 + for _, pod := range in.pods { + for _, cp := range pod.ports { + if cp.Name != "pprof" { + continue + } + pprofPods++ + rules := in.admittingRules(t, pod, cp) + if len(rules) == 0 { + t.Errorf("%s port %s is admitted from nowhere", pod.workload, cp.Name) + } + for _, rule := range rules { + if len(rule.From) == 0 { + t.Errorf("%s port %s is admitted from any source", pod.workload, cp.Name) + } + for _, peer := range rule.From { + if peer.IPBlock != nil || peer.NamespaceSelector == nil { + t.Errorf("%s port %s admits peer %+v, want api-access namespace selector", pod.workload, cp.Name, peer) + continue + } + if want := map[string]string{"ate.dev/api-access": "true"}; !maps.Equal(peer.NamespaceSelector.MatchLabels, want) || len(peer.NamespaceSelector.MatchExpressions) != 0 { + t.Errorf("%s port %s admits namespaces %v, want only %v", pod.workload, cp.Name, peer.NamespaceSelector, want) + } + if peer.PodSelector == nil { + t.Errorf("%s port %s admits every pod of an opted-in namespace, including worker pods", pod.workload, cp.Name) + continue + } + sel := mustSelector(t, peer.PodSelector) + if sel.Matches(labels.Set{workerPoolLabelForTest: "any"}) { + t.Errorf("%s port %s admits worker pods (%s)", pod.workload, cp.Name, workerPoolLabelForTest) + } + if !sel.Matches(labels.Set{"app": "dashboard"}) { + t.Errorf("%s port %s peer %v does not admit ordinary pods of opted-in namespaces", pod.workload, cp.Name, peer.PodSelector) + } + } + } + } + } + if cfg.Pprof != "" && cfg.Pprof != config.PprofOff && pprofPods == 0 { + t.Errorf("found no pods declaring port pprof under --pprof=%s", cfg.Pprof) + } + // The egress gateway admits worker pods only. egress := in.pod(t, "atenet-egress") rules := in.admittingRules(t, egress, namedPort(t, egress, "https")) diff --git a/cmd/ate-setup/internal/steps/version.go b/cmd/ate-setup/internal/steps/version.go index fdd15449a9..0a1676f61e 100644 --- a/cmd/ate-setup/internal/steps/version.go +++ b/cmd/ate-setup/internal/steps/version.go @@ -16,7 +16,6 @@ package steps import ( "os" - "strings" "go.ate.dev/substrate/cmd/ate-setup/internal/ko" ) @@ -32,10 +31,7 @@ func (e *Env) SubstrateVersion() string { if v := os.Getenv("VERSION"); v != "" { return v } - // The tag may carry its digest (v1@sha256:...); the version - // is the tag alone. - v, _, _ := strings.Cut(e.Cfg.Images.Tag, "@") - return v + return e.Cfg.Images.TagWithoutDigest() } // ko.BuildVersion consults VERSION itself before `git describe`. return ko.BuildVersion(e.Cfg.Root) diff --git a/cmd/ate-setup/internal/upgradepolicy/policy.go b/cmd/ate-setup/internal/upgradepolicy/policy.go new file mode 100644 index 0000000000..1c1770cf1f --- /dev/null +++ b/cmd/ate-setup/internal/upgradepolicy/policy.go @@ -0,0 +1,92 @@ +// Copyright 2026 The Agent Substrate 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 upgradepolicy checks release transitions against the version skew +// policy. +package upgradepolicy + +import ( + "fmt" + "regexp" + + "k8s.io/apimachinery/pkg/util/version" +) + +var ( + minimumRelease = version.MustParseSemantic("v1.0.0") + releaseCandidate = regexp.MustCompile(`^rc\.(0|[1-9][0-9]*)$`) +) + +// CheckUpgrade checks an upgrade or redeploy between releases. +func CheckUpgrade(from, to string) error { + fromVersion, err := parseRelease("source", from) + if err != nil { + return err + } + toVersion, err := parseRelease("target", to) + if err != nil { + return err + } + + if fromVersion.LessThan(minimumRelease) || toVersion.LessThan(minimumRelease) { + return fmt.Errorf("the version skew policy applies from v1.0.0") + } + if fromVersion.Major() != toVersion.Major() { + return fmt.Errorf("upgrade from %s to %s changes the major version", from, to) + } + if toVersion.EqualTo(fromVersion) { + return nil + } + if toVersion.LessThan(fromVersion) { + return fmt.Errorf("target release %s must be newer than source release %s", to, from) + } + if toVersion.Minor() > fromVersion.Minor() && toVersion.Minor()-fromVersion.Minor() > 1 { + return fmt.Errorf("upgrade from %s to %s skips a minor release", from, to) + } + return nil +} + +// CheckRollback checks a rollback to upgradeFrom, the release recorded before +// the upgrade started. +func CheckRollback(from, to, upgradeFrom string) error { + targetVersion, err := parseRelease("target", to) + if err != nil { + return err + } + upgradeFromVersion, err := parseRelease("recorded source", upgradeFrom) + if err != nil { + return err + } + if !targetVersion.EqualTo(upgradeFromVersion) { + return fmt.Errorf("rollback target %s does not match recorded source release %s", to, upgradeFrom) + } + if err := CheckUpgrade(upgradeFrom, from); err != nil { + return fmt.Errorf("rollback from %s to %s is unsupported: %w", from, to, err) + } + return nil +} + +func parseRelease(name, raw string) (*version.Version, error) { + if raw == "" { + return nil, fmt.Errorf("%s release is empty", name) + } + v, err := version.ParseSemantic(raw) + if err != nil || raw != "v"+v.String() { + return nil, fmt.Errorf("%s release %q must be a vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-rc.N tag", name, raw) + } + if v.BuildMetadata() != "" || v.PreRelease() != "" && !releaseCandidate.MatchString(v.PreRelease()) { + return nil, fmt.Errorf("%s release %q must be a vMAJOR.MINOR.PATCH or vMAJOR.MINOR.PATCH-rc.N tag", name, raw) + } + return v, nil +} diff --git a/cmd/ate-setup/internal/upgradepolicy/policy_test.go b/cmd/ate-setup/internal/upgradepolicy/policy_test.go new file mode 100644 index 0000000000..7228aa35be --- /dev/null +++ b/cmd/ate-setup/internal/upgradepolicy/policy_test.go @@ -0,0 +1,107 @@ +// Copyright 2026 The Agent Substrate 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 upgradepolicy + +import ( + "strconv" + "strings" + "testing" +) + +func TestCheckUpgrade(t *testing.T) { + maxMinor := strconv.FormatUint(uint64(^uint(0)), 10) + tests := []struct { + name, from, to, wantError string + }{ + {name: "later patch", from: "v1.2.1", to: "v1.2.4"}, + {name: "skipped patches", from: "v1.2.1", to: "v1.2.9"}, + {name: "next minor", from: "v1.2.4", to: "v1.3.0"}, + {name: "next minor later patch", from: "v1.2.4", to: "v1.3.7"}, + {name: "final to next minor release candidate", from: "v1.0.1", to: "v1.1.0-rc.1"}, + {name: "later release candidate", from: "v1.1.0-rc.1", to: "v1.1.0-rc.2"}, + {name: "release candidate to final", from: "v1.1.0-rc.2", to: "v1.1.0"}, + {name: "same release", from: "v1.2.3", to: "v1.2.3"}, + {name: "same release candidate", from: "v1.2.3-rc.1", to: "v1.2.3-rc.1"}, + {name: "maximum minor patch", from: "v1." + maxMinor + ".0", to: "v1." + maxMinor + ".1"}, + {name: "empty source", to: "v1.2.3", wantError: "source release is empty"}, + {name: "empty target", from: "v1.2.3", wantError: "target release is empty"}, + {name: "invalid source", from: "dev", to: "v1.2.3", wantError: "vMAJOR.MINOR.PATCH"}, + {name: "invalid target", from: "v1.2.3", to: "latest", wantError: "vMAJOR.MINOR.PATCH"}, + {name: "missing v", from: "1.2.3", to: "v1.2.4", wantError: "vMAJOR.MINOR.PATCH"}, + {name: "development source", from: "v1.2.3-4-gabcdef", to: "v1.3.0", wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + {name: "development target", from: "v1.2.3", to: "v1.3.0-4-gabcdef", wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + {name: "arbitrary prerelease", from: "v1.2.3", to: "v1.3.0-beta.1", wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + {name: "bare release candidate", from: "v1.2.3", to: "v1.3.0-rc", wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + {name: "malformed release candidate", from: "v1.2.3", to: "v1.3.0-rc.01", wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + {name: "extended release candidate", from: "v1.2.3", to: "v1.3.0-rc.1.test", wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + {name: "build metadata", from: "v1.2.3", to: "v1.2.4+build.1", wantError: "vMAJOR.MINOR.PATCH-rc.N"}, + {name: "image digest", from: "v1.2.3", to: "v1.2.4@sha256:1234", wantError: "vMAJOR.MINOR.PATCH"}, + {name: "before GA", from: "v0.9.1", to: "v1.0.0", wantError: "applies from v1.0.0"}, + {name: "release candidate before GA", from: "v1.0.0-rc.1", to: "v1.0.0", wantError: "applies from v1.0.0"}, + {name: "older patch", from: "v1.2.3", to: "v1.2.2", wantError: "must be newer"}, + {name: "older minor", from: "v1.2.3", to: "v1.1.9", wantError: "must be newer"}, + {name: "older release candidate", from: "v1.3.0-rc.2", to: "v1.3.0-rc.1", wantError: "must be newer"}, + {name: "final to release candidate", from: "v1.3.0", to: "v1.3.0-rc.2", wantError: "must be newer"}, + {name: "skipped minor", from: "v1.2.3", to: "v1.4.0", wantError: "skips a minor release"}, + {name: "skipped minor release candidate", from: "v1.2.3", to: "v1.4.0-rc.1", wantError: "skips a minor release"}, + {name: "new major", from: "v1.9.0", to: "v2.0.0", wantError: "changes the major version"}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := CheckUpgrade(test.from, test.to) + if test.wantError == "" { + if err != nil { + t.Fatalf("CheckUpgrade(%q, %q) error = %v", test.from, test.to, err) + } + return + } + if err == nil || !strings.Contains(err.Error(), test.wantError) { + t.Fatalf("CheckUpgrade(%q, %q) error = %v, want %q", test.from, test.to, err, test.wantError) + } + }) + } +} + +func TestCheckRollback(t *testing.T) { + tests := []struct { + name, from, to, upgradeFrom, wantError string + }{ + {name: "previous patch", from: "v1.2.4", to: "v1.2.1", upgradeFrom: "v1.2.1"}, + {name: "previous minor", from: "v1.3.0", to: "v1.2.4", upgradeFrom: "v1.2.4"}, + {name: "release candidate to previous final", from: "v1.3.0-rc.1", to: "v1.2.4", upgradeFrom: "v1.2.4"}, + {name: "final to previous release candidate", from: "v1.3.0", to: "v1.3.0-rc.2", upgradeFrom: "v1.3.0-rc.2"}, + {name: "different previous minor", from: "v1.3.0", to: "v1.2.9", upgradeFrom: "v1.2.4", wantError: "does not match recorded source"}, + {name: "skipped minor", from: "v1.4.0", to: "v1.2.4", upgradeFrom: "v1.2.4", wantError: "skips a minor release"}, + {name: "newer target", from: "v1.2.3", to: "v1.2.4", upgradeFrom: "v1.2.4", wantError: "must be newer"}, + {name: "before GA", from: "v1.0.0", to: "v0.9.1", upgradeFrom: "v0.9.1", wantError: "applies from v1.0.0"}, + {name: "missing record", from: "v1.2.4", to: "v1.2.1", wantError: "recorded source release is empty"}, + } + + for _, test := range tests { + t.Run(test.name, func(t *testing.T) { + err := CheckRollback(test.from, test.to, test.upgradeFrom) + if test.wantError == "" { + if err != nil { + t.Fatalf("CheckRollback(%q, %q, %q) error = %v", test.from, test.to, test.upgradeFrom, err) + } + return + } + if err == nil || !strings.Contains(err.Error(), test.wantError) { + t.Fatalf("CheckRollback(%q, %q, %q) error = %v, want %q", test.from, test.to, test.upgradeFrom, err, test.wantError) + } + }) + } +} diff --git a/cmd/ateapi/internal/apivalidation/access_policy.go b/cmd/ateapi/internal/apivalidation/access_policy.go index 386bb7e60f..5535e553cc 100644 --- a/cmd/ateapi/internal/apivalidation/access_policy.go +++ b/cmd/ateapi/internal/apivalidation/access_policy.go @@ -20,7 +20,7 @@ import ( "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/authz" - "k8s.io/apimachinery/pkg/api/operation" + "go.ate.dev/substrate/internal/preview" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -34,87 +34,65 @@ var ( bindingsPath = field.NewPath("access_policy", "bindings") ) -func ValidateCreateGlobalAccessPolicyRequest(ctx context.Context, req *ateapi.CreateGlobalAccessPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateCreateGlobalAccessPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateGlobalAccessPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) errs := Validate_CreateGlobalAccessPolicyRequest(ctx, op, nil, req, nil) return append(errs, validateBindings(bindingsPath, req.GetAccessPolicy(), validGlobalRoles)...) } -func ValidateGetGlobalAccessPolicyRequest(ctx context.Context, req *ateapi.GetGlobalAccessPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateGetGlobalAccessPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetGlobalAccessPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_GetGlobalAccessPolicyRequest(ctx, op, nil, req, nil) } -func ValidateUpdateGlobalAccessPolicyRequest(ctx context.Context, req *ateapi.UpdateGlobalAccessPolicyRequest) field.ErrorList { +func ValidateUpdateGlobalAccessPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.UpdateGlobalAccessPolicyRequest) field.ErrorList { // Modeled as a create: this validates the request itself. The result is // validated against the stored value by ValidateGlobalAccessPolicyUpdate. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) errs := Validate_UpdateGlobalAccessPolicyRequest(ctx, op, nil, req, nil) return append(errs, validateBindings(bindingsPath, req.GetAccessPolicy(), validGlobalRoles)...) } // ValidateGlobalAccessPolicyUpdate validates an updated global policy against // the stored one. -func ValidateGlobalAccessPolicyUpdate(ctx context.Context, fldPath *field.Path, newVal, oldVal *ateapi.AccessPolicy) field.ErrorList { - op := MakeUpdateOp(ctx) +func ValidateGlobalAccessPolicyUpdate(ctx context.Context, gates *preview.Gates, fldPath *field.Path, newVal, oldVal *ateapi.AccessPolicy) field.ErrorList { + op := MakeUpdateOp(ctx, gates) errs := Validate_AccessPolicy(ctx, op, fldPath, newVal, oldVal) return append(errs, validateBindings(fldPath.Child("bindings"), newVal, validGlobalRoles)...) } -func ValidateCreateAtespaceAccessPolicyRequest(ctx context.Context, req *ateapi.CreateAtespaceAccessPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateCreateAtespaceAccessPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateAtespaceAccessPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) errs := Validate_CreateAtespaceAccessPolicyRequest(ctx, op, nil, req, nil) return append(errs, validateBindings(bindingsPath, req.GetAccessPolicy(), validAtespaceRoles)...) } -func ValidateGetAtespaceAccessPolicyRequest(ctx context.Context, req *ateapi.GetAtespaceAccessPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateGetAtespaceAccessPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetAtespaceAccessPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_GetAtespaceAccessPolicyRequest(ctx, op, nil, req, nil) } -func ValidateUpdateAtespaceAccessPolicyRequest(ctx context.Context, req *ateapi.UpdateAtespaceAccessPolicyRequest) field.ErrorList { +func ValidateUpdateAtespaceAccessPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.UpdateAtespaceAccessPolicyRequest) field.ErrorList { // Modeled as a create: this validates the request itself. The result is // validated against the stored value by ValidateAtespaceAccessPolicyUpdate. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) errs := Validate_UpdateAtespaceAccessPolicyRequest(ctx, op, nil, req, nil) return append(errs, validateBindings(bindingsPath, req.GetAccessPolicy(), validAtespaceRoles)...) } // ValidateAtespaceAccessPolicyUpdate validates an updated atespace policy // against the stored one. -func ValidateAtespaceAccessPolicyUpdate(ctx context.Context, fldPath *field.Path, newVal, oldVal *ateapi.AccessPolicy) field.ErrorList { - op := MakeUpdateOp(ctx) +func ValidateAtespaceAccessPolicyUpdate(ctx context.Context, gates *preview.Gates, fldPath *field.Path, newVal, oldVal *ateapi.AccessPolicy) field.ErrorList { + op := MakeUpdateOp(ctx, gates) errs := Validate_AccessPolicy(ctx, op, fldPath, newVal, oldVal) return append(errs, validateBindings(fldPath.Child("bindings"), newVal, validAtespaceRoles)...) } -func ValidateDeleteAtespaceAccessPolicyRequest(ctx context.Context, req *ateapi.DeleteAtespaceAccessPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateDeleteAtespaceAccessPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DeleteAtespaceAccessPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_DeleteAtespaceAccessPolicyRequest(ctx, op, nil, req, nil) } -// ValidateCustom_AccessPolicy_Metadata requires an access policy to be the -// unatespaced singleton named "default". -func ValidateCustom_AccessPolicy_Metadata(_ context.Context, _ operation.Operation, root *field.Path, meta, _ *ateapi.ResourceMetadata) field.ErrorList { - var errs field.ErrorList - if meta.GetAtespace() != "" { - errs = append(errs, field.Forbidden(root.Child("atespace"), "must not be set")) - } - return append(errs, validateSingletonName(root.Child("name"), meta.GetName())...) -} - -func ValidateCustom_GetGlobalAccessPolicyRequest_Name(_ context.Context, _ operation.Operation, p *field.Path, name, _ *string) field.ErrorList { - return validateSingletonName(p, *name) -} - -func ValidateCustom_GetAtespaceAccessPolicyRequest_Name(_ context.Context, _ operation.Operation, p *field.Path, name, _ *string) field.ErrorList { - return validateSingletonName(p, *name) -} - -func ValidateCustom_DeleteAtespaceAccessPolicyRequest_Name(_ context.Context, _ operation.Operation, p *field.Path, name, _ *string) field.ErrorList { - return validateSingletonName(p, *name) -} - // validateBindings checks that each binding names an allowed role at most once, // that every member is a valid OpenFGA user, and that the policy stays within // maxMembersPerPolicy. diff --git a/cmd/ateapi/internal/apivalidation/access_policy_test.go b/cmd/ateapi/internal/apivalidation/access_policy_test.go index 47e455c0a9..4df6ad12c1 100644 --- a/cmd/ateapi/internal/apivalidation/access_policy_test.go +++ b/cmd/ateapi/internal/apivalidation/access_policy_test.go @@ -21,6 +21,7 @@ import ( "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/authz" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -101,7 +102,7 @@ func TestValidateCreateGlobalAccessPolicyRequest(t *testing.T) { req: &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: validAccessPolicy(func(p *ateapi.AccessPolicy) { p.Metadata.Name = "other" })}, - wantError: field.ErrorList{field.Invalid(accessPolicyPath.Child("metadata", "name"), nil, "").WithOrigin("custom=default")}, + wantError: field.ErrorList{field.Invalid(accessPolicyPath.Child("metadata", "name"), nil, "").WithOrigin("format=ate-singleton-name")}, }, { // editor is an atespace-only role. name: "editor role", @@ -163,9 +164,10 @@ func TestValidateCreateGlobalAccessPolicyRequest(t *testing.T) { })}, wantError: field.ErrorList{field.TooMany(policyBindings, 0, 0)}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateCreateGlobalAccessPolicyRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateCreateGlobalAccessPolicyRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -186,11 +188,12 @@ func TestValidateGetGlobalAccessPolicyRequest(t *testing.T) { }, { name: "wrong name", req: &ateapi.GetGlobalAccessPolicyRequest{Name: "other"}, - wantError: field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("custom=default")}, + wantError: field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("format=ate-singleton-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateGetGlobalAccessPolicyRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateGetGlobalAccessPolicyRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -215,9 +218,10 @@ func TestValidateUpdateGlobalAccessPolicyRequest(t *testing.T) { })}, wantError: field.ErrorList{field.NotSupported[string](policyBindings.Index(0).Child("role"), "", nil)}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateUpdateGlobalAccessPolicyRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateUpdateGlobalAccessPolicyRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -244,9 +248,10 @@ func TestValidateGlobalAccessPolicyUpdate(t *testing.T) { }), wantError: field.ErrorList{field.Invalid(policyBindings.Index(1).Child("members").Index(0), nil, "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateGlobalAccessPolicyUpdate(ctx, accessPolicyPath, tt.newVal, validAccessPolicy()), tt.wantError) + assertValidateErr(t, ValidateGlobalAccessPolicyUpdate(ctx, gates, accessPolicyPath, tt.newVal, validAccessPolicy()), tt.wantError) }) } } @@ -285,7 +290,7 @@ func TestValidateCreateAtespaceAccessPolicyRequest(t *testing.T) { req: &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: atespace, AccessPolicy: validAccessPolicy(func(p *ateapi.AccessPolicy) { p.Metadata.Name = "other" })}, - wantError: field.ErrorList{field.Invalid(accessPolicyPath.Child("metadata", "name"), nil, "").WithOrigin("custom=default")}, + wantError: field.ErrorList{field.Invalid(accessPolicyPath.Child("metadata", "name"), nil, "").WithOrigin("format=ate-singleton-name")}, }, { name: "unknown role", req: &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: atespace, AccessPolicy: validAccessPolicy(func(p *ateapi.AccessPolicy) { @@ -305,9 +310,10 @@ func TestValidateCreateAtespaceAccessPolicyRequest(t *testing.T) { })}, wantError: field.ErrorList{field.Invalid(policyBindings.Index(0).Child("members").Index(0), nil, "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateCreateAtespaceAccessPolicyRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateCreateAtespaceAccessPolicyRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -332,11 +338,12 @@ func TestValidateGetAtespaceAccessPolicyRequest(t *testing.T) { }, { name: "wrong name", req: &ateapi.GetAtespaceAccessPolicyRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}, Name: "other"}, - wantError: field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("custom=default")}, + wantError: field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("format=ate-singleton-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateGetAtespaceAccessPolicyRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateGetAtespaceAccessPolicyRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -362,9 +369,10 @@ func TestValidateUpdateAtespaceAccessPolicyRequest(t *testing.T) { })}, wantError: field.ErrorList{field.Duplicate(policyBindings.Index(1).Child("role"), nil)}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateUpdateAtespaceAccessPolicyRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateUpdateAtespaceAccessPolicyRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -387,9 +395,10 @@ func TestValidateAtespaceAccessPolicyUpdate(t *testing.T) { }), wantError: field.ErrorList{field.NotSupported[string](policyBindings.Index(0).Child("role"), "", nil)}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateAtespaceAccessPolicyUpdate(ctx, accessPolicyPath, tt.newVal, validAccessPolicy()), tt.wantError) + assertValidateErr(t, ValidateAtespaceAccessPolicyUpdate(ctx, gates, accessPolicyPath, tt.newVal, validAccessPolicy()), tt.wantError) }) } } @@ -414,11 +423,12 @@ func TestValidateDeleteAtespaceAccessPolicyRequest(t *testing.T) { }, { name: "wrong name", req: &ateapi.DeleteAtespaceAccessPolicyRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}, Name: "other"}, - wantError: field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("custom=default")}, + wantError: field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("format=ate-singleton-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateDeleteAtespaceAccessPolicyRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateDeleteAtespaceAccessPolicyRequest(ctx, gates, tt.req), tt.wantError) }) } } diff --git a/cmd/ateapi/internal/apivalidation/actor.go b/cmd/ateapi/internal/apivalidation/actor.go index 5155585e91..958583903f 100644 --- a/cmd/ateapi/internal/apivalidation/actor.go +++ b/cmd/ateapi/internal/apivalidation/actor.go @@ -18,83 +18,84 @@ import ( "context" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "k8s.io/apimachinery/pkg/api/operation" "k8s.io/apimachinery/pkg/api/validate" "k8s.io/apimachinery/pkg/util/validation/field" ) -func ValidateCreateActorRequest(ctx context.Context, req *ateapi.CreateActorRequest) field.ErrorList { +func ValidateCreateActorRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateActorRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_CreateActorRequest(ctx, op, nil, req, nil) } -func ValidateGetActorRequest(ctx context.Context, req *ateapi.GetActorRequest) field.ErrorList { +func ValidateGetActorRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetActorRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_GetActorRequest(ctx, op, nil, req, nil) } -func ValidateListActorsRequest(ctx context.Context, req *ateapi.ListActorsRequest) field.ErrorList { +func ValidateListActorsRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ListActorsRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_ListActorsRequest(ctx, op, nil, req, nil) } -func ValidateUpdateActorRequest(ctx context.Context, req *ateapi.UpdateActorRequest) field.ErrorList { +func ValidateUpdateActorRequest(ctx context.Context, gates *preview.Gates, req *ateapi.UpdateActorRequest) field.ErrorList { // Call the generated validation. // We model this as a create rather than an update because updates assume // the existence of a "current" value, which we do not have yet. This is // validating the request itself. The result will be validated later, after // we have a current value to compare against. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_UpdateActorRequest(ctx, op, nil, req, nil) } -func ValidateDeleteActorRequest(ctx context.Context, req *ateapi.DeleteActorRequest) field.ErrorList { +func ValidateDeleteActorRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DeleteActorRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_DeleteActorRequest(ctx, op, nil, req, nil) } -func ValidateResumeActorRequest(ctx context.Context, req *ateapi.ResumeActorRequest) field.ErrorList { +func ValidateResumeActorRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ResumeActorRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_ResumeActorRequest(ctx, op, nil, req, nil) } -func ValidateSuspendActorRequest(ctx context.Context, req *ateapi.SuspendActorRequest) field.ErrorList { +func ValidateSuspendActorRequest(ctx context.Context, gates *preview.Gates, req *ateapi.SuspendActorRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_SuspendActorRequest(ctx, op, nil, req, nil) } -func ValidateRevertActorRequest(ctx context.Context, req *ateapi.RevertActorRequest) field.ErrorList { +func ValidateRevertActorRequest(ctx context.Context, gates *preview.Gates, req *ateapi.RevertActorRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_RevertActorRequest(ctx, op, nil, req, nil) } -func ValidateMintActorJWTRequest(ctx context.Context, req *ateapi.MintActorJwtRequest) field.ErrorList { +func ValidateMintActorJWTRequest(ctx context.Context, gates *preview.Gates, req *ateapi.MintActorJwtRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_MintActorJwtRequest(ctx, op, nil, req, nil) } -func ValidateMintWorkerActorCertificateRequest(ctx context.Context, req *ateapi.MintWorkerActorCertificateRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateMintWorkerActorCertificateRequest(ctx context.Context, gates *preview.Gates, req *ateapi.MintWorkerActorCertificateRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_MintWorkerActorCertificateRequest(ctx, op, nil, req, nil) } -func ValidateMintWorkerActorJwtRequest(ctx context.Context, req *ateapi.MintWorkerActorJwtRequest) field.ErrorList { - op := operation.Operation{Type: operation.Create} +func ValidateMintWorkerActorJwtRequest(ctx context.Context, gates *preview.Gates, req *ateapi.MintWorkerActorJwtRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_MintWorkerActorJwtRequest(ctx, op, nil, req, nil) } -func ValidateActorUpdate(ctx context.Context, fldPath *field.Path, newVal, oldVal *ateapi.Actor, requireStatus bool) field.ErrorList { +func ValidateActorUpdate(ctx context.Context, gates *preview.Gates, fldPath *field.Path, newVal, oldVal *ateapi.Actor, requireStatus bool) field.ErrorList { // Call the generated validation. - op := MakeUpdateOp(ctx) + op := MakeUpdateOp(ctx, gates) errs := Validate_Actor(ctx, op, fldPath, newVal, oldVal) if requireStatus { // Status is optional in the schema, but is actually required to be set @@ -105,7 +106,7 @@ func ValidateActorUpdate(ctx context.Context, fldPath *field.Path, newVal, oldVa return errs } -// This exists only because nested subfield tags are not supported yet. +// This exists to do partial validation of the target resource in an update. func ValidateCustom_UpdateActorRequest_Actor(ctx context.Context, op operation.Operation, fldPath *field.Path, actor, _ *ateapi.Actor) field.ErrorList { if actor == nil || actor.Metadata == nil { return nil // handled by DV @@ -113,12 +114,9 @@ func ValidateCustom_UpdateActorRequest_Actor(ctx context.Context, op operation.O // Updates are validated in 2 steps: first the update request and then the // resource itself. DV for the request doesn't descend into the resource - // metadata. Once DV supports nested subfield tags, this can be changed to - // something like: - // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:required - errs := Validate_ResourceMetadata(ctx, op, fldPath.Child("metadata"), actor.Metadata, nil) - errs = append(errs, validate.RequiredValue(ctx, op, fldPath.Child("metadata", "atespace"), &actor.Metadata.Atespace, nil)...) - return errs + // metadata. What we need is something like: + // +k8s:subfield(metadata)=+k8s:validateType + return Validate_ResourceMetadata(ctx, op, fldPath.Child("metadata"), actor.Metadata, nil) } // This is needed because DV doesn't have a standard format for IP addresses yet. @@ -131,14 +129,6 @@ func ValidateCustom_WorkerAssignment_WorkerSpiffeId(_ context.Context, _ operati return validateSPIFFEID(fldPath, *value) } -func ValidateCustom_ExternalVolumeStatus_VolumeType(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateVolumeType(fldPath, *value) -} - -func ValidateCustom_ExternalVolumeStatus_StorageVolumeId(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateStorageVolumeID(fldPath, *value) -} - -func ValidateCustom_ExternalVolumeStatus_VolumeContext(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[string]string) field.ErrorList { +func ValidateCustom_ActorExternalVolumeStatus_VolumeContext(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[string]string) field.ErrorList { return resources.ValidateCSIMap(fldPath, value) } diff --git a/cmd/ateapi/internal/apivalidation/actor_template.go b/cmd/ateapi/internal/apivalidation/actor_template.go index 6791331d7e..c453c5abbb 100644 --- a/cmd/ateapi/internal/apivalidation/actor_template.go +++ b/cmd/ateapi/internal/apivalidation/actor_template.go @@ -18,39 +18,40 @@ import ( "context" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "k8s.io/apimachinery/pkg/api/operation" "k8s.io/apimachinery/pkg/util/sets" "k8s.io/apimachinery/pkg/util/validation/field" ) -func ValidateCreateActorTemplateRequest(ctx context.Context, req *ateapi.CreateActorTemplateRequest) field.ErrorList { +func ValidateCreateActorTemplateRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateActorTemplateRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_CreateActorTemplateRequest(ctx, op, nil, req, nil) } -func ValidateGetActorTemplateRequest(ctx context.Context, req *ateapi.GetActorTemplateRequest) field.ErrorList { +func ValidateGetActorTemplateRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetActorTemplateRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_GetActorTemplateRequest(ctx, op, nil, req, nil) } -func ValidateListActorTemplatesRequest(ctx context.Context, req *ateapi.ListActorTemplatesRequest) field.ErrorList { +func ValidateListActorTemplatesRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ListActorTemplatesRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_ListActorTemplatesRequest(ctx, op, nil, req, nil) } -func ValidateDeleteActorTemplateRequest(ctx context.Context, req *ateapi.DeleteActorTemplateRequest) field.ErrorList { +func ValidateDeleteActorTemplateRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DeleteActorTemplateRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_DeleteActorTemplateRequest(ctx, op, nil, req, nil) } -func ValidateActorTemplateUpdate(ctx context.Context, fldPath *field.Path, newVal, oldVal *ateapi.ActorTemplate) field.ErrorList { +func ValidateActorTemplateUpdate(ctx context.Context, gates *preview.Gates, fldPath *field.Path, newVal, oldVal *ateapi.ActorTemplate) field.ErrorList { // Call the generated validation. - op := MakeUpdateOp(ctx) + op := MakeUpdateOp(ctx, gates) return Validate_ActorTemplate(ctx, op, fldPath, newVal, oldVal) } @@ -81,23 +82,6 @@ func ValidateCustom_CreateActorTemplateRequest_ActorTemplate(_ context.Context, return errs } -// ValidateCustom_ActorTemplate_Resources requires both a cpu and a memory -// limit, which the scheduler books against worker capacity. -func ValidateCustom_ActorTemplate_Resources(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *ateapi.ResourceRequirements) field.ErrorList { - var errs field.ErrorList - if value.GetLimits().GetCpuMillicores() == 0 { - errs = append(errs, field.Required(fldPath.Child("limits", "cpu_millicores"), "")) - } - if value.GetLimits().GetMemoryBytes() == 0 { - errs = append(errs, field.Required(fldPath.Child("limits", "memory_bytes"), "")) - } - return errs -} - -func ValidateCustom_HttpGetAction_Path(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateHTTPGetPath(fldPath, *value) -} - func ValidateCustom_VolumeMount_MountPath(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { return resources.ValidateMountPath(fldPath, *value) } @@ -165,18 +149,18 @@ func ValidateCustom_Container_Image(_ context.Context, _ operation.Operation, fl // ValidateCustom_SnapshotConfig_StorageLocation checks an ActorTemplate's // snapshotConfig.storageLocation with resources.ValidateSnapshotLocation, so a -// bad location fails fast. +// bad location fails fast, and with resources.ValidateGCSLocationLength, so +// actors under it get locally minted tokens. func ValidateCustom_SnapshotConfig_StorageLocation(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { if err := resources.ValidateSnapshotLocation(*value); err != nil { return field.ErrorList{field.Invalid(fldPath, *value, err.Error())} } + if err := resources.ValidateGCSLocationLength(*value); err != nil { + return field.ErrorList{field.Invalid(fldPath, *value, err.Error())} + } return nil } -func ValidateCustom_EnvVar_Name(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateEnvVarName(fldPath, *value) -} - func ValidateCustom_Capabilities_Add(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ []string) field.ErrorList { return resources.ValidateAddCapabilities(fldPath, value) } diff --git a/cmd/ateapi/internal/apivalidation/actor_template_test.go b/cmd/ateapi/internal/apivalidation/actor_template_test.go index 0c32ef3440..c9e5cb81b3 100644 --- a/cmd/ateapi/internal/apivalidation/actor_template_test.go +++ b/cmd/ateapi/internal/apivalidation/actor_template_test.go @@ -19,10 +19,12 @@ import ( "fmt" "strings" "testing" + "time" "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" + "google.golang.org/protobuf/types/known/timestamppb" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -68,6 +70,16 @@ func TestValidateCreateActorTemplateRequest(t *testing.T) { }} })}, field.ErrorList{field.Invalid(field.NewPath("actor_template", "golden_egress_policy", "rules").Index(1).Child("tls_passthrough", "hostnames").Index(0), nil, "")}, + }, { + "golden egress token exchange with an invalid token URL", + &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { + tmpl.GoldenEgressPolicy = &ateapi.EgressPolicyTemplate{Rules: []*ateapi.EgressRule{{Https: &ateapi.HttpsRule{ + Hostnames: []string{"api.example.com"}, + Ports: &ateapi.Ports{Numbers: []int32{443}}, + Effects: &ateapi.HttpRuleEffects{ReplaceHeaders: []*ateapi.CredentialHeader{tokenExchangeHeader("http://sts.example.com/token")}}, + }}}} + })}, + field.ErrorList{field.Invalid(field.NewPath("actor_template", "golden_egress_policy", "rules").Index(0).Child("https", "effects", "replace_headers").Index(0).Child("token_exchange", "token_url"), nil, "")}, }, { "too many golden egress rules", &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { @@ -160,6 +172,12 @@ func TestValidateCreateActorTemplateRequest(t *testing.T) { tmpl.Containers[0].VolumeMounts = []*ateapi.VolumeMount{{Name: "ghost-vol", MountPath: "/var/data"}} })}, field.ErrorList{field.Invalid(field.NewPath("actor_template", "containers").Index(0).Child("volume_mounts").Index(0).Child("name"), "ghost-vol", "")}, + }, { + "declared volume that no container mounts", + &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { + tmpl.Volumes = []*ateapi.Volume{{Name: "data", DurableDir: &ateapi.DurableDirVolumeSource{}}} + })}, + nil, }, { "missing snapshot_config is allowed", &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { @@ -229,6 +247,14 @@ func TestValidateCreateActorTemplateRequest(t *testing.T) { &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { tmpl.Resources = &ateapi.ResourceRequirements{} })}, + field.ErrorList{ + field.Required(field.NewPath("actor_template", "resources", "limits"), ""), + }, + }, { + "empty resources.limits", + &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { + tmpl.Resources = &ateapi.ResourceRequirements{Limits: &ateapi.Resources{}} + })}, field.ErrorList{ field.Required(field.NewPath("actor_template", "resources", "limits", "cpu_millicores"), ""), field.Required(field.NewPath("actor_template", "resources", "limits", "memory_bytes"), ""), @@ -246,22 +272,22 @@ func TestValidateCreateActorTemplateRequest(t *testing.T) { want = field.ErrorList{field.Forbidden(field.NewPath("actor_template", "snapshot_config", "storage_location"), "")} wantWithPreview = map[string]field.ErrorList{"PerTemplateSnapshotLocation": tt.want, "ALL": tt.want} } - assertValidate(t, func() field.ErrorList { - return ValidateCreateActorTemplateRequest(context.Background(), tt.req) + assertValidate(t, func(gates *preview.Gates) field.ErrorList { + return ValidateCreateActorTemplateRequest(context.Background(), gates, tt.req) }, want, wantWithPreview) }) } } func TestValidateCreateActorTemplateRequest_PreviewRestricted(t *testing.T) { - setPreviewForTest(t, "ALL") + gates := previewForTest(t, "ALL") req := &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { tmpl.Volumes = []*ateapi.Volume{{Name: "data", External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{CapacityBytes: 10 << 30, StorageClassName: "fast-ssd"}}}} tmpl.SnapshotConfig.StorageLocation = "gs://my-bucket/snapshots" })} t.Run("allowed", func(t *testing.T) { - assertValidateErr(t, ValidateCreateActorTemplateRequest(context.Background(), req), nil) + assertValidateErr(t, ValidateCreateActorTemplateRequest(context.Background(), gates, req), nil) }) t.Run("restricted", func(t *testing.T) { ctx := preview.ContextWithOptOut(context.Background()) @@ -269,7 +295,7 @@ func TestValidateCreateActorTemplateRequest_PreviewRestricted(t *testing.T) { field.Forbidden(field.NewPath("actor_template", "volumes").Index(0).Child("external"), ""), field.Forbidden(field.NewPath("actor_template", "snapshot_config", "storage_location"), ""), } - assertValidateErr(t, ValidateCreateActorTemplateRequest(ctx, req), want) + assertValidateErr(t, ValidateCreateActorTemplateRequest(ctx, gates, req), want) }) } @@ -314,7 +340,7 @@ func TestValidateCreateActorTemplateRequest_PerTemplateSnapshotLocation(t *testi }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - setPreviewForTest(t, tt.gates) + gates := previewForTest(t, tt.gates) ctx := context.Background() if tt.optOut { ctx = preview.ContextWithOptOut(ctx) @@ -324,7 +350,7 @@ func TestValidateCreateActorTemplateRequest_PerTemplateSnapshotLocation(t *testi mutations = append(mutations, tt.mutate) } req := &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(mutations...)} - assertValidateErr(t, ValidateCreateActorTemplateRequest(ctx, req), tt.want) + assertValidateErr(t, ValidateCreateActorTemplateRequest(ctx, gates, req), tt.want) }) } } @@ -351,9 +377,10 @@ func TestValidateGetActorTemplateRequest(t *testing.T) { &ateapi.GetActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: "ns1"}}, field.ErrorList{field.Required(field.NewPath("actor_template", "name"), "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateGetActorTemplateRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateGetActorTemplateRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -384,9 +411,10 @@ func TestValidateListActorTemplatesRequest(t *testing.T) { &ateapi.ListActorTemplatesRequest{Options: &ateapi.ListOptions{PageSize: -1}}, field.ErrorList{field.Invalid(field.NewPath("options", "page_size"), int32(-1), "").WithOrigin("minimum")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateListActorTemplatesRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateListActorTemplatesRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -413,9 +441,10 @@ func TestValidateDeleteActorTemplateRequest(t *testing.T) { &ateapi.DeleteActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: "ns1"}}, field.ErrorList{field.Required(field.NewPath("actor_template", "name"), "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateDeleteActorTemplateRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateDeleteActorTemplateRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -493,8 +522,18 @@ func TestValidateActorTemplate(t *testing.T) { mutate: func(tmpl *ateapi.ActorTemplate) { tmpl.SnapshotConfig.StorageLocation = "gs://" + strings.Repeat("x", 1020) }, + want: field.ErrorList{field.Forbidden(field.NewPath("snapshot_config", "storage_location"), "")}, + wantWithPreview: map[string]field.ErrorList{"PerTemplateSnapshotLocation": { + field.Invalid(field.NewPath("snapshot_config", "storage_location"), nil, ""), + field.TooLong(field.NewPath("snapshot_config", "storage_location"), nil, 1024).WithOrigin("maxLength"), + }}, + }, { + name: "gs:// storage_location too long for GCS", + mutate: func(tmpl *ateapi.ActorTemplate) { + tmpl.SnapshotConfig.StorageLocation = "gs://bucket/" + strings.Repeat("a", 333) + }, want: field.ErrorList{field.Forbidden(field.NewPath("snapshot_config", "storage_location"), "")}, - wantWithPreview: map[string]field.ErrorList{"PerTemplateSnapshotLocation": {field.TooLong(field.NewPath("snapshot_config", "storage_location"), nil, 1024).WithOrigin("maxLength")}}, + wantWithPreview: map[string]field.ErrorList{"PerTemplateSnapshotLocation": {field.Invalid(field.NewPath("snapshot_config", "storage_location"), nil, "")}}, }, { name: "missing storage_location", mutate: func(tmpl *ateapi.ActorTemplate) { tmpl.SnapshotConfig.StorageLocation = "" }, @@ -679,7 +718,7 @@ func TestValidateActorTemplate(t *testing.T) { mutate: func(tmpl *ateapi.ActorTemplate) { tmpl.Containers[0].Env = []*ateapi.EnvVar{{Name: "FOO=BAR"}} }, - want: field.ErrorList{field.Invalid(field.NewPath("containers").Index(0).Child("env").Index(0).Child("name"), nil, "")}, + want: field.ErrorList{field.Invalid(field.NewPath("containers").Index(0).Child("env").Index(0).Child("name"), nil, "").WithOrigin("format=ate-env-var-name")}, }, { name: "env missing name", mutate: func(tmpl *ateapi.ActorTemplate) { @@ -813,7 +852,7 @@ func TestValidateActorTemplate(t *testing.T) { TimeoutSeconds: 60, } }, - want: field.ErrorList{field.Invalid(field.NewPath("containers").Index(0).Child("wakeup_probe", "http_get", "path"), nil, "")}, + want: field.ErrorList{field.Invalid(field.NewPath("containers").Index(0).Child("wakeup_probe", "http_get", "path"), nil, "").WithOrigin("format=ate-http-probe-path")}, }, { name: "wakeup probe path not starting with slash", mutate: func(tmpl *ateapi.ActorTemplate) { @@ -822,7 +861,7 @@ func TestValidateActorTemplate(t *testing.T) { TimeoutSeconds: 60, } }, - want: field.ErrorList{field.Invalid(field.NewPath("containers").Index(0).Child("wakeup_probe", "http_get", "path"), nil, "")}, + want: field.ErrorList{field.Invalid(field.NewPath("containers").Index(0).Child("wakeup_probe", "http_get", "path"), nil, "").WithOrigin("format=ate-http-probe-path")}, }, { name: "valid volume_mount", mutate: func(tmpl *ateapi.ActorTemplate) { @@ -981,14 +1020,72 @@ func TestValidateActorTemplate(t *testing.T) { if tt.mutate != nil { tt.mutate(tmpl) } - assertValidate(t, func() field.ErrorList { - op := MakeCreateOp(context.Background()) - return Validate_ActorTemplate(context.Background(), op, nil, tmpl, nil) + assertValidate(t, func(gates *preview.Gates) field.ErrorList { + ctx := context.Background() + op := MakeCreateOp(ctx, gates) + return Validate_ActorTemplate(ctx, op, nil, tmpl, nil) }, tt.want, tt.wantWithPreview) }) } } +// TestValidateActorTemplateUpdate covers the rules that compare an +// ActorTemplate to its stored value. TestValidateActorTemplate covers the rest. +func TestValidateActorTemplateUpdate(t *testing.T) { + stored := func() *ateapi.ActorTemplate { + return validActorTemplate(func(tmpl *ateapi.ActorTemplate) { + tmpl.Metadata.Uid = "01234567-89ab-cdef-0123-456789abcdef" + tmpl.Metadata.Version = 3 + tmpl.Metadata.CreateTime = timestamppb.New(time.Unix(1000, 0)) + tmpl.Metadata.UpdateTime = timestamppb.New(time.Unix(2000, 0)) + tmpl.Status = &ateapi.ActorTemplateStatus{} + }) + } + tests := []struct { + name string + mutate func(*ateapi.ActorTemplate) + want field.ErrorList + }{{ + name: "unchanged", + }, { + name: "golden snapshot status set", + mutate: func(tmpl *ateapi.ActorTemplate) { + tmpl.Status.GoldenSnapshotStatus = &ateapi.GoldenSnapshotStatus{ErrorMessage: "failed"} + }, + }, { + name: "metadata cleared", + mutate: func(tmpl *ateapi.ActorTemplate) { tmpl.Metadata = nil }, + want: field.ErrorList{field.Required(field.NewPath("metadata"), "")}, + }, { + name: "metadata.atespace changed", + mutate: func(tmpl *ateapi.ActorTemplate) { tmpl.Metadata.Atespace = "ns2" }, + want: field.ErrorList{field.Invalid(field.NewPath("metadata", "atespace"), nil, "").WithOrigin("immutable")}, + }, { + name: "metadata.name changed", + mutate: func(tmpl *ateapi.ActorTemplate) { tmpl.Metadata.Name = "tmpl-b" }, + want: field.ErrorList{field.Invalid(field.NewPath("metadata", "name"), nil, "").WithOrigin("immutable")}, + }, { + name: "metadata.uid changed", + mutate: func(tmpl *ateapi.ActorTemplate) { tmpl.Metadata.Uid = "fedcba98-7654-3210-fedc-ba9876543210" }, + want: field.ErrorList{field.Invalid(field.NewPath("metadata", "uid"), nil, "").WithOrigin("immutable")}, + }, { + name: "metadata.create_time changed", + mutate: func(tmpl *ateapi.ActorTemplate) { tmpl.Metadata.CreateTime = timestamppb.New(time.Unix(1500, 0)) }, + want: field.ErrorList{field.Invalid(field.NewPath("metadata", "create_time"), nil, "").WithOrigin("immutable")}, + }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + newVal := stored() + if tt.mutate != nil { + tt.mutate(newVal) + } + assertValidate(t, func(gates *preview.Gates) field.ErrorList { + return ValidateActorTemplateUpdate(context.Background(), gates, nil, newVal, stored()) + }, tt.want, nil) + }) + } +} + // validActorTemplate returns the smallest template that passes create // validation; mutations tweak it per test case. The snapshot scopes and // resume policy are set explicitly because TestValidateActorTemplate diff --git a/cmd/ateapi/internal/apivalidation/actor_test.go b/cmd/ateapi/internal/apivalidation/actor_test.go index 3c5595f15c..a676822249 100644 --- a/cmd/ateapi/internal/apivalidation/actor_test.go +++ b/cmd/ateapi/internal/apivalidation/actor_test.go @@ -21,6 +21,7 @@ import ( "testing" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -153,9 +154,10 @@ func TestValidateCreateActorRequest(t *testing.T) { validReq(validActor(withSourceTag("as", "invalid value"))), field.ErrorList{field.Invalid(field.NewPath("actor", "source_tag", "name"), nil, "").WithOrigin("format=k8s-short-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateCreateActorRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateCreateActorRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -173,6 +175,7 @@ func TestValidateActorUpdate(t *testing.T) { return a } withMetadata := withActorMetadata + volTypePath := field.NewPath("status", "external_volumes", "volumes").Index(0).Child("volume_type") withWorkerSelector := withActorWorkerSelector withActorTemplate := withActorActorTemplate withSourceTag := withActorSourceTag @@ -648,27 +651,47 @@ func TestValidateActorUpdate(t *testing.T) { name: "adding a volume", oldVal: validActor(withActorStatus()), newVal: validActor(withActorStatus(func(s *ateapi.ActorStatus) { - s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{{Name: "vol-a", VolumeType: "substrate.io/mock"}}} + s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{Name: "vol-a", VolumeType: "mock.ate.dev"}}} })), want: nil, wantWithPreview: map[string]field.ErrorList{"ALL": nil}, + }, { + name: "adding a volume with a prefixed volume type", + oldVal: validActor(withActorStatus()), + newVal: validActor(withActorStatus(func(s *ateapi.ActorStatus) { + s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{Name: "vol-a", VolumeType: "ate.dev/mock"}}} + })), + want: field.ErrorList{field.Invalid(volTypePath, nil, "").WithOrigin("format=k8s-long-name")}, + wantWithPreview: map[string]field.ErrorList{ + "ALL": {field.Invalid(volTypePath, nil, "").WithOrigin("format=k8s-long-name")}, + }, + }, { + name: "adding a volume with a substrate.io prefixed volume type", + oldVal: validActor(withActorStatus()), + newVal: validActor(withActorStatus(func(s *ateapi.ActorStatus) { + s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{Name: "vol-a", VolumeType: "substrate.io/mock"}}} + })), + want: field.ErrorList{field.Invalid(volTypePath, nil, "").WithOrigin("format=k8s-long-name")}, + wantWithPreview: map[string]field.ErrorList{ + "ALL": {field.Invalid(volTypePath, nil, "").WithOrigin("format=k8s-long-name")}, + }, }, { name: "adding a volume to an actor with no status", oldVal: validActor(), newVal: validActor(withActorStatus(func(s *ateapi.ActorStatus) { - s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{{Name: "vol-a", VolumeType: "substrate.io/mock"}}} + s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{Name: "vol-a", VolumeType: "mock.ate.dev"}}} })), want: nil, wantWithPreview: map[string]field.ErrorList{"ALL": nil}, }, { name: "provisioning transition on an existing volume", oldVal: validInput(withStatus(func(s *ateapi.ActorStatus) { - s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{{Name: "vol-a", VolumeType: "substrate.io/mock"}}} + s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{Name: "vol-a", VolumeType: "mock.ate.dev"}}} })), newVal: validActor(withActorStatus(func(s *ateapi.ActorStatus) { - s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{{ + s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{ Name: "vol-a", - VolumeType: "substrate.io/mock", + VolumeType: "mock.ate.dev", StorageVolumeId: "csi-426d29b7", VolumeContext: map[string]string{"attachment": "iqn.2026-08.io.ate:vol-a"}, }}} @@ -679,9 +702,9 @@ func TestValidateActorUpdate(t *testing.T) { name: "duplicate external_volumes volume_name", oldVal: validActor(withActorStatus()), newVal: validActor(withActorStatus(func(s *ateapi.ActorStatus) { - s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ - {Name: "vol-a", VolumeType: "substrate.io/mock"}, - {Name: "vol-a", VolumeType: "substrate.io/mock"}, + s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ + {Name: "vol-a", VolumeType: "mock.ate.dev"}, + {Name: "vol-a", VolumeType: "mock.ate.dev"}, }} })), want: field.ErrorList{field.Duplicate(field.NewPath("status", "external_volumes", "volumes").Index(1), nil)}, @@ -692,9 +715,9 @@ func TestValidateActorUpdate(t *testing.T) { name: "too many external_volumes", oldVal: validActor(withActorStatus()), newVal: validActor(withActorStatus(func(s *ateapi.ActorStatus) { - vols := make([]*ateapi.ExternalVolumeStatus, 33) + vols := make([]*ateapi.ActorExternalVolumeStatus, 33) for i := range vols { - vols[i] = &ateapi.ExternalVolumeStatus{Name: fmt.Sprintf("vol-%d", i), VolumeType: "substrate.io/mock"} + vols[i] = &ateapi.ActorExternalVolumeStatus{Name: fmt.Sprintf("vol-%d", i), VolumeType: "mock.ate.dev"} } s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: vols} })), @@ -705,8 +728,8 @@ func TestValidateActorUpdate(t *testing.T) { }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidate(t, func() field.ErrorList { - return ValidateActorUpdate(context.Background(), nil, tt.newVal, tt.oldVal, true) + assertValidate(t, func(gates *preview.Gates) field.ErrorList { + return ValidateActorUpdate(context.Background(), gates, nil, tt.newVal, tt.oldVal, true) }, tt.want, tt.wantWithPreview) }) } @@ -742,9 +765,10 @@ func TestValidateGetActorRequest(t *testing.T) { &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "ID1"}}, field.ErrorList{field.Invalid(field.NewPath("actor", "name"), "ID1", "").WithOrigin("format=k8s-short-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateGetActorRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateGetActorRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -784,9 +808,10 @@ func TestValidateListActorsRequest(t *testing.T) { &ateapi.ListActorsRequest{Atespace: "ns1", Options: &ateapi.ListOptions{PageToken: strings.Repeat("x", 257)}}, field.ErrorList{field.TooLongCharacters(field.NewPath("options", "page_token"), "", 256).WithOrigin("maxLength")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateListActorsRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateListActorsRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -879,9 +904,10 @@ func TestValidateUpdateActorRequest(t *testing.T) { }))), nil, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateUpdateActorRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateUpdateActorRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -916,9 +942,10 @@ func TestValidateDeleteActorRequest(t *testing.T) { &ateapi.DeleteActorRequest{Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "ID1"}}, field.ErrorList{field.Invalid(field.NewPath("actor", "name"), "ID1", "").WithOrigin("format=k8s-short-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateDeleteActorRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateDeleteActorRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -952,10 +979,32 @@ func TestValidateResumeActorRequest(t *testing.T) { "invalid actor.name", &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "ID1"}}, field.ErrorList{field.Invalid(field.NewPath("actor", "name"), "ID1", "").WithOrigin("format=k8s-short-name")}, + }, { + "valid options", + &ateapi.ResumeActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.ResumeActorRequest_Options{Uid: someActorUID, Version: 3}, + }, + nil, + }, { + "invalid options.uid", + &ateapi.ResumeActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.ResumeActorRequest_Options{Uid: "not-a-uuid"}, + }, + field.ErrorList{field.Invalid(field.NewPath("options", "uid"), nil, "").WithOrigin("format=k8s-uuid")}, + }, { + "negative options.version", + &ateapi.ResumeActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.ResumeActorRequest_Options{Version: -1}, + }, + field.ErrorList{field.Invalid(field.NewPath("options", "version"), nil, "").WithOrigin("minimum")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateResumeActorRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateResumeActorRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -1024,10 +1073,75 @@ func TestValidateSuspendActorRequest(t *testing.T) { Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode(3)}, }, field.ErrorList{field.Invalid(field.NewPath("options", "mode"), nil, "").WithOrigin("maximum")}, + }, { + "valid options guards", + &ateapi.SuspendActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS, Uid: someActorUID, Version: 3}, + }, + nil, + }, { + "invalid options.uid", + &ateapi.SuspendActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.SuspendOptions{Uid: "not-a-uuid"}, + }, + field.ErrorList{field.Invalid(field.NewPath("options", "uid"), nil, "").WithOrigin("format=k8s-uuid")}, + }, { + "negative options.version", + &ateapi.SuspendActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.SuspendOptions{Version: -1}, + }, + field.ErrorList{field.Invalid(field.NewPath("options", "version"), nil, "").WithOrigin("minimum")}, + }} + gates := preview.NewForTest(t) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateSuspendActorRequest(context.Background(), gates, tt.req), tt.want) + }) + } +} + +func TestValidateRevertActorRequest(t *testing.T) { + tests := []struct { + name string + req *ateapi.RevertActorRequest + want field.ErrorList + }{{ + "valid", + &ateapi.RevertActorRequest{Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}}, + nil, + }, { + "missing actor", + &ateapi.RevertActorRequest{}, + field.ErrorList{field.Required(field.NewPath("actor"), "")}, + }, { + "valid options", + &ateapi.RevertActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.RevertActorRequest_Options{Uid: someActorUID, Version: 3}, + }, + nil, + }, { + "invalid options.uid", + &ateapi.RevertActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.RevertActorRequest_Options{Uid: "not-a-uuid"}, + }, + field.ErrorList{field.Invalid(field.NewPath("options", "uid"), nil, "").WithOrigin("format=k8s-uuid")}, + }, { + "negative options.version", + &ateapi.RevertActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: "ns1", Name: "id1"}, + Options: &ateapi.RevertActorRequest_Options{Version: -1}, + }, + field.ErrorList{field.Invalid(field.NewPath("options", "version"), nil, "").WithOrigin("minimum")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateSuspendActorRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateRevertActorRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -1125,9 +1239,10 @@ func TestValidateMintActorJWTRequest(t *testing.T) { {name: "expiration below minimum", req: withExpiration(299), want: field.ErrorList{field.Invalid(path, int64(299), "").WithOrigin("minimum")}}, {name: "expiration above maximum", req: withExpiration(3601), want: field.ErrorList{field.Invalid(path, int64(3601), "").WithOrigin("maximum")}}, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateMintActorJWTRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateMintActorJWTRequest(context.Background(), gates, tt.req), tt.want) }) } } diff --git a/cmd/ateapi/internal/apivalidation/atespace.go b/cmd/ateapi/internal/apivalidation/atespace.go index d79fcad806..f82e5abcae 100644 --- a/cmd/ateapi/internal/apivalidation/atespace.go +++ b/cmd/ateapi/internal/apivalidation/atespace.go @@ -18,29 +18,30 @@ import ( "context" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "k8s.io/apimachinery/pkg/util/validation/field" ) -func ValidateCreateAtespaceRequest(ctx context.Context, req *ateapi.CreateAtespaceRequest) field.ErrorList { +func ValidateCreateAtespaceRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateAtespaceRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_CreateAtespaceRequest(ctx, op, nil, req, nil) } -func ValidateGetAtespaceRequest(ctx context.Context, req *ateapi.GetAtespaceRequest) field.ErrorList { +func ValidateGetAtespaceRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetAtespaceRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_GetAtespaceRequest(ctx, op, nil, req, nil) } -func ValidateListAtespacesRequest(ctx context.Context, req *ateapi.ListAtespacesRequest) field.ErrorList { +func ValidateListAtespacesRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ListAtespacesRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_ListAtespacesRequest(ctx, op, nil, req, nil) } -func ValidateDeleteAtespaceRequest(ctx context.Context, req *ateapi.DeleteAtespaceRequest) field.ErrorList { +func ValidateDeleteAtespaceRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DeleteAtespaceRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_DeleteAtespaceRequest(ctx, op, nil, req, nil) } diff --git a/cmd/ateapi/internal/apivalidation/atespace_test.go b/cmd/ateapi/internal/apivalidation/atespace_test.go index 5bdc0dc361..8e6e7bb833 100644 --- a/cmd/ateapi/internal/apivalidation/atespace_test.go +++ b/cmd/ateapi/internal/apivalidation/atespace_test.go @@ -20,6 +20,7 @@ import ( "testing" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -65,9 +66,10 @@ func TestValidateCreateAtespaceRequest(t *testing.T) { validReq(validAtespace(withMetadata(func(m *ateapi.ResourceMetadata) { m.Name = "invalid value" }))), field.ErrorList{field.Invalid(field.NewPath("atespace", "metadata", "name"), nil, "").WithOrigin("format=k8s-short-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateCreateAtespaceRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateCreateAtespaceRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -109,9 +111,10 @@ func TestValidateGetAtespaceRequest(t *testing.T) { validReq(func(r *ateapi.GetAtespaceRequest) { r.Atespace.Name = "invalid value" }), field.ErrorList{field.Invalid(field.NewPath("atespace", "name"), nil, "").WithOrigin("format=k8s-short-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateGetAtespaceRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateGetAtespaceRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -155,9 +158,10 @@ func TestValidateListAtespacesRequest(t *testing.T) { }), field.ErrorList{field.TooLongCharacters(field.NewPath("options", "page_token"), "", 256).WithOrigin("maxLength")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateListAtespacesRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateListAtespacesRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -199,9 +203,10 @@ func TestValidateDeleteAtespaceRequest(t *testing.T) { validReq(func(r *ateapi.DeleteAtespaceRequest) { r.Atespace.Name = "invalid value" }), field.ErrorList{field.Invalid(field.NewPath("atespace", "name"), nil, "").WithOrigin("format=k8s-short-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateDeleteAtespaceRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateDeleteAtespaceRequest(context.Background(), gates, tt.req), tt.want) }) } } diff --git a/cmd/ateapi/internal/apivalidation/common.go b/cmd/ateapi/internal/apivalidation/common.go index 8734e7f30d..4f6db85903 100644 --- a/cmd/ateapi/internal/apivalidation/common.go +++ b/cmd/ateapi/internal/apivalidation/common.go @@ -16,7 +16,6 @@ package apivalidation import ( "context" - "fmt" "net/netip" "github.com/spiffe/go-spiffe/v2/spiffeid" @@ -34,36 +33,26 @@ func ateDeepEqual[T any](a, b T) bool { return resources.DeepEqual(a, b) } -// validateSingletonName requires the name of a singleton subresource to be -// resources.SingletonName. An empty name is left to the required tag. -func validateSingletonName(fldPath *field.Path, name string) field.ErrorList { - if name == "" || name == resources.SingletonName { - return nil - } - return field.ErrorList{field.Invalid(fldPath, name, fmt.Sprintf("must be %q", resources.SingletonName)).WithOrigin("custom=default")} -} - -// MakeCreateOp returns an operation.Operation for a create operation. If ctx -// has opted-out of preview features, the returned operation will have all -// preview gates disabled (see preview.Header). -func MakeCreateOp(ctx context.Context) operation.Operation { - return operation.Operation{Type: operation.Create, Options: optionsFor(ctx)} +// MakeCreateOp returns an operation.Operation for a create operation with the +// preview gates in gates. If ctx has opted out of preview features, all gates +// are disabled (see preview.Header). +func MakeCreateOp(ctx context.Context, gates *preview.Gates) operation.Operation { + return operation.Operation{Type: operation.Create, OptionGetter: optionsFor(ctx, gates)} } -// MakeUpdateOp returns an operation.Operation for an update operation. If ctx -// has opted-out of preview features, the returned operation will have all -// preview gates disabled (see preview.Header). -func MakeUpdateOp(ctx context.Context) operation.Operation { - return operation.Operation{Type: operation.Update, Options: optionsFor(ctx)} +// MakeUpdateOp returns an operation.Operation for an update operation with the +// preview gates in gates. If ctx has opted out of preview features, all gates +// are disabled (see preview.Header). +func MakeUpdateOp(ctx context.Context, gates *preview.Gates) operation.Operation { + return operation.Operation{Type: operation.Update, OptionGetter: optionsFor(ctx, gates)} } -// optionsFor returns the preview gates enabled for ctx. -// The returned map MUST NOT be modified. -func optionsFor(ctx context.Context) map[string]bool { +// optionsFor returns a getter for the preview gates enabled for ctx. +func optionsFor(ctx context.Context, gates *preview.Gates) operation.OptionGetter { if preview.IsOptedOut(ctx) { - return preview.DisabledMap() + return gates.DisabledOptionGetter() } - return preview.AsMap() + return gates.OptionGetter() } // ValidateCustom_ResourceMetadata checks the server-stamped timestamps: each, diff --git a/cmd/ateapi/internal/apivalidation/common_test.go b/cmd/ateapi/internal/apivalidation/common_test.go index 5da2b9116e..6f73f9f833 100644 --- a/cmd/ateapi/internal/apivalidation/common_test.go +++ b/cmd/ateapi/internal/apivalidation/common_test.go @@ -40,28 +40,26 @@ const ( // Then, for each entry in wantWithPreview, it enables the gates the key names // and checks validate against that entry's errors. Only cases that set fields // behind a preview gate need wantWithPreview. -func assertValidate(t *testing.T, validate func() field.ErrorList, want field.ErrorList, wantWithPreview map[string]field.ErrorList) { +func assertValidate(t *testing.T, validate func(*preview.Gates) field.ErrorList, want field.ErrorList, wantWithPreview map[string]field.ErrorList) { t.Helper() - setPreviewForTest(t, "") - assertValidateErr(t, validate(), want) + assertValidateErr(t, validate(previewForTest(t, "")), want) for _, gates := range slices.Sorted(maps.Keys(wantWithPreview)) { t.Run("preview="+gates, func(t *testing.T) { t.Helper() - setPreviewForTest(t, gates) - assertValidateErr(t, validate(), wantWithPreview[gates]) + assertValidateErr(t, validate(previewForTest(t, gates)), wantWithPreview[gates]) }) } } -// setPreviewForTest enables the preview gates named by gates, a --preview -// value such as "ALL", for the duration of t. An empty value enables none. -func setPreviewForTest(t *testing.T, gates string) { +// previewForTest returns the preview gates named by gates, a --preview value +// such as "ALL". An empty value enables none. +func previewForTest(t *testing.T, gates string) *preview.Gates { t.Helper() var values []string if gates != "" { values = strings.Split(gates, ",") } - preview.InitForTest(t, values...) + return preview.NewForTest(t, values...) } func selectorLabelsOfSize(n int) map[string]string { diff --git a/cmd/ateapi/internal/apivalidation/csi_driver.go b/cmd/ateapi/internal/apivalidation/csi_driver.go new file mode 100644 index 0000000000..f7da421545 --- /dev/null +++ b/cmd/ateapi/internal/apivalidation/csi_driver.go @@ -0,0 +1,76 @@ +// Copyright 2026 The Agent Substrate 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 apivalidation + +import ( + "context" + "net/netip" + "strings" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" + "k8s.io/apimachinery/pkg/api/operation" + "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +func ValidateCreateCSIDriverRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateCsiDriverRequest) field.ErrorList { + return Validate_CreateCsiDriverRequest(ctx, MakeCreateOp(ctx, gates), nil, req, nil) +} + +func ValidateGetCSIDriverRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetCsiDriverRequest) field.ErrorList { + return Validate_GetCsiDriverRequest(ctx, MakeCreateOp(ctx, gates), nil, req, nil) +} + +func ValidateListCSIDriversRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ListCsiDriversRequest) field.ErrorList { + return Validate_ListCsiDriversRequest(ctx, MakeCreateOp(ctx, gates), nil, req, nil) +} + +func ValidateUpdateCSIDriverRequest(ctx context.Context, gates *preview.Gates, req *ateapi.UpdateCsiDriverRequest) field.ErrorList { + return Validate_UpdateCsiDriverRequest(ctx, MakeCreateOp(ctx, gates), nil, req, nil) +} + +func ValidateDeleteCSIDriverRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DeleteCsiDriverRequest) field.ErrorList { + return Validate_DeleteCsiDriverRequest(ctx, MakeCreateOp(ctx, gates), nil, req, nil) +} + +func ValidateCSIDriverUpdate(ctx context.Context, gates *preview.Gates, fldPath *field.Path, newVal, oldVal *ateapi.CsiDriver) field.ErrorList { + return Validate_CsiDriver(ctx, MakeUpdateOp(ctx, gates), fldPath, newVal, oldVal) +} + +func ValidateCustom_UpdateCsiDriverRequest_CsiDriver(ctx context.Context, op operation.Operation, fldPath *field.Path, driver, _ *ateapi.CsiDriver) field.ErrorList { + if driver == nil || driver.Metadata == nil { + return nil // handled by DV + } + return Validate_ResourceMetadata(ctx, op, fldPath.Child("metadata"), driver.Metadata, nil) +} + +func ValidateCustom_CsiDriverEndpoint_Host(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { + host := *value + if !isValidEndpointHost(host) { + return field.ErrorList{field.Invalid(fldPath, host, "must be a DNS-1123 subdomain or IPv4/IPv6 address without a zone ID")} + } + return nil +} + +func isValidEndpointHost(host string) bool { + if host == "" { + return false + } + if ip, err := netip.ParseAddr(host); err == nil { + return ip.Zone() == "" + } + return len(validation.IsDNS1123Subdomain(strings.TrimSuffix(host, "."))) == 0 +} diff --git a/cmd/ateapi/internal/apivalidation/csi_driver_test.go b/cmd/ateapi/internal/apivalidation/csi_driver_test.go new file mode 100644 index 0000000000..6cdcffcbe9 --- /dev/null +++ b/cmd/ateapi/internal/apivalidation/csi_driver_test.go @@ -0,0 +1,220 @@ +// Copyright 2026 The Agent Substrate 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 apivalidation + +import ( + "context" + "strings" + "testing" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" + "google.golang.org/protobuf/types/known/timestamppb" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +func validCSIDriver(mutate ...func(*ateapi.CsiDriver)) *ateapi.CsiDriver { + driver := &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, + DriverName: "nfs.csi.k8s.io", + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "csi-nfs.ate-system.svc", Port: 9000}, + } + for _, fn := range mutate { + if fn != nil { + fn(driver) + } + } + return driver +} + +func TestValidateCreateCSIDriverRequest(t *testing.T) { + cd := field.NewPath("csi_driver") + ep, tlsPath := cd.Child("controller_endpoint"), cd.Child("tls") + tests := []struct { + name string + req *ateapi.CreateCsiDriverRequest + want field.ErrorList + }{ + {"missing csi_driver", &ateapi.CreateCsiDriverRequest{}, field.ErrorList{field.Required(cd, "")}}, + {"valid default", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver()}, nil}, + {"valid ipv4 + port 65535", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { + d.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "127.0.0.1", Port: 65535} + })}, nil}, + {"valid ipv6 + tls", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { + d.DriverName = "pd.csi.storage.gke.io" + d.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "::1", Port: 9000} + d.Tls = &ateapi.CsiDriverTlsConfig{ServerName: "csi.ate-system.svc"} + })}, nil}, + {"valid fqdn with trailing dot", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { + d.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "csi-nfs.ate-system.svc.cluster.local.", Port: 1} + })}, nil}, + {"atespace forbidden", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.Metadata.Atespace = "as" })}, field.ErrorList{field.Forbidden(cd.Child("metadata", "atespace"), "")}}, + {"missing driver_name", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.DriverName = "" })}, field.ErrorList{field.Required(cd.Child("driver_name"), "")}}, + {"invalid driver_name", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.DriverName = "Bad_Driver" })}, field.ErrorList{field.Invalid(cd.Child("driver_name"), nil, "").WithOrigin("format=k8s-long-name")}}, + {"substrate.io prefix rejected", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.DriverName = "substrate.io/mock" })}, field.ErrorList{field.Invalid(cd.Child("driver_name"), nil, "").WithOrigin("format=k8s-long-name")}}, + {"too-long driver_name", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.DriverName = "nfs.csi." + strings.Repeat("a", 56) })}, field.ErrorList{field.TooLong(cd.Child("driver_name"), "", 63).WithOrigin("maxLength")}}, + {"missing controller_endpoint", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint = nil })}, field.ErrorList{field.Required(ep, "")}}, + {"missing endpoint host", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Host = "" })}, field.ErrorList{field.Required(ep.Child("host"), "")}}, + {"endpoint host with scheme rejected", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Host = "tcp://127.0.0.1" })}, field.ErrorList{field.Invalid(ep.Child("host"), nil, "")}}, + {"endpoint host with port rejected", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Host = "127.0.0.1:9000" })}, field.ErrorList{field.Invalid(ep.Child("host"), nil, "")}}, + {"endpoint host bracketed ipv6 rejected", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Host = "[::1]" })}, field.ErrorList{field.Invalid(ep.Child("host"), nil, "")}}, + {"endpoint host ipv6 with zone rejected", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Host = "fe80::1%eth0" })}, field.ErrorList{field.Invalid(ep.Child("host"), nil, "")}}, + {"endpoint host invalid dns", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Host = "Bad_Host" })}, field.ErrorList{field.Invalid(ep.Child("host"), nil, "")}}, + {"missing endpoint port", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Port = 0 })}, field.ErrorList{field.Required(ep.Child("port"), "")}}, + {"negative endpoint port", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Port = -1 })}, field.ErrorList{field.Invalid(ep.Child("port"), int32(-1), "").WithOrigin("minimum")}}, + {"too-large endpoint port", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { d.ControllerEndpoint.Port = 65536 })}, field.ErrorList{field.Invalid(ep.Child("port"), int32(65536), "").WithOrigin("maximum")}}, + {"tls missing server_name", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { + d.Tls = &ateapi.CsiDriverTlsConfig{} + })}, field.ErrorList{field.Required(tlsPath.Child("server_name"), "")}}, + {"tls invalid server_name format", &ateapi.CreateCsiDriverRequest{CsiDriver: validCSIDriver(func(d *ateapi.CsiDriver) { + d.Tls = &ateapi.CsiDriverTlsConfig{ServerName: "Bad_Host"} + })}, field.ErrorList{field.Invalid(tlsPath.Child("server_name"), nil, "").WithOrigin("format=k8s-long-name")}}, + } + gates := preview.NewForTest(t) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateCreateCSIDriverRequest(context.Background(), gates, tt.req), tt.want) + }) + } +} + +func TestValidateGetCSIDriverRequest(t *testing.T) { + tests := []struct { + name string + ref *ateapi.ObjectRef + want field.ErrorList + }{ + {"valid", &ateapi.ObjectRef{Name: "csi-nfs"}, nil}, + {"missing ref", nil, field.ErrorList{field.Required(field.NewPath("csi_driver"), "")}}, + {"atespace must be empty", &ateapi.ObjectRef{Atespace: "as", Name: "csi-nfs"}, field.ErrorList{field.Forbidden(field.NewPath("csi_driver", "atespace"), "")}}, + {"missing name", &ateapi.ObjectRef{}, field.ErrorList{field.Required(field.NewPath("csi_driver", "name"), "")}}, + } + gates := preview.NewForTest(t) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateGetCSIDriverRequest(context.Background(), gates, &ateapi.GetCsiDriverRequest{CsiDriver: tt.ref}), tt.want) + }) + } +} + +func TestValidateDeleteCSIDriverRequest(t *testing.T) { + tests := []struct { + name string + req *ateapi.DeleteCsiDriverRequest + want field.ErrorList + }{ + {"valid", &ateapi.DeleteCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}}, nil}, + {"missing ref", &ateapi.DeleteCsiDriverRequest{}, field.ErrorList{field.Required(field.NewPath("csi_driver"), "")}}, + {"atespace must be empty", &ateapi.DeleteCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Atespace: "as", Name: "csi-nfs"}}, field.ErrorList{field.Forbidden(field.NewPath("csi_driver", "atespace"), "")}}, + {"missing name", &ateapi.DeleteCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{}}, field.ErrorList{field.Required(field.NewPath("csi_driver", "name"), "")}}, + {"invalid delete options uid", &ateapi.DeleteCsiDriverRequest{ + CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}, + Options: &ateapi.DeleteOptions{Uid: "not-a-uuid"}, + }, field.ErrorList{field.Invalid(field.NewPath("options", "uid"), nil, "").WithOrigin("format=k8s-uuid")}}, + } + gates := preview.NewForTest(t) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateDeleteCSIDriverRequest(context.Background(), gates, tt.req), tt.want) + }) + } +} + +func TestValidateListCSIDriversRequest(t *testing.T) { + tests := []struct { + name string + req *ateapi.ListCsiDriversRequest + want field.ErrorList + }{ + {"valid", &ateapi.ListCsiDriversRequest{}, nil}, + {"negative page_size", &ateapi.ListCsiDriversRequest{Options: &ateapi.ListOptions{PageSize: -1}}, field.ErrorList{field.Invalid(field.NewPath("options", "page_size"), int32(-1), "").WithOrigin("minimum")}}, + } + gates := preview.NewForTest(t) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateListCSIDriversRequest(context.Background(), gates, tt.req), tt.want) + }) + } +} + +func TestValidateUpdateCSIDriverRequest(t *testing.T) { + cd := field.NewPath("csi_driver") + validReq := func(mutate ...func(*ateapi.CsiDriver)) *ateapi.UpdateCsiDriverRequest { + driver := validCSIDriver(func(d *ateapi.CsiDriver) { + d.Metadata.Uid = someActorUID + d.Metadata.Version = 3 + }) + for _, fn := range mutate { + fn(driver) + } + return &ateapi.UpdateCsiDriverRequest{CsiDriver: driver} + } + tests := []struct { + name string + req *ateapi.UpdateCsiDriverRequest + want field.ErrorList + }{ + {"missing csi_driver", &ateapi.UpdateCsiDriverRequest{}, field.ErrorList{field.Required(cd, "")}}, + {"valid", validReq(), nil}, + {"missing uid and version pass request validation", validReq(func(d *ateapi.CsiDriver) { d.Metadata.Uid = ""; d.Metadata.Version = 0 }), nil}, + {"missing metadata", validReq(func(d *ateapi.CsiDriver) { d.Metadata = nil }), field.ErrorList{field.Required(cd.Child("metadata"), "")}}, + {"missing metadata.name", validReq(func(d *ateapi.CsiDriver) { d.Metadata.Name = "" }), field.ErrorList{field.Required(cd.Child("metadata", "name"), "")}}, + {"invalid metadata.name", validReq(func(d *ateapi.CsiDriver) { d.Metadata.Name = "Bad_Name" }), field.ErrorList{field.Invalid(cd.Child("metadata", "name"), nil, "").WithOrigin("format=k8s-short-name")}}, + {"invalid metadata.uid", validReq(func(d *ateapi.CsiDriver) { d.Metadata.Uid = "not-a-uuid" }), field.ErrorList{field.Invalid(cd.Child("metadata", "uid"), nil, "").WithOrigin("format=k8s-uuid")}}, + {"metadata.atespace forbidden", validReq(func(d *ateapi.CsiDriver) { d.Metadata.Atespace = "as" }), field.ErrorList{field.Forbidden(cd.Child("metadata", "atespace"), "")}}, + } + gates := preview.NewForTest(t) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateUpdateCSIDriverRequest(context.Background(), gates, tt.req), tt.want) + }) + } +} + +func TestValidateCSIDriverUpdate(t *testing.T) { + stored := func(mutate ...func(*ateapi.CsiDriver)) *ateapi.CsiDriver { + return validCSIDriver(append([]func(*ateapi.CsiDriver){func(d *ateapi.CsiDriver) { + d.Metadata.Uid = someActorUID + d.Metadata.Version = 2 + d.Metadata.CreateTime = ×tamppb.Timestamp{Seconds: 100} + d.Metadata.UpdateTime = ×tamppb.Timestamp{Seconds: 200} + }}, mutate...)...) + } + cd := field.NewPath("csi_driver") + tests := []struct { + name string + mutate func(*ateapi.CsiDriver) + want field.ErrorList + }{ + {"valid mutable fields changed", func(d *ateapi.CsiDriver) { + d.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "10.0.0.2", Port: 9000} + d.Tls = &ateapi.CsiDriverTlsConfig{ServerName: "csi.ate-system.svc"} + }, nil}, + {"driver_name immutable", func(d *ateapi.CsiDriver) { d.DriverName = "other.csi.k8s.io" }, field.ErrorList{field.Invalid(cd.Child("driver_name"), nil, "").WithOrigin("immutable")}}, + {"metadata.name immutable", func(d *ateapi.CsiDriver) { d.Metadata.Name = "other" }, field.ErrorList{field.Invalid(cd.Child("metadata", "name"), nil, "").WithOrigin("immutable")}}, + {"metadata.uid immutable", func(d *ateapi.CsiDriver) { d.Metadata.Uid = "11111111-2222-3333-4444-555555555555" }, field.ErrorList{field.Invalid(cd.Child("metadata", "uid"), nil, "").WithOrigin("immutable")}}, + {"metadata.create_time immutable", func(d *ateapi.CsiDriver) { d.Metadata.CreateTime = ×tamppb.Timestamp{Seconds: 101} }, field.ErrorList{field.Invalid(cd.Child("metadata", "create_time"), nil, "").WithOrigin("immutable")}}, + {"metadata.atespace forbidden and immutable", func(d *ateapi.CsiDriver) { d.Metadata.Atespace = "as" }, field.ErrorList{ + field.Forbidden(cd.Child("metadata", "atespace"), ""), + field.Invalid(cd.Child("metadata", "atespace"), nil, "").WithOrigin("immutable"), + }}, + } + gates := preview.NewForTest(t) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateCSIDriverUpdate(context.Background(), gates, cd, stored(tt.mutate), stored()), tt.want) + }) + } +} diff --git a/cmd/ateapi/internal/apivalidation/egress_policy.go b/cmd/ateapi/internal/apivalidation/egress_policy.go index 4e8c8883fb..00282f8145 100644 --- a/cmd/ateapi/internal/apivalidation/egress_policy.go +++ b/cmd/ateapi/internal/apivalidation/egress_policy.go @@ -22,33 +22,34 @@ import ( "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/internal/egresspolicy" + "go.ate.dev/substrate/internal/preview" "k8s.io/apimachinery/pkg/api/operation" "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation/field" ) -func ValidateCreateActorEgressPolicyRequest(ctx context.Context, req *ateapi.CreateActorEgressPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateCreateActorEgressPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateActorEgressPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_CreateActorEgressPolicyRequest(ctx, op, nil, req, nil) } -func ValidateGetActorEgressPolicyRequest(ctx context.Context, req *ateapi.GetActorEgressPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateGetActorEgressPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetActorEgressPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_GetActorEgressPolicyRequest(ctx, op, nil, req, nil) } -func ValidateUpdateActorEgressPolicyRequest(ctx context.Context, req *ateapi.UpdateActorEgressPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateUpdateActorEgressPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.UpdateActorEgressPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_UpdateActorEgressPolicyRequest(ctx, op, nil, req, nil) } -func ValidateDeleteActorEgressPolicyRequest(ctx context.Context, req *ateapi.DeleteActorEgressPolicyRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateDeleteActorEgressPolicyRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DeleteActorEgressPolicyRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_DeleteActorEgressPolicyRequest(ctx, op, nil, req, nil) } -func ValidateEgressPolicyUpdate(ctx context.Context, p *field.Path, newVal, oldVal *ateapi.EgressPolicy) field.ErrorList { - op := MakeUpdateOp(ctx) +func ValidateEgressPolicyUpdate(ctx context.Context, gates *preview.Gates, p *field.Path, newVal, oldVal *ateapi.EgressPolicy) field.ErrorList { + op := MakeUpdateOp(ctx, gates) return Validate_EgressPolicy(ctx, op, p, newVal, oldVal) } @@ -77,18 +78,6 @@ func validateEgressPolicyParentAtespace(actor *ateapi.ObjectRef, policy *ateapi. return nil } -func ValidateCustom_EgressPolicy_Metadata(_ context.Context, _ operation.Operation, root *field.Path, meta, _ *ateapi.ResourceMetadata) field.ErrorList { - return validateSingletonName(root.Child("name"), meta.GetName()) -} - -func ValidateCustom_GetActorEgressPolicyRequest_Name(_ context.Context, _ operation.Operation, p *field.Path, name, _ *string) field.ErrorList { - return validateSingletonName(p, *name) -} - -func ValidateCustom_DeleteActorEgressPolicyRequest_Name(_ context.Context, _ operation.Operation, p *field.Path, name, _ *string) field.ErrorList { - return validateSingletonName(p, *name) -} - // ValidateCustom_EgressPolicy_Rules rejects two rules that tie on a pattern // and a port, whatever their protocols: the gateway would have no way to pick // one. Defaults are applied before validation, so an http rule left on 80 @@ -227,34 +216,101 @@ func validateHostnamePattern(raw string, p *field.Path) field.ErrorList { return nil } -func ValidateCustom_CredentialHeader_Header(_ context.Context, _ operation.Operation, p *field.Path, header, _ *string) field.ErrorList { - if !validHeaderName(*header) { +func ValidateCustom_CredentialHeader_CredentialUri(_ context.Context, _ operation.Operation, p *field.Path, uri, _ *string) field.ErrorList { + if !validCredentialURI(*uri) { return field.ErrorList{ - field.Invalid(p, *header, "must be an HTTP header name"), + field.Invalid(p, *uri, "must be ate-secret:////"), } } return nil } -func ValidateCustom_CredentialHeader_Prefix(_ context.Context, _ operation.Operation, p *field.Path, prefix, _ *string) field.ErrorList { - if !validHeaderValue(*prefix) { +func ValidateCustom_TokenExchangeSource_TokenUrl(_ context.Context, _ operation.Operation, p *field.Path, raw, _ *string) field.ErrorList { + if _, ok := egresspolicy.TokenURLDestination(*raw); !ok { return field.ErrorList{ - field.Invalid(p, *prefix, "must be a valid HTTP field value prefix"), + field.Invalid(p, *raw, "must be an https URL with a DNS hostname and no userinfo, query, or fragment"), } } return nil } -func ValidateCustom_CredentialHeader_CredentialUri(_ context.Context, _ operation.Operation, p *field.Path, uri, _ *string) field.ErrorList { - if !validCredentialURI(*uri) { - return field.ErrorList{ - field.Invalid(p, *uri, "must be ate-secret:////"), +func ValidateCustom_TokenExchangeSource_Resources(_ context.Context, _ operation.Operation, p *field.Path, resources, _ []string) field.ErrorList { + var errs field.ErrorList + for i, raw := range resources { + if !validResourceURI(raw) { + errs = append(errs, field.Invalid(p.Index(i), raw, "must be an absolute URI without a fragment")) } } - return nil + return errs +} + +func ValidateCustom_TokenExchangeSource_Scopes(_ context.Context, _ operation.Operation, p *field.Path, scopes, _ []string) field.ErrorList { + var errs field.ErrorList + for i, scope := range scopes { + if !validScopeToken(scope) { + errs = append(errs, field.Invalid(p.Index(i), scope, `must be printable ASCII without spaces, '"', or '\'`)) + } + } + return errs +} + +// reservedTokenExchangeParams are the RFC 8693 section 2.1 form parameters +// managed by structured fields on TokenExchangeSource. +var reservedTokenExchangeParams = map[string]bool{ + "grant_type": true, + "subject_token": true, + "subject_token_type": true, + "actor_token": true, + "actor_token_type": true, + "resource": true, + "audience": true, + "scope": true, + "requested_token_type": true, +} + +func ValidateCustom_TokenExchangeSource_AdditionalParameters(_ context.Context, _ operation.Operation, p *field.Path, params, _ []*ateapi.FormEntry) field.ErrorList { + var errs field.ErrorList + for i, entry := range params { + if entry == nil { + continue + } + if reservedTokenExchangeParams[entry.Key] { + errs = append(errs, field.Invalid(p.Index(i).Child("key"), entry.Key, "is a reserved RFC 8693 parameter name")) + } + } + return errs +} + +// validResourceURI reports whether raw is an RFC 3986 section 4.3 absolute URI +// without a fragment (RFC 8693 section 2.1). +func validResourceURI(raw string) bool { + if raw == "" || strings.ContainsRune(raw, '#') || strings.ContainsAny(raw, " \t\r\n") { + return false + } + u, err := url.Parse(raw) + if err != nil || u.Scheme == "" { + return false + } + return u.Host != "" || u.Path != "" || u.Opaque != "" +} + +// validScopeToken reports whether scope holds only RFC 6749 scope-token +// characters, which exclude the space that joins scopes in a request. +func validScopeToken(scope string) bool { + for _, c := range []byte(scope) { + if c < 0x21 || c > 0x7e || c == '"' || c == '\\' { + return false + } + } + return true } func validCredentialURI(raw string) bool { + // url.Parse lowercases the scheme and treats a bare ? or # as empty, so we + // check the raw string. + if !strings.HasPrefix(raw, "ate-secret://") || strings.ContainsAny(raw, "?#") { + return false + } u, err := url.Parse(raw) if err != nil || u.Scheme != "ate-secret" || u.Host == "" || u.Host != u.Hostname() || u.User != nil || u.RawQuery != "" || u.Fragment != "" || len(validation.IsDNS1123Subdomain(u.Host)) != 0 { return false @@ -272,28 +328,8 @@ func validCredentialURI(raw string) bool { return false } for _, part := range parts { - if part == "" { - return false - } - } - return true -} - -func validHeaderName(value string) bool { - if value == "" { - return false - } - for _, c := range []byte(value) { - if !((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || strings.ContainsRune("!#$%&'*+-.^_`|~", rune(c))) { - return false - } - } - return true -} - -func validHeaderValue(value string) bool { - for _, c := range []byte(value) { - if c != '\t' && (c < ' ' || c == 0x7f) { + // We don't want a URI normalizer to resolve a dot segment to a different path. + if part == "" || part == "." || part == ".." { return false } } diff --git a/cmd/ateapi/internal/apivalidation/egress_policy_test.go b/cmd/ateapi/internal/apivalidation/egress_policy_test.go index 07457b4cc2..3472a5c87e 100644 --- a/cmd/ateapi/internal/apivalidation/egress_policy_test.go +++ b/cmd/ateapi/internal/apivalidation/egress_policy_test.go @@ -22,6 +22,7 @@ import ( "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/defaults" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "google.golang.org/protobuf/proto" "k8s.io/apimachinery/pkg/util/validation/field" @@ -55,6 +56,20 @@ func actorJWTHeader(audiences ...string) *ateapi.CredentialHeader { } } +// tokenExchangeHeader is an Authorization header replaced with a token +// exchanged at tokenURL. +func tokenExchangeHeader(tokenURL string, scopes ...string) *ateapi.CredentialHeader { + return &ateapi.CredentialHeader{ + Header: "Authorization", + Prefix: "Bearer ", + TokenExchange: &ateapi.TokenExchangeSource{ + TokenUrl: tokenURL, + SubjectActorJwt: &ateapi.ActorJwtSource{Audiences: []string{"https://sts.example.com"}, ExpirationSeconds: 900}, + Scopes: scopes, + }, + } +} + func TestValidateCreateActorEgressPolicyRequest(t *testing.T) { validReq := func() *ateapi.CreateActorEgressPolicyRequest { return &ateapi.CreateActorEgressPolicyRequest{ @@ -169,7 +184,7 @@ func TestValidateCreateActorEgressPolicyRequest(t *testing.T) { return r }(), want: field.ErrorList{ - field.Invalid(field.NewPath("egress_policy", "metadata", "name"), "other", `must be "default"`).WithOrigin("custom=default"), + field.Invalid(field.NewPath("egress_policy", "metadata", "name"), "other", `must be "default"`).WithOrigin("format=ate-singleton-name"), }, }, { name: "mismatched policy atespace", @@ -182,9 +197,10 @@ func TestValidateCreateActorEgressPolicyRequest(t *testing.T) { field.Invalid(field.NewPath("egress_policy", "metadata", "atespace"), "other", "must match actor.atespace"), }, }} + gates := preview.NewForTest(t) for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - assertValidateErr(t, ValidateCreateActorEgressPolicyRequest(context.Background(), tc.req), tc.want) + assertValidateErr(t, ValidateCreateActorEgressPolicyRequest(context.Background(), gates, tc.req), tc.want) }) } } @@ -267,12 +283,13 @@ func TestValidateGetActorEgressPolicyRequest(t *testing.T) { return r }(), want: field.ErrorList{ - field.Invalid(field.NewPath("name"), nil, "").WithOrigin("custom=default"), + field.Invalid(field.NewPath("name"), nil, "").WithOrigin("format=ate-singleton-name"), }, }} + gates := preview.NewForTest(t) for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - assertValidateErr(t, ValidateGetActorEgressPolicyRequest(context.Background(), tc.req), tc.want) + assertValidateErr(t, ValidateGetActorEgressPolicyRequest(context.Background(), gates, tc.req), tc.want) }) } } @@ -331,10 +348,22 @@ func TestValidateUpdateActorEgressPolicyRequest(t *testing.T) { want: field.ErrorList{ field.Required(field.NewPath("egress_policy", "rules").Index(0).Child("http", "hostnames"), ""), }, + }, { + // An update has to fix an ill-formed URI, even one the policy already stores. + name: "ill-formed credential URI", + req: func() *ateapi.UpdateActorEgressPolicyRequest { + r := validReq() + r.EgressPolicy.Rules[0].Http.Effects.ReplaceHeaders[0].CredentialUri = "ATE-SECRET://kubernetes.io/provider/ns/name" + return r + }(), + want: field.ErrorList{ + field.Invalid(field.NewPath("egress_policy", "rules").Index(0).Child("http", "effects", "replace_headers").Index(0).Child("credential_uri"), nil, ""), + }, }} + gates := preview.NewForTest(t) for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - assertValidateErr(t, ValidateUpdateActorEgressPolicyRequest(context.Background(), tc.req), tc.want) + assertValidateErr(t, ValidateUpdateActorEgressPolicyRequest(context.Background(), gates, tc.req), tc.want) }) } } @@ -417,12 +446,13 @@ func TestValidateDeleteActorEgressPolicyRequest(t *testing.T) { return r }(), want: field.ErrorList{ - field.Invalid(field.NewPath("name"), nil, "").WithOrigin("custom=default"), + field.Invalid(field.NewPath("name"), nil, "").WithOrigin("format=ate-singleton-name"), }, }} + gates := preview.NewForTest(t) for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - assertValidateErr(t, ValidateDeleteActorEgressPolicyRequest(context.Background(), tc.req), tc.want) + assertValidateErr(t, ValidateDeleteActorEgressPolicyRequest(context.Background(), gates, tc.req), tc.want) }) } } @@ -435,6 +465,7 @@ func TestValidateEgressPolicyRules(t *testing.T) { pattern := httpRule.Child("hostnames").Index(0) ports := httpRule.Child("ports") staticHeader := httpRule.Child("effects", "replace_headers").Index(0) + httpsHeader := rule.Child("https", "effects", "replace_headers").Index(0) const badPattern = `must be a DNS hostname, optionally with a complete leftmost-label wildcard, or "*"` validReq := func() *ateapi.CreateActorEgressPolicyRequest { return &ateapi.CreateActorEgressPolicyRequest{ @@ -454,6 +485,13 @@ func TestValidateEgressPolicyRules(t *testing.T) { } portNumbers := func(numbers ...int32) *ateapi.Ports { return &ateapi.Ports{Numbers: numbers} } allPorts := func() *ateapi.Ports { return &ateapi.Ports{All: &ateapi.AllPorts{}} } + // tokenExchangeRule is an https rule for api.example.com that replaces h. + tokenExchangeRule := func(h *ateapi.CredentialHeader) *ateapi.EgressRule { + return &ateapi.EgressRule{Https: &ateapi.HttpsRule{ + Hostnames: []string{"api.example.com"}, + Effects: &ateapi.HttpRuleEffects{ReplaceHeaders: []*ateapi.CredentialHeader{h}}, + }} + } tests := []struct { name string @@ -799,7 +837,7 @@ func TestValidateEgressPolicyRules(t *testing.T) { p.Rules[0].Http.Effects.ReplaceHeaders[0].Header = "bad header" }, want: field.ErrorList{ - field.Invalid(staticHeader.Child("header"), "bad header", "must be an HTTP header name"), + field.Invalid(staticHeader.Child("header"), "bad header", "must be an HTTP header name").WithOrigin("format=ate-http-header-name"), }, }, { name: "duplicate header", @@ -852,7 +890,7 @@ func TestValidateEgressPolicyRules(t *testing.T) { p.Rules[0].Http.Effects.ReplaceHeaders[0].Prefix = "Bearer\r" }, want: field.ErrorList{ - field.Invalid(staticHeader.Child("prefix"), "Bearer\r", "must be a valid HTTP field value prefix"), + field.Invalid(staticHeader.Child("prefix"), "Bearer\r", "must be a valid HTTP field value").WithOrigin("format=ate-http-header-value"), }, }, { name: "no credential source", @@ -870,6 +908,23 @@ func TestValidateEgressPolicyRules(t *testing.T) { want: field.ErrorList{ field.Invalid(staticHeader.Child("credential_uri"), "https://example.com/secret", "must be ate-secret:////"), }, + }, { + name: "credential URI with an uppercase scheme", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0].Http.Effects.ReplaceHeaders[0].CredentialUri = "ATE-SECRET://kubernetes.io/provider/ns/name" + }, + want: field.ErrorList{ + field.Invalid(staticHeader.Child("credential_uri"), nil, ""), + }, + }, { + name: "credential URI too long", + mutate: func(p *ateapi.EgressPolicy) { + const prefix = "ate-secret://kubernetes.io/provider/" + p.Rules[0].Http.Effects.ReplaceHeaders[0].CredentialUri = prefix + strings.Repeat("x", 1025-len(prefix)) + }, + want: field.ErrorList{ + field.TooLong(staticHeader.Child("credential_uri"), nil, 1024).WithOrigin("maxLength"), + }, }, { name: "actor JWT on an http rule", mutate: func(p *ateapi.EgressPolicy) { @@ -977,6 +1032,257 @@ func TestValidateEgressPolicyRules(t *testing.T) { want: field.ErrorList{ field.Invalid(staticHeader.Child("actor_jwt", "expiration_seconds"), 3601, "").WithOrigin("maximum"), }, + }, { + name: "token exchange in an http rule without an https rule for the token URL", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0].Http.Effects.ReplaceHeaders[0] = tokenExchangeHeader("https://sts.example.com/token") + }, + }, { + name: "token exchange in an https rule without a separate rule for the token URL", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token", "read", "https://www.googleapis.com/auth/cloud-platform")) + }, + }, { + name: "token exchange with an explicit port and uppercase trailing-dot host", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://STS.Example.com.:8443/token")) + }, + }, { + name: "token exchange with an empty query", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token?")) + }, + want: field.ErrorList{ + field.Invalid(httpsHeader.Child("token_exchange", "token_url"), nil, ""), + }, + }, { + name: "token exchange over http", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("http://sts.example.com/token")) + }, + want: field.ErrorList{ + field.Invalid(httpsHeader.Child("token_exchange", "token_url"), nil, ""), + }, + }, { + name: "token exchange with a long token URL", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/" + strings.Repeat("a", 2025))) + }, + want: field.ErrorList{ + field.TooLong(httpsHeader.Child("token_exchange", "token_url"), "", 2048).WithOrigin("maxLength"), + }, + }, { + name: "token exchange without a token URL", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("")) + }, + want: field.ErrorList{ + field.Required(httpsHeader.Child("token_exchange", "token_url"), ""), + }, + }, { + name: "token exchange with all optional fields and repeated additional parameter keys", + mutate: func(p *ateapi.EgressPolicy) { + h := tokenExchangeHeader("https://sts.example.com/token", "read") + h.TokenExchange.Resources = []string{"https://api.example.com/v1", "urn:example:service"} + h.TokenExchange.Audiences = []string{"https://api.example.com", "https://other.example.com"} + h.TokenExchange.RequestedTokenType = "urn:ietf:params:oauth:token-type:access_token" + h.TokenExchange.AdditionalParameters = []*ateapi.FormEntry{ + {Key: "identity_provider_id", Value: "idp-1"}, + {Key: "tag", Value: "a"}, + {Key: "tag", Value: "b"}, + } + p.Rules[0] = tokenExchangeRule(h) + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + }, { + name: "token exchange without subject_actor_jwt", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.SubjectActorJwt = nil + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Required(httpsHeader.Child("token_exchange", "subject_actor_jwt"), ""), + }, + }, { + name: "token exchange with an invalid subject_actor_jwt", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.SubjectActorJwt.ExpirationSeconds = 60 + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Invalid(httpsHeader.Child("token_exchange", "subject_actor_jwt", "expiration_seconds"), 60, "").WithOrigin("minimum"), + }, + }, { + name: "token exchange with a non-absolute resource URI", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.Resources = []string{"/relative/path"} + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Invalid(httpsHeader.Child("token_exchange", "resources").Index(0), nil, ""), + }, + }, { + name: "token exchange with a resource URI fragment", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.Resources = []string{"https://api.example.com/v1#frag"} + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Invalid(httpsHeader.Child("token_exchange", "resources").Index(0), nil, ""), + }, + }, { + name: "token exchange with a duplicate resource", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.Resources = []string{"https://api.example.com", "https://api.example.com"} + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Duplicate(httpsHeader.Child("token_exchange", "resources").Index(1), "https://api.example.com"), + }, + }, { + name: "token exchange with a long audience", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.Audiences = []string{strings.Repeat("a", 513)} + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.TooLong(httpsHeader.Child("token_exchange", "audiences").Index(0), "", 512).WithOrigin("maxLength"), + }, + }, { + name: "token exchange with a duplicate audience", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.Audiences = []string{"aud", "aud"} + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Duplicate(httpsHeader.Child("token_exchange", "audiences").Index(1), "aud"), + }, + }, { + name: "token exchange with a long requested_token_type", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.RequestedTokenType = strings.Repeat("a", 513) + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.TooLong(httpsHeader.Child("token_exchange", "requested_token_type"), "", 512).WithOrigin("maxLength"), + }, + }, { + name: "token exchange with a reserved additional parameter", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.AdditionalParameters = []*ateapi.FormEntry{ + {Key: "subject_token", Value: "forged"}, + } + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Invalid(httpsHeader.Child("token_exchange", "additional_parameters").Index(0).Child("key"), nil, ""), + }, + }, { + name: "token exchange with an empty additional parameter value", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.AdditionalParameters = []*ateapi.FormEntry{ + {Key: "options", Value: ""}, + } + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Required(httpsHeader.Child("token_exchange", "additional_parameters").Index(0).Child("value"), ""), + }, + }, { + name: "token exchange with too many additional parameters", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token")) + var params []*ateapi.FormEntry + for i := range 17 { + params = append(params, &ateapi.FormEntry{Key: fmt.Sprintf("k%d", i), Value: "v"}) + } + p.Rules[0].Https.Effects.ReplaceHeaders[0].TokenExchange.AdditionalParameters = params + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.TooMany(httpsHeader.Child("token_exchange", "additional_parameters"), 17, 16).WithOrigin("maxItems"), + }, + }, { + name: "token exchange with a scope containing a space", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token", "read write")) + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Invalid(httpsHeader.Child("token_exchange", "scopes").Index(0), nil, ""), + }, + }, { + name: "token exchange with an empty scope", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token", "")) + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.TooShort(httpsHeader.Child("token_exchange", "scopes").Index(0), "", 1).WithOrigin("minLength"), + }, + }, { + name: "token exchange with a long scope", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token", strings.Repeat("a", 257))) + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.TooLong(httpsHeader.Child("token_exchange", "scopes").Index(0), "", 256).WithOrigin("maxLength"), + }, + }, { + name: "token exchange with too many scopes", + mutate: func(p *ateapi.EgressPolicy) { + var scopes []string + for i := range 17 { + scopes = append(scopes, fmt.Sprintf("scope-%d", i)) + } + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token", scopes...)) + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.TooMany(httpsHeader.Child("token_exchange", "scopes"), 17, 16).WithOrigin("maxItems"), + }, + }, { + name: "token exchange with a repeated scope", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules[0] = tokenExchangeRule(tokenExchangeHeader("https://sts.example.com/token", "read", "read")) + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Duplicate(httpsHeader.Child("token_exchange", "scopes").Index(1), "read"), + }, + }, { + name: "more than 16 token exchanges across rules", + mutate: func(p *ateapi.EgressPolicy) { + p.Rules = nil + for i := range 17 { + p.Rules = append(p.Rules, &ateapi.EgressRule{Https: &ateapi.HttpsRule{ + Hostnames: []string{fmt.Sprintf("api-%d.example.com", i)}, + Effects: &ateapi.HttpRuleEffects{ReplaceHeaders: []*ateapi.CredentialHeader{tokenExchangeHeader("https://sts.example.com/token")}}, + }}) + } + }, + }, { + name: "credential URI and token exchange in one header", + mutate: func(p *ateapi.EgressPolicy) { + h := tokenExchangeHeader("https://sts.example.com/token") + h.CredentialUri = "ate-secret://kubernetes.io/provider/ns/name" + p.Rules[0] = tokenExchangeRule(h) + p.Rules = append(p.Rules, httpsRule(nil, "sts.example.com")) + }, + want: field.ErrorList{ + field.Invalid(httpsHeader, nil, "one of").WithOrigin("union"), + }, }, { name: "empty effects", mutate: func(p *ateapi.EgressPolicy) { @@ -994,6 +1300,7 @@ func TestValidateEgressPolicyRules(t *testing.T) { field.Required(rule.Child("https", "effects"), "at least one effect must be specified"), }, }} + gates := preview.NewForTest(t) for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { req := validReq() @@ -1001,7 +1308,7 @@ func TestValidateEgressPolicyRules(t *testing.T) { tc.mutate(req.EgressPolicy) } defaults.Apply(req.EgressPolicy) - assertValidateErr(t, ValidateCreateActorEgressPolicyRequest(context.Background(), req), tc.want) + assertValidateErr(t, ValidateCreateActorEgressPolicyRequest(context.Background(), gates, req), tc.want) }) } } @@ -1017,41 +1324,59 @@ func TestCredentialURIValidation(t *testing.T) { } for _, uri := range []string{ "https://kubernetes.io/provider/ns/name", + "ATE-SECRET://kubernetes.io/provider/secret", + "Ate-Secret://kubernetes.io/provider/secret", "ate-secret://kubernetes.io/provider", "ate-secret://kubernetes.io//provider/secret", "ate-secret://kubernetes.io/provider/secret/", "ate-secret://kubernetes.io:443/provider/secret", "ate-secret://kubernetes.io/provider/sec%2Fret", // percent-encoded separator "ate-secret://kubernetes.io/provider/sec%2Dret", // percent-encoding of any kind + "ate-secret://kubernetes.io/provider/secret?", // empty query + "ate-secret://kubernetes.io/provider/secret#", // empty fragment + "ate-secret://kubernetes.io/provider/../secret", // dot segments + "ate-secret://kubernetes.io/./provider/secret", + "ate-secret://kubernetes.io/provider/..", } { if validCredentialURI(uri) { t.Errorf("validCredentialURI(%q) = true", uri) } } } - -func TestHeaderValueValidation(t *testing.T) { - for _, value := range []string{"Bearer token", "value\tvalue", "\u0080\u0081"} { - if !validHeaderValue(value) { - t.Errorf("validHeaderValue(%q) = false", value) +func TestScopeTokenValidation(t *testing.T) { + for _, scope := range []string{"read", "https://www.googleapis.com/auth/cloud-platform", "!#[]~"} { + if !validScopeToken(scope) { + t.Errorf("validScopeToken(%q) = false", scope) } } - for _, value := range []string{"a\rb", "a\nb", "a\x00b", "a\x1fb", "a\x7fb"} { - if validHeaderValue(value) { - t.Errorf("validHeaderValue(%q) = true", value) + for _, scope := range []string{"a b", `a"b`, `a\b`, "a\tb", "a\x7fb", "é"} { + if validScopeToken(scope) { + t.Errorf("validScopeToken(%q) = true", scope) } } } -func TestHeaderNameValidation(t *testing.T) { - for _, value := range []string{"Authorization", "x-custom_header", "!#$%&'*+-.^_`|~"} { - if !validHeaderName(value) { - t.Errorf("validHeaderName(%q) = false", value) +func TestResourceURIValidation(t *testing.T) { + for _, uri := range []string{ + "https://api.example.com", + "https://api.example.com/v1?x=1", + "urn:example:service", + } { + if !validResourceURI(uri) { + t.Errorf("validResourceURI(%q) = false", uri) } } - for _, value := range []string{"", "bad header", "bad:header", "héader"} { - if validHeaderName(value) { - t.Errorf("validHeaderName(%q) = true", value) + for _, uri := range []string{ + "", + "/relative/path", + "api.example.com", + "https:", + "https://api.example.com/v1#frag", + "https://api.example.com/v1#", + "https://api.example.com/a b", + } { + if validResourceURI(uri) { + t.Errorf("validResourceURI(%q) = true", uri) } } } diff --git a/cmd/ateapi/internal/apivalidation/external_volume.go b/cmd/ateapi/internal/apivalidation/external_volume.go new file mode 100644 index 0000000000..f43709f63e --- /dev/null +++ b/cmd/ateapi/internal/apivalidation/external_volume.go @@ -0,0 +1,81 @@ +// Copyright 2026 The Agent Substrate 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 apivalidation + +import ( + "context" + "maps" + "slices" + "strings" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" + "k8s.io/apimachinery/pkg/api/operation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +// csiVolumeContextMaxBytes is the CSI spec's size limit for a map field, +// counting keys and values. +const csiVolumeContextMaxBytes = 4096 + +func ValidateGetExternalVolumeRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetExternalVolumeRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) + return Validate_GetExternalVolumeRequest(ctx, op, nil, req, nil) +} + +func ValidateListExternalVolumesRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ListExternalVolumesRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) + return Validate_ListExternalVolumesRequest(ctx, op, nil, req, nil) +} + +// ValidateCSIVolumeID is the custom validation of CsiVolumeStatus.volume_id. +// It is stricter than ActorExternalVolumeStatus.storage_volume_id: tabs, line +// breaks and surrounding whitespace are rejected too. +// +// TODO: rename to ValidateCustom_CsiVolumeStatus_VolumeId once a request +// carries a CsiVolumeStatus. validation-gen generates no code for the type +// until then. +func ValidateCSIVolumeID(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { + if strings.ContainsAny(*value, "\t\n\r") { + return field.ErrorList{field.Invalid(fldPath, *value, "must not contain tabs or line breaks")} + } + if strings.TrimSpace(*value) != *value { + return field.ErrorList{field.Invalid(fldPath, *value, "must not start or end with whitespace")} + } + return nil +} + +// ValidateCSIVolumeContext is the custom validation of +// CsiVolumeStatus.volume_context. Node plugins pass its entries to mount(2) +// as C strings, so a NUL byte would truncate an option. The total size is +// capped at the CSI spec's limit for map fields. +// +// TODO: rename to ValidateCustom_CsiVolumeStatus_VolumeContext, as above. +func ValidateCSIVolumeContext(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[string]string) field.ErrorList { + size := 0 + for _, k := range slices.Sorted(maps.Keys(value)) { + size += len(k) + len(value[k]) + if strings.ContainsRune(k, 0) { + return field.ErrorList{field.Invalid(fldPath, k, "keys must not contain NUL bytes")} + } + if strings.ContainsRune(value[k], 0) { + return field.ErrorList{field.Invalid(fldPath.Key(k), value[k], "must not contain NUL bytes")} + } + } + if size > csiVolumeContextMaxBytes { + return field.ErrorList{field.TooLong(fldPath, nil, csiVolumeContextMaxBytes)} + } + return nil +} diff --git a/cmd/ateapi/internal/apivalidation/external_volume_test.go b/cmd/ateapi/internal/apivalidation/external_volume_test.go new file mode 100644 index 0000000000..8ad2c0d2d3 --- /dev/null +++ b/cmd/ateapi/internal/apivalidation/external_volume_test.go @@ -0,0 +1,170 @@ +// Copyright 2026 The Agent Substrate 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 apivalidation + +import ( + "context" + "strings" + "testing" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" + "k8s.io/apimachinery/pkg/api/operation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +func TestValidateCSIVolumeID(t *testing.T) { + path := field.NewPath("volume_id") + invalid := field.ErrorList{field.Invalid(path, nil, "")} + + tests := []struct { + name string + id string + want field.ErrorList + }{{ + name: "valid", + id: "nfs-server#exports#ctx", + }, { + name: "an interior space", + id: "vol 1", + }, { + name: "a leading space", + id: " vol-1", + want: invalid, + }, { + name: "a trailing space", + id: "vol-1 ", + want: invalid, + }, { + name: "a tab", + id: "vol\t1", + want: invalid, + }, { + name: "a line break", + id: "vol-1\n", + want: invalid, + }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateCSIVolumeID(context.Background(), operation.Operation{}, path, &tt.id, nil), tt.want) + }) + } +} + +func TestValidateCSIVolumeContext(t *testing.T) { + path := field.NewPath("volume_context") + + tests := []struct { + name string + ctx map[string]string + want field.ErrorList + }{{ + name: "valid", + ctx: map[string]string{"server": "nfs-server", "share": "/exports/ctx"}, + }, { + name: "unset", + }, { + name: "a key with a NUL byte", + ctx: map[string]string{"k\x00ey": "v"}, + want: field.ErrorList{field.Invalid(path, nil, "")}, + }, { + name: "a value with a NUL byte", + ctx: map[string]string{"k": "v\x00alue"}, + want: field.ErrorList{field.Invalid(path.Key("k"), nil, "")}, + }, { + // A one-byte key and a 4095-byte value fill the 4096-byte total. + name: "at the size bound", + ctx: map[string]string{"k": strings.Repeat("v", 4095)}, + }, { + // Each entry is small; only the total is over. + name: "over the size bound", + ctx: map[string]string{"a": strings.Repeat("v", 2048), "b": strings.Repeat("v", 2048)}, + want: field.ErrorList{field.TooLong(path, nil, 4096)}, + }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateCSIVolumeContext(context.Background(), operation.Operation{}, path, tt.ctx, nil), tt.want) + }) + } +} + +func TestValidateGetExternalVolumeRequest(t *testing.T) { + volumePath := field.NewPath("external_volume") + + tests := []struct { + name string + ref *ateapi.ObjectRef + want field.ErrorList + }{{ + name: "valid", + ref: &ateapi.ObjectRef{Atespace: "as", Name: "nm"}, + }, { + name: "missing external_volume", + want: field.ErrorList{field.Required(volumePath, "")}, + }, { + name: "missing external_volume.atespace", + ref: &ateapi.ObjectRef{Name: "nm"}, + want: field.ErrorList{field.Required(volumePath.Child("atespace"), "")}, + }, { + name: "invalid external_volume.atespace", + ref: &ateapi.ObjectRef{Atespace: "AS", Name: "nm"}, + want: field.ErrorList{field.Invalid(volumePath.Child("atespace"), nil, "").WithOrigin("format=k8s-short-name")}, + }, { + name: "missing external_volume.name", + ref: &ateapi.ObjectRef{Atespace: "as"}, + want: field.ErrorList{field.Required(volumePath.Child("name"), "")}, + }, { + name: "invalid external_volume.name", + ref: &ateapi.ObjectRef{Atespace: "as", Name: "NM"}, + want: field.ErrorList{field.Invalid(volumePath.Child("name"), nil, "").WithOrigin("format=k8s-short-name")}, + }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + req := &ateapi.GetExternalVolumeRequest{ExternalVolume: tt.ref} + assertValidateErr(t, ValidateGetExternalVolumeRequest(context.Background(), preview.NewForTest(t), req), tt.want) + }) + } +} + +func TestValidateListExternalVolumesRequest(t *testing.T) { + tests := []struct { + name string + req *ateapi.ListExternalVolumesRequest + want field.ErrorList + }{{ + name: "valid across atespaces", + req: &ateapi.ListExternalVolumesRequest{}, + }, { + name: "valid in one atespace", + req: &ateapi.ListExternalVolumesRequest{Atespace: "as", Options: &ateapi.ListOptions{PageSize: 10, PageToken: "tok"}}, + }, { + name: "invalid atespace", + req: &ateapi.ListExternalVolumesRequest{Atespace: "AS"}, + want: field.ErrorList{field.Invalid(field.NewPath("atespace"), nil, "").WithOrigin("format=k8s-short-name")}, + }, { + name: "negative page size", + req: &ateapi.ListExternalVolumesRequest{Options: &ateapi.ListOptions{PageSize: -1}}, + want: field.ErrorList{field.Invalid(field.NewPath("options", "page_size"), nil, "").WithOrigin("minimum")}, + }, { + name: "page token too long", + req: &ateapi.ListExternalVolumesRequest{Options: &ateapi.ListOptions{PageToken: strings.Repeat("t", 257)}}, + want: field.ErrorList{field.TooLongCharacters(field.NewPath("options", "page_token"), "", 256).WithOrigin("maxLength")}, + }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + assertValidateErr(t, ValidateListExternalVolumesRequest(context.Background(), preview.NewForTest(t), tt.req), tt.want) + }) + } +} diff --git a/cmd/ateapi/internal/apivalidation/tag.go b/cmd/ateapi/internal/apivalidation/tag.go index d22e092cb2..96e1268cae 100644 --- a/cmd/ateapi/internal/apivalidation/tag.go +++ b/cmd/ateapi/internal/apivalidation/tag.go @@ -18,42 +18,43 @@ import ( "context" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" + "google.golang.org/protobuf/proto" "k8s.io/apimachinery/pkg/api/operation" - "k8s.io/apimachinery/pkg/api/validate" "k8s.io/apimachinery/pkg/util/validation/field" ) -func ValidateCreateTagRequest(ctx context.Context, req *ateapi.CreateTagRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateCreateTagRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateTagRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_CreateTagRequest(ctx, op, nil, req, nil) } -func ValidateGetTagRequest(ctx context.Context, req *ateapi.GetTagRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateGetTagRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetTagRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_GetTagRequest(ctx, op, nil, req, nil) } -func ValidateListTagsRequest(ctx context.Context, req *ateapi.ListTagsRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateListTagsRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ListTagsRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_ListTagsRequest(ctx, op, nil, req, nil) } -func ValidateUpdateTagRequest(ctx context.Context, req *ateapi.UpdateTagRequest) field.ErrorList { +func ValidateUpdateTagRequest(ctx context.Context, gates *preview.Gates, req *ateapi.UpdateTagRequest) field.ErrorList { // We model this as a create rather than an update because updates assume // the existence of a "current" value, which we do not have yet. This is // validating the request itself. The result will be validated later, after // we have a current value to compare against. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_UpdateTagRequest(ctx, op, nil, req, nil) } -func ValidateDeleteTagRequest(ctx context.Context, req *ateapi.DeleteTagRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateDeleteTagRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DeleteTagRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_DeleteTagRequest(ctx, op, nil, req, nil) } -func ValidateTagUpdate(ctx context.Context, fldPath *field.Path, newVal, oldVal *ateapi.Tag) field.ErrorList { - op := MakeUpdateOp(ctx) +func ValidateTagUpdate(ctx context.Context, gates *preview.Gates, fldPath *field.Path, newVal, oldVal *ateapi.Tag) field.ErrorList { + op := MakeUpdateOp(ctx, gates) return Validate_Tag(ctx, op, fldPath, newVal, oldVal) } @@ -72,7 +73,7 @@ func ValidateCustom_CreateTagRequest(_ context.Context, _ operation.Operation, p return nil } -// This exists only because nested subfield tags are not supported yet. +// This exists to do partial validation of the target resource in an update. func ValidateCustom_UpdateTagRequest_Tag(ctx context.Context, op operation.Operation, fldPath *field.Path, tag, _ *ateapi.Tag) field.ErrorList { if tag == nil || tag.Metadata == nil { return nil // handled by DV @@ -80,10 +81,25 @@ func ValidateCustom_UpdateTagRequest_Tag(ctx context.Context, op operation.Opera // Updates are validated in 2 steps: first the update request and then the // resource itself. DV for the request doesn't descend into the resource - // metadata. Once DV supports nested subfield tags, this can be changed to - // something like: - // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:required - errs := Validate_ResourceMetadata(ctx, op, fldPath.Child("metadata"), tag.Metadata, nil) - errs = append(errs, validate.RequiredValue(ctx, op, fldPath.Child("metadata", "atespace"), &tag.Metadata.Atespace, nil)...) - return errs + // metadata. What we need is something like: + // +k8s:subfield(metadata)=+k8s:validateType + return Validate_ResourceMetadata(ctx, op, fldPath.Child("metadata"), tag.Metadata, nil) +} + +// ValidateCustom_TagStatus_Snapshot allows an update to record status.snapshot +// once, and then only to move its durable_snapshot from PENDING to COMPLETED. A +// tag never moves between snapshots. +func ValidateCustom_TagStatus_Snapshot(_ context.Context, op operation.Operation, fldPath *field.Path, value, oldValue *ateapi.Snapshot) field.ErrorList { + if op.Type != operation.Update || oldValue == nil || proto.Equal(value, oldValue) { + return nil + } + if oldValue.GetDurableSnapshot().GetState() == ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING && + value.GetDurableSnapshot().GetState() == ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED { + completed := proto.CloneOf(oldValue) + completed.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED + if proto.Equal(completed, value) { + return nil + } + } + return field.ErrorList{field.Forbidden(fldPath, "may only change durable_snapshot.state from PENDING to COMPLETED")} } diff --git a/cmd/ateapi/internal/apivalidation/tag_test.go b/cmd/ateapi/internal/apivalidation/tag_test.go index 2f77483900..83d67c303b 100644 --- a/cmd/ateapi/internal/apivalidation/tag_test.go +++ b/cmd/ateapi/internal/apivalidation/tag_test.go @@ -20,6 +20,7 @@ import ( "testing" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -184,9 +185,10 @@ func TestValidateCreateTagRequest(t *testing.T) { wantError: field.ErrorList{field.Invalid(field.NewPath("tag", "scope"), nil, "").WithOrigin("minimum")}, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateCreateTagRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateCreateTagRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -301,9 +303,10 @@ func TestValidateUpdateTagRequest(t *testing.T) { wantError: nil, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateUpdateTagRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateUpdateTagRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -325,8 +328,28 @@ func TestValidateTagUpdateResult(t *testing.T) { } return tag } + withSnapshot := func(state ateapi.SnapshotStorageState) func(*ateapi.Tag) { + return func(tag *ateapi.Tag) { + tag.Status = &ateapi.TagStatus{ + ActorTemplateUid: "01234567-89ab-cdef-0123-456789abcdef", + Snapshot: &ateapi.Snapshot{ + Uuid: "8c1f5a2e-3b7d-4e9a-a6c0-2d4f8b1e7a35", + Generation: 1, + Owner: ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, + Fidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + DurableSnapshot: &ateapi.SnapshotStorage{ + State: state, + Object: &ateapi.ObjectSnapshot{SnapshotUri: "gs://bucket/atespaces/ns1/tags/tag1"}, + }, + }, + } + } + } + pending := withSnapshot(ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING) + completed := withSnapshot(ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED) tests := []struct { name string + oldVal *ateapi.Tag // nil means storedTag() newVal *ateapi.Tag wantError field.ErrorList }{ @@ -403,10 +426,81 @@ func TestValidateTagUpdateResult(t *testing.T) { newVal: storedTag(func(tag *ateapi.Tag) { tag.Metadata = nil }), wantError: field.ErrorList{field.Required(tagPath.Child("metadata"), "")}, }, + { + name: "tag.status.snapshot recorded", + oldVal: storedTag(func(tag *ateapi.Tag) { + tag.Status = &ateapi.TagStatus{ActorTemplateUid: "01234567-89ab-cdef-0123-456789abcdef"} + }), + newVal: storedTag(pending), + }, + { + name: "tag.status.snapshot completed", + oldVal: storedTag(pending), + newVal: storedTag(completed), + }, + { + name: "tag.status.snapshot moved back to pending", + oldVal: storedTag(completed), + newVal: storedTag(pending), + wantError: field.ErrorList{ + field.Forbidden(tagPath.Child("status", "snapshot"), ""), + }, + }, + { + name: "tag.status.snapshot repointed while completing", + oldVal: storedTag(pending), + newVal: storedTag(completed, func(tag *ateapi.Tag) { + tag.Status.Snapshot.DurableSnapshot.Object.SnapshotUri = "gs://bucket/elsewhere" + }), + wantError: field.ErrorList{ + field.Forbidden(tagPath.Child("status", "snapshot"), ""), + }, + }, + { + name: "tag.status.snapshot repointed", + oldVal: storedTag(completed), + newVal: storedTag(completed, func(tag *ateapi.Tag) { + tag.Status.Snapshot.DurableSnapshot.Object.SnapshotUri = "gs://bucket/elsewhere" + }), + wantError: field.ErrorList{ + field.Forbidden(tagPath.Child("status", "snapshot"), ""), + }, + }, + { + name: "tag.status.snapshot cleared", + oldVal: storedTag(completed), + newVal: storedTag(completed, func(tag *ateapi.Tag) { tag.Status.Snapshot = nil }), + wantError: field.ErrorList{ + field.Invalid(tagPath.Child("status", "snapshot"), nil, "").WithOrigin("update"), + }, + }, + { + name: "tag.status cleared", + oldVal: storedTag(completed), + newVal: storedTag(), + wantError: field.ErrorList{ + field.Invalid(tagPath.Child("status"), nil, "").WithOrigin("update"), + }, + }, + { + name: "tag.status.actor_template_uid changed", + oldVal: storedTag(completed), + newVal: storedTag(completed, func(tag *ateapi.Tag) { + tag.Status.ActorTemplateUid = "fedcba98-7654-3210-fedc-ba9876543210" + }), + wantError: field.ErrorList{ + field.Invalid(tagPath.Child("status", "actor_template_uid"), nil, "").WithOrigin("immutable"), + }, + }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateTagUpdate(ctx, tagPath, tt.newVal, storedTag()), tt.wantError) + oldVal := tt.oldVal + if oldVal == nil { + oldVal = storedTag() + } + assertValidateErr(t, ValidateTagUpdate(ctx, gates, tagPath, tt.newVal, oldVal), tt.wantError) }) } } @@ -456,9 +550,10 @@ func TestValidateListTagsRequest(t *testing.T) { wantError: field.ErrorList{field.TooLongCharacters(field.NewPath("options", "page_token"), "", 256).WithOrigin("maxLength")}, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateListTagsRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateListTagsRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -501,9 +596,10 @@ func TestValidateGetTagRequest(t *testing.T) { wantError: field.ErrorList{field.Invalid(field.NewPath("tag", "name"), nil, "").WithOrigin("format=k8s-short-name")}, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateGetTagRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateGetTagRequest(ctx, gates, tt.req), tt.wantError) }) } } @@ -546,9 +642,10 @@ func TestValidateDeleteTagRequest(t *testing.T) { wantError: field.ErrorList{field.Invalid(field.NewPath("tag", "name"), nil, "").WithOrigin("format=k8s-short-name")}, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateDeleteTagRequest(ctx, tt.req), tt.wantError) + assertValidateErr(t, ValidateDeleteTagRequest(ctx, gates, tt.req), tt.wantError) }) } } diff --git a/cmd/ateapi/internal/apivalidation/validation_test.go b/cmd/ateapi/internal/apivalidation/validation_test.go index 6534715a8c..e1125fff18 100644 --- a/cmd/ateapi/internal/apivalidation/validation_test.go +++ b/cmd/ateapi/internal/apivalidation/validation_test.go @@ -22,6 +22,7 @@ import ( "testing" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" "k8s.io/apimachinery/pkg/api/operation" @@ -114,11 +115,13 @@ func TestValidateResourceMetadataCreate(t *testing.T) { obj: valid(func(rm *ateapi.ResourceMetadata) { rm.CreateTime = nil }), want: nil, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() - matcher.Test(t, tt.want, Validate_ResourceMetadata(context.Background(), op, nil, tt.obj, nil)) + matcher.Test(t, tt.want, Validate_ResourceMetadata(ctx, op, nil, tt.obj, nil)) }) } } @@ -230,11 +233,13 @@ func TestValidateResourceMetadataUpdate(t *testing.T) { newObj: valid(func(rm *ateapi.ResourceMetadata) { rm.UpdateTime.Seconds = 866 }), want: field.ErrorList{field.Invalid(field.NewPath("update_time"), nil, "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeUpdateOp(context.Background()) + ctx := context.Background() + op := MakeUpdateOp(ctx, gates) matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() - matcher.Test(t, tt.want, Validate_ResourceMetadata(context.Background(), op, nil, tt.newObj, tt.oldObj)) + matcher.Test(t, tt.want, Validate_ResourceMetadata(ctx, op, nil, tt.newObj, tt.oldObj)) }) } } @@ -428,12 +433,14 @@ func TestValidateResourceMetadataNameAndAtespaceFormat(t *testing.T) { valid(func(rm *ateapi.ResourceMetadata) { rm.Name = strings.Repeat("x", 64) }), field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("format=k8s-short-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { obj := proto.CloneOf(tt.obj) // avoid internal mutations - op := MakeCreateOp(context.Background()) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() - matcher.Test(t, tt.want, Validate_ResourceMetadata(context.Background(), op, nil, obj, nil)) + matcher.Test(t, tt.want, Validate_ResourceMetadata(ctx, op, nil, obj, nil)) }) } } @@ -643,11 +650,13 @@ func TestValidateObjectRef(t *testing.T) { valid(func(r *ateapi.ObjectRef) { r.Name = strings.Repeat("x", 64) }), field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("format=k8s-short-name")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() - matcher.Test(t, tt.want, Validate_ObjectRef(context.Background(), op, nil, tt.ref, nil)) + matcher.Test(t, tt.want, Validate_ObjectRef(ctx, op, nil, tt.ref, nil)) }) } } @@ -798,11 +807,13 @@ func TestValidateSystemInfoVolumeSource(t *testing.T) { }), want: field.ErrorList{field.Forbidden(dsPath.Index(2).Child("actor_metadata"), "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() - matcher.Test(t, tt.want, Validate_SystemInfoVolumeSource(context.Background(), op, nil, tt.obj, nil)) + matcher.Test(t, tt.want, Validate_SystemInfoVolumeSource(ctx, op, nil, tt.obj, nil)) }) } } @@ -862,17 +873,19 @@ func TestValidateTrustBundleDataSource(t *testing.T) { obj: valid(func(tb *ateapi.TrustBundleDataSource) { tb.Path = "../escape" }), want: field.ErrorList{field.Invalid(field.NewPath("path"), nil, "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() - matcher.Test(t, tt.want, Validate_TrustBundleDataSource(context.Background(), op, nil, tt.obj, nil)) + matcher.Test(t, tt.want, Validate_TrustBundleDataSource(ctx, op, nil, tt.obj, nil)) }) } } -func validExternalVolume(mutate ...func(*ateapi.ExternalVolumeStatus)) *ateapi.ExternalVolumeStatus { - v := &ateapi.ExternalVolumeStatus{ +func validExternalVolume(mutate ...func(*ateapi.ActorExternalVolumeStatus)) *ateapi.ActorExternalVolumeStatus { + v := &ateapi.ActorExternalVolumeStatus{ Name: "my-vol", StorageVolumeId: "valid-storage-id", VolumeType: "mock", @@ -888,57 +901,66 @@ func TestValidateExternalVolume(t *testing.T) { tests := []struct { name string - obj *ateapi.ExternalVolumeStatus + obj *ateapi.ActorExternalVolumeStatus want field.ErrorList }{{ name: "valid external volume", obj: valid(), }, { name: "missing volume name", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.Name = "" }), + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.Name = "" }), want: field.ErrorList{field.Required(field.NewPath("name"), "")}, }, { name: "invalid volume name", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.Name = "NOT A VOLUME" }), + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.Name = "NOT A VOLUME" }), want: field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("format=k8s-short-name")}, }, { name: "valid external volume with empty storage volume id", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = "" }), + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = "" }), }, { name: "invalid storage volume id with null U+0000", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = "vol\x00id" }), - want: field.ErrorList{field.Invalid(field.NewPath("storage_volume_id"), nil, "")}, + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = "vol\x00id" }), + want: field.ErrorList{field.Invalid(field.NewPath("storage_volume_id"), nil, "").WithOrigin("format=ate-volume-storage-id")}, }, { name: "storage volume id too long", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = strings.Repeat("x", 257) }), + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = strings.Repeat("x", 257) }), want: field.ErrorList{field.TooLong(field.NewPath("storage_volume_id"), nil, 256).WithOrigin("maxLength")}, }, { name: "missing volume type", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeType = "" }), + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = "" }), want: field.ErrorList{field.Required(field.NewPath("volume_type"), "")}, }, { name: "invalid volume type with uppercase", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeType = "MockPlugin" }), - want: field.ErrorList{field.Invalid(field.NewPath("volume_type"), nil, "")}, + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = "MockPlugin" }), + want: field.ErrorList{field.Invalid(field.NewPath("volume_type"), nil, "").WithOrigin("format=k8s-long-name")}, }, { - name: "valid volume type with 253 characters", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeType = strings.Repeat("a", 253) }), + name: "valid volume type with 63 characters", + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = strings.Repeat("a", 63) }), + }, { + name: "invalid volume type with 64 characters", + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = strings.Repeat("a", 64) }), + want: field.ErrorList{field.TooLong(field.NewPath("volume_type"), nil, 63).WithOrigin("maxLength")}, }, { name: "invalid volume type exceeding 253 characters", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeType = strings.Repeat("a", 254) }), + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = strings.Repeat("a", 254) }), want: field.ErrorList{ - field.Invalid(field.NewPath("volume_type"), nil, ""), - field.TooLong(field.NewPath("volume_type"), nil, 253).WithOrigin("maxLength"), + field.Invalid(field.NewPath("volume_type"), nil, "").WithOrigin("format=k8s-long-name"), + field.TooLong(field.NewPath("volume_type"), nil, 63).WithOrigin("maxLength"), }, }, { - name: "valid volume with substrate.io prefixed volume type", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeType = "substrate.io/mock" }), + name: "invalid volume type with ate.dev prefix", + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = "ate.dev/mock" }), + want: field.ErrorList{field.Invalid(field.NewPath("volume_type"), nil, "").WithOrigin("format=k8s-long-name")}, + }, { + name: "invalid volume type with substrate.io prefix", + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = "substrate.io/mock" }), + want: field.ErrorList{field.Invalid(field.NewPath("volume_type"), nil, "").WithOrigin("format=k8s-long-name")}, }, { name: "storage volume id at the bound", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = strings.Repeat("x", 256) }), + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = strings.Repeat("x", 256) }), }, { name: "volume_context with many entries, as a CSI driver may return", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { ctxMap := make(map[string]string, 100) for i := range 100 { ctxMap[fmt.Sprintf("key-%03d", i)] = "v" @@ -947,20 +969,22 @@ func TestValidateExternalVolume(t *testing.T) { }), }, { name: "volume_context with one long value, as a CSI driver may return", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeContext = map[string]string{"attachment": strings.Repeat("v", 4000)} }), }, { name: "volume_context over the size bound", - obj: valid(func(v *ateapi.ExternalVolumeStatus) { + obj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeContext = map[string]string{"attachment": strings.Repeat("v", 40*1024)} }), want: field.ErrorList{field.TooLong(field.NewPath("volume_context"), nil, 40*1024)}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) - assertValidateErr(t, Validate_ExternalVolumeStatus(context.Background(), op, nil, tt.obj, nil), tt.want) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) + assertValidateErr(t, Validate_ActorExternalVolumeStatus(ctx, op, nil, tt.obj, nil), tt.want) }) } } @@ -970,8 +994,8 @@ func TestValidateExternalVolume_Update(t *testing.T) { tests := []struct { name string - oldObj *ateapi.ExternalVolumeStatus - newObj *ateapi.ExternalVolumeStatus + oldObj *ateapi.ActorExternalVolumeStatus + newObj *ateapi.ActorExternalVolumeStatus want field.ErrorList }{{ name: "unchanged volume is valid", @@ -979,80 +1003,102 @@ func TestValidateExternalVolume_Update(t *testing.T) { newObj: valid(), }, { name: "name changed is invalid", - oldObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.Name = "vol1" }), - newObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.Name = "vol2" }), + oldObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.Name = "vol1" }), + newObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.Name = "vol2" }), want: field.ErrorList{field.Invalid(field.NewPath("name"), nil, "").WithOrigin("update")}, }, { name: "storage_volume_id transition from empty to non-empty is valid", - oldObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = "" }), - newObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = "vol-id-1" }), + oldObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = "" }), + newObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = "vol-id-1" }), }, { name: "storage_volume_id changed once set is invalid", - oldObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = "vol-id-1" }), - newObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = "vol-id-2" }), + oldObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = "vol-id-1" }), + newObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = "vol-id-2" }), want: field.ErrorList{field.Invalid(field.NewPath("storage_volume_id"), nil, "").WithOrigin("update")}, }, { name: "storage_volume_id unset once set is invalid", - oldObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = "vol-id-1" }), - newObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.StorageVolumeId = "" }), + oldObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = "vol-id-1" }), + newObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.StorageVolumeId = "" }), want: field.ErrorList{field.Invalid(field.NewPath("storage_volume_id"), nil, "").WithOrigin("update")}, }, { name: "volume_type changed is invalid", - oldObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeType = "mock" }), - newObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeType = "pd.csi.storage.gke.io" }), + oldObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = "mock" }), + newObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = "pd.csi.storage.gke.io" }), want: field.ErrorList{field.Invalid(field.NewPath("volume_type"), nil, "").WithOrigin("update")}, + }, { + name: "unchanged volume_type with substrate.io prefix is valid", + oldObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = "substrate.io/mock" }), + newObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = "substrate.io/mock" }), + }, { + name: "unchanged volume_type over 63 characters is valid", + oldObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = strings.Repeat("a", 64) }), + newObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeType = strings.Repeat("a", 64) }), }, { name: "volume_context changed is valid", - oldObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeContext = nil }), - newObj: valid(func(v *ateapi.ExternalVolumeStatus) { v.VolumeContext = map[string]string{"foo": "bar"} }), + oldObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeContext = nil }), + newObj: valid(func(v *ateapi.ActorExternalVolumeStatus) { v.VolumeContext = map[string]string{"foo": "bar"} }), }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeUpdateOp(context.Background()) - assertValidateErr(t, Validate_ExternalVolumeStatus(context.Background(), op, nil, tt.newObj, tt.oldObj), tt.want) + ctx := context.Background() + op := MakeUpdateOp(ctx, gates) + assertValidateErr(t, Validate_ActorExternalVolumeStatus(ctx, op, nil, tt.newObj, tt.oldObj), tt.want) }) } } -func TestValidateDeleteOptions(t *testing.T) { - valid := func(mutate ...func(*ateapi.DeleteOptions)) *ateapi.DeleteOptions { - tb := &ateapi.DeleteOptions{} - for _, m := range mutate { - m(tb) - } - return tb +// TestValidateGuards covers the options messages that carry optional version +// and uid guards. +func TestValidateGuards(t *testing.T) { + gates := preview.NewForTest(t) + validators := map[string]func(version int64, uid string) field.ErrorList{ + "DeleteOptions": func(version int64, uid string) field.ErrorList { + ctx := context.Background() + return Validate_DeleteOptions(ctx, MakeCreateOp(ctx, gates), nil, &ateapi.DeleteOptions{Version: version, Uid: uid}, nil) + }, + "SuspendOptions": func(version int64, uid string) field.ErrorList { + ctx := context.Background() + return Validate_SuspendOptions(ctx, MakeCreateOp(ctx, gates), nil, &ateapi.SuspendOptions{Version: version, Uid: uid}, nil) + }, + "ResumeActorRequest_Options": func(version int64, uid string) field.ErrorList { + ctx := context.Background() + return Validate_ResumeActorRequest_Options(ctx, MakeCreateOp(ctx, gates), nil, &ateapi.ResumeActorRequest_Options{Version: version, Uid: uid}, nil) + }, + "RevertActorRequest_Options": func(version int64, uid string) field.ErrorList { + ctx := context.Background() + return Validate_RevertActorRequest_Options(ctx, MakeCreateOp(ctx, gates), nil, &ateapi.RevertActorRequest_Options{Version: version, Uid: uid}, nil) + }, } - tests := []struct { - name string - obj *ateapi.DeleteOptions - want field.ErrorList + name string + version int64 + uid string + want field.ErrorList }{{ - name: "valid", - obj: valid(), // all optional fields + name: "valid", // all optional fields }, { - name: "valid version", - obj: valid(func(do *ateapi.DeleteOptions) { do.Version = 1 }), - want: nil, + name: "valid version", + version: 1, }, { - name: "invalid version", - obj: valid(func(do *ateapi.DeleteOptions) { do.Version = -1 }), - want: field.ErrorList{field.Invalid(field.NewPath("version"), nil, "").WithOrigin("minimum")}, + name: "invalid version", + version: -1, + want: field.ErrorList{field.Invalid(field.NewPath("version"), nil, "").WithOrigin("minimum")}, }, { name: "valid uid", - obj: valid(func(do *ateapi.DeleteOptions) { do.Uid = "11111111-2222-3333-4444-555555555555" }), - want: nil, + uid: "11111111-2222-3333-4444-555555555555", }, { name: "invalid uid", - obj: valid(func(do *ateapi.DeleteOptions) { do.Uid = "not a uid" }), + uid: "not a uid", want: field.ErrorList{field.Invalid(field.NewPath("uid"), nil, "").WithOrigin("format=k8s-uuid")}, }} - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) - matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() - matcher.Test(t, tt.want, Validate_DeleteOptions(context.Background(), op, nil, tt.obj, nil)) - }) + for msg, validate := range validators { + for _, tt := range tests { + t.Run(msg+"/"+tt.name, func(t *testing.T) { + matcher := field.ErrorMatcher{}.ByType().ByField().ByOrigin() + matcher.Test(t, tt.want, validate(tt.version, tt.uid)) + }) + } } } @@ -1243,10 +1289,12 @@ func TestValidateSnapshot(t *testing.T) { }, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) - assertValidateErr(t, Validate_Snapshot(context.Background(), op, nil, tt.obj, nil), tt.want) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) + assertValidateErr(t, Validate_Snapshot(ctx, op, nil, tt.obj, nil), tt.want) }) } } @@ -1330,10 +1378,12 @@ func TestValidateSnapshotUpdate(t *testing.T) { newObj: valid(), }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeUpdateOp(context.Background()) - assertValidateErr(t, Validate_Snapshot(context.Background(), op, nil, tt.newObj, tt.oldObj), tt.want) + ctx := context.Background() + op := MakeUpdateOp(ctx, gates) + assertValidateErr(t, Validate_Snapshot(ctx, op, nil, tt.newObj, tt.oldObj), tt.want) }) } } @@ -1342,6 +1392,7 @@ func TestValidateSnapshotUpdate(t *testing.T) { // holds Snapshot has to descend into it, and report under // the holder's own path. func TestValidateNestedSnapshot(t *testing.T) { + gates := preview.NewForTest(t) tests := []struct { name string // path is where the offending Snapshot sits in the holder. @@ -1354,7 +1405,7 @@ func TestValidateNestedSnapshot(t *testing.T) { validate: func(ctx context.Context) field.ErrorList { // The live path: the server validates the Actor it is about to // write, as an update against the stored one. - op := MakeUpdateOp(context.Background()) + op := MakeUpdateOp(ctx, gates) oldVal := validActor(withActorStatus()) newVal := validActor(withActorStatus(func(s *ateapi.ActorStatus) { s.Snapshots = []*ateapi.Snapshot{badSnapshot()} @@ -1366,7 +1417,7 @@ func TestValidateNestedSnapshot(t *testing.T) { name: "tag.status.snapshot", path: field.NewPath("status", "snapshot"), validate: func(ctx context.Context) field.ErrorList { - op := MakeCreateOp(context.Background()) + op := MakeCreateOp(ctx, gates) obj := validTag(func(tag *ateapi.Tag) { tag.Status.Snapshot = badSnapshot() }) @@ -1492,10 +1543,12 @@ func TestValidateTag(t *testing.T) { want: field.ErrorList{field.Required(statusPath.Child("snapshot", "durable_snapshot"), "")}, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) - assertValidateErr(t, Validate_Tag(context.Background(), op, nil, tt.obj, nil), tt.want) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) + assertValidateErr(t, Validate_Tag(ctx, op, nil, tt.obj, nil), tt.want) }) } } @@ -1536,10 +1589,12 @@ func TestValidateTagUpdate(t *testing.T) { }), }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeUpdateOp(context.Background()) - assertValidateErr(t, Validate_Tag(context.Background(), op, nil, tt.newObj, tt.oldObj), tt.want) + ctx := context.Background() + op := MakeUpdateOp(ctx, gates) + assertValidateErr(t, Validate_Tag(ctx, op, nil, tt.newObj, tt.oldObj), tt.want) }) } } @@ -1702,10 +1757,12 @@ func TestValidateTagRequestPayloads(t *testing.T) { want: field.ErrorList{field.TooLong(field.NewPath("options", "page_token"), nil, 256).WithOrigin("maxLength")}, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) - assertValidateErr(t, tt.validate(context.Background(), op), tt.want) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) + assertValidateErr(t, tt.validate(ctx, op), tt.want) }) } } @@ -1766,10 +1823,12 @@ func TestValidateGoldenSnapshotStatus(t *testing.T) { want: field.ErrorList{field.Required(field.NewPath("golden_tag", "atespace"), "")}, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeCreateOp(context.Background()) - assertValidateErr(t, Validate_GoldenSnapshotStatus(context.Background(), op, nil, tt.obj, nil), tt.want) + ctx := context.Background() + op := MakeCreateOp(ctx, gates) + assertValidateErr(t, Validate_GoldenSnapshotStatus(ctx, op, nil, tt.obj, nil), tt.want) }) } } @@ -1818,10 +1877,12 @@ func TestValidateGoldenSnapshotStatusUpdate(t *testing.T) { want: field.ErrorList{field.TooLong(field.NewPath("error_message"), nil, 4096).WithOrigin("maxLength")}, }, } + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - op := MakeUpdateOp(context.Background()) - assertValidateErr(t, Validate_GoldenSnapshotStatus(context.Background(), op, nil, tt.newObj, tt.oldObj), tt.want) + ctx := context.Background() + op := MakeUpdateOp(ctx, gates) + assertValidateErr(t, Validate_GoldenSnapshotStatus(ctx, op, nil, tt.newObj, tt.oldObj), tt.want) }) } } diff --git a/cmd/ateapi/internal/apivalidation/worker.go b/cmd/ateapi/internal/apivalidation/worker.go index 3d81d55c19..6b2ec47121 100644 --- a/cmd/ateapi/internal/apivalidation/worker.go +++ b/cmd/ateapi/internal/apivalidation/worker.go @@ -18,98 +18,99 @@ import ( "context" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "k8s.io/apimachinery/pkg/api/operation" "k8s.io/apimachinery/pkg/api/validate" "k8s.io/apimachinery/pkg/util/validation/field" ) -func ValidateListWorkerActorAssignmentsRequest(ctx context.Context, req *ateapi.ListWorkerActorAssignmentsRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateListWorkerActorAssignmentsRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ListWorkerActorAssignmentsRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_ListWorkerActorAssignmentsRequest(ctx, op, nil, req, nil) } -func ValidateListWorkersRequest(ctx context.Context, req *ateapi.ListWorkersRequest) field.ErrorList { +func ValidateListWorkersRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ListWorkersRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_ListWorkersRequest(ctx, op, nil, req, nil) } -func ValidateGetWorkerRequest(ctx context.Context, req *ateapi.GetWorkerRequest) field.ErrorList { +func ValidateGetWorkerRequest(ctx context.Context, gates *preview.Gates, req *ateapi.GetWorkerRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_GetWorkerRequest(ctx, op, nil, req, nil) } -func ValidateCreateWorkerRequest(ctx context.Context, req *ateapi.CreateWorkerRequest) field.ErrorList { +func ValidateCreateWorkerRequest(ctx context.Context, gates *preview.Gates, req *ateapi.CreateWorkerRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_CreateWorkerRequest(ctx, op, nil, req, nil) } -func ValidateUpdateWorkerRequest(ctx context.Context, req *ateapi.UpdateWorkerRequest) field.ErrorList { +func ValidateUpdateWorkerRequest(ctx context.Context, gates *preview.Gates, req *ateapi.UpdateWorkerRequest) field.ErrorList { // Call the generated validation. // We model this as a create rather than an update because updates assume // the existence of a "current" value, which we do not have yet. This is // validating the request itself. The result will be validated later, after // we have a current value to compare against. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_UpdateWorkerRequest(ctx, op, nil, req, nil) } -func ValidateDeleteWorkerRequest(ctx context.Context, req *ateapi.DeleteWorkerRequest) field.ErrorList { +func ValidateDeleteWorkerRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DeleteWorkerRequest) field.ErrorList { // Call the generated validation. The preconditions in options are each // optional: a zero value waives that guard, so only non-zero values are // checked for shape. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_DeleteWorkerRequest(ctx, op, nil, req, nil) } -func ValidateDrainWorkerRequest(ctx context.Context, req *ateapi.DrainWorkerRequest) field.ErrorList { +func ValidateDrainWorkerRequest(ctx context.Context, gates *preview.Gates, req *ateapi.DrainWorkerRequest) field.ErrorList { // Call the generated validation. - op := MakeCreateOp(ctx) + op := MakeCreateOp(ctx, gates) return Validate_DrainWorkerRequest(ctx, op, nil, req, nil) } -func ValidateAcquireWorkerEpochRequest(ctx context.Context, req *ateapi.AcquireWorkerEpochRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateAcquireWorkerEpochRequest(ctx context.Context, gates *preview.Gates, req *ateapi.AcquireWorkerEpochRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_AcquireWorkerEpochRequest(ctx, op, nil, req, nil) } -func ValidateRegisterWorkerRequest(ctx context.Context, req *ateapi.RegisterWorkerRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateRegisterWorkerRequest(ctx context.Context, gates *preview.Gates, req *ateapi.RegisterWorkerRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_RegisterWorkerRequest(ctx, op, nil, req, nil) } -func ValidateSetWorkerSandboxRuntimesRequest(ctx context.Context, req *ateapi.SetWorkerSandboxRuntimesRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateSetWorkerSandboxRuntimesRequest(ctx context.Context, gates *preview.Gates, req *ateapi.SetWorkerSandboxRuntimesRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_SetWorkerSandboxRuntimesRequest(ctx, op, nil, req, nil) } -func ValidateRequestActorSuspendRequest(ctx context.Context, req *ateapi.RequestActorSuspendRequest) field.ErrorList { - op := MakeCreateOp(ctx) +func ValidateRequestActorSuspendRequest(ctx context.Context, gates *preview.Gates, req *ateapi.RequestActorSuspendRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_RequestActorSuspendRequest(ctx, op, nil, req, nil) } -func ValidateReportActorCrashedRequest(ctx context.Context, req *ateapi.ReportActorCrashedRequest) field.ErrorList { - op := operation.Operation{Type: operation.Create} +func ValidateReportActorCrashedRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ReportActorCrashedRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) return Validate_ReportActorCrashedRequest(ctx, op, nil, req, nil) } -func ValidateMarkWorkerAvailableRequest(ctx context.Context, req *ateapi.MarkWorkerAvailableRequest) field.ErrorList { +func ValidateMarkWorkerAvailableRequest(ctx context.Context, gates *preview.Gates, req *ateapi.MarkWorkerAvailableRequest) field.ErrorList { // Call the generated validation. - op := operation.Operation{Type: operation.Create} + op := MakeCreateOp(ctx, gates) return Validate_MarkWorkerAvailableRequest(ctx, op, nil, req, nil) } -func ValidateMarkWorkerUnavailableRequest(ctx context.Context, req *ateapi.MarkWorkerUnavailableRequest) field.ErrorList { +func ValidateMarkWorkerUnavailableRequest(ctx context.Context, gates *preview.Gates, req *ateapi.MarkWorkerUnavailableRequest) field.ErrorList { // Call the generated validation. - op := operation.Operation{Type: operation.Create} + op := MakeCreateOp(ctx, gates) return Validate_MarkWorkerUnavailableRequest(ctx, op, nil, req, nil) } -func ValidateReportActorSnapshotStateRequest(ctx context.Context, req *ateapi.ReportActorSnapshotStateRequest) field.ErrorList { - op := operation.Operation{Type: operation.Create} +func ValidateReportActorSnapshotStateRequest(ctx context.Context, gates *preview.Gates, req *ateapi.ReportActorSnapshotStateRequest) field.ErrorList { + op := MakeCreateOp(ctx, gates) errs := Validate_ReportActorSnapshotStateRequest(ctx, op, nil, req, nil) // A report with neither latest_local nor uploading is a detach, which // names the snapshot it made durable. @@ -122,9 +123,9 @@ func ValidateReportActorSnapshotStateRequest(ctx context.Context, req *ateapi.Re // validateWorkerUpdate validates a Worker against the previous stored value. // It is what enforces the immutable fields, which need an old value to compare // against. -func ValidateWorkerUpdate(ctx context.Context, fldPath *field.Path, newVal, oldVal *ateapi.Worker, requireStatus bool) field.ErrorList { +func ValidateWorkerUpdate(ctx context.Context, gates *preview.Gates, fldPath *field.Path, newVal, oldVal *ateapi.Worker, requireStatus bool) field.ErrorList { // Call the generated validation. - op := MakeUpdateOp(ctx) + op := MakeUpdateOp(ctx, gates) errs := Validate_Worker(ctx, op, fldPath, newVal, oldVal) if requireStatus { // Status is optional in the schema, but is actually required to be set @@ -158,7 +159,7 @@ func ValidateCustom_Worker_WorkerSpiffeId(_ context.Context, _ operation.Operati return validateSPIFFEID(fldPath, *value) } -// This exists only because nested subfield tags are not supported yet. +// This exists to do partial validation of the target resource in an update. func ValidateCustom_UpdateWorkerRequest_Worker(ctx context.Context, op operation.Operation, fldPath *field.Path, worker, _ *ateapi.Worker) field.ErrorList { if worker == nil || worker.Metadata == nil { return nil // handled by DV @@ -166,11 +167,7 @@ func ValidateCustom_UpdateWorkerRequest_Worker(ctx context.Context, op operation // Updates are validated in 2 steps: first the update request and then the // resource itself. DV for the request doesn't descend into the resource - // metadata. Once DV supports nested subfield tags, this can be changed to - // something like: - // +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:forbidden - // Workers are global-scoped, so metadata.atespace must be empty. - errs := Validate_ResourceMetadata(ctx, op, fldPath.Child("metadata"), worker.Metadata, nil) - errs = append(errs, validate.ForbiddenValue(ctx, op, fldPath.Child("metadata", "atespace"), &worker.Metadata.Atespace, nil)...) - return errs + // metadata. What we need is something like: + // +k8s:subfield(metadata)=+k8s:validateType + return Validate_ResourceMetadata(ctx, op, fldPath.Child("metadata"), worker.Metadata, nil) } diff --git a/cmd/ateapi/internal/apivalidation/worker_test.go b/cmd/ateapi/internal/apivalidation/worker_test.go index e87ee2f159..2d9dd53b4e 100644 --- a/cmd/ateapi/internal/apivalidation/worker_test.go +++ b/cmd/ateapi/internal/apivalidation/worker_test.go @@ -21,6 +21,7 @@ import ( "testing" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/types/known/timestamppb" "k8s.io/apimachinery/pkg/util/validation/field" @@ -201,9 +202,10 @@ func TestValidateCreateWorkerRequest(t *testing.T) { req: validReq(validWorker(apiWorkerName, withStatus(func(s *ateapi.WorkerStatus) { s.State = 99 }))), want: field.ErrorList{field.Invalid(field.NewPath("worker", "status", "state"), nil, "").WithOrigin("maximum")}, }} + gates := preview.NewForTest(t) for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - assertValidateErr(t, ValidateCreateWorkerRequest(context.Background(), tc.req), tc.want) + assertValidateErr(t, ValidateCreateWorkerRequest(context.Background(), gates, tc.req), tc.want) }) } } @@ -259,9 +261,10 @@ func TestValidateDeleteWorkerRequest(t *testing.T) { }, nil, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateDeleteWorkerRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateDeleteWorkerRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -319,9 +322,10 @@ func TestValidateUpdateWorkerRequest(t *testing.T) { validReq(func(w *ateapi.Worker) { w.Metadata.Atespace = "team-a" }), field.ErrorList{field.Forbidden(field.NewPath("worker", "metadata", "atespace"), "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateUpdateWorkerRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateUpdateWorkerRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -335,12 +339,13 @@ func TestValidateWorkerUpdate_RequireStatus(t *testing.T) { newVal := proto.Clone(oldVal).(*ateapi.Worker) newVal.Status = nil + gates := preview.NewForTest(t) want := field.ErrorList{field.Required(field.NewPath("worker", "status"), "")} - assertValidateErr(t, ValidateWorkerUpdate(context.Background(), field.NewPath("worker"), newVal, oldVal, true), want) + assertValidateErr(t, ValidateWorkerUpdate(context.Background(), gates, field.NewPath("worker"), newVal, oldVal, true), want) // Without requireStatus the same worker passes: status is optional in the // schema, and clearing it is not otherwise constrained. - assertValidateErr(t, ValidateWorkerUpdate(context.Background(), field.NewPath("worker"), newVal, oldVal, false), nil) + assertValidateErr(t, ValidateWorkerUpdate(context.Background(), gates, field.NewPath("worker"), newVal, oldVal, false), nil) } func TestValidateAcquireWorkerEpochRequest(t *testing.T) { @@ -364,9 +369,10 @@ func TestValidateAcquireWorkerEpochRequest(t *testing.T) { req: &ateapi.AcquireWorkerEpochRequest{Worker: &ateapi.ObjectRef{}}, want: field.ErrorList{field.Required(field.NewPath("worker", "name"), "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateAcquireWorkerEpochRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateAcquireWorkerEpochRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -453,9 +459,10 @@ func TestValidateRegisterWorkerRequest(t *testing.T) { req: valid(func(r *ateapi.RegisterWorkerRequest) { r.Capacity.MemoryBytes = -1 }), want: field.ErrorList{field.Invalid(field.NewPath("capacity", "memory_bytes"), nil, "").WithOrigin("minimum")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateRegisterWorkerRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateRegisterWorkerRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -643,9 +650,10 @@ func TestValidateSetWorkerSandboxRuntimesRequest(t *testing.T) { }), want: field.ErrorList{field.TooMany(restorablePath, 33, 32).WithOrigin("maxItems")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateSetWorkerSandboxRuntimesRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateSetWorkerSandboxRuntimesRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -716,11 +724,12 @@ func TestValidateWorkerUpdate_SandboxClasses(t *testing.T) { }, want: field.ErrorList{field.TooMany(classPath.Child("restorable_runtimes"), 33, 32).WithOrigin("maxItems")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { newVal := proto.Clone(oldVal).(*ateapi.Worker) tt.mutate(newVal.Status) - assertValidateErr(t, ValidateWorkerUpdate(context.Background(), field.NewPath("worker"), newVal, oldVal, true), tt.want) + assertValidateErr(t, ValidateWorkerUpdate(context.Background(), gates, field.NewPath("worker"), newVal, oldVal, true), tt.want) }) } } @@ -789,9 +798,10 @@ func TestValidateRequestActorSuspendRequest(t *testing.T) { req: valid(func(r *ateapi.RequestActorSuspendRequest) { r.ActorUid = "not-a-uuid" }), want: field.ErrorList{field.Invalid(field.NewPath("actor_uid"), nil, "").WithOrigin("format=k8s-uuid")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateRequestActorSuspendRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateRequestActorSuspendRequest(context.Background(), gates, tt.req), tt.want) }) } } @@ -914,9 +924,10 @@ func TestValidateReportActorSnapshotStateRequest(t *testing.T) { req: valid(func(r *ateapi.ReportActorSnapshotStateRequest) { r.State.LatestDurable.Object = nil }), want: field.ErrorList{field.Required(field.NewPath("state", "latest_durable", "object"), "")}, }} + gates := preview.NewForTest(t) for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, ValidateReportActorSnapshotStateRequest(context.Background(), tt.req), tt.want) + assertValidateErr(t, ValidateReportActorSnapshotStateRequest(context.Background(), gates, tt.req), tt.want) }) } } diff --git a/cmd/ateapi/internal/apivalidation/zz_generated.validation.go b/cmd/ateapi/internal/apivalidation/zz_generated.validation.go index 4719d8d4f4..3a37ec9bc0 100644 --- a/cmd/ateapi/internal/apivalidation/zz_generated.validation.go +++ b/cmd/ateapi/internal/apivalidation/zz_generated.validation.go @@ -21,6 +21,7 @@ package apivalidation import ( context "context" + regexp "regexp" v1 "go.ate.dev/substrate/api/ateapi/v1" timestamppb "google.golang.org/protobuf/types/known/timestamppb" @@ -30,6 +31,8 @@ import ( field "k8s.io/apimachinery/pkg/util/validation/field" ) +var formatPattern_ate_singleton_name = regexp.MustCompile("(^$|^default$)") + // Validate_AccessPolicy validates an instance of AccessPolicy according // to declarative validation rules in the API schema. func Validate_AccessPolicy( @@ -56,10 +59,33 @@ func Validate_AccessPolicy( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_AccessPolicy_Metadata(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + func() { // cohort = "name" + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "name", + func(o *v1.ResourceMetadata) *string { return &o.Name }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name") + }); len(e) != 0 { + errs = append(errs, e...) + } + }() // call the type's validation function errs = append(errs, Validate_ResourceMetadata(ctx, op, fldPath, obj, oldObj)...) return @@ -143,16 +169,15 @@ func Validate_AcquireWorkerEpochRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -202,18 +227,13 @@ func Validate_Actor( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.Immutable).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -252,14 +272,13 @@ func Validate_Actor( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -331,14 +350,13 @@ func Validate_Actor( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -455,6 +473,165 @@ func Validate_ActorCrash( return errs } +var formatPattern_ate_volume_storage_id = regexp.MustCompile("^[^\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x9F]*$") + +// Validate_ActorExternalVolumeStatus validates an instance of ActorExternalVolumeStatus according +// to declarative validation rules in the API schema. +func Validate_ActorExternalVolumeStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ActorExternalVolumeStatus) (errs field.ErrorList) { + + { // field v1.ActorExternalVolumeStatus.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.UpdateValue(ctx, op, fldPath, obj, oldObj, + func(a string, b string) bool { return a == b }, validate.NoUnset, validate.NoModify).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ActorExternalVolumeStatus) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field v1.ActorExternalVolumeStatus.StorageVolumeId + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.UpdateValue(ctx, op, fldPath, obj, oldObj, + func(a string, b string) bool { return a == b }, validate.NoUnset, validate.NoModify).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_volume_storage_id, "must not contain control characters", "format=ate-volume-storage-id"); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ActorExternalVolumeStatus) *string { + return &oldObj.StorageVolumeId + }) + errs = append(errs, fn(fldPath.Child("storage_volume_id"), &obj.StorageVolumeId, oldVal, oldObj != nil)...) + } + + { // field v1.ActorExternalVolumeStatus.VolumeType + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.UpdateValue(ctx, op, fldPath, obj, oldObj, + func(a string, b string) bool { return a == b }, validate.NoUnset, validate.NoModify).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 63); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ActorExternalVolumeStatus) *string { + return &oldObj.VolumeType + }) + errs = append(errs, fn(fldPath.Child("volume_type"), &obj.VolumeType, oldVal, oldObj != nil)...) + } + + { // field v1.ActorExternalVolumeStatus.VolumeContext + fn := func( + fldPath *field.Path, + obj, oldObj map[string]string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalMap(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // custom validation + if e := ValidateCustom_ActorExternalVolumeStatus_VolumeContext(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ActorExternalVolumeStatus) map[string]string { + return oldObj.VolumeContext + }) + errs = append(errs, fn(fldPath.Child("volume_context"), obj.VolumeContext, oldVal, oldObj != nil)...) + } + + return errs +} + // Validate_ActorJwtSource validates an instance of ActorJwtSource according // to declarative validation rules in the API schema. func Validate_ActorJwtSource( @@ -1125,10 +1302,10 @@ func Validate_ActorStatus( if earlyReturn { return // do not proceed } - if e := validate.Monotonic(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { errs = append(errs, e...) } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { + if e := validate.Monotonic(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } return @@ -1172,18 +1349,13 @@ func Validate_ActorTemplate( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.Immutable).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -1372,10 +1544,56 @@ func Validate_ActorTemplate( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_ActorTemplate_Resources(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "limits" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "limits", + func(o *v1.ResourceRequirements) *v1.Resources { return o.Limits }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.Resources) field.ErrorList { + return validate.RequiredPointer(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + func() { // cohort = "limits.cpu_millicores" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "limits", + func(o *v1.ResourceRequirements) *v1.Resources { return o.Limits }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.Resources) field.ErrorList { + return validate.Subfield(ctx, op, fldPath, obj, oldObj, "cpu_millicores", + func(o *v1.Resources) *int64 { return &o.CpuMillicores }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *int64) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + func() { // cohort = "limits.memory_bytes" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "limits", + func(o *v1.ResourceRequirements) *v1.Resources { return o.Limits }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.Resources) field.ErrorList { + return validate.Subfield(ctx, op, fldPath, obj, oldObj, "memory_bytes", + func(o *v1.Resources) *int64 { return &o.MemoryBytes }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *int64) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function errs = append(errs, Validate_ResourceRequirements(ctx, op, fldPath, obj, oldObj)...) return @@ -1400,7 +1618,10 @@ func Validate_ActorTemplate( } // call field-attached validations earlyReturn := false - if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "GoldenEgressPolicy", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "GoldenEgressPolicy", false, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.EgressPolicyTemplate) field.ErrorList { + return validate.ForbiddenPointer(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } @@ -1525,20 +1746,15 @@ func Validate_Atespace( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.Immutable).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -2178,14 +2394,13 @@ func Validate_CreateActorEgressPolicyRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -2348,16 +2563,15 @@ func Validate_CreateAtespaceAccessPolicyRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -2449,16 +2663,16 @@ func Validate_CreateAtespaceRequest( return errs } -// Validate_CreateGlobalAccessPolicyRequest validates an instance of CreateGlobalAccessPolicyRequest according +// Validate_CreateCsiDriverRequest validates an instance of CreateCsiDriverRequest according // to declarative validation rules in the API schema. -func Validate_CreateGlobalAccessPolicyRequest( +func Validate_CreateCsiDriverRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.CreateGlobalAccessPolicyRequest) (errs field.ErrorList) { + obj, oldObj *v1.CreateCsiDriverRequest) (errs field.ErrorList) { - { // field v1.CreateGlobalAccessPolicyRequest.AccessPolicy + { // field v1.CreateCsiDriverRequest.CsiDriver fn := func( fldPath *field.Path, - obj, oldObj *v1.AccessPolicy, + obj, oldObj *v1.CsiDriver, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -2476,29 +2690,69 @@ func Validate_CreateGlobalAccessPolicyRequest( return // do not proceed } // call the type's validation function - errs = append(errs, Validate_AccessPolicy(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_CsiDriver(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.CreateGlobalAccessPolicyRequest) *v1.AccessPolicy { - return oldObj.AccessPolicy + func(oldObj *v1.CreateCsiDriverRequest) *v1.CsiDriver { + return oldObj.CsiDriver }) - errs = append(errs, fn(fldPath.Child("access_policy"), obj.AccessPolicy, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("csi_driver"), obj.CsiDriver, oldVal, oldObj != nil)...) } return errs } -// Validate_CreateTagRequest validates an instance of CreateTagRequest according +// Validate_CreateGlobalAccessPolicyRequest validates an instance of CreateGlobalAccessPolicyRequest according // to declarative validation rules in the API schema. -func Validate_CreateTagRequest( +func Validate_CreateGlobalAccessPolicyRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.CreateTagRequest) (errs field.ErrorList) { - - // custom validation - if e := ValidateCustom_CreateTagRequest(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + obj, oldObj *v1.CreateGlobalAccessPolicyRequest) (errs field.ErrorList) { + + { // field v1.CreateGlobalAccessPolicyRequest.AccessPolicy + fn := func( + fldPath *field.Path, + obj, oldObj *v1.AccessPolicy, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_AccessPolicy(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.CreateGlobalAccessPolicyRequest) *v1.AccessPolicy { + return oldObj.AccessPolicy + }) + errs = append(errs, fn(fldPath.Child("access_policy"), obj.AccessPolicy, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_CreateTagRequest validates an instance of CreateTagRequest according +// to declarative validation rules in the API schema. +func Validate_CreateTagRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.CreateTagRequest) (errs field.ErrorList) { + + // custom validation + if e := ValidateCustom_CreateTagRequest(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } { // field v1.CreateTagRequest.Tag fn := func( @@ -2574,7 +2828,9 @@ func Validate_CreateWorkerRequest( return errs } -var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_CredentialHeader_ = validate.NewUnionMembership(validate.NewUnionMember("credential_uri"), validate.NewUnionMember("actor_jwt")) +var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_CredentialHeader_ = validate.NewUnionMembership(validate.NewUnionMember("credential_uri"), validate.NewUnionMember("actor_jwt"), validate.NewUnionMember("token_exchange")) +var formatPattern_ate_http_header_name = regexp.MustCompile("(^$|^[-A-Za-z0-9!#$%&'*+.^_`|~]+$)") +var formatPattern_ate_http_header_value = regexp.MustCompile("^[^\\x00-\\x08\\x0A-\\x1F\\x7F]*$") // Validate_CredentialHeader validates an instance of CredentialHeader according // to declarative validation rules in the API schema. @@ -2595,6 +2851,12 @@ func Validate_CredentialHeader( return false } return obj.ActorJwt != nil + }, + func(obj *v1.CredentialHeader) bool { + if obj == nil { + return false + } + return obj.TokenExchange != nil }); len(e) != 0 { errs = append(errs, e...) } @@ -2619,8 +2881,7 @@ func Validate_CredentialHeader( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_CredentialHeader_Header(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_header_name, "must be an HTTP header name", "format=ate-http-header-name"); len(e) != 0 { errs = append(errs, e...) } return @@ -2651,8 +2912,7 @@ func Validate_CredentialHeader( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_CredentialHeader_Prefix(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_header_value, "must be a valid HTTP field value", "format=ate-http-header-value"); len(e) != 0 { errs = append(errs, e...) } return @@ -2687,6 +2947,9 @@ func Validate_CredentialHeader( if e := ValidateCustom_CredentialHeader_CredentialUri(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 1024); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, @@ -2726,19 +2989,49 @@ func Validate_CredentialHeader( errs = append(errs, fn(fldPath.Child("actor_jwt"), obj.ActorJwt, oldVal, oldObj != nil)...) } + { // field v1.CredentialHeader.TokenExchange + fn := func( + fldPath *field.Path, + obj, oldObj *v1.TokenExchangeSource, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_TokenExchangeSource(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.CredentialHeader) *v1.TokenExchangeSource { + return oldObj.TokenExchange + }) + errs = append(errs, fn(fldPath.Child("token_exchange"), obj.TokenExchange, oldVal, oldObj != nil)...) + } + return errs } -// Validate_DeleteActorEgressPolicyRequest validates an instance of DeleteActorEgressPolicyRequest according +// Validate_CsiDriver validates an instance of CsiDriver according // to declarative validation rules in the API schema. -func Validate_DeleteActorEgressPolicyRequest( +func Validate_CsiDriver( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DeleteActorEgressPolicyRequest) (errs field.ErrorList) { + obj, oldObj *v1.CsiDriver) (errs field.ErrorList) { - { // field v1.DeleteActorEgressPolicyRequest.Actor + { // field v1.CsiDriver.Metadata fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.ResourceMetadata, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -2758,12 +3051,15 @@ func Validate_DeleteActorEgressPolicyRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -2771,17 +3067,17 @@ func Validate_DeleteActorEgressPolicyRequest( } }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ResourceMetadata(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteActorEgressPolicyRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.CsiDriver) *v1.ResourceMetadata { + return oldObj.Metadata }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("metadata"), obj.Metadata, oldVal, oldObj != nil)...) } - { // field v1.DeleteActorEgressPolicyRequest.Name + { // field v1.CsiDriver.DriverName fn := func( fldPath *field.Path, obj, oldObj *string, @@ -2794,6 +3090,10 @@ func Validate_DeleteActorEgressPolicyRequest( } // call field-attached validations earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true @@ -2801,26 +3101,25 @@ func Validate_DeleteActorEgressPolicyRequest( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_DeleteActorEgressPolicyRequest_Name(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 63); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteActorEgressPolicyRequest) *string { - return &oldObj.Name + func(oldObj *v1.CsiDriver) *string { + return &oldObj.DriverName }) - errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("driver_name"), &obj.DriverName, oldVal, oldObj != nil)...) } - { // field v1.DeleteActorEgressPolicyRequest.Options + { // field v1.CsiDriver.ControllerEndpoint fn := func( fldPath *field.Path, - obj, oldObj *v1.DeleteOptions, + obj, oldObj *v1.CsiDriverEndpoint, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -2830,36 +3129,28 @@ func Validate_DeleteActorEgressPolicyRequest( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } // call the type's validation function - errs = append(errs, Validate_DeleteOptions(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_CsiDriverEndpoint(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteActorEgressPolicyRequest) *v1.DeleteOptions { - return oldObj.Options + func(oldObj *v1.CsiDriver) *v1.CsiDriverEndpoint { + return oldObj.ControllerEndpoint }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("controller_endpoint"), obj.ControllerEndpoint, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_DeleteActorRequest validates an instance of DeleteActorRequest according -// to declarative validation rules in the API schema. -func Validate_DeleteActorRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DeleteActorRequest) (errs field.ErrorList) { - - { // field v1.DeleteActorRequest.Actor + { // field v1.CsiDriver.Tls fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.CsiDriverTlsConfig, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -2869,164 +3160,157 @@ func Validate_DeleteActorRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_CsiDriverTlsConfig(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteActorRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.CsiDriver) *v1.CsiDriverTlsConfig { + return oldObj.Tls }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("tls"), obj.Tls, oldVal, oldObj != nil)...) } - { // field v1.DeleteActorRequest.Options + return errs +} + +// Validate_CsiDriverEndpoint validates an instance of CsiDriverEndpoint according +// to declarative validation rules in the API schema. +func Validate_CsiDriverEndpoint( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.CsiDriverEndpoint) (errs field.ErrorList) { + + { // field v1.CsiDriverEndpoint.Host fn := func( fldPath *field.Path, - obj, oldObj *v1.DeleteOptions, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_DeleteOptions(ctx, op, fldPath, obj, oldObj)...) + // custom validation + if e := ValidateCustom_CsiDriverEndpoint_Host(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 253); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteActorRequest) *v1.DeleteOptions { - return oldObj.Options + func(oldObj *v1.CsiDriverEndpoint) *string { + return &oldObj.Host }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("host"), &obj.Host, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_DeleteActorTemplateRequest validates an instance of DeleteActorTemplateRequest according -// to declarative validation rules in the API schema. -func Validate_DeleteActorTemplateRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DeleteActorTemplateRequest) (errs field.ErrorList) { - - { // field v1.DeleteActorTemplateRequest.ActorTemplate + { // field v1.CsiDriverEndpoint.Port fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *int32, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 65535); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteActorTemplateRequest) *v1.ObjectRef { - return oldObj.ActorTemplate + func(oldObj *v1.CsiDriverEndpoint) *int32 { + return &oldObj.Port }) - errs = append(errs, fn(fldPath.Child("actor_template"), obj.ActorTemplate, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("port"), &obj.Port, oldVal, oldObj != nil)...) } - { // field v1.DeleteActorTemplateRequest.Options + return errs +} + +// Validate_CsiDriverTlsConfig validates an instance of CsiDriverTlsConfig according +// to declarative validation rules in the API schema. +func Validate_CsiDriverTlsConfig( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.CsiDriverTlsConfig) (errs field.ErrorList) { + + { // field v1.CsiDriverTlsConfig.ServerName fn := func( fldPath *field.Path, - obj, oldObj *v1.DeleteOptions, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_DeleteOptions(ctx, op, fldPath, obj, oldObj)...) + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 253); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteActorTemplateRequest) *v1.DeleteOptions { - return oldObj.Options + func(oldObj *v1.CsiDriverTlsConfig) *string { + return &oldObj.ServerName }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("server_name"), &obj.ServerName, oldVal, oldObj != nil)...) } return errs } -// Validate_DeleteAtespaceAccessPolicyRequest validates an instance of DeleteAtespaceAccessPolicyRequest according +// Validate_DeleteActorEgressPolicyRequest validates an instance of DeleteActorEgressPolicyRequest according // to declarative validation rules in the API schema. -func Validate_DeleteAtespaceAccessPolicyRequest( +func Validate_DeleteActorEgressPolicyRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DeleteAtespaceAccessPolicyRequest) (errs field.ErrorList) { + obj, oldObj *v1.DeleteActorEgressPolicyRequest) (errs field.ErrorList) { - { // field v1.DeleteAtespaceAccessPolicyRequest.Atespace + { // field v1.DeleteActorEgressPolicyRequest.Actor fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -3049,18 +3333,13 @@ func Validate_DeleteAtespaceAccessPolicyRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -3070,13 +3349,13 @@ func Validate_DeleteAtespaceAccessPolicyRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteAtespaceAccessPolicyRequest) *v1.ObjectRef { - return oldObj.Atespace + func(oldObj *v1.DeleteActorEgressPolicyRequest) *v1.ObjectRef { + return oldObj.Actor }) - errs = append(errs, fn(fldPath.Child("atespace"), obj.Atespace, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - { // field v1.DeleteAtespaceAccessPolicyRequest.Name + { // field v1.DeleteActorEgressPolicyRequest.Name fn := func( fldPath *field.Path, obj, oldObj *string, @@ -3096,23 +3375,19 @@ func Validate_DeleteAtespaceAccessPolicyRequest( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_DeleteAtespaceAccessPolicyRequest_Name(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name"); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteAtespaceAccessPolicyRequest) *string { + func(oldObj *v1.DeleteActorEgressPolicyRequest) *string { return &oldObj.Name }) errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) } - { // field v1.DeleteAtespaceAccessPolicyRequest.Options + { // field v1.DeleteActorEgressPolicyRequest.Options fn := func( fldPath *field.Path, obj, oldObj *v1.DeleteOptions, @@ -3136,7 +3411,7 @@ func Validate_DeleteAtespaceAccessPolicyRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteAtespaceAccessPolicyRequest) *v1.DeleteOptions { + func(oldObj *v1.DeleteActorEgressPolicyRequest) *v1.DeleteOptions { return oldObj.Options }) errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) @@ -3145,13 +3420,13 @@ func Validate_DeleteAtespaceAccessPolicyRequest( return errs } -// Validate_DeleteAtespaceRequest validates an instance of DeleteAtespaceRequest according +// Validate_DeleteActorRequest validates an instance of DeleteActorRequest according // to declarative validation rules in the API schema. -func Validate_DeleteAtespaceRequest( +func Validate_DeleteActorRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DeleteAtespaceRequest) (errs field.ErrorList) { + obj, oldObj *v1.DeleteActorRequest) (errs field.ErrorList) { - { // field v1.DeleteAtespaceRequest.Atespace + { // field v1.DeleteActorRequest.Actor fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -3174,18 +3449,13 @@ func Validate_DeleteAtespaceRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -3195,13 +3465,13 @@ func Validate_DeleteAtespaceRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteAtespaceRequest) *v1.ObjectRef { - return oldObj.Atespace + func(oldObj *v1.DeleteActorRequest) *v1.ObjectRef { + return oldObj.Actor }) - errs = append(errs, fn(fldPath.Child("atespace"), obj.Atespace, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - { // field v1.DeleteAtespaceRequest.Options + { // field v1.DeleteActorRequest.Options fn := func( fldPath *field.Path, obj, oldObj *v1.DeleteOptions, @@ -3225,7 +3495,7 @@ func Validate_DeleteAtespaceRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteAtespaceRequest) *v1.DeleteOptions { + func(oldObj *v1.DeleteActorRequest) *v1.DeleteOptions { return oldObj.Options }) errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) @@ -3234,84 +3504,97 @@ func Validate_DeleteAtespaceRequest( return errs } -// Validate_DeleteOptions validates an instance of DeleteOptions according +// Validate_DeleteActorTemplateRequest validates an instance of DeleteActorTemplateRequest according // to declarative validation rules in the API schema. -func Validate_DeleteOptions( +func Validate_DeleteActorTemplateRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DeleteOptions) (errs field.ErrorList) { + obj, oldObj *v1.DeleteActorTemplateRequest) (errs field.ErrorList) { - { // field v1.DeleteOptions.Version + { // field v1.DeleteActorTemplateRequest.ActorTemplate fn := func( fldPath *field.Path, - obj, oldObj *int64, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteOptions) *int64 { - return &oldObj.Version + func(oldObj *v1.DeleteActorTemplateRequest) *v1.ObjectRef { + return oldObj.ActorTemplate }) - errs = append(errs, fn(fldPath.Child("version"), &obj.Version, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor_template"), obj.ActorTemplate, oldVal, oldObj != nil)...) } - { // field v1.DeleteOptions.Uid + { // field v1.DeleteActorTemplateRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.DeleteOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_DeleteOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteOptions) *string { - return &oldObj.Uid + func(oldObj *v1.DeleteActorTemplateRequest) *v1.DeleteOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("uid"), &obj.Uid, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } return errs } -// Validate_DeleteTagRequest validates an instance of DeleteTagRequest according +// Validate_DeleteAtespaceAccessPolicyRequest validates an instance of DeleteAtespaceAccessPolicyRequest according // to declarative validation rules in the API schema. -func Validate_DeleteTagRequest( +func Validate_DeleteAtespaceAccessPolicyRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DeleteTagRequest) (errs field.ErrorList) { + obj, oldObj *v1.DeleteAtespaceAccessPolicyRequest) (errs field.ErrorList) { - { // field v1.DeleteTagRequest.Tag + { // field v1.DeleteAtespaceAccessPolicyRequest.Atespace fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -3334,7 +3617,10 @@ func Validate_DeleteTagRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } @@ -3351,13 +3637,45 @@ func Validate_DeleteTagRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteTagRequest) *v1.ObjectRef { - return oldObj.Tag + func(oldObj *v1.DeleteAtespaceAccessPolicyRequest) *v1.ObjectRef { + return oldObj.Atespace }) - errs = append(errs, fn(fldPath.Child("tag"), obj.Tag, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("atespace"), obj.Atespace, oldVal, oldObj != nil)...) } - { // field v1.DeleteTagRequest.Options + { // field v1.DeleteAtespaceAccessPolicyRequest.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.DeleteAtespaceAccessPolicyRequest) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field v1.DeleteAtespaceAccessPolicyRequest.Options fn := func( fldPath *field.Path, obj, oldObj *v1.DeleteOptions, @@ -3381,7 +3699,7 @@ func Validate_DeleteTagRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteTagRequest) *v1.DeleteOptions { + func(oldObj *v1.DeleteAtespaceAccessPolicyRequest) *v1.DeleteOptions { return oldObj.Options }) errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) @@ -3390,13 +3708,13 @@ func Validate_DeleteTagRequest( return errs } -// Validate_DeleteWorkerRequest validates an instance of DeleteWorkerRequest according +// Validate_DeleteAtespaceRequest validates an instance of DeleteAtespaceRequest according // to declarative validation rules in the API schema. -func Validate_DeleteWorkerRequest( +func Validate_DeleteAtespaceRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DeleteWorkerRequest) (errs field.ErrorList) { + obj, oldObj *v1.DeleteAtespaceRequest) (errs field.ErrorList) { - { // field v1.DeleteWorkerRequest.Worker + { // field v1.DeleteAtespaceRequest.Atespace fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -3419,16 +3737,15 @@ func Validate_DeleteWorkerRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -3440,13 +3757,13 @@ func Validate_DeleteWorkerRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteWorkerRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.DeleteAtespaceRequest) *v1.ObjectRef { + return oldObj.Atespace }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("atespace"), obj.Atespace, oldVal, oldObj != nil)...) } - { // field v1.DeleteWorkerRequest.Options + { // field v1.DeleteAtespaceRequest.Options fn := func( fldPath *field.Path, obj, oldObj *v1.DeleteOptions, @@ -3470,7 +3787,7 @@ func Validate_DeleteWorkerRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DeleteWorkerRequest) *v1.DeleteOptions { + func(oldObj *v1.DeleteAtespaceRequest) *v1.DeleteOptions { return oldObj.Options }) errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) @@ -3479,13 +3796,13 @@ func Validate_DeleteWorkerRequest( return errs } -// Validate_DrainWorkerRequest validates an instance of DrainWorkerRequest according +// Validate_DeleteCsiDriverRequest validates an instance of DeleteCsiDriverRequest according // to declarative validation rules in the API schema. -func Validate_DrainWorkerRequest( +func Validate_DeleteCsiDriverRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.DrainWorkerRequest) (errs field.ErrorList) { + obj, oldObj *v1.DeleteCsiDriverRequest) (errs field.ErrorList) { - { // field v1.DrainWorkerRequest.Worker + { // field v1.DeleteCsiDriverRequest.CsiDriver fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -3508,16 +3825,15 @@ func Validate_DrainWorkerRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -3529,25 +3845,16 @@ func Validate_DrainWorkerRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.DrainWorkerRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.DeleteCsiDriverRequest) *v1.ObjectRef { + return oldObj.CsiDriver }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("csi_driver"), obj.CsiDriver, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_EgressPolicy validates an instance of EgressPolicy according -// to declarative validation rules in the API schema. -func Validate_EgressPolicy( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.EgressPolicy) (errs field.ErrorList) { - - { // field v1.EgressPolicy.Metadata + { // field v1.DeleteCsiDriverRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *v1.ResourceMetadata, + obj, oldObj *v1.DeleteOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -3557,104 +3864,1144 @@ func Validate_EgressPolicy( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_EgressPolicy_Metadata(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.Immutable).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ResourceMetadata(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_DeleteOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.EgressPolicy) *v1.ResourceMetadata { - return oldObj.Metadata + func(oldObj *v1.DeleteCsiDriverRequest) *v1.DeleteOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("metadata"), obj.Metadata, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } - { // field v1.EgressPolicy.Rules + return errs +} + +// Validate_DeleteOptions validates an instance of DeleteOptions according +// to declarative validation rules in the API schema. +func Validate_DeleteOptions( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.DeleteOptions) (errs field.ErrorList) { + + { // field v1.DeleteOptions.Version fn := func( fldPath *field.Path, - obj, oldObj []*v1.EgressRule, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.PtrSliceNoNils[v1.EgressRule](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_EgressPolicy_Rules(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - // iterate the list and call the type's validation function - if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_EgressRule); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.EgressPolicy) []*v1.EgressRule { - return oldObj.Rules + func(oldObj *v1.DeleteOptions) *int64 { + return &oldObj.Version }) - errs = append(errs, fn(fldPath.Child("rules"), obj.Rules, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("version"), &obj.Version, oldVal, oldObj != nil)...) + } + + { // field v1.DeleteOptions.Uid + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.DeleteOptions) *string { + return &oldObj.Uid + }) + errs = append(errs, fn(fldPath.Child("uid"), &obj.Uid, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeleteTagRequest validates an instance of DeleteTagRequest according +// to declarative validation rules in the API schema. +func Validate_DeleteTagRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.DeleteTagRequest) (errs field.ErrorList) { + + { // field v1.DeleteTagRequest.Tag + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.DeleteTagRequest) *v1.ObjectRef { + return oldObj.Tag + }) + errs = append(errs, fn(fldPath.Child("tag"), obj.Tag, oldVal, oldObj != nil)...) + } + + { // field v1.DeleteTagRequest.Options + fn := func( + fldPath *field.Path, + obj, oldObj *v1.DeleteOptions, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DeleteOptions(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.DeleteTagRequest) *v1.DeleteOptions { + return oldObj.Options + }) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DeleteWorkerRequest validates an instance of DeleteWorkerRequest according +// to declarative validation rules in the API schema. +func Validate_DeleteWorkerRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.DeleteWorkerRequest) (errs field.ErrorList) { + + { // field v1.DeleteWorkerRequest.Worker + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.DeleteWorkerRequest) *v1.ObjectRef { + return oldObj.Worker + }) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + } + + { // field v1.DeleteWorkerRequest.Options + fn := func( + fldPath *field.Path, + obj, oldObj *v1.DeleteOptions, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_DeleteOptions(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.DeleteWorkerRequest) *v1.DeleteOptions { + return oldObj.Options + }) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_DrainWorkerRequest validates an instance of DrainWorkerRequest according +// to declarative validation rules in the API schema. +func Validate_DrainWorkerRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.DrainWorkerRequest) (errs field.ErrorList) { + + { // field v1.DrainWorkerRequest.Worker + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.DrainWorkerRequest) *v1.ObjectRef { + return oldObj.Worker + }) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_EgressPolicy validates an instance of EgressPolicy according +// to declarative validation rules in the API schema. +func Validate_EgressPolicy( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.EgressPolicy) (errs field.ErrorList) { + + { // field v1.EgressPolicy.Metadata + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ResourceMetadata, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + func() { // cohort = "name" + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "name", + func(o *v1.ResourceMetadata) *string { return &o.Name }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name") + }); len(e) != 0 { + errs = append(errs, e...) + } + }() + // call the type's validation function + errs = append(errs, Validate_ResourceMetadata(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.EgressPolicy) *v1.ResourceMetadata { + return oldObj.Metadata + }) + errs = append(errs, fn(fldPath.Child("metadata"), obj.Metadata, oldVal, oldObj != nil)...) + } + + { // field v1.EgressPolicy.Rules + fn := func( + fldPath *field.Path, + obj, oldObj []*v1.EgressRule, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.PtrSliceNoNils[v1.EgressRule](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // custom validation + if e := ValidateCustom_EgressPolicy_Rules(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_EgressRule); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.EgressPolicy) []*v1.EgressRule { + return oldObj.Rules + }) + errs = append(errs, fn(fldPath.Child("rules"), obj.Rules, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_EgressPolicyTemplate validates an instance of EgressPolicyTemplate according +// to declarative validation rules in the API schema. +func Validate_EgressPolicyTemplate( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.EgressPolicyTemplate) (errs field.ErrorList) { + + { // field v1.EgressPolicyTemplate.Rules + fn := func( + fldPath *field.Path, + obj, oldObj []*v1.EgressRule, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.PtrSliceNoNils[v1.EgressRule](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // custom validation + if e := ValidateCustom_EgressPolicyTemplate_Rules(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_EgressRule); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.EgressPolicyTemplate) []*v1.EgressRule { + return oldObj.Rules + }) + errs = append(errs, fn(fldPath.Child("rules"), obj.Rules, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_EgressRule_ = validate.NewUnionMembership(validate.NewUnionMember("http"), validate.NewUnionMember("https"), validate.NewUnionMember("tls_passthrough")) + +// Validate_EgressRule validates an instance of EgressRule according +// to declarative validation rules in the API schema. +func Validate_EgressRule( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.EgressRule) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_EgressRule_, + func(obj *v1.EgressRule) bool { + if obj == nil { + return false + } + return obj.Http != nil + }, + func(obj *v1.EgressRule) bool { + if obj == nil { + return false + } + return obj.Https != nil + }, + func(obj *v1.EgressRule) bool { + if obj == nil { + return false + } + return obj.TlsPassthrough != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field v1.EgressRule.Http + fn := func( + fldPath *field.Path, + obj, oldObj *v1.HttpRule, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_HttpRule(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.EgressRule) *v1.HttpRule { + return oldObj.Http + }) + errs = append(errs, fn(fldPath.Child("http"), obj.Http, oldVal, oldObj != nil)...) + } + + { // field v1.EgressRule.Https + fn := func( + fldPath *field.Path, + obj, oldObj *v1.HttpsRule, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_HttpsRule(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.EgressRule) *v1.HttpsRule { + return oldObj.Https + }) + errs = append(errs, fn(fldPath.Child("https"), obj.Https, oldVal, oldObj != nil)...) + } + + { // field v1.EgressRule.TlsPassthrough + fn := func( + fldPath *field.Path, + obj, oldObj *v1.TlsPassthroughRule, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_TlsPassthroughRule(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.EgressRule) *v1.TlsPassthroughRule { + return oldObj.TlsPassthrough + }) + errs = append(errs, fn(fldPath.Child("tls_passthrough"), obj.TlsPassthrough, oldVal, oldObj != nil)...) + } + + return errs +} + +var formatPattern_ate_env_var_name = regexp.MustCompile("(^$|^[ -<>-~]+$)") + +// Validate_EnvVar validates an instance of EnvVar according +// to declarative validation rules in the API schema. +func Validate_EnvVar( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.EnvVar) (errs field.ErrorList) { + + { // field v1.EnvVar.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_env_var_name, "may contain any printable ASCII character except '='", "format=ate-env-var-name"); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.EnvVar) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + { // field v1.EnvVar.Value + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 32768); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.EnvVar) *string { + return &oldObj.Value + }) + errs = append(errs, fn(fldPath.Child("value"), &obj.Value, oldVal, oldObj != nil)...) + } + + return errs +} + +var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_ExternalVolumeSource_ = validate.NewUnionMembership(validate.NewUnionMember("template")) + +// Validate_ExternalVolumeSource validates an instance of ExternalVolumeSource according +// to declarative validation rules in the API schema. +func Validate_ExternalVolumeSource( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ExternalVolumeSource) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_ExternalVolumeSource_, + func(obj *v1.ExternalVolumeSource) bool { + if obj == nil { + return false + } + return obj.Template != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field v1.ExternalVolumeSource.Template + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ExternalVolumeTemplate, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // call the type's validation function + errs = append(errs, Validate_ExternalVolumeTemplate(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ExternalVolumeSource) *v1.ExternalVolumeTemplate { + return oldObj.Template + }) + errs = append(errs, fn(fldPath.Child("template"), obj.Template, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_ExternalVolumeTemplate validates an instance of ExternalVolumeTemplate according +// to declarative validation rules in the API schema. +func Validate_ExternalVolumeTemplate( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ExternalVolumeTemplate) (errs field.ErrorList) { + + { // field v1.ExternalVolumeTemplate.CapacityBytes + fn := func( + fldPath *field.Path, + obj, oldObj *int64, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ExternalVolumeTemplate) *int64 { + return &oldObj.CapacityBytes + }) + errs = append(errs, fn(fldPath.Child("capacity_bytes"), &obj.CapacityBytes, oldVal, oldObj != nil)...) + } + + { // field v1.ExternalVolumeTemplate.StorageClassName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ExternalVolumeTemplate) *string { + return &oldObj.StorageClassName + }) + errs = append(errs, fn(fldPath.Child("storage_class_name"), &obj.StorageClassName, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_ExternalVolumes validates an instance of ExternalVolumes according +// to declarative validation rules in the API schema. +func Validate_ExternalVolumes( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ExternalVolumes) (errs field.ErrorList) { + + { // field v1.ExternalVolumes.Volumes + fn := func( + fldPath *field.Path, + obj, oldObj []*v1.ActorExternalVolumeStatus, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.PtrSliceNoNils[v1.ActorExternalVolumeStatus](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // lists with map semantics require unique keys + if e := validate.PtrSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *v1.ActorExternalVolumeStatus, b *v1.ActorExternalVolumeStatus) bool { return a.Name == b.Name }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *v1.ActorExternalVolumeStatus, b *v1.ActorExternalVolumeStatus) bool { return a.Name == b.Name }, ateDeepEqual, Validate_ActorExternalVolumeStatus); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.ExternalVolumes) []*v1.ActorExternalVolumeStatus { + return oldObj.Volumes + }) + errs = append(errs, fn(fldPath.Child("volumes"), obj.Volumes, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_FormEntry validates an instance of FormEntry according +// to declarative validation rules in the API schema. +func Validate_FormEntry( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.FormEntry) (errs field.ErrorList) { + + { // field v1.FormEntry.Key + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 128); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.FormEntry) *string { + return &oldObj.Key + }) + errs = append(errs, fn(fldPath.Child("key"), &obj.Key, oldVal, oldObj != nil)...) + } + + { // field v1.FormEntry.Value + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 2048); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.FormEntry) *string { + return &oldObj.Value + }) + errs = append(errs, fn(fldPath.Child("value"), &obj.Value, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_GetActorEgressPolicyRequest validates an instance of GetActorEgressPolicyRequest according +// to declarative validation rules in the API schema. +func Validate_GetActorEgressPolicyRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GetActorEgressPolicyRequest) (errs field.ErrorList) { + + { // field v1.GetActorEgressPolicyRequest.Actor + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.GetActorEgressPolicyRequest) *v1.ObjectRef { + return oldObj.Actor + }) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + } + + { // field v1.GetActorEgressPolicyRequest.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.GetActorEgressPolicyRequest) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_GetActorRequest validates an instance of GetActorRequest according +// to declarative validation rules in the API schema. +func Validate_GetActorRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GetActorRequest) (errs field.ErrorList) { + + { // field v1.GetActorRequest.Actor + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.GetActorRequest) *v1.ObjectRef { + return oldObj.Actor + }) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_GetActorTemplateRequest validates an instance of GetActorTemplateRequest according +// to declarative validation rules in the API schema. +func Validate_GetActorTemplateRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GetActorTemplateRequest) (errs field.ErrorList) { + + { // field v1.GetActorTemplateRequest.ActorTemplate + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.GetActorTemplateRequest) *v1.ObjectRef { + return oldObj.ActorTemplate + }) + errs = append(errs, fn(fldPath.Child("actor_template"), obj.ActorTemplate, oldVal, oldObj != nil)...) } return errs } -// Validate_EgressPolicyTemplate validates an instance of EgressPolicyTemplate according +// Validate_GetAtespaceAccessPolicyRequest validates an instance of GetAtespaceAccessPolicyRequest according // to declarative validation rules in the API schema. -func Validate_EgressPolicyTemplate( +func Validate_GetAtespaceAccessPolicyRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.EgressPolicyTemplate) (errs field.ErrorList) { + obj, oldObj *v1.GetAtespaceAccessPolicyRequest) (errs field.ErrorList) { - { // field v1.EgressPolicyTemplate.Rules + { // field v1.GetAtespaceAccessPolicyRequest.Atespace fn := func( fldPath *field.Path, - obj, oldObj []*v1.EgressRule, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -3664,75 +5011,203 @@ func Validate_EgressPolicyTemplate( } // call field-attached validations earlyReturn := false - if e := validate.PtrSliceNoNils[v1.EgressRule](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true + if earlyReturn { + return // do not proceed } - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.GetAtespaceAccessPolicyRequest) *v1.ObjectRef { + return oldObj.Atespace + }) + errs = append(errs, fn(fldPath.Child("atespace"), obj.Atespace, oldVal, oldObj != nil)...) + } + + { // field v1.GetAtespaceAccessPolicyRequest.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_EgressPolicyTemplate_Rules(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name"); len(e) != 0 { errs = append(errs, e...) } - // iterate the list and call the type's validation function - if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_EgressRule); len(e) != 0 { + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.GetAtespaceAccessPolicyRequest) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_GetAtespaceRequest validates an instance of GetAtespaceRequest according +// to declarative validation rules in the API schema. +func Validate_GetAtespaceRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GetAtespaceRequest) (errs field.ErrorList) { + + { // field v1.GetAtespaceRequest.Atespace + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) + earlyReturn = true } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.EgressPolicyTemplate) []*v1.EgressRule { - return oldObj.Rules + func(oldObj *v1.GetAtespaceRequest) *v1.ObjectRef { + return oldObj.Atespace }) - errs = append(errs, fn(fldPath.Child("rules"), obj.Rules, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("atespace"), obj.Atespace, oldVal, oldObj != nil)...) } return errs } -var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_EgressRule_ = validate.NewUnionMembership(validate.NewUnionMember("http"), validate.NewUnionMember("https"), validate.NewUnionMember("tls_passthrough")) - -// Validate_EgressRule validates an instance of EgressRule according +// Validate_GetCsiDriverRequest validates an instance of GetCsiDriverRequest according // to declarative validation rules in the API schema. -func Validate_EgressRule( +func Validate_GetCsiDriverRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.EgressRule) (errs field.ErrorList) { + obj, oldObj *v1.GetCsiDriverRequest) (errs field.ErrorList) { - if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_EgressRule_, - func(obj *v1.EgressRule) bool { - if obj == nil { - return false + { // field v1.GetCsiDriverRequest.CsiDriver + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } } - return obj.Http != nil - }, - func(obj *v1.EgressRule) bool { - if obj == nil { - return false + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true } - return obj.Https != nil - }, - func(obj *v1.EgressRule) bool { - if obj == nil { - return false + if earlyReturn { + return // do not proceed } - return obj.TlsPassthrough != nil - }); len(e) != 0 { - errs = append(errs, e...) + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.GetCsiDriverRequest) *v1.ObjectRef { + return oldObj.CsiDriver + }) + errs = append(errs, fn(fldPath.Child("csi_driver"), obj.CsiDriver, oldVal, oldObj != nil)...) } - { // field v1.EgressRule.Http + return errs +} + +// Validate_GetExternalVolumeRequest validates an instance of GetExternalVolumeRequest according +// to declarative validation rules in the API schema. +func Validate_GetExternalVolumeRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GetExternalVolumeRequest) (errs field.ErrorList) { + + { // field v1.GetExternalVolumeRequest.ExternalVolume fn := func( fldPath *field.Path, - obj, oldObj *v1.HttpRule, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -3742,27 +5217,92 @@ func Validate_EgressRule( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function - errs = append(errs, Validate_HttpRule(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.EgressRule) *v1.HttpRule { - return oldObj.Http + func(oldObj *v1.GetExternalVolumeRequest) *v1.ObjectRef { + return oldObj.ExternalVolume }) - errs = append(errs, fn(fldPath.Child("http"), obj.Http, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("external_volume"), obj.ExternalVolume, oldVal, oldObj != nil)...) } - { // field v1.EgressRule.Https + return errs +} + +// Validate_GetGlobalAccessPolicyRequest validates an instance of GetGlobalAccessPolicyRequest according +// to declarative validation rules in the API schema. +func Validate_GetGlobalAccessPolicyRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GetGlobalAccessPolicyRequest) (errs field.ErrorList) { + + { // field v1.GetGlobalAccessPolicyRequest.Name + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.GetGlobalAccessPolicyRequest) *string { + return &oldObj.Name + }) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_GetTagRequest validates an instance of GetTagRequest according +// to declarative validation rules in the API schema. +func Validate_GetTagRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GetTagRequest) (errs field.ErrorList) { + + { // field v1.GetTagRequest.Tag fn := func( fldPath *field.Path, - obj, oldObj *v1.HttpsRule, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -3772,27 +5312,51 @@ func Validate_EgressRule( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function - errs = append(errs, Validate_HttpsRule(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.EgressRule) *v1.HttpsRule { - return oldObj.Https + func(oldObj *v1.GetTagRequest) *v1.ObjectRef { + return oldObj.Tag }) - errs = append(errs, fn(fldPath.Child("https"), obj.Https, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("tag"), obj.Tag, oldVal, oldObj != nil)...) } - { // field v1.EgressRule.TlsPassthrough + return errs +} + +// Validate_GetWorkerRequest validates an instance of GetWorkerRequest according +// to declarative validation rules in the API schema. +func Validate_GetWorkerRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GetWorkerRequest) (errs field.ErrorList) { + + { // field v1.GetWorkerRequest.Worker fn := func( fldPath *field.Path, - obj, oldObj *v1.TlsPassthroughRule, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -3802,36 +5366,55 @@ func Validate_EgressRule( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function - errs = append(errs, Validate_TlsPassthroughRule(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.EgressRule) *v1.TlsPassthroughRule { - return oldObj.TlsPassthrough + func(oldObj *v1.GetWorkerRequest) *v1.ObjectRef { + return oldObj.Worker }) - errs = append(errs, fn(fldPath.Child("tls_passthrough"), obj.TlsPassthrough, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } return errs } -// Validate_EnvVar validates an instance of EnvVar according +// Validate_GoldenSnapshotConfig validates an instance of GoldenSnapshotConfig according // to declarative validation rules in the API schema. -func Validate_EnvVar( +func Validate_GoldenSnapshotConfig( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.EnvVar) (errs field.ErrorList) { + obj, oldObj *v1.GoldenSnapshotConfig) (errs field.ErrorList) { - { // field v1.EnvVar.Name + { // field v1.GoldenSnapshotConfig.Mode fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.GoldenSnapshotMode, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -3848,78 +5431,78 @@ func Validate_EnvVar( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_EnvVar_Name(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 2); len(e) != 0 { errs = append(errs, e...) } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.EnvVar) *string { - return &oldObj.Name + func(oldObj *v1.GoldenSnapshotConfig) *v1.GoldenSnapshotMode { + return &oldObj.Mode }) - errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("mode"), &obj.Mode, oldVal, oldObj != nil)...) } - { // field v1.EnvVar.Value + return errs +} + +// Validate_GoldenSnapshotStatus validates an instance of GoldenSnapshotStatus according +// to declarative validation rules in the API schema. +func Validate_GoldenSnapshotStatus( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.GoldenSnapshotStatus) (errs field.ErrorList) { + + { // field v1.GoldenSnapshotStatus.GoldenTag fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 32768); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.EnvVar) *string { - return &oldObj.Value + func(oldObj *v1.GoldenSnapshotStatus) *v1.ObjectRef { + return oldObj.GoldenTag }) - errs = append(errs, fn(fldPath.Child("value"), &obj.Value, oldVal, oldObj != nil)...) - } - - return errs -} - -var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_ExternalVolumeSource_ = validate.NewUnionMembership(validate.NewUnionMember("template")) - -// Validate_ExternalVolumeSource validates an instance of ExternalVolumeSource according -// to declarative validation rules in the API schema. -func Validate_ExternalVolumeSource( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ExternalVolumeSource) (errs field.ErrorList) { - - if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_ExternalVolumeSource_, - func(obj *v1.ExternalVolumeSource) bool { - if obj == nil { - return false - } - return obj.Template != nil - }); len(e) != 0 { - errs = append(errs, e...) + errs = append(errs, fn(fldPath.Child("golden_tag"), obj.GoldenTag, oldVal, oldObj != nil)...) } - { // field v1.ExternalVolumeSource.Template + { // field v1.GoldenSnapshotStatus.SnapshotTime fn := func( fldPath *field.Path, - obj, oldObj *v1.ExternalVolumeTemplate, + obj, oldObj *timestamppb.Timestamp, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -3935,27 +5518,16 @@ func Validate_ExternalVolumeSource( if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ExternalVolumeTemplate(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ExternalVolumeSource) *v1.ExternalVolumeTemplate { - return oldObj.Template + func(oldObj *v1.GoldenSnapshotStatus) *timestamppb.Timestamp { + return oldObj.SnapshotTime }) - errs = append(errs, fn(fldPath.Child("template"), obj.Template, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("snapshot_time"), obj.SnapshotTime, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_ExternalVolumeStatus validates an instance of ExternalVolumeStatus according -// to declarative validation rules in the API schema. -func Validate_ExternalVolumeStatus( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ExternalVolumeStatus) (errs field.ErrorList) { - - { // field v1.ExternalVolumeStatus.Name + { // field v1.GoldenSnapshotStatus.ErrorMessage fn := func( fldPath *field.Path, obj, oldObj *string, @@ -3968,31 +5540,36 @@ func Validate_ExternalVolumeStatus( } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.UpdateValue(ctx, op, fldPath, obj, oldObj, - func(a string, b string) bool { return a == b }, validate.NoUnset, validate.NoModify).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 4096); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ExternalVolumeStatus) *string { - return &oldObj.Name + func(oldObj *v1.GoldenSnapshotStatus) *string { + return &oldObj.ErrorMessage }) - errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("error_message"), &obj.ErrorMessage, oldVal, oldObj != nil)...) } - { // field v1.ExternalVolumeStatus.StorageVolumeId + return errs +} + +var formatPattern_ate_http_probe_path = regexp.MustCompile("(^$|^/([A-Za-z0-9\\-._~!$&'\\(\\)*+,;=:@/]|%[0-9A-Fa-f]{2})*$)") + +// Validate_HttpGetAction validates an instance of HttpGetAction according +// to declarative validation rules in the API schema. +func Validate_HttpGetAction( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.HttpGetAction) (errs field.ErrorList) { + + { // field v1.HttpGetAction.Path fn := func( fldPath *field.Path, obj, oldObj *string, @@ -4005,37 +5582,32 @@ func Validate_ExternalVolumeStatus( } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.UpdateValue(ctx, op, fldPath, obj, oldObj, - func(a string, b string) bool { return a == b }, validate.NoUnset, validate.NoModify).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_ExternalVolumeStatus_StorageVolumeId(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_probe_path, "must be a valid HTTP path (RFC 3986)", "format=ate-http-probe-path"); len(e) != 0 { errs = append(errs, e...) } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256); len(e) != 0 { + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 1024); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ExternalVolumeStatus) *string { - return &oldObj.StorageVolumeId + func(oldObj *v1.HttpGetAction) *string { + return &oldObj.Path }) - errs = append(errs, fn(fldPath.Child("storage_volume_id"), &obj.StorageVolumeId, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("path"), &obj.Path, oldVal, oldObj != nil)...) } - { // field v1.ExternalVolumeStatus.VolumeType + { // field v1.HttpGetAction.Port fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *int32, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -4049,34 +5621,37 @@ func Validate_ExternalVolumeStatus( errs = append(errs, e...) earlyReturn = true } - if e := validate.UpdateValue(ctx, op, fldPath, obj, oldObj, - func(a string, b string) bool { return a == b }, validate.NoUnset, validate.NoModify).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_ExternalVolumeStatus_VolumeType(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 65535); len(e) != 0 { errs = append(errs, e...) } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 253); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ExternalVolumeStatus) *string { - return &oldObj.VolumeType + func(oldObj *v1.HttpGetAction) *int32 { + return &oldObj.Port }) - errs = append(errs, fn(fldPath.Child("volume_type"), &obj.VolumeType, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("port"), &obj.Port, oldVal, oldObj != nil)...) } - { // field v1.ExternalVolumeStatus.VolumeContext + return errs +} + +// Validate_HttpRule validates an instance of HttpRule according +// to declarative validation rules in the API schema. +func Validate_HttpRule( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.HttpRule) (errs field.ErrorList) { + + { // field v1.HttpRule.Hostnames fn := func( fldPath *field.Path, - obj, oldObj map[string]string, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -4086,112 +5661,114 @@ func Validate_ExternalVolumeStatus( } // call field-attached validations earlyReturn := false - if e := validate.OptionalMap(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } // custom validation - if e := ValidateCustom_ExternalVolumeStatus_VolumeContext(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := ValidateCustom_HttpRule_Hostnames(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ExternalVolumeStatus) map[string]string { - return oldObj.VolumeContext + func(oldObj *v1.HttpRule) []string { + return oldObj.Hostnames }) - errs = append(errs, fn(fldPath.Child("volume_context"), obj.VolumeContext, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("hostnames"), obj.Hostnames, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_ExternalVolumeTemplate validates an instance of ExternalVolumeTemplate according -// to declarative validation rules in the API schema. -func Validate_ExternalVolumeTemplate( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ExternalVolumeTemplate) (errs field.ErrorList) { - - { // field v1.ExternalVolumeTemplate.CapacityBytes + { // field v1.HttpRule.Ports fn := func( fldPath *field.Path, - obj, oldObj *int64, + obj, oldObj *v1.Ports, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_Ports(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ExternalVolumeTemplate) *int64 { - return &oldObj.CapacityBytes + func(oldObj *v1.HttpRule) *v1.Ports { + return oldObj.Ports }) - errs = append(errs, fn(fldPath.Child("capacity_bytes"), &obj.CapacityBytes, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("ports"), obj.Ports, oldVal, oldObj != nil)...) } - { // field v1.ExternalVolumeTemplate.StorageClassName + { // field v1.HttpRule.Effects fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.HttpRuleEffects, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_HttpRuleEffects(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ExternalVolumeTemplate) *string { - return &oldObj.StorageClassName + func(oldObj *v1.HttpRule) *v1.HttpRuleEffects { + return oldObj.Effects }) - errs = append(errs, fn(fldPath.Child("storage_class_name"), &obj.StorageClassName, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("effects"), obj.Effects, oldVal, oldObj != nil)...) } return errs } -// Validate_ExternalVolumes validates an instance of ExternalVolumes according +// Validate_HttpRuleEffects validates an instance of HttpRuleEffects according // to declarative validation rules in the API schema. -func Validate_ExternalVolumes( +func Validate_HttpRuleEffects( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ExternalVolumes) (errs field.ErrorList) { + obj, oldObj *v1.HttpRuleEffects) (errs field.ErrorList) { - { // field v1.ExternalVolumes.Volumes + // custom validation + if e := ValidateCustom_HttpRuleEffects(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + + { // field v1.HttpRuleEffects.ReplaceHeaders fn := func( fldPath *field.Path, - obj, oldObj []*v1.ExternalVolumeStatus, + obj, oldObj []*v1.CredentialHeader, oldValueCorrelated bool) (errs field.ErrorList) { + // Uniqueness validation is implemented via custom, handwritten validation // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { if ateDeepEqual(obj, oldObj) { @@ -4200,11 +5777,11 @@ func Validate_ExternalVolumes( } // call field-attached validations earlyReturn := false - if e := validate.PtrSliceNoNils[v1.ExternalVolumeStatus](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.PtrSliceNoNils[v1.CredentialHeader](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 32).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } @@ -4214,38 +5791,37 @@ func Validate_ExternalVolumes( if earlyReturn { return // do not proceed } - // lists with map semantics require unique keys - if e := validate.PtrSliceUnique(ctx, op, fldPath, obj, oldObj, - func(a *v1.ExternalVolumeStatus, b *v1.ExternalVolumeStatus) bool { return a.Name == b.Name }); len(e) != 0 { + // custom validation + if e := ValidateCustom_HttpRuleEffects_ReplaceHeaders(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } // iterate the list and call the type's validation function if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, - func(a *v1.ExternalVolumeStatus, b *v1.ExternalVolumeStatus) bool { return a.Name == b.Name }, ateDeepEqual, Validate_ExternalVolumeStatus); len(e) != 0 { + func(a *v1.CredentialHeader, b *v1.CredentialHeader) bool { return a.Header == b.Header }, ateDeepEqual, Validate_CredentialHeader); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ExternalVolumes) []*v1.ExternalVolumeStatus { - return oldObj.Volumes + func(oldObj *v1.HttpRuleEffects) []*v1.CredentialHeader { + return oldObj.ReplaceHeaders }) - errs = append(errs, fn(fldPath.Child("volumes"), obj.Volumes, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("replace_headers"), obj.ReplaceHeaders, oldVal, oldObj != nil)...) } return errs } -// Validate_GetActorEgressPolicyRequest validates an instance of GetActorEgressPolicyRequest according +// Validate_HttpsRule validates an instance of HttpsRule according // to declarative validation rules in the API schema. -func Validate_GetActorEgressPolicyRequest( +func Validate_HttpsRule( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GetActorEgressPolicyRequest) (errs field.ErrorList) { + obj, oldObj *v1.HttpsRule) (errs field.ErrorList) { - { // field v1.GetActorEgressPolicyRequest.Actor + { // field v1.HttpsRule.Hostnames fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -4255,88 +5831,68 @@ func Validate_GetActorEgressPolicyRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + // custom validation + if e := ValidateCustom_HttpsRule_Hostnames(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetActorEgressPolicyRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.HttpsRule) []string { + return oldObj.Hostnames }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("hostnames"), obj.Hostnames, oldVal, oldObj != nil)...) } - { // field v1.GetActorEgressPolicyRequest.Name + { // field v1.HttpsRule.Ports fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.Ports, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_GetActorEgressPolicyRequest_Name(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_Ports(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetActorEgressPolicyRequest) *string { - return &oldObj.Name + func(oldObj *v1.HttpsRule) *v1.Ports { + return oldObj.Ports }) - errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("ports"), obj.Ports, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_GetActorRequest validates an instance of GetActorRequest according -// to declarative validation rules in the API schema. -func Validate_GetActorRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GetActorRequest) (errs field.ErrorList) { - - { // field v1.GetActorRequest.Actor + { // field v1.HttpsRule.Effects fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.HttpRuleEffects, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -4346,306 +5902,221 @@ func Validate_GetActorRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_HttpRuleEffects(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetActorRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.HttpsRule) *v1.HttpRuleEffects { + return oldObj.Effects }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("effects"), obj.Effects, oldVal, oldObj != nil)...) } return errs } -// Validate_GetActorTemplateRequest validates an instance of GetActorTemplateRequest according +// Validate_ImageVolumeSource validates an instance of ImageVolumeSource according // to declarative validation rules in the API schema. -func Validate_GetActorTemplateRequest( +func Validate_ImageVolumeSource( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GetActorTemplateRequest) (errs field.ErrorList) { + obj, oldObj *v1.ImageVolumeSource) (errs field.ErrorList) { - { // field v1.GetActorTemplateRequest.ActorTemplate + { // field v1.ImageVolumeSource.Reference fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + // custom validation + if e := ValidateCustom_ImageVolumeSource_Reference(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 512); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetActorTemplateRequest) *v1.ObjectRef { - return oldObj.ActorTemplate + func(oldObj *v1.ImageVolumeSource) *string { + return &oldObj.Reference }) - errs = append(errs, fn(fldPath.Child("actor_template"), obj.ActorTemplate, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("reference"), &obj.Reference, oldVal, oldObj != nil)...) } return errs } -// Validate_GetAtespaceAccessPolicyRequest validates an instance of GetAtespaceAccessPolicyRequest according +// Validate_ListActorTemplatesRequest validates an instance of ListActorTemplatesRequest according // to declarative validation rules in the API schema. -func Validate_GetAtespaceAccessPolicyRequest( +func Validate_ListActorTemplatesRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GetAtespaceAccessPolicyRequest) (errs field.ErrorList) { + obj, oldObj *v1.ListActorTemplatesRequest) (errs field.ErrorList) { - { // field v1.GetAtespaceAccessPolicyRequest.Atespace + { // field v1.ListActorTemplatesRequest.Atespace fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetAtespaceAccessPolicyRequest) *v1.ObjectRef { - return oldObj.Atespace + func(oldObj *v1.ListActorTemplatesRequest) *string { + return &oldObj.Atespace }) - errs = append(errs, fn(fldPath.Child("atespace"), obj.Atespace, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) } - { // field v1.GetAtespaceAccessPolicyRequest.Name + { // field v1.ListActorTemplatesRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.ListOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_GetAtespaceAccessPolicyRequest_Name(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetAtespaceAccessPolicyRequest) *string { - return &oldObj.Name + func(oldObj *v1.ListActorTemplatesRequest) *v1.ListOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } return errs } -// Validate_GetAtespaceRequest validates an instance of GetAtespaceRequest according +// Validate_ListActorsRequest validates an instance of ListActorsRequest according // to declarative validation rules in the API schema. -func Validate_GetAtespaceRequest( +func Validate_ListActorsRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GetAtespaceRequest) (errs field.ErrorList) { + obj, oldObj *v1.ListActorsRequest) (errs field.ErrorList) { - { // field v1.GetAtespaceRequest.Atespace + { // field v1.ListActorsRequest.Atespace fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetAtespaceRequest) *v1.ObjectRef { - return oldObj.Atespace + func(oldObj *v1.ListActorsRequest) *string { + return &oldObj.Atespace }) - errs = append(errs, fn(fldPath.Child("atespace"), obj.Atespace, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_GetGlobalAccessPolicyRequest validates an instance of GetGlobalAccessPolicyRequest according -// to declarative validation rules in the API schema. -func Validate_GetGlobalAccessPolicyRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GetGlobalAccessPolicyRequest) (errs field.ErrorList) { - - { // field v1.GetGlobalAccessPolicyRequest.Name + { // field v1.ListActorsRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.ListOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_GetGlobalAccessPolicyRequest_Name(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetGlobalAccessPolicyRequest) *string { - return &oldObj.Name + func(oldObj *v1.ListActorsRequest) *v1.ListOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } return errs } -// Validate_GetTagRequest validates an instance of GetTagRequest according +// Validate_ListAtespacesRequest validates an instance of ListAtespacesRequest according // to declarative validation rules in the API schema. -func Validate_GetTagRequest( +func Validate_ListAtespacesRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GetTagRequest) (errs field.ErrorList) { + obj, oldObj *v1.ListAtespacesRequest) (errs field.ErrorList) { - { // field v1.GetTagRequest.Tag + { // field v1.ListAtespacesRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.ListOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -4655,52 +6126,36 @@ func Validate_GetTagRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetTagRequest) *v1.ObjectRef { - return oldObj.Tag + func(oldObj *v1.ListAtespacesRequest) *v1.ListOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("tag"), obj.Tag, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } return errs } -// Validate_GetWorkerRequest validates an instance of GetWorkerRequest according +// Validate_ListCsiDriversRequest validates an instance of ListCsiDriversRequest according // to declarative validation rules in the API schema. -func Validate_GetWorkerRequest( +func Validate_ListCsiDriversRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GetWorkerRequest) (errs field.ErrorList) { + obj, oldObj *v1.ListCsiDriversRequest) (errs field.ErrorList) { - { // field v1.GetWorkerRequest.Worker + { // field v1.ListCsiDriversRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.ListOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -4710,56 +6165,36 @@ func Validate_GetWorkerRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GetWorkerRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.ListCsiDriversRequest) *v1.ListOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } return errs } -// Validate_GoldenSnapshotConfig validates an instance of GoldenSnapshotConfig according +// Validate_ListExternalVolumesRequest validates an instance of ListExternalVolumesRequest according // to declarative validation rules in the API schema. -func Validate_GoldenSnapshotConfig( +func Validate_ListExternalVolumesRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GoldenSnapshotConfig) (errs field.ErrorList) { + obj, oldObj *v1.ListExternalVolumesRequest) (errs field.ErrorList) { - { // field v1.GoldenSnapshotConfig.Mode + { // field v1.ListExternalVolumesRequest.Atespace fn := func( fldPath *field.Path, - obj, oldObj *v1.GoldenSnapshotMode, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -4769,41 +6204,28 @@ func Validate_GoldenSnapshotConfig( } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 2); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GoldenSnapshotConfig) *v1.GoldenSnapshotMode { - return &oldObj.Mode + func(oldObj *v1.ListExternalVolumesRequest) *string { + return &oldObj.Atespace }) - errs = append(errs, fn(fldPath.Child("mode"), &obj.Mode, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_GoldenSnapshotStatus validates an instance of GoldenSnapshotStatus according -// to declarative validation rules in the API schema. -func Validate_GoldenSnapshotStatus( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.GoldenSnapshotStatus) (errs field.ErrorList) { - - { // field v1.GoldenSnapshotStatus.GoldenTag + { // field v1.ListExternalVolumesRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.ListOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -4819,61 +6241,58 @@ func Validate_GoldenSnapshotStatus( if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GoldenSnapshotStatus) *v1.ObjectRef { - return oldObj.GoldenTag + func(oldObj *v1.ListExternalVolumesRequest) *v1.ListOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("golden_tag"), obj.GoldenTag, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } - { // field v1.GoldenSnapshotStatus.SnapshotTime + return errs +} + +// Validate_ListOptions validates an instance of ListOptions according +// to declarative validation rules in the API schema. +func Validate_ListOptions( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ListOptions) (errs field.ErrorList) { + + { // field v1.ListOptions.PageSize fn := func( fldPath *field.Path, - obj, oldObj *timestamppb.Timestamp, + obj, oldObj *int32, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GoldenSnapshotStatus) *timestamppb.Timestamp { - return oldObj.SnapshotTime + func(oldObj *v1.ListOptions) *int32 { + return &oldObj.PageSize }) - errs = append(errs, fn(fldPath.Child("snapshot_time"), obj.SnapshotTime, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("page_size"), &obj.PageSize, oldVal, oldObj != nil)...) } - { // field v1.GoldenSnapshotStatus.ErrorMessage + { // field v1.ListOptions.PageToken fn := func( fldPath *field.Path, obj, oldObj *string, @@ -4892,28 +6311,28 @@ func Validate_GoldenSnapshotStatus( if earlyReturn { return // do not proceed } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 4096); len(e) != 0 { + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.GoldenSnapshotStatus) *string { - return &oldObj.ErrorMessage + func(oldObj *v1.ListOptions) *string { + return &oldObj.PageToken }) - errs = append(errs, fn(fldPath.Child("error_message"), &obj.ErrorMessage, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("page_token"), &obj.PageToken, oldVal, oldObj != nil)...) } return errs } -// Validate_HttpGetAction validates an instance of HttpGetAction according +// Validate_ListTagsRequest validates an instance of ListTagsRequest according // to declarative validation rules in the API schema. -func Validate_HttpGetAction( +func Validate_ListTagsRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.HttpGetAction) (errs field.ErrorList) { + obj, oldObj *v1.ListTagsRequest) (errs field.ErrorList) { - { // field v1.HttpGetAction.Path + { // field v1.ListTagsRequest.Atespace fn := func( fldPath *field.Path, obj, oldObj *string, @@ -4926,77 +6345,67 @@ func Validate_HttpGetAction( } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_HttpGetAction_Path(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 1024); len(e) != 0 { + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpGetAction) *string { - return &oldObj.Path + func(oldObj *v1.ListTagsRequest) *string { + return &oldObj.Atespace }) - errs = append(errs, fn(fldPath.Child("path"), &obj.Path, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) } - { // field v1.HttpGetAction.Port + { // field v1.ListTagsRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *int32, + obj, oldObj *v1.ListOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 65535); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpGetAction) *int32 { - return &oldObj.Port + func(oldObj *v1.ListTagsRequest) *v1.ListOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("port"), &obj.Port, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } return errs } -// Validate_HttpRule validates an instance of HttpRule according +// Validate_ListWorkerActorAssignmentsRequest validates an instance of ListWorkerActorAssignmentsRequest according // to declarative validation rules in the API schema. -func Validate_HttpRule( +func Validate_ListWorkerActorAssignmentsRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.HttpRule) (errs field.ErrorList) { + obj, oldObj *v1.ListWorkerActorAssignmentsRequest) (errs field.ErrorList) { - { // field v1.HttpRule.Hostnames + { // field v1.ListWorkerActorAssignmentsRequest.Worker fn := func( fldPath *field.Path, - obj, oldObj []string, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5006,38 +6415,46 @@ func Validate_HttpRule( } // call field-attached validations earlyReturn := false - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_HttpRule_Hostnames(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - // lists with set semantics require unique values - if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpRule) []string { - return oldObj.Hostnames + func(oldObj *v1.ListWorkerActorAssignmentsRequest) *v1.ObjectRef { + return oldObj.Worker }) - errs = append(errs, fn(fldPath.Child("hostnames"), obj.Hostnames, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } - { // field v1.HttpRule.Ports + { // field v1.ListWorkerActorAssignmentsRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *v1.Ports, + obj, oldObj *v1.ListOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5054,20 +6471,29 @@ func Validate_HttpRule( return // do not proceed } // call the type's validation function - errs = append(errs, Validate_Ports(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpRule) *v1.Ports { - return oldObj.Ports + func(oldObj *v1.ListWorkerActorAssignmentsRequest) *v1.ListOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("ports"), obj.Ports, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } - { // field v1.HttpRule.Effects + return errs +} + +// Validate_ListWorkersRequest validates an instance of ListWorkersRequest according +// to declarative validation rules in the API schema. +func Validate_ListWorkersRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ListWorkersRequest) (errs field.ErrorList) { + + { // field v1.ListWorkersRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *v1.HttpRuleEffects, + obj, oldObj *v1.ListOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5084,36 +6510,30 @@ func Validate_HttpRule( return // do not proceed } // call the type's validation function - errs = append(errs, Validate_HttpRuleEffects(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpRule) *v1.HttpRuleEffects { - return oldObj.Effects + func(oldObj *v1.ListWorkersRequest) *v1.ListOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("effects"), obj.Effects, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } return errs } -// Validate_HttpRuleEffects validates an instance of HttpRuleEffects according +// Validate_MarkWorkerAvailableRequest validates an instance of MarkWorkerAvailableRequest according // to declarative validation rules in the API schema. -func Validate_HttpRuleEffects( +func Validate_MarkWorkerAvailableRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.HttpRuleEffects) (errs field.ErrorList) { - - // custom validation - if e := ValidateCustom_HttpRuleEffects(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + obj, oldObj *v1.MarkWorkerAvailableRequest) (errs field.ErrorList) { - { // field v1.HttpRuleEffects.ReplaceHeaders + { // field v1.MarkWorkerAvailableRequest.Worker fn := func( fldPath *field.Path, - obj, oldObj []*v1.CredentialHeader, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { - // Uniqueness validation is implemented via custom, handwritten validation // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { if ateDeepEqual(obj, oldObj) { @@ -5122,51 +6542,55 @@ func Validate_HttpRuleEffects( } // call field-attached validations earlyReturn := false - if e := validate.PtrSliceNoNils[v1.CredentialHeader](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_HttpRuleEffects_ReplaceHeaders(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - // iterate the list and call the type's validation function - if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, - func(a *v1.CredentialHeader, b *v1.CredentialHeader) bool { return a.Header == b.Header }, ateDeepEqual, Validate_CredentialHeader); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpRuleEffects) []*v1.CredentialHeader { - return oldObj.ReplaceHeaders + func(oldObj *v1.MarkWorkerAvailableRequest) *v1.ObjectRef { + return oldObj.Worker }) - errs = append(errs, fn(fldPath.Child("replace_headers"), obj.ReplaceHeaders, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } return errs } -// Validate_HttpsRule validates an instance of HttpsRule according +// Validate_MarkWorkerUnavailableRequest validates an instance of MarkWorkerUnavailableRequest according // to declarative validation rules in the API schema. -func Validate_HttpsRule( +func Validate_MarkWorkerUnavailableRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.HttpsRule) (errs field.ErrorList) { + obj, oldObj *v1.MarkWorkerUnavailableRequest) (errs field.ErrorList) { - { // field v1.HttpsRule.Hostnames + { // field v1.MarkWorkerUnavailableRequest.Worker fn := func( fldPath *field.Path, - obj, oldObj []string, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5176,38 +6600,55 @@ func Validate_HttpsRule( } // call field-attached validations earlyReturn := false - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_HttpsRule_Hostnames(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - // lists with set semantics require unique values - if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpsRule) []string { - return oldObj.Hostnames + func(oldObj *v1.MarkWorkerUnavailableRequest) *v1.ObjectRef { + return oldObj.Worker }) - errs = append(errs, fn(fldPath.Child("hostnames"), obj.Hostnames, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } - { // field v1.HttpsRule.Ports + return errs +} + +// Validate_MintActorJwtRequest validates an instance of MintActorJwtRequest according +// to declarative validation rules in the API schema. +func Validate_MintActorJwtRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.MintActorJwtRequest) (errs field.ErrorList) { + + { // field v1.MintActorJwtRequest.Actor fn := func( fldPath *field.Path, - obj, oldObj *v1.Ports, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5217,27 +6658,28 @@ func Validate_HttpsRule( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } // call the type's validation function - errs = append(errs, Validate_Ports(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpsRule) *v1.Ports { - return oldObj.Ports + func(oldObj *v1.MintActorJwtRequest) *v1.ObjectRef { + return oldObj.Actor }) - errs = append(errs, fn(fldPath.Child("ports"), obj.Ports, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - { // field v1.HttpsRule.Effects + { // field v1.MintActorJwtRequest.Audiences fn := func( fldPath *field.Path, - obj, oldObj *v1.HttpRuleEffects, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5247,36 +6689,40 @@ func Validate_HttpsRule( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_HttpRuleEffects(ctx, op, fldPath, obj, oldObj)...) + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MaxLength(ctx, op, fldPath, obj, oldObj, 512) + }); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.HttpsRule) *v1.HttpRuleEffects { - return oldObj.Effects + func(oldObj *v1.MintActorJwtRequest) []string { + return oldObj.Audiences }) - errs = append(errs, fn(fldPath.Child("effects"), obj.Effects, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("audiences"), obj.Audiences, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_ImageVolumeSource validates an instance of ImageVolumeSource according -// to declarative validation rules in the API schema. -func Validate_ImageVolumeSource( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ImageVolumeSource) (errs field.ErrorList) { - - { // field v1.ImageVolumeSource.Reference + { // field v1.MintActorJwtRequest.ExpirationSeconds fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5293,136 +6739,143 @@ func Validate_ImageVolumeSource( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_ImageVolumeSource_Reference(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 3600); len(e) != 0 { errs = append(errs, e...) } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 512); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 300); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ImageVolumeSource) *string { - return &oldObj.Reference + func(oldObj *v1.MintActorJwtRequest) *int64 { + return &oldObj.ExpirationSeconds }) - errs = append(errs, fn(fldPath.Child("reference"), &obj.Reference, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("expiration_seconds"), &obj.ExpirationSeconds, oldVal, oldObj != nil)...) } return errs } -// Validate_ListActorTemplatesRequest validates an instance of ListActorTemplatesRequest according +// Validate_MintWorkerActorCertificateRequest validates an instance of MintWorkerActorCertificateRequest according // to declarative validation rules in the API schema. -func Validate_ListActorTemplatesRequest( +func Validate_MintWorkerActorCertificateRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ListActorTemplatesRequest) (errs field.ErrorList) { + obj, oldObj *v1.MintWorkerActorCertificateRequest) (errs field.ErrorList) { - { // field v1.ListActorTemplatesRequest.Atespace + { // field v1.MintWorkerActorCertificateRequest.Actor fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListActorTemplatesRequest) *string { - return &oldObj.Atespace + func(oldObj *v1.MintWorkerActorCertificateRequest) *v1.ObjectRef { + return oldObj.Actor }) - errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - { // field v1.ListActorTemplatesRequest.Options + { // field v1.MintWorkerActorCertificateRequest.ActorUid fn := func( fldPath *field.Path, - obj, oldObj *v1.ListOptions, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListActorTemplatesRequest) *v1.ListOptions { - return oldObj.Options + func(oldObj *v1.MintWorkerActorCertificateRequest) *string { + return &oldObj.ActorUid }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor_uid"), &obj.ActorUid, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_ListActorsRequest validates an instance of ListActorsRequest according -// to declarative validation rules in the API schema. -func Validate_ListActorsRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ListActorsRequest) (errs field.ErrorList) { - - { // field v1.ListActorsRequest.Atespace + { // field v1.MintWorkerActorCertificateRequest.CertificateSigningRequest fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj []byte, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.MaxBytesSlice(ctx, op, fldPath, obj, oldObj, 16384); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListActorsRequest) *string { - return &oldObj.Atespace + func(oldObj *v1.MintWorkerActorCertificateRequest) []byte { + return oldObj.CertificateSigningRequest }) - errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("certificate_signing_request"), obj.CertificateSigningRequest, oldVal, oldObj != nil)...) } - { // field v1.ListActorsRequest.Options + { // field v1.MintWorkerActorCertificateRequest.Worker fn := func( fldPath *field.Path, - obj, oldObj *v1.ListOptions, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5432,36 +6885,55 @@ func Validate_ListActorsRequest( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function - errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListActorsRequest) *v1.ListOptions { - return oldObj.Options + func(oldObj *v1.MintWorkerActorCertificateRequest) *v1.ObjectRef { + return oldObj.Worker }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } return errs } -// Validate_ListAtespacesRequest validates an instance of ListAtespacesRequest according +// Validate_MintWorkerActorJwtRequest validates an instance of MintWorkerActorJwtRequest according // to declarative validation rules in the API schema. -func Validate_ListAtespacesRequest( +func Validate_MintWorkerActorJwtRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ListAtespacesRequest) (errs field.ErrorList) { + obj, oldObj *v1.MintWorkerActorJwtRequest) (errs field.ErrorList) { - { // field v1.ListAtespacesRequest.Options + { // field v1.MintWorkerActorJwtRequest.Actor fn := func( fldPath *field.Path, - obj, oldObj *v1.ListOptions, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5471,36 +6943,42 @@ func Validate_ListAtespacesRequest( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function - errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListAtespacesRequest) *v1.ListOptions { - return oldObj.Options + func(oldObj *v1.MintWorkerActorJwtRequest) *v1.ObjectRef { + return oldObj.Actor }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_ListOptions validates an instance of ListOptions according -// to declarative validation rules in the API schema. -func Validate_ListOptions( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ListOptions) (errs field.ErrorList) { - - { // field v1.ListOptions.PageSize + { // field v1.MintWorkerActorJwtRequest.ActorUid fn := func( fldPath *field.Path, - obj, oldObj *int32, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5510,65 +6988,84 @@ func Validate_ListOptions( } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListOptions) *int32 { - return &oldObj.PageSize + func(oldObj *v1.MintWorkerActorJwtRequest) *string { + return &oldObj.ActorUid }) - errs = append(errs, fn(fldPath.Child("page_size"), &obj.PageSize, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor_uid"), &obj.ActorUid, oldVal, oldObj != nil)...) } - { // field v1.ListOptions.PageToken + { // field v1.MintWorkerActorJwtRequest.Audiences fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256); len(e) != 0 { + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MinLength(ctx, op, fldPath, obj, oldObj, 1) + }); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MaxLength(ctx, op, fldPath, obj, oldObj, 512) + }); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListOptions) *string { - return &oldObj.PageToken + func(oldObj *v1.MintWorkerActorJwtRequest) []string { + return oldObj.Audiences }) - errs = append(errs, fn(fldPath.Child("page_token"), &obj.PageToken, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("audiences"), obj.Audiences, oldVal, oldObj != nil)...) } return errs } -// Validate_ListTagsRequest validates an instance of ListTagsRequest according +// Validate_ObjectRef validates an instance of ObjectRef according // to declarative validation rules in the API schema. -func Validate_ListTagsRequest( +func Validate_ObjectRef( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ListTagsRequest) (errs field.ErrorList) { + obj, oldObj *v1.ObjectRef) (errs field.ErrorList) { - { // field v1.ListTagsRequest.Atespace + { // field v1.ObjectRef.Atespace fn := func( fldPath *field.Path, obj, oldObj *string, @@ -5593,105 +7090,116 @@ func Validate_ListTagsRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListTagsRequest) *string { + func(oldObj *v1.ObjectRef) *string { return &oldObj.Atespace }) errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) } - { // field v1.ListTagsRequest.Options + { // field v1.ObjectRef.Name fn := func( fldPath *field.Path, - obj, oldObj *v1.ListOptions, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListTagsRequest) *v1.ListOptions { - return oldObj.Options + func(oldObj *v1.ObjectRef) *string { + return &oldObj.Name }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) } return errs } -// Validate_ListWorkerActorAssignmentsRequest validates an instance of ListWorkerActorAssignmentsRequest according +// Validate_ObjectSnapshot validates an instance of ObjectSnapshot according // to declarative validation rules in the API schema. -func Validate_ListWorkerActorAssignmentsRequest( +func Validate_ObjectSnapshot( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ListWorkerActorAssignmentsRequest) (errs field.ErrorList) { + obj, oldObj *v1.ObjectSnapshot) (errs field.ErrorList) { - { // field v1.ListWorkerActorAssignmentsRequest.Worker + { // field v1.ObjectSnapshot.SnapshotUri fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 2048); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListWorkerActorAssignmentsRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.ObjectSnapshot) *string { + return &oldObj.SnapshotUri }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("snapshot_uri"), &obj.SnapshotUri, oldVal, oldObj != nil)...) } - { // field v1.ListWorkerActorAssignmentsRequest.Options + return errs +} + +var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_Ports_ = validate.NewUnionMembership(validate.NewUnionMember("all"), validate.NewUnionMember("numbers")) + +// Validate_Ports validates an instance of Ports according +// to declarative validation rules in the API schema. +func Validate_Ports( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.Ports) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_Ports_, + func(obj *v1.Ports) bool { + if obj == nil { + return false + } + return obj.All != nil + }, + func(obj *v1.Ports) bool { + if obj == nil { + return false + } + return len(obj.Numbers) != 0 + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field v1.Ports.All fn := func( fldPath *field.Path, - obj, oldObj *v1.ListOptions, + obj, oldObj *v1.AllPorts, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5707,30 +7215,19 @@ func Validate_ListWorkerActorAssignmentsRequest( if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListWorkerActorAssignmentsRequest) *v1.ListOptions { - return oldObj.Options + func(oldObj *v1.Ports) *v1.AllPorts { + return oldObj.All }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("all"), obj.All, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_ListWorkersRequest validates an instance of ListWorkersRequest according -// to declarative validation rules in the API schema. -func Validate_ListWorkersRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ListWorkersRequest) (errs field.ErrorList) { - - { // field v1.ListWorkersRequest.Options + { // field v1.Ports.Numbers fn := func( fldPath *field.Path, - obj, oldObj *v1.ListOptions, + obj, oldObj []int32, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5740,33 +7237,51 @@ func Validate_ListWorkersRequest( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ListOptions(ctx, op, fldPath, obj, oldObj)...) + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *int32) field.ErrorList { + return validate.Minimum(ctx, op, fldPath, obj, oldObj, 1) + }); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *int32) field.ErrorList { + return validate.Maximum(ctx, op, fldPath, obj, oldObj, 65535) + }); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ListWorkersRequest) *v1.ListOptions { - return oldObj.Options + func(oldObj *v1.Ports) []int32 { + return oldObj.Numbers }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("numbers"), obj.Numbers, oldVal, oldObj != nil)...) } return errs } -// Validate_MarkWorkerAvailableRequest validates an instance of MarkWorkerAvailableRequest according +// Validate_RegisterWorkerRequest validates an instance of RegisterWorkerRequest according // to declarative validation rules in the API schema. -func Validate_MarkWorkerAvailableRequest( +func Validate_RegisterWorkerRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.MarkWorkerAvailableRequest) (errs field.ErrorList) { + obj, oldObj *v1.RegisterWorkerRequest) (errs field.ErrorList) { - { // field v1.MarkWorkerAvailableRequest.Worker + { // field v1.RegisterWorkerRequest.Worker fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -5789,16 +7304,15 @@ func Validate_MarkWorkerAvailableRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -5810,84 +7324,48 @@ func Validate_MarkWorkerAvailableRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MarkWorkerAvailableRequest) *v1.ObjectRef { + func(oldObj *v1.RegisterWorkerRequest) *v1.ObjectRef { return oldObj.Worker }) errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_MarkWorkerUnavailableRequest validates an instance of MarkWorkerUnavailableRequest according -// to declarative validation rules in the API schema. -func Validate_MarkWorkerUnavailableRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.MarkWorkerUnavailableRequest) (errs field.ErrorList) { - - { // field v1.MarkWorkerUnavailableRequest.Worker + { // field v1.RegisterWorkerRequest.Epoch fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MarkWorkerUnavailableRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.RegisterWorkerRequest) *int64 { + return &oldObj.Epoch }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("epoch"), &obj.Epoch, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_MintActorJwtRequest validates an instance of MintActorJwtRequest according -// to declarative validation rules in the API schema. -func Validate_MintActorJwtRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.MintActorJwtRequest) (errs field.ErrorList) { - - { // field v1.MintActorJwtRequest.Actor + { // field v1.RegisterWorkerRequest.Ips fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5897,28 +7375,34 @@ func Validate_MintActorJwtRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 2).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + // custom validation + if e := ValidateCustom_RegisterWorkerRequest_Ips(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintActorJwtRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.RegisterWorkerRequest) []string { + return oldObj.Ips }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("ips"), obj.Ips, oldVal, oldObj != nil)...) } - { // field v1.MintActorJwtRequest.Audiences + { // field v1.RegisterWorkerRequest.Capacity fn := func( fldPath *field.Path, - obj, oldObj []string, + obj, oldObj *v1.WorkerResources, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -5928,81 +7412,83 @@ func Validate_MintActorJwtRequest( } // call field-attached validations earlyReturn := false - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, - func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { - return validate.MaxLength(ctx, op, fldPath, obj, oldObj, 512) - }); len(e) != 0 { - errs = append(errs, e...) - } - // lists with set semantics require unique values - if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_WorkerResources(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintActorJwtRequest) []string { - return oldObj.Audiences + func(oldObj *v1.RegisterWorkerRequest) *v1.WorkerResources { + return oldObj.Capacity }) - errs = append(errs, fn(fldPath.Child("audiences"), obj.Audiences, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("capacity"), obj.Capacity, oldVal, oldObj != nil)...) } - { // field v1.MintActorJwtRequest.ExpirationSeconds + return errs +} + +// Validate_ReportActorCrashedRequest validates an instance of ReportActorCrashedRequest according +// to declarative validation rules in the API schema. +func Validate_ReportActorCrashedRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ReportActorCrashedRequest) (errs field.ErrorList) { + + { // field v1.ReportActorCrashedRequest.Worker fn := func( fldPath *field.Path, - obj, oldObj *int64, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 3600); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 300); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintActorJwtRequest) *int64 { - return &oldObj.ExpirationSeconds + func(oldObj *v1.ReportActorCrashedRequest) *v1.ObjectRef { + return oldObj.Worker }) - errs = append(errs, fn(fldPath.Child("expiration_seconds"), &obj.ExpirationSeconds, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_MintWorkerActorCertificateRequest validates an instance of MintWorkerActorCertificateRequest according -// to declarative validation rules in the API schema. -func Validate_MintWorkerActorCertificateRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.MintWorkerActorCertificateRequest) (errs field.ErrorList) { - - { // field v1.MintWorkerActorCertificateRequest.Actor + { // field v1.ReportActorCrashedRequest.Actor fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -6025,14 +7511,13 @@ func Validate_MintWorkerActorCertificateRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -6042,13 +7527,13 @@ func Validate_MintWorkerActorCertificateRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintWorkerActorCertificateRequest) *v1.ObjectRef { + func(oldObj *v1.ReportActorCrashedRequest) *v1.ObjectRef { return oldObj.Actor }) errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - { // field v1.MintWorkerActorCertificateRequest.ActorUid + { // field v1.ReportActorCrashedRequest.ActorUid fn := func( fldPath *field.Path, obj, oldObj *string, @@ -6074,104 +7559,85 @@ func Validate_MintWorkerActorCertificateRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintWorkerActorCertificateRequest) *string { + func(oldObj *v1.ReportActorCrashedRequest) *string { return &oldObj.ActorUid }) errs = append(errs, fn(fldPath.Child("actor_uid"), &obj.ActorUid, oldVal, oldObj != nil)...) } - { // field v1.MintWorkerActorCertificateRequest.CertificateSigningRequest + { // field v1.ReportActorCrashedRequest.Message fn := func( fldPath *field.Path, - obj, oldObj []byte, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.MaxBytesSlice(ctx, op, fldPath, obj, oldObj, 16384); len(e) != 0 { + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 4096); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintWorkerActorCertificateRequest) []byte { - return oldObj.CertificateSigningRequest + func(oldObj *v1.ReportActorCrashedRequest) *string { + return &oldObj.Message }) - errs = append(errs, fn(fldPath.Child("certificate_signing_request"), obj.CertificateSigningRequest, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("message"), &obj.Message, oldVal, oldObj != nil)...) } - { // field v1.MintWorkerActorCertificateRequest.Worker + { // field v1.ReportActorCrashedRequest.ActivationUid fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintWorkerActorCertificateRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.ReportActorCrashedRequest) *string { + return &oldObj.ActivationUid }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("activation_uid"), &obj.ActivationUid, oldVal, oldObj != nil)...) } return errs } -// Validate_MintWorkerActorJwtRequest validates an instance of MintWorkerActorJwtRequest according +// Validate_ReportActorSnapshotStateRequest validates an instance of ReportActorSnapshotStateRequest according // to declarative validation rules in the API schema. -func Validate_MintWorkerActorJwtRequest( +func Validate_ReportActorSnapshotStateRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.MintWorkerActorJwtRequest) (errs field.ErrorList) { + obj, oldObj *v1.ReportActorSnapshotStateRequest) (errs field.ErrorList) { - { // field v1.MintWorkerActorJwtRequest.Actor + { // field v1.ReportActorSnapshotStateRequest.Actor fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -6194,14 +7660,13 @@ func Validate_MintWorkerActorJwtRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -6211,13 +7676,13 @@ func Validate_MintWorkerActorJwtRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintWorkerActorJwtRequest) *v1.ObjectRef { + func(oldObj *v1.ReportActorSnapshotStateRequest) *v1.ObjectRef { return oldObj.Actor }) errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - { // field v1.MintWorkerActorJwtRequest.ActorUid + { // field v1.ReportActorSnapshotStateRequest.ActorUid fn := func( fldPath *field.Path, obj, oldObj *string, @@ -6243,16 +7708,16 @@ func Validate_MintWorkerActorJwtRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintWorkerActorJwtRequest) *string { + func(oldObj *v1.ReportActorSnapshotStateRequest) *string { return &oldObj.ActorUid }) errs = append(errs, fn(fldPath.Child("actor_uid"), &obj.ActorUid, oldVal, oldObj != nil)...) } - { // field v1.MintWorkerActorJwtRequest.Audiences + { // field v1.ReportActorSnapshotStateRequest.State fn := func( fldPath *field.Path, - obj, oldObj []string, + obj, oldObj *v1.ActorSnapshotState, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -6262,124 +7727,128 @@ func Validate_MintWorkerActorJwtRequest( } // call field-attached validations earlyReturn := false - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, - func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { - return validate.MinLength(ctx, op, fldPath, obj, oldObj, 1) - }); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, - func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { - return validate.MaxLength(ctx, op, fldPath, obj, oldObj, 512) - }); len(e) != 0 { - errs = append(errs, e...) - } - // lists with set semantics require unique values - if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ActorSnapshotState(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.MintWorkerActorJwtRequest) []string { - return oldObj.Audiences + func(oldObj *v1.ReportActorSnapshotStateRequest) *v1.ActorSnapshotState { + return oldObj.State }) - errs = append(errs, fn(fldPath.Child("audiences"), obj.Audiences, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("state"), obj.State, oldVal, oldObj != nil)...) } return errs } -// Validate_ObjectRef validates an instance of ObjectRef according +// Validate_RequestActorSuspendRequest validates an instance of RequestActorSuspendRequest according // to declarative validation rules in the API schema. -func Validate_ObjectRef( +func Validate_RequestActorSuspendRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ObjectRef) (errs field.ErrorList) { + obj, oldObj *v1.RequestActorSuspendRequest) (errs field.ErrorList) { - { // field v1.ObjectRef.Atespace + { // field v1.RequestActorSuspendRequest.Worker fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ObjectRef) *string { - return &oldObj.Atespace + func(oldObj *v1.RequestActorSuspendRequest) *v1.ObjectRef { + return oldObj.Worker }) - errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } - { // field v1.ObjectRef.Name + { // field v1.RequestActorSuspendRequest.Actor fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ObjectRef) *string { - return &oldObj.Name + func(oldObj *v1.RequestActorSuspendRequest) *v1.ObjectRef { + return oldObj.Actor }) - errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_ObjectSnapshot validates an instance of ObjectSnapshot according -// to declarative validation rules in the API schema. -func Validate_ObjectSnapshot( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ObjectSnapshot) (errs field.ErrorList) { - - { // field v1.ObjectSnapshot.SnapshotUri + { // field v1.RequestActorSuspendRequest.ActorUid fn := func( fldPath *field.Path, obj, oldObj *string, @@ -6399,181 +7868,139 @@ func Validate_ObjectSnapshot( if earlyReturn { return // do not proceed } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 2048); len(e) != 0 { + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ObjectSnapshot) *string { - return &oldObj.SnapshotUri + func(oldObj *v1.RequestActorSuspendRequest) *string { + return &oldObj.ActorUid }) - errs = append(errs, fn(fldPath.Child("snapshot_uri"), &obj.SnapshotUri, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor_uid"), &obj.ActorUid, oldVal, oldObj != nil)...) } return errs } -var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_Ports_ = validate.NewUnionMembership(validate.NewUnionMember("all"), validate.NewUnionMember("numbers")) - -// Validate_Ports validates an instance of Ports according +// Validate_ResourceMetadata validates an instance of ResourceMetadata according // to declarative validation rules in the API schema. -func Validate_Ports( +func Validate_ResourceMetadata( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.Ports) (errs field.ErrorList) { + obj, oldObj *v1.ResourceMetadata) (errs field.ErrorList) { - if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_Ports_, - func(obj *v1.Ports) bool { - if obj == nil { - return false - } - return obj.All != nil - }, - func(obj *v1.Ports) bool { - if obj == nil { - return false - } - return len(obj.Numbers) != 0 - }); len(e) != 0 { + // custom validation + if e := ValidateCustom_ResourceMetadata(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } - { // field v1.Ports.All + { // field v1.ResourceMetadata.Atespace fn := func( fldPath *field.Path, - obj, oldObj *v1.AllPorts, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Ports) *v1.AllPorts { - return oldObj.All + func(oldObj *v1.ResourceMetadata) *string { + return &oldObj.Atespace }) - errs = append(errs, fn(fldPath.Child("all"), obj.All, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) } - { // field v1.Ports.Numbers + { // field v1.ResourceMetadata.Name fn := func( fldPath *field.Path, - obj, oldObj []int32, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, - func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *int32) field.ErrorList { - return validate.Minimum(ctx, op, fldPath, obj, oldObj, 1) - }); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, - func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *int32) field.ErrorList { - return validate.Maximum(ctx, op, fldPath, obj, oldObj, 65535) - }); len(e) != 0 { - errs = append(errs, e...) - } - // lists with set semantics require unique values - if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Ports) []int32 { - return oldObj.Numbers + func(oldObj *v1.ResourceMetadata) *string { + return &oldObj.Name }) - errs = append(errs, fn(fldPath.Child("numbers"), obj.Numbers, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_RegisterWorkerRequest validates an instance of RegisterWorkerRequest according -// to declarative validation rules in the API schema. -func Validate_RegisterWorkerRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.RegisterWorkerRequest) (errs field.ErrorList) { - - { // field v1.RegisterWorkerRequest.Worker + { // field v1.ResourceMetadata.Uid fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RegisterWorkerRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.ResourceMetadata) *string { + return &oldObj.Uid }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("uid"), &obj.Uid, oldVal, oldObj != nil)...) } - { // field v1.RegisterWorkerRequest.Epoch + { // field v1.ResourceMetadata.Version fn := func( fldPath *field.Path, obj, oldObj *int64, @@ -6586,7 +8013,11 @@ func Validate_RegisterWorkerRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.UpdateValue(ctx, op, fldPath, obj, oldObj, + func(a int64, b int64) bool { return a == b }, validate.NoUnset).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } @@ -6596,19 +8027,22 @@ func Validate_RegisterWorkerRequest( if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } + if e := validate.Monotonic(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RegisterWorkerRequest) *int64 { - return &oldObj.Epoch + func(oldObj *v1.ResourceMetadata) *int64 { + return &oldObj.Version }) - errs = append(errs, fn(fldPath.Child("epoch"), &obj.Epoch, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("version"), &obj.Version, oldVal, oldObj != nil)...) } - { // field v1.RegisterWorkerRequest.Ips + { // field v1.ResourceMetadata.CreateTime fn := func( fldPath *field.Path, - obj, oldObj []string, + obj, oldObj *timestamppb.Timestamp, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -6618,34 +8052,29 @@ func Validate_RegisterWorkerRequest( } // call field-attached validations earlyReturn := false - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 2).MarkShortCircuit(); len(e) != 0 { + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_RegisterWorkerRequest_Ips(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RegisterWorkerRequest) []string { - return oldObj.Ips + func(oldObj *v1.ResourceMetadata) *timestamppb.Timestamp { + return oldObj.CreateTime }) - errs = append(errs, fn(fldPath.Child("ips"), obj.Ips, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("create_time"), obj.CreateTime, oldVal, oldObj != nil)...) } - { // field v1.RegisterWorkerRequest.Capacity + { // field v1.ResourceMetadata.UpdateTime fn := func( fldPath *field.Path, - obj, oldObj *v1.WorkerResources, + obj, oldObj *timestamppb.Timestamp, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -6655,37 +8084,29 @@ func Validate_RegisterWorkerRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoUnset).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_WorkerResources(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RegisterWorkerRequest) *v1.WorkerResources { - return oldObj.Capacity + func(oldObj *v1.ResourceMetadata) *timestamppb.Timestamp { + return oldObj.UpdateTime }) - errs = append(errs, fn(fldPath.Child("capacity"), obj.Capacity, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("update_time"), obj.UpdateTime, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_ReportActorCrashedRequest validates an instance of ReportActorCrashedRequest according -// to declarative validation rules in the API schema. -func Validate_ReportActorCrashedRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ReportActorCrashedRequest) (errs field.ErrorList) { - - { // field v1.ReportActorCrashedRequest.Worker + { // field v1.ResourceMetadata.DeleteTime fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *timestamppb.Timestamp, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -6695,47 +8116,38 @@ func Validate_ReportActorCrashedRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoUnset, validate.NoModify).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ReportActorCrashedRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.ResourceMetadata) *timestamppb.Timestamp { + return oldObj.DeleteTime }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("delete_time"), obj.DeleteTime, oldVal, oldObj != nil)...) } - { // field v1.ReportActorCrashedRequest.Actor + return errs +} + +// Validate_ResourceRequirements validates an instance of ResourceRequirements according +// to declarative validation rules in the API schema. +func Validate_ResourceRequirements( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ResourceRequirements) (errs field.ErrorList) { + + { // field v1.ResourceRequirements.Limits fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.Resources, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -6745,43 +8157,36 @@ func Validate_ReportActorCrashedRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_Resources(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ReportActorCrashedRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.ResourceRequirements) *v1.Resources { + return oldObj.Limits }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("limits"), obj.Limits, oldVal, oldObj != nil)...) } - { // field v1.ReportActorCrashedRequest.ActorUid + return errs +} + +// Validate_Resources validates an instance of Resources according +// to declarative validation rules in the API schema. +func Validate_Resources( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.Resources) (errs field.ErrorList) { + + { // field v1.Resources.CpuMillicores fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -6791,29 +8196,31 @@ func Validate_ReportActorCrashedRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 999999); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ReportActorCrashedRequest) *string { - return &oldObj.ActorUid + func(oldObj *v1.Resources) *int64 { + return &oldObj.CpuMillicores }) - errs = append(errs, fn(fldPath.Child("actor_uid"), &obj.ActorUid, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("cpu_millicores"), &obj.CpuMillicores, oldVal, oldObj != nil)...) } - { // field v1.ReportActorCrashedRequest.Message + { // field v1.Resources.MemoryBytes fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -6823,35 +8230,34 @@ func Validate_ReportActorCrashedRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 4096); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ReportActorCrashedRequest) *string { - return &oldObj.Message + func(oldObj *v1.Resources) *int64 { + return &oldObj.MemoryBytes }) - errs = append(errs, fn(fldPath.Child("message"), &obj.Message, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("memory_bytes"), &obj.MemoryBytes, oldVal, oldObj != nil)...) } return errs } -// Validate_ReportActorSnapshotStateRequest validates an instance of ReportActorSnapshotStateRequest according +// Validate_ResumeActorRequest validates an instance of ResumeActorRequest according // to declarative validation rules in the API schema. -func Validate_ReportActorSnapshotStateRequest( +func Validate_ResumeActorRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ReportActorSnapshotStateRequest) (errs field.ErrorList) { + obj, oldObj *v1.ResumeActorRequest) (errs field.ErrorList) { - { // field v1.ReportActorSnapshotStateRequest.Actor + { // field v1.ResumeActorRequest.Actor fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -6874,14 +8280,13 @@ func Validate_ReportActorSnapshotStateRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -6891,135 +8296,123 @@ func Validate_ReportActorSnapshotStateRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ReportActorSnapshotStateRequest) *v1.ObjectRef { + func(oldObj *v1.ResumeActorRequest) *v1.ObjectRef { return oldObj.Actor }) errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - { // field v1.ReportActorSnapshotStateRequest.ActorUid + { // field v1.ResumeActorRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.ResumeActorRequest_Options, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ResumeActorRequest_Options(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ReportActorSnapshotStateRequest) *string { - return &oldObj.ActorUid + func(oldObj *v1.ResumeActorRequest) *v1.ResumeActorRequest_Options { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("actor_uid"), &obj.ActorUid, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } - { // field v1.ReportActorSnapshotStateRequest.State + return errs +} + +// Validate_ResumeActorRequest_Options validates an instance of ResumeActorRequest_Options according +// to declarative validation rules in the API schema. +func Validate_ResumeActorRequest_Options( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.ResumeActorRequest_Options) (errs field.ErrorList) { + + { // field v1.ResumeActorRequest_Options.Version fn := func( fldPath *field.Path, - obj, oldObj *v1.ActorSnapshotState, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ActorSnapshotState(ctx, op, fldPath, obj, oldObj)...) + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ReportActorSnapshotStateRequest) *v1.ActorSnapshotState { - return oldObj.State + func(oldObj *v1.ResumeActorRequest_Options) *int64 { + return &oldObj.Version }) - errs = append(errs, fn(fldPath.Child("state"), obj.State, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("version"), &obj.Version, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_RequestActorSuspendRequest validates an instance of RequestActorSuspendRequest according -// to declarative validation rules in the API schema. -func Validate_RequestActorSuspendRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.RequestActorSuspendRequest) (errs field.ErrorList) { - - { // field v1.RequestActorSuspendRequest.Worker + { // field v1.ResumeActorRequest_Options.Uid fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RequestActorSuspendRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.ResumeActorRequest_Options) *string { + return &oldObj.Uid }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("uid"), &obj.Uid, oldVal, oldObj != nil)...) } - { // field v1.RequestActorSuspendRequest.Actor + return errs +} + +// Validate_RevertActorRequest validates an instance of RevertActorRequest according +// to declarative validation rules in the API schema. +func Validate_RevertActorRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.RevertActorRequest) (errs field.ErrorList) { + + { // field v1.RevertActorRequest.Actor fn := func( fldPath *field.Path, obj, oldObj *v1.ObjectRef, @@ -7042,14 +8435,13 @@ func Validate_RequestActorSuspendRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -7059,62 +8451,55 @@ func Validate_RequestActorSuspendRequest( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RequestActorSuspendRequest) *v1.ObjectRef { + func(oldObj *v1.RevertActorRequest) *v1.ObjectRef { return oldObj.Actor }) errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - { // field v1.RequestActorSuspendRequest.ActorUid + { // field v1.RevertActorRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.RevertActorRequest_Options, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_RevertActorRequest_Options(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RequestActorSuspendRequest) *string { - return &oldObj.ActorUid + func(oldObj *v1.RevertActorRequest) *v1.RevertActorRequest_Options { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("actor_uid"), &obj.ActorUid, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } return errs } -// Validate_ResourceMetadata validates an instance of ResourceMetadata according +// Validate_RevertActorRequest_Options validates an instance of RevertActorRequest_Options according // to declarative validation rules in the API schema. -func Validate_ResourceMetadata( +func Validate_RevertActorRequest_Options( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ResourceMetadata) (errs field.ErrorList) { - - // custom validation - if e := ValidateCustom_ResourceMetadata(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + obj, oldObj *v1.RevertActorRequest_Options) (errs field.ErrorList) { - { // field v1.ResourceMetadata.Atespace + { // field v1.RevertActorRequest_Options.Version fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7124,65 +8509,25 @@ func Validate_ResourceMetadata( } // call field-attached validations earlyReturn := false - if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - return - } - oldVal := safe.Field(oldObj, - func(oldObj *v1.ResourceMetadata) *string { - return &oldObj.Atespace - }) - errs = append(errs, fn(fldPath.Child("atespace"), &obj.Atespace, oldVal, oldObj != nil)...) - } - - { // field v1.ResourceMetadata.Name - fn := func( - fldPath *field.Path, - obj, oldObj *string, - oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { - return nil - } - } - // call field-attached validations - earlyReturn := false - if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ResourceMetadata) *string { - return &oldObj.Name + func(oldObj *v1.RevertActorRequest_Options) *int64 { + return &oldObj.Version }) - errs = append(errs, fn(fldPath.Child("name"), &obj.Name, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("version"), &obj.Version, oldVal, oldObj != nil)...) } - { // field v1.ResourceMetadata.Uid + { // field v1.RevertActorRequest_Options.Uid fn := func( fldPath *field.Path, obj, oldObj *string, @@ -7195,10 +8540,6 @@ func Validate_ResourceMetadata( } // call field-attached validations earlyReturn := false - if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } @@ -7211,13 +8552,22 @@ func Validate_ResourceMetadata( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ResourceMetadata) *string { + func(oldObj *v1.RevertActorRequest_Options) *string { return &oldObj.Uid }) errs = append(errs, fn(fldPath.Child("uid"), &obj.Uid, oldVal, oldObj != nil)...) } - { // field v1.ResourceMetadata.Version + return errs +} + +// Validate_RuntimeOverhead validates an instance of RuntimeOverhead according +// to declarative validation rules in the API schema. +func Validate_RuntimeOverhead( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.RuntimeOverhead) (errs field.ErrorList) { + + { // field v1.RuntimeOverhead.MemoryBytes fn := func( fldPath *field.Path, obj, oldObj *int64, @@ -7229,69 +8579,75 @@ func Validate_ResourceMetadata( } } // call field-attached validations - earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.UpdateValue(ctx, op, fldPath, obj, oldObj, - func(a int64, b int64) bool { return a == b }, validate.NoUnset).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Monotonic(ctx, op, fldPath, obj, oldObj).MarkAlpha(); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 1099511627776); len(e) != 0 { errs = append(errs, e...) } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ResourceMetadata) *int64 { - return &oldObj.Version + func(oldObj *v1.RuntimeOverhead) *int64 { + return &oldObj.MemoryBytes }) - errs = append(errs, fn(fldPath.Child("version"), &obj.Version, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("memory_bytes"), &obj.MemoryBytes, oldVal, oldObj != nil)...) } - { // field v1.ResourceMetadata.CreateTime + { // field v1.RuntimeOverhead.MemoryBytesPerGib fn := func( fldPath *field.Path, - obj, oldObj *timestamppb.Timestamp, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 1073741824); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ResourceMetadata) *timestamppb.Timestamp { - return oldObj.CreateTime + func(oldObj *v1.RuntimeOverhead) *int64 { + return &oldObj.MemoryBytesPerGib }) - errs = append(errs, fn(fldPath.Child("create_time"), obj.CreateTime, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("memory_bytes_per_gib"), &obj.MemoryBytesPerGib, oldVal, oldObj != nil)...) } - { // field v1.ResourceMetadata.UpdateTime + return errs +} + +// Validate_SecurityContext validates an instance of SecurityContext according +// to declarative validation rules in the API schema. +func Validate_SecurityContext( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.SecurityContext) (errs field.ErrorList) { + + { // field v1.SecurityContext.Capabilities fn := func( fldPath *field.Path, - obj, oldObj *timestamppb.Timestamp, + obj, oldObj *v1.Capabilities, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7304,26 +8660,45 @@ func Validate_ResourceMetadata( if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } - if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoUnset).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } if earlyReturn { return // do not proceed } + // call the type's validation function + errs = append(errs, Validate_Capabilities(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ResourceMetadata) *timestamppb.Timestamp { - return oldObj.UpdateTime + func(oldObj *v1.SecurityContext) *v1.Capabilities { + return oldObj.Capabilities }) - errs = append(errs, fn(fldPath.Child("update_time"), obj.UpdateTime, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("capabilities"), obj.Capabilities, oldVal, oldObj != nil)...) } - { // field v1.ResourceMetadata.DeleteTime + return errs +} + +var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_Selector_ = validate.NewUnionMembership(validate.NewUnionMember("match_labels")) + +// Validate_Selector validates an instance of Selector according +// to declarative validation rules in the API schema. +func Validate_Selector( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.Selector) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_Selector_, + func(obj *v1.Selector) bool { + if obj == nil { + return false + } + return len(obj.MatchLabels) != 0 + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field v1.Selector.MatchLabels fn := func( fldPath *field.Path, - obj, oldObj *timestamppb.Timestamp, + obj, oldObj map[string]string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7333,38 +8708,47 @@ func Validate_ResourceMetadata( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxProperties(ctx, op, fldPath, obj, oldObj, 10).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } - if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoUnset, validate.NoModify).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalMap(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } + if e := validate.EachMapKey(ctx, op, fldPath, obj, oldObj, validate.LabelKey); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MinProperties(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.EachMapVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, validate.LabelValue); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ResourceMetadata) *timestamppb.Timestamp { - return oldObj.DeleteTime + func(oldObj *v1.Selector) map[string]string { + return oldObj.MatchLabels }) - errs = append(errs, fn(fldPath.Child("delete_time"), obj.DeleteTime, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("match_labels"), obj.MatchLabels, oldVal, oldObj != nil)...) } return errs } -// Validate_ResourceRequirements validates an instance of ResourceRequirements according +// Validate_SetWorkerSandboxRuntimesRequest validates an instance of SetWorkerSandboxRuntimesRequest according // to declarative validation rules in the API schema. -func Validate_ResourceRequirements( +func Validate_SetWorkerSandboxRuntimesRequest( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ResourceRequirements) (errs field.ErrorList) { + obj, oldObj *v1.SetWorkerSandboxRuntimesRequest) (errs field.ErrorList) { - { // field v1.ResourceRequirements.Limits + { // field v1.SetWorkerSandboxRuntimesRequest.Worker fn := func( fldPath *field.Path, - obj, oldObj *v1.Resources, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7374,33 +8758,43 @@ func Validate_ResourceRequirements( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function - errs = append(errs, Validate_Resources(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ResourceRequirements) *v1.Resources { - return oldObj.Limits + func(oldObj *v1.SetWorkerSandboxRuntimesRequest) *v1.ObjectRef { + return oldObj.Worker }) - errs = append(errs, fn(fldPath.Child("limits"), obj.Limits, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_Resources validates an instance of Resources according -// to declarative validation rules in the API schema. -func Validate_Resources( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.Resources) (errs field.ErrorList) { - - { // field v1.Resources.CpuMillicores + { // field v1.SetWorkerSandboxRuntimesRequest.Epoch fn := func( fldPath *field.Path, obj, oldObj *int64, @@ -7413,181 +8807,152 @@ func Validate_Resources( } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 999999); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Resources) *int64 { - return &oldObj.CpuMillicores + func(oldObj *v1.SetWorkerSandboxRuntimesRequest) *int64 { + return &oldObj.Epoch }) - errs = append(errs, fn(fldPath.Child("cpu_millicores"), &obj.CpuMillicores, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("epoch"), &obj.Epoch, oldVal, oldObj != nil)...) } - { // field v1.Resources.MemoryBytes + { // field v1.SetWorkerSandboxRuntimesRequest.SandboxClasses fn := func( fldPath *field.Path, - obj, oldObj *int64, + obj, oldObj []*v1.WorkerSandboxClass, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.PtrSliceNoNils[v1.WorkerSandboxClass](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 1).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { + if e := validate.MinItems(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } + // lists with map semantics require unique keys + if e := validate.PtrSliceUnique(ctx, op, fldPath, obj, oldObj, + func(a *v1.WorkerSandboxClass, b *v1.WorkerSandboxClass) bool { return a.SandboxClass == b.SandboxClass }); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, + func(a *v1.WorkerSandboxClass, b *v1.WorkerSandboxClass) bool { return a.SandboxClass == b.SandboxClass }, ateDeepEqual, Validate_WorkerSandboxClass); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Resources) *int64 { - return &oldObj.MemoryBytes + func(oldObj *v1.SetWorkerSandboxRuntimesRequest) []*v1.WorkerSandboxClass { + return oldObj.SandboxClasses }) - errs = append(errs, fn(fldPath.Child("memory_bytes"), &obj.MemoryBytes, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("sandbox_classes"), obj.SandboxClasses, oldVal, oldObj != nil)...) } return errs } -// Validate_ResumeActorRequest validates an instance of ResumeActorRequest according +// Validate_Snapshot validates an instance of Snapshot according // to declarative validation rules in the API schema. -func Validate_ResumeActorRequest( +func Validate_Snapshot( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.ResumeActorRequest) (errs field.ErrorList) { + obj, oldObj *v1.Snapshot) (errs field.ErrorList) { - { // field v1.ResumeActorRequest.Actor + { // field v1.Snapshot.Uuid fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.ResumeActorRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.Snapshot) *string { + return &oldObj.Uuid }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("uuid"), &obj.Uuid, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_RevertActorRequest validates an instance of RevertActorRequest according -// to declarative validation rules in the API schema. -func Validate_RevertActorRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.RevertActorRequest) (errs field.ErrorList) { - - { // field v1.RevertActorRequest.Actor + { // field v1.Snapshot.Generation fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *int32, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RevertActorRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.Snapshot) *int32 { + return &oldObj.Generation }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("generation"), &obj.Generation, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_RuntimeOverhead validates an instance of RuntimeOverhead according -// to declarative validation rules in the API schema. -func Validate_RuntimeOverhead( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.RuntimeOverhead) (errs field.ErrorList) { - - { // field v1.RuntimeOverhead.MemoryBytes + { // field v1.Snapshot.Owner fn := func( fldPath *field.Path, - obj, oldObj *int64, + obj, oldObj *v1.SnapshotOwner, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7597,31 +8962,32 @@ func Validate_RuntimeOverhead( } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 1099511627776); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 2); len(e) != 0 { errs = append(errs, e...) } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RuntimeOverhead) *int64 { - return &oldObj.MemoryBytes + func(oldObj *v1.Snapshot) *v1.SnapshotOwner { + return &oldObj.Owner }) - errs = append(errs, fn(fldPath.Child("memory_bytes"), &obj.MemoryBytes, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("owner"), &obj.Owner, oldVal, oldObj != nil)...) } - { // field v1.RuntimeOverhead.MemoryBytesPerGib + { // field v1.Snapshot.Fidelity fn := func( fldPath *field.Path, - obj, oldObj *int64, + obj, oldObj *v1.SnapshotFidelity, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7631,141 +8997,94 @@ func Validate_RuntimeOverhead( } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 1073741824); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 3); len(e) != 0 { errs = append(errs, e...) } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 0); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.RuntimeOverhead) *int64 { - return &oldObj.MemoryBytesPerGib + func(oldObj *v1.Snapshot) *v1.SnapshotFidelity { + return &oldObj.Fidelity }) - errs = append(errs, fn(fldPath.Child("memory_bytes_per_gib"), &obj.MemoryBytesPerGib, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("fidelity"), &obj.Fidelity, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_SecurityContext validates an instance of SecurityContext according -// to declarative validation rules in the API schema. -func Validate_SecurityContext( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SecurityContext) (errs field.ErrorList) { - - { // field v1.SecurityContext.Capabilities + { // field v1.Snapshot.ActorTemplateUid fn := func( fldPath *field.Path, - obj, oldObj *v1.Capabilities, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_Capabilities(ctx, op, fldPath, obj, oldObj)...) + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SecurityContext) *v1.Capabilities { - return oldObj.Capabilities + func(oldObj *v1.Snapshot) *string { + return &oldObj.ActorTemplateUid }) - errs = append(errs, fn(fldPath.Child("capabilities"), obj.Capabilities, oldVal, oldObj != nil)...) - } - - return errs -} - -var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_Selector_ = validate.NewUnionMembership(validate.NewUnionMember("match_labels")) - -// Validate_Selector validates an instance of Selector according -// to declarative validation rules in the API schema. -func Validate_Selector( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.Selector) (errs field.ErrorList) { - - if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_Selector_, - func(obj *v1.Selector) bool { - if obj == nil { - return false - } - return len(obj.MatchLabels) != 0 - }); len(e) != 0 { - errs = append(errs, e...) + errs = append(errs, fn(fldPath.Child("actor_template_uid"), &obj.ActorTemplateUid, oldVal, oldObj != nil)...) } - { // field v1.Selector.MatchLabels + { // field v1.Snapshot.Locality fn := func( fldPath *field.Path, - obj, oldObj map[string]string, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.MaxProperties(ctx, op, fldPath, obj, oldObj, 10).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.OptionalMap(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.EachMapKey(ctx, op, fldPath, obj, oldObj, validate.LabelKey); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.MinProperties(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.EachMapVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, validate.LabelValue); len(e) != 0 { + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Selector) map[string]string { - return oldObj.MatchLabels + func(oldObj *v1.Snapshot) *string { + return &oldObj.Locality }) - errs = append(errs, fn(fldPath.Child("match_labels"), obj.MatchLabels, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("locality"), &obj.Locality, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_SetWorkerSandboxRuntimesRequest validates an instance of SetWorkerSandboxRuntimesRequest according -// to declarative validation rules in the API schema. -func Validate_SetWorkerSandboxRuntimesRequest( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SetWorkerSandboxRuntimesRequest) (errs field.ErrorList) { - - { // field v1.SetWorkerSandboxRuntimesRequest.Worker + { // field v1.Snapshot.DurableSnapshot fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.SnapshotStorage, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7775,138 +9094,111 @@ func Validate_SetWorkerSandboxRuntimesRequest( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_SnapshotStorage(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SetWorkerSandboxRuntimesRequest) *v1.ObjectRef { - return oldObj.Worker + func(oldObj *v1.Snapshot) *v1.SnapshotStorage { + return oldObj.DurableSnapshot }) - errs = append(errs, fn(fldPath.Child("worker"), obj.Worker, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("durable_snapshot"), obj.DurableSnapshot, oldVal, oldObj != nil)...) } - { // field v1.SetWorkerSandboxRuntimesRequest.Epoch + { // field v1.Snapshot.SandboxRuntime fn := func( fldPath *field.Path, - obj, oldObj *int64, + obj, oldObj *v1.ActorSandboxRuntime, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ActorSandboxRuntime(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SetWorkerSandboxRuntimesRequest) *int64 { - return &oldObj.Epoch + func(oldObj *v1.Snapshot) *v1.ActorSandboxRuntime { + return oldObj.SandboxRuntime }) - errs = append(errs, fn(fldPath.Child("epoch"), &obj.Epoch, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("sandbox_runtime"), obj.SandboxRuntime, oldVal, oldObj != nil)...) } - { // field v1.SetWorkerSandboxRuntimesRequest.SandboxClasses + return errs +} + +// Validate_SnapshotConfig validates an instance of SnapshotConfig according +// to declarative validation rules in the API schema. +func Validate_SnapshotConfig( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.SnapshotConfig) (errs field.ErrorList) { + + { // field v1.SnapshotConfig.StorageLocation fn := func( fldPath *field.Path, - obj, oldObj []*v1.WorkerSandboxClass, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.PtrSliceNoNils[v1.WorkerSandboxClass](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PerTemplateSnapshotLocation", false, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 1).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PerTemplateSnapshotLocation", false, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.MinItems(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } - // lists with map semantics require unique keys - if e := validate.PtrSliceUnique(ctx, op, fldPath, obj, oldObj, - func(a *v1.WorkerSandboxClass, b *v1.WorkerSandboxClass) bool { return a.SandboxClass == b.SandboxClass }); len(e) != 0 { + // custom validation + if e := ValidateCustom_SnapshotConfig_StorageLocation(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } - // iterate the list and call the type's validation function - if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, - func(a *v1.WorkerSandboxClass, b *v1.WorkerSandboxClass) bool { return a.SandboxClass == b.SandboxClass }, ateDeepEqual, Validate_WorkerSandboxClass); len(e) != 0 { + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 1024); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SetWorkerSandboxRuntimesRequest) []*v1.WorkerSandboxClass { - return oldObj.SandboxClasses + func(oldObj *v1.SnapshotConfig) *string { + return &oldObj.StorageLocation }) - errs = append(errs, fn(fldPath.Child("sandbox_classes"), obj.SandboxClasses, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("storage_location"), &obj.StorageLocation, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_Snapshot validates an instance of Snapshot according -// to declarative validation rules in the API schema. -func Validate_Snapshot( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.Snapshot) (errs field.ErrorList) { - - { // field v1.Snapshot.Uuid + { // field v1.SnapshotConfig.PreferredFidelity fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.SnapshotFidelity, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7923,54 +9215,64 @@ func Validate_Snapshot( if earlyReturn { return // do not proceed } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 3); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Snapshot) *string { - return &oldObj.Uuid + func(oldObj *v1.SnapshotConfig) *v1.SnapshotFidelity { + return &oldObj.PreferredFidelity }) - errs = append(errs, fn(fldPath.Child("uuid"), &obj.Uuid, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("preferred_fidelity"), &obj.PreferredFidelity, oldVal, oldObj != nil)...) } - { // field v1.Snapshot.Generation + { // field v1.SnapshotConfig.GoldenSnapshotConfig fn := func( fldPath *field.Path, - obj, oldObj *int32, + obj, oldObj *v1.GoldenSnapshotConfig, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_GoldenSnapshotConfig(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Snapshot) *int32 { - return &oldObj.Generation + func(oldObj *v1.SnapshotConfig) *v1.GoldenSnapshotConfig { + return oldObj.GoldenSnapshotConfig }) - errs = append(errs, fn(fldPath.Child("generation"), &obj.Generation, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("golden_snapshot_config"), obj.GoldenSnapshotConfig, oldVal, oldObj != nil)...) } - { // field v1.Snapshot.Owner + return errs +} + +// Validate_SnapshotReport validates an instance of SnapshotReport according +// to declarative validation rules in the API schema. +func Validate_SnapshotReport( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.SnapshotReport) (errs field.ErrorList) { + + { // field v1.SnapshotReport.Uuid fn := func( fldPath *field.Path, - obj, oldObj *v1.SnapshotOwner, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -7987,25 +9289,22 @@ func Validate_Snapshot( if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 2); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Snapshot) *v1.SnapshotOwner { - return &oldObj.Owner + func(oldObj *v1.SnapshotReport) *string { + return &oldObj.Uuid }) - errs = append(errs, fn(fldPath.Child("owner"), &obj.Owner, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("uuid"), &obj.Uuid, oldVal, oldObj != nil)...) } - { // field v1.Snapshot.Fidelity + { // field v1.SnapshotReport.Generation fn := func( fldPath *field.Path, - obj, oldObj *v1.SnapshotFidelity, + obj, oldObj *int32, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8022,25 +9321,22 @@ func Validate_Snapshot( if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 3); len(e) != 0 { - errs = append(errs, e...) - } if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Snapshot) *v1.SnapshotFidelity { - return &oldObj.Fidelity + func(oldObj *v1.SnapshotReport) *int32 { + return &oldObj.Generation }) - errs = append(errs, fn(fldPath.Child("fidelity"), &obj.Fidelity, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("generation"), &obj.Generation, oldVal, oldObj != nil)...) } - { // field v1.Snapshot.ActorTemplateUid + { // field v1.SnapshotReport.Fidelity fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.SnapshotFidelity, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8050,59 +9346,63 @@ func Validate_Snapshot( } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 3); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Snapshot) *string { - return &oldObj.ActorTemplateUid + func(oldObj *v1.SnapshotReport) *v1.SnapshotFidelity { + return &oldObj.Fidelity }) - errs = append(errs, fn(fldPath.Child("actor_template_uid"), &obj.ActorTemplateUid, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("fidelity"), &obj.Fidelity, oldVal, oldObj != nil)...) } - { // field v1.Snapshot.Locality + { // field v1.SnapshotReport.Object fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.ObjectSnapshot, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ObjectSnapshot(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Snapshot) *string { - return &oldObj.Locality + func(oldObj *v1.SnapshotReport) *v1.ObjectSnapshot { + return oldObj.Object }) - errs = append(errs, fn(fldPath.Child("locality"), &obj.Locality, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("object"), obj.Object, oldVal, oldObj != nil)...) } - { // field v1.Snapshot.DurableSnapshot + { // field v1.SnapshotReport.LocalCommitTime fn := func( fldPath *field.Path, - obj, oldObj *v1.SnapshotStorage, + obj, oldObj *timestamppb.Timestamp, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8118,21 +9418,19 @@ func Validate_Snapshot( if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_SnapshotStorage(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Snapshot) *v1.SnapshotStorage { - return oldObj.DurableSnapshot + func(oldObj *v1.SnapshotReport) *timestamppb.Timestamp { + return oldObj.LocalCommitTime }) - errs = append(errs, fn(fldPath.Child("durable_snapshot"), obj.DurableSnapshot, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("local_commit_time"), obj.LocalCommitTime, oldVal, oldObj != nil)...) } - { // field v1.Snapshot.SandboxRuntime + { // field v1.SnapshotReport.DurableCompleteTime fn := func( fldPath *field.Path, - obj, oldObj *v1.ActorSandboxRuntime, + obj, oldObj *timestamppb.Timestamp, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8148,30 +9446,28 @@ func Validate_Snapshot( if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ActorSandboxRuntime(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Snapshot) *v1.ActorSandboxRuntime { - return oldObj.SandboxRuntime + func(oldObj *v1.SnapshotReport) *timestamppb.Timestamp { + return oldObj.DurableCompleteTime }) - errs = append(errs, fn(fldPath.Child("sandbox_runtime"), obj.SandboxRuntime, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("durable_complete_time"), obj.DurableCompleteTime, oldVal, oldObj != nil)...) } return errs } -// Validate_SnapshotConfig validates an instance of SnapshotConfig according +// Validate_SnapshotStorage validates an instance of SnapshotStorage according // to declarative validation rules in the API schema. -func Validate_SnapshotConfig( +func Validate_SnapshotStorage( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SnapshotConfig) (errs field.ErrorList) { + obj, oldObj *v1.SnapshotStorage) (errs field.ErrorList) { - { // field v1.SnapshotConfig.StorageLocation + { // field v1.SnapshotStorage.State fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.SnapshotStorageState, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8181,74 +9477,72 @@ func Validate_SnapshotConfig( } // call field-attached validations earlyReturn := false - if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PerTemplateSnapshotLocation", false, validate.ForbiddenValue).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "PerTemplateSnapshotLocation", false, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_SnapshotConfig_StorageLocation(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 2); len(e) != 0 { errs = append(errs, e...) } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 1024); len(e) != 0 { + if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotConfig) *string { - return &oldObj.StorageLocation + func(oldObj *v1.SnapshotStorage) *v1.SnapshotStorageState { + return &oldObj.State }) - errs = append(errs, fn(fldPath.Child("storage_location"), &obj.StorageLocation, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("state"), &obj.State, oldVal, oldObj != nil)...) } - { // field v1.SnapshotConfig.PreferredFidelity + { // field v1.SnapshotStorage.Object fn := func( fldPath *field.Path, - obj, oldObj *v1.SnapshotFidelity, + obj, oldObj *v1.ObjectSnapshot, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 3); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ObjectSnapshot(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotConfig) *v1.SnapshotFidelity { - return &oldObj.PreferredFidelity + func(oldObj *v1.SnapshotStorage) *v1.ObjectSnapshot { + return oldObj.Object }) - errs = append(errs, fn(fldPath.Child("preferred_fidelity"), &obj.PreferredFidelity, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("object"), obj.Object, oldVal, oldObj != nil)...) } - { // field v1.SnapshotConfig.GoldenSnapshotConfig + return errs +} + +// Validate_SuspendActorRequest validates an instance of SuspendActorRequest according +// to declarative validation rules in the API schema. +func Validate_SuspendActorRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.SuspendActorRequest) (errs field.ErrorList) { + + { // field v1.SuspendActorRequest.Actor fn := func( fldPath *field.Path, - obj, oldObj *v1.GoldenSnapshotConfig, + obj, oldObj *v1.ObjectRef, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8258,68 +9552,81 @@ func Validate_SnapshotConfig( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function - errs = append(errs, Validate_GoldenSnapshotConfig(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotConfig) *v1.GoldenSnapshotConfig { - return oldObj.GoldenSnapshotConfig + func(oldObj *v1.SuspendActorRequest) *v1.ObjectRef { + return oldObj.Actor }) - errs = append(errs, fn(fldPath.Child("golden_snapshot_config"), obj.GoldenSnapshotConfig, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_SnapshotReport validates an instance of SnapshotReport according -// to declarative validation rules in the API schema. -func Validate_SnapshotReport( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SnapshotReport) (errs field.ErrorList) { - - { // field v1.SnapshotReport.Uuid + { // field v1.SuspendActorRequest.Options fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj *v1.SuspendOptions, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.ShortName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_SuspendOptions(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotReport) *string { - return &oldObj.Uuid + func(oldObj *v1.SuspendActorRequest) *v1.SuspendOptions { + return oldObj.Options }) - errs = append(errs, fn(fldPath.Child("uuid"), &obj.Uuid, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) } - { // field v1.SnapshotReport.Generation + return errs +} + +// Validate_SuspendOptions validates an instance of SuspendOptions according +// to declarative validation rules in the API schema. +func Validate_SuspendOptions( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.SuspendOptions) (errs field.ErrorList) { + + { // field v1.SuspendOptions.Mode fn := func( fldPath *field.Path, - obj, oldObj *int32, + obj, oldObj *v1.DurabilityMode, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8329,29 +9636,31 @@ func Validate_SnapshotReport( } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } + if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 2); len(e) != 0 { + errs = append(errs, e...) + } if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotReport) *int32 { - return &oldObj.Generation + func(oldObj *v1.SuspendOptions) *v1.DurabilityMode { + return &oldObj.Mode }) - errs = append(errs, fn(fldPath.Child("generation"), &obj.Generation, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("mode"), &obj.Mode, oldVal, oldObj != nil)...) } - { // field v1.SnapshotReport.Fidelity + { // field v1.SuspendOptions.Version fn := func( fldPath *field.Path, - obj, oldObj *v1.SnapshotFidelity, + obj, oldObj *int64, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8361,63 +9670,86 @@ func Validate_SnapshotReport( } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 3); len(e) != 0 { - errs = append(errs, e...) - } if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotReport) *v1.SnapshotFidelity { - return &oldObj.Fidelity + func(oldObj *v1.SuspendOptions) *int64 { + return &oldObj.Version }) - errs = append(errs, fn(fldPath.Child("fidelity"), &obj.Fidelity, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("version"), &obj.Version, oldVal, oldObj != nil)...) } - { // field v1.SnapshotReport.Object + { // field v1.SuspendOptions.Uid fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectSnapshot, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ObjectSnapshot(ctx, op, fldPath, obj, oldObj)...) + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotReport) *v1.ObjectSnapshot { - return oldObj.Object + func(oldObj *v1.SuspendOptions) *string { + return &oldObj.Uid }) - errs = append(errs, fn(fldPath.Child("object"), obj.Object, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("uid"), &obj.Uid, oldVal, oldObj != nil)...) } - { // field v1.SnapshotReport.LocalCommitTime + return errs +} + +var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_SystemInfoDataSource_ = validate.NewUnionMembership(validate.NewUnionMember("actor_metadata"), validate.NewUnionMember("trust_bundle")) + +// Validate_SystemInfoDataSource validates an instance of SystemInfoDataSource according +// to declarative validation rules in the API schema. +func Validate_SystemInfoDataSource( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.SystemInfoDataSource) (errs field.ErrorList) { + + if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_SystemInfoDataSource_, + func(obj *v1.SystemInfoDataSource) bool { + if obj == nil { + return false + } + return obj.ActorMetadata != nil + }, + func(obj *v1.SystemInfoDataSource) bool { + if obj == nil { + return false + } + return obj.TrustBundle != nil + }); len(e) != 0 { + errs = append(errs, e...) + } + + { // field v1.SystemInfoDataSource.ActorMetadata fn := func( fldPath *field.Path, - obj, oldObj *timestamppb.Timestamp, + obj, oldObj *v1.ActorMetadataDataSource, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8433,19 +9765,21 @@ func Validate_SnapshotReport( if earlyReturn { return // do not proceed } + // call the type's validation function + errs = append(errs, Validate_ActorMetadataDataSource(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotReport) *timestamppb.Timestamp { - return oldObj.LocalCommitTime + func(oldObj *v1.SystemInfoDataSource) *v1.ActorMetadataDataSource { + return oldObj.ActorMetadata }) - errs = append(errs, fn(fldPath.Child("local_commit_time"), obj.LocalCommitTime, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor_metadata"), obj.ActorMetadata, oldVal, oldObj != nil)...) } - { // field v1.SnapshotReport.DurableCompleteTime + { // field v1.SystemInfoDataSource.TrustBundle fn := func( fldPath *field.Path, - obj, oldObj *timestamppb.Timestamp, + obj, oldObj *v1.TrustBundleDataSource, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8461,103 +9795,83 @@ func Validate_SnapshotReport( if earlyReturn { return // do not proceed } + // call the type's validation function + errs = append(errs, Validate_TrustBundleDataSource(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotReport) *timestamppb.Timestamp { - return oldObj.DurableCompleteTime + func(oldObj *v1.SystemInfoDataSource) *v1.TrustBundleDataSource { + return oldObj.TrustBundle }) - errs = append(errs, fn(fldPath.Child("durable_complete_time"), obj.DurableCompleteTime, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("trust_bundle"), obj.TrustBundle, oldVal, oldObj != nil)...) } return errs } -// Validate_SnapshotStorage validates an instance of SnapshotStorage according +// Validate_SystemInfoVolumeSource validates an instance of SystemInfoVolumeSource according // to declarative validation rules in the API schema. -func Validate_SnapshotStorage( +func Validate_SystemInfoVolumeSource( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SnapshotStorage) (errs field.ErrorList) { + obj, oldObj *v1.SystemInfoVolumeSource) (errs field.ErrorList) { - { // field v1.SnapshotStorage.State + { // field v1.SystemInfoVolumeSource.DataSources fn := func( fldPath *field.Path, - obj, oldObj *v1.SnapshotStorageState, + obj, oldObj []*v1.SystemInfoDataSource, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.PtrSliceNoNils[v1.SystemInfoDataSource](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if earlyReturn { - return // do not proceed - } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 2); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 8).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) + earlyReturn = true } - return - } - oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotStorage) *v1.SnapshotStorageState { - return &oldObj.State - }) - errs = append(errs, fn(fldPath.Child("state"), &obj.State, oldVal, oldObj != nil)...) - } - - { // field v1.SnapshotStorage.Object - fn := func( - fldPath *field.Path, - obj, oldObj *v1.ObjectSnapshot, - oldValueCorrelated bool) (errs field.ErrorList) { - // don't revalidate unchanged data - if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { - return nil - } - } - // call field-attached validations - earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_ObjectSnapshot(ctx, op, fldPath, obj, oldObj)...) + // custom validation + if e := ValidateCustom_SystemInfoVolumeSource_DataSources(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_SystemInfoDataSource); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SnapshotStorage) *v1.ObjectSnapshot { - return oldObj.Object + func(oldObj *v1.SystemInfoVolumeSource) []*v1.SystemInfoDataSource { + return oldObj.DataSources }) - errs = append(errs, fn(fldPath.Child("object"), obj.Object, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("data_sources"), obj.DataSources, oldVal, oldObj != nil)...) } return errs } -// Validate_SuspendActorRequest validates an instance of SuspendActorRequest according +// Validate_Tag validates an instance of Tag according // to declarative validation rules in the API schema. -func Validate_SuspendActorRequest( +func Validate_Tag( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SuspendActorRequest) (errs field.ErrorList) { + obj, oldObj *v1.Tag) (errs field.ErrorList) { - { // field v1.SuspendActorRequest.Actor + { // field v1.Tag.Metadata fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj *v1.ResourceMetadata, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8577,33 +9891,32 @@ func Validate_SuspendActorRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } }() // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_ResourceMetadata(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SuspendActorRequest) *v1.ObjectRef { - return oldObj.Actor + func(oldObj *v1.Tag) *v1.ResourceMetadata { + return oldObj.Metadata }) - errs = append(errs, fn(fldPath.Child("actor"), obj.Actor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("metadata"), obj.Metadata, oldVal, oldObj != nil)...) } - { // field v1.SuspendActorRequest.Options + { // field v1.Tag.Status fn := func( fldPath *field.Path, - obj, oldObj *v1.SuspendOptions, + obj, oldObj *v1.TagStatus, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8616,33 +9929,28 @@ func Validate_SuspendActorRequest( if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } + if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoUnset).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } if earlyReturn { return // do not proceed } // call the type's validation function - errs = append(errs, Validate_SuspendOptions(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_TagStatus(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SuspendActorRequest) *v1.SuspendOptions { - return oldObj.Options + func(oldObj *v1.Tag) *v1.TagStatus { + return oldObj.Status }) - errs = append(errs, fn(fldPath.Child("options"), obj.Options, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("status"), obj.Status, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_SuspendOptions validates an instance of SuspendOptions according -// to declarative validation rules in the API schema. -func Validate_SuspendOptions( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SuspendOptions) (errs field.ErrorList) { - - { // field v1.SuspendOptions.Mode + { // field v1.Tag.Scope fn := func( fldPath *field.Path, - obj, oldObj *v1.DurabilityMode, + obj, oldObj *v1.TagScope, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8652,7 +9960,8 @@ func Validate_SuspendOptions( } // call field-attached validations earlyReturn := false - if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { @@ -8667,43 +9976,74 @@ func Validate_SuspendOptions( return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SuspendOptions) *v1.DurabilityMode { - return &oldObj.Mode + func(oldObj *v1.Tag) *v1.TagScope { + return &oldObj.Scope + }) + errs = append(errs, fn(fldPath.Child("scope"), &obj.Scope, oldVal, oldObj != nil)...) + } + + { // field v1.Tag.SourceActor + fn := func( + fldPath *field.Path, + obj, oldObj *v1.ObjectRef, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + func() { // cohort = "atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + // call the type's validation function + errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.Tag) *v1.ObjectRef { + return oldObj.SourceActor }) - errs = append(errs, fn(fldPath.Child("mode"), &obj.Mode, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("source_actor"), obj.SourceActor, oldVal, oldObj != nil)...) } return errs } -var unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_SystemInfoDataSource_ = validate.NewUnionMembership(validate.NewUnionMember("actor_metadata"), validate.NewUnionMember("trust_bundle")) - -// Validate_SystemInfoDataSource validates an instance of SystemInfoDataSource according +// Validate_TagStatus validates an instance of TagStatus according // to declarative validation rules in the API schema. -func Validate_SystemInfoDataSource( +func Validate_TagStatus( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SystemInfoDataSource) (errs field.ErrorList) { - - if e := validate.Union(ctx, op, fldPath, obj, oldObj, unionMembershipFor_go_ate_dev_substrate_api_ateapi_v1_SystemInfoDataSource_, - func(obj *v1.SystemInfoDataSource) bool { - if obj == nil { - return false - } - return obj.ActorMetadata != nil - }, - func(obj *v1.SystemInfoDataSource) bool { - if obj == nil { - return false - } - return obj.TrustBundle != nil - }); len(e) != 0 { - errs = append(errs, e...) - } + obj, oldObj *v1.TagStatus) (errs field.ErrorList) { - { // field v1.SystemInfoDataSource.ActorMetadata + { // field v1.TagStatus.Snapshot fn := func( fldPath *field.Path, - obj, oldObj *v1.ActorMetadataDataSource, + obj, oldObj *v1.Snapshot, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8716,63 +10056,91 @@ func Validate_SystemInfoDataSource( if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } + if e := validate.UpdatePointer(ctx, op, fldPath, obj, oldObj, validate.NoUnset).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } if earlyReturn { return // do not proceed } + // custom validation + if e := ValidateCustom_TagStatus_Snapshot(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + func() { // cohort = "durable_snapshot" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "durable_snapshot", + func(o *v1.Snapshot) *v1.SnapshotStorage { return o.DurableSnapshot }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.SnapshotStorage) field.ErrorList { + return validate.RequiredPointer(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() // call the type's validation function - errs = append(errs, Validate_ActorMetadataDataSource(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_Snapshot(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SystemInfoDataSource) *v1.ActorMetadataDataSource { - return oldObj.ActorMetadata + func(oldObj *v1.TagStatus) *v1.Snapshot { + return oldObj.Snapshot }) - errs = append(errs, fn(fldPath.Child("actor_metadata"), obj.ActorMetadata, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("snapshot"), obj.Snapshot, oldVal, oldObj != nil)...) } - { // field v1.SystemInfoDataSource.TrustBundle + { // field v1.TagStatus.ActorTemplateUid fn := func( fldPath *field.Path, - obj, oldObj *v1.TrustBundleDataSource, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_TrustBundleDataSource(ctx, op, fldPath, obj, oldObj)...) + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SystemInfoDataSource) *v1.TrustBundleDataSource { - return oldObj.TrustBundle + func(oldObj *v1.TagStatus) *string { + return &oldObj.ActorTemplateUid }) - errs = append(errs, fn(fldPath.Child("trust_bundle"), obj.TrustBundle, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("actor_template_uid"), &obj.ActorTemplateUid, oldVal, oldObj != nil)...) } return errs } -// Validate_SystemInfoVolumeSource validates an instance of SystemInfoVolumeSource according +// Validate_TlsPassthroughRule validates an instance of TlsPassthroughRule according // to declarative validation rules in the API schema. -func Validate_SystemInfoVolumeSource( +func Validate_TlsPassthroughRule( ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.SystemInfoVolumeSource) (errs field.ErrorList) { + obj, oldObj *v1.TlsPassthroughRule) (errs field.ErrorList) { - { // field v1.SystemInfoVolumeSource.DataSources + { // field v1.TlsPassthroughRule.Hostnames fn := func( fldPath *field.Path, - obj, oldObj []*v1.SystemInfoDataSource, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8782,50 +10150,38 @@ func Validate_SystemInfoVolumeSource( } // call field-attached validations earlyReturn := false - if e := validate.PtrSliceNoNils[v1.SystemInfoDataSource](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 8).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } // custom validation - if e := ValidateCustom_SystemInfoVolumeSource_DataSources(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := ValidateCustom_TlsPassthroughRule_Hostnames(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } - // iterate the list and call the type's validation function - if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_SystemInfoDataSource); len(e) != 0 { + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.SystemInfoVolumeSource) []*v1.SystemInfoDataSource { - return oldObj.DataSources + func(oldObj *v1.TlsPassthroughRule) []string { + return oldObj.Hostnames }) - errs = append(errs, fn(fldPath.Child("data_sources"), obj.DataSources, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("hostnames"), obj.Hostnames, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_Tag validates an instance of Tag according -// to declarative validation rules in the API schema. -func Validate_Tag( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.Tag) (errs field.ErrorList) { - - { // field v1.Tag.Metadata + { // field v1.TlsPassthroughRule.Ports fn := func( fldPath *field.Path, - obj, oldObj *v1.ResourceMetadata, + obj, oldObj *v1.Ports, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8842,105 +10198,97 @@ func Validate_Tag( if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.Immutable).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() // call the type's validation function - errs = append(errs, Validate_ResourceMetadata(ctx, op, fldPath, obj, oldObj)...) + errs = append(errs, Validate_Ports(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Tag) *v1.ResourceMetadata { - return oldObj.Metadata + func(oldObj *v1.TlsPassthroughRule) *v1.Ports { + return oldObj.Ports }) - errs = append(errs, fn(fldPath.Child("metadata"), obj.Metadata, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("ports"), obj.Ports, oldVal, oldObj != nil)...) } - { // field v1.Tag.Status + return errs +} + +// Validate_TokenExchangeSource validates an instance of TokenExchangeSource according +// to declarative validation rules in the API schema. +func Validate_TokenExchangeSource( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.TokenExchangeSource) (errs field.ErrorList) { + + { // field v1.TokenExchangeSource.TokenUrl fn := func( fldPath *field.Path, - obj, oldObj *v1.TagStatus, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_TagStatus(ctx, op, fldPath, obj, oldObj)...) + // custom validation + if e := ValidateCustom_TokenExchangeSource_TokenUrl(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 2048); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Tag) *v1.TagStatus { - return oldObj.Status + func(oldObj *v1.TokenExchangeSource) *string { + return &oldObj.TokenUrl }) - errs = append(errs, fn(fldPath.Child("status"), obj.Status, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("token_url"), &obj.TokenUrl, oldVal, oldObj != nil)...) } - { // field v1.Tag.Scope + { // field v1.TokenExchangeSource.SubjectActorJwt fn := func( fldPath *field.Path, - obj, oldObj *v1.TagScope, + obj, oldObj *v1.ActorJwtSource, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if earlyReturn { return // do not proceed } - if e := validate.Maximum(ctx, op, fldPath, obj, oldObj, 2); len(e) != 0 { - errs = append(errs, e...) - } - if e := validate.Minimum(ctx, op, fldPath, obj, oldObj, 1); len(e) != 0 { - errs = append(errs, e...) - } + // call the type's validation function + errs = append(errs, Validate_ActorJwtSource(ctx, op, fldPath, obj, oldObj)...) return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Tag) *v1.TagScope { - return &oldObj.Scope + func(oldObj *v1.TokenExchangeSource) *v1.ActorJwtSource { + return oldObj.SubjectActorJwt }) - errs = append(errs, fn(fldPath.Child("scope"), &obj.Scope, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("subject_actor_jwt"), obj.SubjectActorJwt, oldVal, oldObj != nil)...) } - { // field v1.Tag.SourceActor + { // field v1.TokenExchangeSource.Resources fn := func( fldPath *field.Path, - obj, oldObj *v1.ObjectRef, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -8950,56 +10298,49 @@ func Validate_Tag( } // call field-attached validations earlyReturn := false - if e := validate.Immutable(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "atespace" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_ObjectRef(ctx, op, fldPath, obj, oldObj)...) + // custom validation + if e := ValidateCustom_TokenExchangeSource_Resources(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MinLength(ctx, op, fldPath, obj, oldObj, 1) + }); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MaxLength(ctx, op, fldPath, obj, oldObj, 2048) + }); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.Tag) *v1.ObjectRef { - return oldObj.SourceActor + func(oldObj *v1.TokenExchangeSource) []string { + return oldObj.Resources }) - errs = append(errs, fn(fldPath.Child("source_actor"), obj.SourceActor, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("resources"), obj.Resources, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_TagStatus validates an instance of TagStatus according -// to declarative validation rules in the API schema. -func Validate_TagStatus( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.TagStatus) (errs field.ErrorList) { - - { // field v1.TagStatus.Snapshot + { // field v1.TokenExchangeSource.Audiences fn := func( fldPath *field.Path, - obj, oldObj *v1.Snapshot, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -9009,124 +10350,128 @@ func Validate_TagStatus( } // call field-attached validations earlyReturn := false - if e := validate.OptionalPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - func() { // cohort = "durable_snapshot" - earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "durable_snapshot", - func(o *v1.Snapshot) *v1.SnapshotStorage { return o.DurableSnapshot }, ateDeepEqual, validate.RequiredPointer).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "durable_snapshot", - func(o *v1.Snapshot) *v1.SnapshotStorage { return o.DurableSnapshot }, ateDeepEqual, validate.OptionalPointer).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if earlyReturn { - return // do not proceed - } - }() - // call the type's validation function - errs = append(errs, Validate_Snapshot(ctx, op, fldPath, obj, oldObj)...) + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MinLength(ctx, op, fldPath, obj, oldObj, 1) + }); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MaxLength(ctx, op, fldPath, obj, oldObj, 512) + }); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.TagStatus) *v1.Snapshot { - return oldObj.Snapshot + func(oldObj *v1.TokenExchangeSource) []string { + return oldObj.Audiences }) - errs = append(errs, fn(fldPath.Child("snapshot"), obj.Snapshot, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("audiences"), obj.Audiences, oldVal, oldObj != nil)...) } - { // field v1.TagStatus.ActorTemplateUid + { // field v1.TokenExchangeSource.Scopes fn := func( fldPath *field.Path, - obj, oldObj *string, + obj, oldObj []string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + if ateDeepEqual(obj, oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.RequiredValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } if earlyReturn { return // do not proceed } - if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + // custom validation + if e := ValidateCustom_TokenExchangeSource_Scopes(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MinLength(ctx, op, fldPath, obj, oldObj, 1) + }); len(e) != 0 { + errs = append(errs, e...) + } + if e := validate.EachValSliceVal(ctx, op, fldPath, obj, oldObj, validate.DirectEqual, nil, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256) + }); len(e) != 0 { + errs = append(errs, e...) + } + // lists with set semantics require unique values + if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.TagStatus) *string { - return &oldObj.ActorTemplateUid + func(oldObj *v1.TokenExchangeSource) []string { + return oldObj.Scopes }) - errs = append(errs, fn(fldPath.Child("actor_template_uid"), &obj.ActorTemplateUid, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("scopes"), obj.Scopes, oldVal, oldObj != nil)...) } - return errs -} - -// Validate_TlsPassthroughRule validates an instance of TlsPassthroughRule according -// to declarative validation rules in the API schema. -func Validate_TlsPassthroughRule( - ctx context.Context, op operation.Operation, fldPath *field.Path, - obj, oldObj *v1.TlsPassthroughRule) (errs field.ErrorList) { - - { // field v1.TlsPassthroughRule.Hostnames + { // field v1.TokenExchangeSource.RequestedTokenType fn := func( fldPath *field.Path, - obj, oldObj []string, + obj, oldObj *string, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { - if ateDeepEqual(obj, oldObj) { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { return nil } } // call field-attached validations earlyReturn := false - if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 256).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } - if e := validate.RequiredSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_TlsPassthroughRule_Hostnames(ctx, op, fldPath, obj, oldObj); len(e) != 0 { - errs = append(errs, e...) - } - // lists with set semantics require unique values - if e := validate.ValSliceUnique(ctx, op, fldPath, obj, oldObj, validate.DirectEqual); len(e) != 0 { + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 512); len(e) != 0 { errs = append(errs, e...) } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.TlsPassthroughRule) []string { - return oldObj.Hostnames + func(oldObj *v1.TokenExchangeSource) *string { + return &oldObj.RequestedTokenType }) - errs = append(errs, fn(fldPath.Child("hostnames"), obj.Hostnames, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("requested_token_type"), &obj.RequestedTokenType, oldVal, oldObj != nil)...) } - { // field v1.TlsPassthroughRule.Ports + { // field v1.TokenExchangeSource.AdditionalParameters fn := func( fldPath *field.Path, - obj, oldObj *v1.Ports, + obj, oldObj []*v1.FormEntry, oldValueCorrelated bool) (errs field.ErrorList) { // don't revalidate unchanged data if oldValueCorrelated && op.Type == operation.Update { @@ -9136,22 +10481,35 @@ func Validate_TlsPassthroughRule( } // call field-attached validations earlyReturn := false - if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + if e := validate.PtrSliceNoNils[v1.FormEntry](ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.MaxItems(ctx, op, fldPath, obj, oldObj, 16).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } + if e := validate.OptionalSlice(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } if earlyReturn { return // do not proceed } - // call the type's validation function - errs = append(errs, Validate_Ports(ctx, op, fldPath, obj, oldObj)...) + // custom validation + if e := ValidateCustom_TokenExchangeSource_AdditionalParameters(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + // iterate the list and call the type's validation function + if e := validate.EachPtrSliceVal(ctx, op, fldPath, obj, oldObj, nil, nil, Validate_FormEntry); len(e) != 0 { + errs = append(errs, e...) + } return } oldVal := safe.Field(oldObj, - func(oldObj *v1.TlsPassthroughRule) *v1.Ports { - return oldObj.Ports + func(oldObj *v1.TokenExchangeSource) []*v1.FormEntry { + return oldObj.AdditionalParameters }) - errs = append(errs, fn(fldPath.Child("ports"), obj.Ports, oldVal, oldObj != nil)...) + errs = append(errs, fn(fldPath.Child("additional_parameters"), obj.AdditionalParameters, oldVal, oldObj != nil)...) } return errs @@ -9291,14 +10649,13 @@ func Validate_UpdateActorEgressPolicyRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.RequiredValue).MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } if earlyReturn { return // do not proceed } @@ -9381,7 +10738,28 @@ func Validate_UpdateActorRequest( func() { // cohort = "metadata" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", - func(o *v1.Actor) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, validate.RequiredPointer).MarkShortCircuit(); len(e) != 0 { + func(o *v1.Actor) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.RequiredPointer(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + func() { // cohort = "metadata.atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", + func(o *v1.Actor) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } @@ -9430,16 +10808,15 @@ func Validate_UpdateAtespaceAccessPolicyRequest( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -9491,6 +10868,88 @@ func Validate_UpdateAtespaceAccessPolicyRequest( return errs } +// Validate_UpdateCsiDriverRequest validates an instance of UpdateCsiDriverRequest according +// to declarative validation rules in the API schema. +func Validate_UpdateCsiDriverRequest( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *v1.UpdateCsiDriverRequest) (errs field.ErrorList) { + + { // field v1.UpdateCsiDriverRequest.CsiDriver + fn := func( + fldPath *field.Path, + obj, oldObj *v1.CsiDriver, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if ateDeepEqual(obj, oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.RequiredPointer(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + // custom validation + if e := ValidateCustom_UpdateCsiDriverRequest_CsiDriver(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + func() { // cohort = "metadata" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", + func(o *v1.CsiDriver) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.RequiredPointer(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + func() { // cohort = "metadata.atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", + func(o *v1.CsiDriver) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", + func(o *v1.CsiDriver) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue) + }).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.UpdateCsiDriverRequest) *v1.CsiDriver { + return oldObj.CsiDriver + }) + errs = append(errs, fn(fldPath.Child("csi_driver"), obj.CsiDriver, oldVal, oldObj != nil)...) + } + + return errs +} + // Validate_UpdateGlobalAccessPolicyRequest validates an instance of UpdateGlobalAccessPolicyRequest according // to declarative validation rules in the API schema. func Validate_UpdateGlobalAccessPolicyRequest( @@ -9564,7 +11023,28 @@ func Validate_UpdateTagRequest( func() { // cohort = "metadata" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", - func(o *v1.Tag) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, validate.RequiredPointer).MarkShortCircuit(); len(e) != 0 { + func(o *v1.Tag) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.RequiredPointer(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + func() { // cohort = "metadata.atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", + func(o *v1.Tag) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.RequiredValue(ctx, op, fldPath, obj, oldObj) + }) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } @@ -9617,10 +11097,39 @@ func Validate_UpdateWorkerRequest( func() { // cohort = "metadata" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", - func(o *v1.Worker) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, validate.RequiredPointer).MarkShortCircuit(); len(e) != 0 { + func(o *v1.Worker) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.RequiredPointer(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + }() + func() { // cohort = "metadata.atespace" + earlyReturn := false + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", + func(o *v1.Worker) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "metadata", + func(o *v1.Worker) *v1.ResourceMetadata { return o.Metadata }, ateDeepEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ResourceMetadata) field.ErrorList { + return validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue) + }).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } if earlyReturn { return // do not proceed } @@ -9834,7 +11343,10 @@ func Validate_Volume( } // call field-attached validations earlyReturn := false - if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "ExternalVolumes", false, validate.ForbiddenPointer).MarkShortCircuit(); len(e) != 0 { + if e := validate.IfOption(ctx, op, fldPath, obj, oldObj, "ExternalVolumes", false, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *v1.ExternalVolumeSource) field.ErrorList { + return validate.ForbiddenPointer(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } @@ -10102,20 +11614,15 @@ func Validate_Worker( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.Immutable).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ResourceMetadata) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -10456,16 +11963,15 @@ func Validate_WorkerAssignment( func() { // cohort = "atespace" earlyReturn := false if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.ForbiddenValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.ForbiddenValue(ctx, op, fldPath, obj, oldObj) + }).MarkShortCircuit(); len(e) != 0 { errs = append(errs, e...) earlyReturn = true } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "atespace", - func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkBeta().MarkShortCircuit(); len(e) != 0 { + func(o *v1.ObjectRef) *string { return &o.Atespace }, validate.DirectEqual, validate.OptionalValue).MarkShortCircuit(); len(e) != 0 { earlyReturn = true } if earlyReturn { @@ -10810,6 +12316,37 @@ func Validate_WorkerAssignment( errs = append(errs, fn(fldPath.Child("worker_spiffe_id"), &obj.WorkerSpiffeId, oldVal, oldObj != nil)...) } + { // field v1.WorkerAssignment.ActorActivationUid + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *v1.WorkerAssignment) *string { + return &oldObj.ActorActivationUid + }) + errs = append(errs, fn(fldPath.Child("actor_activation_uid"), &obj.ActorActivationUid, oldVal, oldObj != nil)...) + } + return errs } diff --git a/cmd/ateapi/internal/authz/authorizer.go b/cmd/ateapi/internal/authz/authorizer.go index dac3a324f0..1888944b28 100644 --- a/cmd/ateapi/internal/authz/authorizer.go +++ b/cmd/ateapi/internal/authz/authorizer.go @@ -52,9 +52,9 @@ type Authorizer struct { } // Check verifies that the principal in ctx has relation on object. -// Structural hierarchy links (global:root as parent_global of every atespace -// and worker, and each atespace as parent_atespace of its actors, actor -// templates and tags) and +// Structural hierarchy links (global:root as parent_global of every atespace, +// worker and CSI driver, and each atespace as parent_atespace of its +// actors, actor templates, tags and external volumes) and // the caller's bootstrap owner and system role grants, if any, are injected as OpenFGA // ContextualTuples at evaluation time rather than persisted in the tuple table. func (a *Authorizer) Check(ctx context.Context, relation, object string) error { @@ -129,22 +129,24 @@ func (a *Authorizer) checkRaw(ctx context.Context, user, relation, object string // tuples in PostgreSQL. // // Why contextual tuples are used instead of storing parent links in the database: -// 1. Deterministic structure: Every `atespace:` and `worker:` -// unconditionally has `global:root` as its `parent_global`, and every -// `actor:/`, `actor_template:/` and -// `tag:/` has `atespace:` as its -// `parent_atespace`. Because these +// 1. Deterministic structure: Every `atespace:`, `worker:` and +// `csi_driver:` unconditionally has `global:root` as its +// `parent_global`, and every `actor:/`, +// `actor_template:/`, `tag:/` and +// `external_volume:/` has +// `atespace:` as its `parent_atespace`. Because these // relationships are derived purely from the object type/ID, storing a row // per resource in the OpenFGA `tuple` table would be redundant. // 2. No write amplification on create: `CreateAtespace`, `CreateWorker`, -// `CreateActorTemplate`, `CreateActor` and `CreateTag` can insert their rows without -// opening an OpenFGA write transaction just to link the parent. +// `CreateCsiDriver`, `CreateActorTemplate`, `CreateActor` and +// `CreateTag` can insert their rows without opening an OpenFGA write +// transaction just to link the parent. func contextualTuples(object string) []*openfgav1.TupleKey { objectType, id, _ := strings.Cut(object, ":") switch objectType { - case "atespace", "worker": + case "atespace", "worker", "csi_driver": return []*openfgav1.TupleKey{parentGlobalTuple(object)} - case "actor", "actor_template", "tag": + case "actor", "actor_template", "tag", "external_volume": atespace, _, ok := strings.Cut(id, "/") if !ok { return nil @@ -159,8 +161,8 @@ func contextualTuples(object string) []*openfgav1.TupleKey { return nil } -// parentGlobalTuple links a global-scoped object (an atespace or a worker) to -// global:root. +// parentGlobalTuple links a global-scoped object (an atespace, worker or CSI +// driver) to global:root. func parentGlobalTuple(object string) *openfgav1.TupleKey { return &openfgav1.TupleKey{ User: GlobalRootObject, diff --git a/cmd/ateapi/internal/authz/authorizer_test.go b/cmd/ateapi/internal/authz/authorizer_test.go index c35b7179e0..172fa18ec5 100644 --- a/cmd/ateapi/internal/authz/authorizer_test.go +++ b/cmd/ateapi/internal/authz/authorizer_test.go @@ -50,6 +50,11 @@ func TestContextualTuples(t *testing.T) { object: WorkerObject("w-1"), want: []*openfgav1.TupleKey{parentGlobal("worker:w-1")}, }, + { + name: "csi driver", + object: CSIDriverObject("csi-nfs"), + want: []*openfgav1.TupleKey{parentGlobal("csi_driver:csi-nfs")}, + }, { name: "actor", object: ActorObject("team-a", "runner"), @@ -66,6 +71,14 @@ func TestContextualTuples(t *testing.T) { parentGlobal("atespace:shared"), }, }, + { + name: "external volume", + object: ExternalVolumeObject("team-a", "ctx"), + want: []*openfgav1.TupleKey{ + parentAtespace("atespace:team-a", "external_volume:team-a/ctx"), + parentGlobal("atespace:team-a"), + }, + }, { name: "parent of an escaped actor is the atespace's own object", object: ActorObject("a/b", "c"), diff --git a/cmd/ateapi/internal/authz/authz_util.go b/cmd/ateapi/internal/authz/authz_util.go index 092beb80fd..b2f86f88a1 100644 --- a/cmd/ateapi/internal/authz/authz_util.go +++ b/cmd/ateapi/internal/authz/authz_util.go @@ -78,8 +78,11 @@ const ( RelationCanCreateTag = "can_create_tag" RelationCanListTags = "can_list_tags" RelationCanUseTag = "can_use_tag" + RelationCanListExternalVolumes = "can_list_external_volumes" RelationCanMintActorJWT = "can_mint_actor_jwt" + RelationCanCreateCSIDriver = "can_create_csi_driver" + RelationCanListCSIDrivers = "can_list_csi_drivers" // maxTuplesPerWrite is OpenFGA's default maximum number of tuples allowed in a single Write request. maxTuplesPerWrite = 100 ) @@ -128,6 +131,12 @@ func WorkerObject(name string) string { return "worker:" + objectIDReplacer.Replace(name) } +// CSIDriverObject formats a CSI driver name as an OpenFGA object string. +// CSI drivers are global-scoped. +func CSIDriverObject(name string) string { + return "csi_driver:" + objectIDReplacer.Replace(name) +} + // ActorObject formats an actor as an OpenFGA object string. func ActorObject(atespace, name string) string { return "actor:" + atespacedID(atespace, name) @@ -143,6 +152,11 @@ func TagObject(atespace, name string) string { return "tag:" + atespacedID(atespace, name) } +// ExternalVolumeObject formats an external volume as an OpenFGA object string. +func ExternalVolumeObject(atespace, name string) string { + return "external_volume:" + atespacedID(atespace, name) +} + // atespacedID formats the object ID of an atespaced resource as // "/". contextualTuples parses the atespace back out of it. func atespacedID(atespace, name string) string { @@ -230,10 +244,11 @@ func EnsureStoreAndModel(ctx context.Context, pool *pgxpool.Pool, fgaServer *ser // SystemPrincipals holds the mTLS SPIFFE IDs of Substrate's own components. // The Authorizer grants each one its system component role on global:root on // every check, independent of any stored AccessPolicy. +// An empty gateway list leaves that role with no holder. type SystemPrincipals struct { ControllerSPIFFEID string EgressGatewaySPIFFEIDs []string - IngressRouterSPIFFEID string + IngressRouterSPIFFEIDs []string AteletSPIFFEID string APIServerSidecarSPIFFEID string } @@ -288,19 +303,18 @@ func parseBootstrapOwners(ids []string) (map[string]struct{}, error) { // parseSystemPrincipals validates system's SPIFFE IDs and maps each OpenFGA // user string to the system component roles it holds. func parseSystemPrincipals(system SystemPrincipals) (map[string][]string, error) { - if len(system.EgressGatewaySPIFFEIDs) == 0 { - return nil, fmt.Errorf("no %s SPIFFE ID", RoleEgressGateway) - } type binding struct { role string spiffeID string } bindings := []binding{ {role: RoleController, spiffeID: system.ControllerSPIFFEID}, - {role: RoleIngressRouter, spiffeID: system.IngressRouterSPIFFEID}, {role: RoleAtelet, spiffeID: system.AteletSPIFFEID}, {role: RoleAPIServerSidecar, spiffeID: system.APIServerSidecarSPIFFEID}, } + for _, id := range system.IngressRouterSPIFFEIDs { + bindings = append(bindings, binding{role: RoleIngressRouter, spiffeID: id}) + } for _, id := range system.EgressGatewaySPIFFEIDs { bindings = append(bindings, binding{role: RoleEgressGateway, spiffeID: id}) } diff --git a/cmd/ateapi/internal/authz/authz_util_test.go b/cmd/ateapi/internal/authz/authz_util_test.go index 4c66881fc8..59ee03ae7c 100644 --- a/cmd/ateapi/internal/authz/authz_util_test.go +++ b/cmd/ateapi/internal/authz/authz_util_test.go @@ -27,7 +27,7 @@ func testSystemPrincipals() SystemPrincipals { return SystemPrincipals{ ControllerSPIFFEID: installdefaults.ControllerSPIFFEID(installdefaults.SystemNamespace), EgressGatewaySPIFFEIDs: []string{installdefaults.EgressSPIFFEID(installdefaults.SystemNamespace)}, - IngressRouterSPIFFEID: installdefaults.RouterSPIFFEID(installdefaults.SystemNamespace), + IngressRouterSPIFFEIDs: []string{installdefaults.RouterSPIFFEID(installdefaults.SystemNamespace)}, AteletSPIFFEID: installdefaults.AteletSPIFFEID(installdefaults.SystemNamespace), APIServerSidecarSPIFFEID: installdefaults.APIServerSPIFFEID(installdefaults.SystemNamespace), } @@ -94,25 +94,49 @@ func TestParseBootstrapOwners(t *testing.T) { func TestParseSystemPrincipals(t *testing.T) { const router = "spiffe://cluster.local/ns/ate-system/sa/atenet-router" - got, err := parseSystemPrincipals(SystemPrincipals{ - ControllerSPIFFEID: "spiffe://cluster.local/ns/ate-system/sa/ate-controller", - EgressGatewaySPIFFEIDs: []string{router, "spiffe://cluster.local/ns/plugins/sa/token-exchange"}, - IngressRouterSPIFFEID: router, - AteletSPIFFEID: "spiffe://cluster.local/ns/ate-system/sa/atelet", - APIServerSidecarSPIFFEID: "spiffe://cluster.local/ns/ate-system/sa/ate-api-server", - }) - if err != nil { - t.Fatalf("parseSystemPrincipals failed: %v", err) - } - want := map[string][]string{ - "user:spiffe%3A//cluster.local/ns/ate-system/sa/ate-controller": {RoleController}, - "user:spiffe%3A//cluster.local/ns/ate-system/sa/atenet-router": {RoleIngressRouter, RoleEgressGateway}, - "user:spiffe%3A//cluster.local/ns/plugins/sa/token-exchange": {RoleEgressGateway}, - "user:spiffe%3A//cluster.local/ns/ate-system/sa/atelet": {RoleAtelet}, - "user:spiffe%3A//cluster.local/ns/ate-system/sa/ate-api-server": {RoleAPIServerSidecar}, - } - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("parseSystemPrincipals (-want +got):\n%s", diff) + for _, tc := range []struct { + name string + egressGateways []string + ingressRouters []string + want map[string][]string + }{ + { + name: "several gateway IDs", + egressGateways: []string{router, "spiffe://cluster.local/ns/plugins/sa/token-exchange"}, + ingressRouters: []string{router, "spiffe://cluster.local/ns/gateways/sa/ingress"}, + want: map[string][]string{ + "user:spiffe%3A//cluster.local/ns/ate-system/sa/ate-controller": {RoleController}, + "user:spiffe%3A//cluster.local/ns/ate-system/sa/atenet-router": {RoleIngressRouter, RoleEgressGateway}, + "user:spiffe%3A//cluster.local/ns/gateways/sa/ingress": {RoleIngressRouter}, + "user:spiffe%3A//cluster.local/ns/plugins/sa/token-exchange": {RoleEgressGateway}, + "user:spiffe%3A//cluster.local/ns/ate-system/sa/atelet": {RoleAtelet}, + "user:spiffe%3A//cluster.local/ns/ate-system/sa/ate-api-server": {RoleAPIServerSidecar}, + }, + }, + { + name: "no gateway IDs", + want: map[string][]string{ + "user:spiffe%3A//cluster.local/ns/ate-system/sa/ate-controller": {RoleController}, + "user:spiffe%3A//cluster.local/ns/ate-system/sa/atelet": {RoleAtelet}, + "user:spiffe%3A//cluster.local/ns/ate-system/sa/ate-api-server": {RoleAPIServerSidecar}, + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := parseSystemPrincipals(SystemPrincipals{ + ControllerSPIFFEID: "spiffe://cluster.local/ns/ate-system/sa/ate-controller", + EgressGatewaySPIFFEIDs: tc.egressGateways, + IngressRouterSPIFFEIDs: tc.ingressRouters, + AteletSPIFFEID: "spiffe://cluster.local/ns/ate-system/sa/atelet", + APIServerSidecarSPIFFEID: "spiffe://cluster.local/ns/ate-system/sa/ate-api-server", + }) + if err != nil { + t.Fatalf("parseSystemPrincipals failed: %v", err) + } + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("parseSystemPrincipals (-want +got):\n%s", diff) + } + }) } } @@ -124,11 +148,10 @@ func TestNewRejectsInvalidSystemPrincipals(t *testing.T) { wantErr string }{ {"empty controller SPIFFE ID", func(p *SystemPrincipals) { p.ControllerSPIFFEID = "" }, "invalid controller SPIFFE ID"}, - {"no egress gateway SPIFFE IDs", func(p *SystemPrincipals) { p.EgressGatewaySPIFFEIDs = nil }, "no egress_gateway SPIFFE ID"}, {"empty egress gateway SPIFFE ID in list", func(p *SystemPrincipals) { p.EgressGatewaySPIFFEIDs = []string{defaults.EgressGatewaySPIFFEIDs[0], ""} }, "invalid egress_gateway SPIFFE ID"}, - {"empty ingress router SPIFFE ID", func(p *SystemPrincipals) { p.IngressRouterSPIFFEID = "" }, "invalid ingress_router SPIFFE ID"}, + {"empty ingress router SPIFFE ID", func(p *SystemPrincipals) { p.IngressRouterSPIFFEIDs = []string{""} }, "invalid ingress_router SPIFFE ID"}, {"empty atelet SPIFFE ID", func(p *SystemPrincipals) { p.AteletSPIFFEID = "" }, "invalid atelet SPIFFE ID"}, {"empty api server sidecar SPIFFE ID", func(p *SystemPrincipals) { p.APIServerSidecarSPIFFEID = "" }, "invalid api_server_sidecar SPIFFE ID"}, {"bare ServiceAccount name", func(p *SystemPrincipals) { p.ControllerSPIFFEID = "ate-controller" }, "invalid controller SPIFFE ID"}, diff --git a/cmd/ateapi/internal/authz/interceptor_test.go b/cmd/ateapi/internal/authz/interceptor_test.go index f8383c0f69..0257f8e951 100644 --- a/cmd/ateapi/internal/authz/interceptor_test.go +++ b/cmd/ateapi/internal/authz/interceptor_test.go @@ -483,6 +483,10 @@ func TestUnaryServerInterceptor_LifecycleEgressWorkerAndTagChecks(t *testing.T) Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "v1"}, }}} deleteTag := rpcCall{ateapi.Control_DeleteTag_FullMethodName, &ateapi.DeleteTagRequest{Tag: tag}} + externalVolume := &ateapi.ObjectRef{Atespace: "team-a", Name: "ctx"} + getExternalVolume := rpcCall{ateapi.Control_GetExternalVolume_FullMethodName, &ateapi.GetExternalVolumeRequest{ExternalVolume: externalVolume}} + listExternalVolumes := rpcCall{ateapi.Control_ListExternalVolumes_FullMethodName, &ateapi.ListExternalVolumesRequest{Atespace: "team-a"}} + listAllExternalVolumes := rpcCall{ateapi.Control_ListExternalVolumes_FullMethodName, &ateapi.ListExternalVolumesRequest{}} mintJWT := rpcCall{ateapi.Control_MintActorJwt_FullMethodName, &ateapi.MintActorJwtRequest{Actor: actor}} // cloneTag creates an actor in atespace from team-a's tag v1, with a // template in that same atespace so only the tag check can differ. @@ -586,6 +590,15 @@ func TestUnaryServerInterceptor_LifecycleEgressWorkerAndTagChecks(t *testing.T) {"editor cannot mint actor JWT", "editor", mintJWT, codes.PermissionDenied}, {"global owner cannot mint actor JWT", "global-owner", mintJWT, codes.PermissionDenied}, {"bootstrap owner cannot mint actor JWT", "bootstrap-owner", mintJWT, codes.PermissionDenied}, + + // External volumes: viewers read within the owning atespace. + {"viewer gets external volume", "viewer", getExternalVolume, codes.OK}, + {"global viewer gets external volume", "global-viewer", getExternalVolume, codes.OK}, + {"outsider cannot get external volume", "outsider", getExternalVolume, codes.PermissionDenied}, + {"viewer lists external volumes", "viewer", listExternalVolumes, codes.OK}, + {"outsider cannot list external volumes", "outsider", listExternalVolumes, codes.PermissionDenied}, + {"global viewer lists all external volumes", "global-viewer", listAllExternalVolumes, codes.OK}, + {"atespace editor cannot list all external volumes", "editor", listAllExternalVolumes, codes.PermissionDenied}, } interceptor := UnaryServerInterceptor(authorizer) @@ -626,7 +639,7 @@ func TestUnaryServerInterceptor_SystemPrincipals(t *testing.T) { authorizer, _, err := New(ctx, pool, fgaServer, nil, SystemPrincipals{ ControllerSPIFFEID: controllerID, EgressGatewaySPIFFEIDs: []string{egressID}, - IngressRouterSPIFFEID: routerID, + IngressRouterSPIFFEIDs: []string{routerID}, AteletSPIFFEID: ateletID, APIServerSidecarSPIFFEID: pluginID, }) diff --git a/cmd/ateapi/internal/authz/model.fga b/cmd/ateapi/internal/authz/model.fga index bf689b48e0..b7daa44c69 100644 --- a/cmd/ateapi/internal/authz/model.fga +++ b/cmd/ateapi/internal/authz/model.fga @@ -64,12 +64,24 @@ type global define can_list_actors: viewer or ingress_router or egress_gateway define can_list_actor_templates: viewer define can_list_tags: viewer + define can_list_external_volumes: viewer + # --- Volume Infrastructure --- + define can_create_csi_driver: owner + define can_list_csi_drivers: viewer # --- Policy Governance --- define can_create_access_policy: owner define can_get_access_policy: viewer define can_update_access_policy: owner +# Global-scoped; inherits its roles from global. +type csi_driver + relations + define parent_global: [global] + + define can_get: viewer from parent_global + define can_update: owner from parent_global + define can_delete: owner from parent_global type atespace relations define parent_global: [global] @@ -99,6 +111,7 @@ type atespace define can_list_actor_templates: viewer define can_create_tag: editor define can_list_tags: viewer + define can_list_external_volumes: viewer define can_get: viewer define can_delete: owner @@ -132,6 +145,14 @@ type tag # Create actors from this tag (CreateActor source_tag). define can_use_tag: editor from parent_atespace +# A record of a storage volume, owned by its atespace. Read-only: the server +# creates and deletes it. +type external_volume + relations + define parent_atespace: [atespace] + + define can_get: viewer from parent_atespace + type actor relations define parent_atespace: [atespace] diff --git a/cmd/ateapi/internal/authz/model_test.fga.yaml b/cmd/ateapi/internal/authz/model_test.fga.yaml index c9cb9916ce..652e6b1841 100644 --- a/cmd/ateapi/internal/authz/model_test.fga.yaml +++ b/cmd/ateapi/internal/authz/model_test.fga.yaml @@ -45,6 +45,9 @@ tuples: - user: atespace:space-1 relation: parent_atespace object: tag:v1 + - user: atespace:space-1 + relation: parent_atespace + object: external_volume:ctx # Physical Topology & Scheduling (Node -> Worker -> Actor) - user: node:node-1 @@ -94,6 +97,10 @@ tuples: relation: api_server_sidecar object: global:root + # CSI driver (csi-nfs linked to global:root) + - user: global:root + relation: parent_global + object: csi_driver:csi-nfs tests: - name: 1. Global Superadmin & Viewer Propagation check: @@ -558,7 +565,26 @@ tests: can_create_tag: false can_list_tags: false - - name: 9. Actor Credentials (Egress Gateway Only) + - name: 9. External Volume Operations + check: + - user: user:dave # Viewer reads + object: atespace:space-1 + assertions: + can_list_external_volumes: true + - user: user:dave + object: external_volume:ctx + assertions: + can_get: true + - user: user:eve # External + object: atespace:space-1 + assertions: + can_list_external_volumes: false + - user: user:eve + object: external_volume:ctx + assertions: + can_get: false + + - name: 10. Actor Credentials (Egress Gateway Only) check: - user: user:carol # Global owner object: actor:runner-1 @@ -572,3 +598,49 @@ tests: object: actor:runner-1 assertions: can_mint_actor_jwt: false + - name: 10. CSI Drivers (Inherited from Global) + check: + - user: user:carol # Global owner + object: global:root + assertions: + can_create_csi_driver: true + can_list_csi_drivers: true + - user: user:frank # Global viewer + object: global:root + assertions: + can_create_csi_driver: false + can_list_csi_drivers: true + - user: user:sys-atelet # atelet system role + object: global:root + assertions: + can_create_csi_driver: false + can_list_csi_drivers: false + - user: user:bob # Atespace editor + object: global:root + assertions: + can_create_csi_driver: false + can_list_csi_drivers: false + - user: user:carol + object: csi_driver:csi-nfs + assertions: + can_get: true + can_update: true + can_delete: true + - user: user:frank + object: csi_driver:csi-nfs + assertions: + can_get: true + can_update: false + can_delete: false + - user: user:sys-atelet + object: csi_driver:csi-nfs + assertions: + can_get: false + can_update: false + can_delete: false + - user: user:bob + object: csi_driver:csi-nfs + assertions: + can_get: false + can_update: false + can_delete: false diff --git a/cmd/ateapi/internal/authz/registry.go b/cmd/ateapi/internal/authz/registry.go index b4bf601a0e..6f6bd5a5b9 100644 --- a/cmd/ateapi/internal/authz/registry.go +++ b/cmd/ateapi/internal/authz/registry.go @@ -88,6 +88,13 @@ func onWorker(relation, name string, fldPath *field.Path) ([]check, field.ErrorL return []check{{relation: relation, object: WorkerObject(name)}}, nil } +func onCSIDriver(relation, name string, fldPath *field.Path) ([]check, field.ErrorList) { + if errs := validateName(name, fldPath); len(errs) > 0 { + return nil, errs + } + return []check{{relation: relation, object: CSIDriverObject(name)}}, nil +} + // resourceRef identifies an atespaced resource. Both *ateapi.ObjectRef and // *ateapi.ResourceMetadata satisfy it, including as nil pointers. type resourceRef interface { @@ -123,6 +130,13 @@ func onTag(relation string, ref resourceRef, fldPath *field.Path) ([]check, fiel return []check{{relation: relation, object: TagObject(ref.GetAtespace(), ref.GetName())}}, nil } +func onExternalVolume(relation string, ref resourceRef, fldPath *field.Path) ([]check, field.ErrorList) { + if errs := validateRef(ref, fldPath); len(errs) > 0 { + return nil, errs + } + return []check{{relation: relation, object: ExternalVolumeObject(ref.GetAtespace(), ref.GetName())}}, nil +} + // onSourceTag checks can_use_tag on the tag an actor is created from, if the // request names one. func onSourceTag(ref *ateapi.ObjectRef, fldPath *field.Path) ([]check, field.ErrorList) { @@ -294,6 +308,22 @@ var defaultRPCPermissions = map[string]rpcRule{ return onWorker(RelationCanListActorAssignments, r.GetWorker().GetName(), field.NewPath("worker", "name")) })), + // CSI drivers. Global-scoped like workers. + ateapi.Control_CreateCsiDriver_FullMethodName: rule(checksOf(func(*ateapi.CreateCsiDriverRequest) ([]check, field.ErrorList) { + return onGlobal(RelationCanCreateCSIDriver) + })), + ateapi.Control_ListCsiDrivers_FullMethodName: rule(checksOf(func(*ateapi.ListCsiDriversRequest) ([]check, field.ErrorList) { + return onGlobal(RelationCanListCSIDrivers) + })), + ateapi.Control_GetCsiDriver_FullMethodName: rule(checksOf(func(r *ateapi.GetCsiDriverRequest) ([]check, field.ErrorList) { + return onCSIDriver(RelationCanGet, r.GetCsiDriver().GetName(), field.NewPath("csi_driver", "name")) + })), + ateapi.Control_UpdateCsiDriver_FullMethodName: rule(checksOf(func(r *ateapi.UpdateCsiDriverRequest) ([]check, field.ErrorList) { + return onCSIDriver(RelationCanUpdate, r.GetCsiDriver().GetMetadata().GetName(), field.NewPath("csi_driver", "metadata", "name")) + })), + ateapi.Control_DeleteCsiDriver_FullMethodName: rule(checksOf(func(r *ateapi.DeleteCsiDriverRequest) ([]check, field.ErrorList) { + return onCSIDriver(RelationCanDelete, r.GetCsiDriver().GetName(), field.NewPath("csi_driver", "name")) + })), // Actor identity credentials. ateapi.Control_MintActorJwt_FullMethodName: rule(checksOf(func(r *ateapi.MintActorJwtRequest) ([]check, field.ErrorList) { return onActor(RelationCanMintActorJWT, r.GetActor(), field.NewPath("actor")) @@ -321,6 +351,14 @@ var defaultRPCPermissions = map[string]rpcRule{ return onTag(RelationCanDelete, r.GetTag(), field.NewPath("tag")) })), + // External volumes are read-only: atespace viewers get and list. + ateapi.Control_GetExternalVolume_FullMethodName: rule(checksOf(func(r *ateapi.GetExternalVolumeRequest) ([]check, field.ErrorList) { + return onExternalVolume(RelationCanGet, r.GetExternalVolume(), field.NewPath("external_volume")) + })), + ateapi.Control_ListExternalVolumes_FullMethodName: rule(checksOf(func(r *ateapi.ListExternalVolumesRequest) ([]check, field.ErrorList) { + return onAtespaceOrGlobal(RelationCanListExternalVolumes, r.GetAtespace(), field.NewPath("atespace")) + })), + // WorkerService is served only to atelet, which each handler // authenticates by its mTLS SPIFFE ID. ateapi.WorkerService_AcquireWorkerEpoch_FullMethodName: inHandler("ateletauth: caller is atelet on the Worker's node"), diff --git a/cmd/ateapi/internal/authz/registry_test.go b/cmd/ateapi/internal/authz/registry_test.go index d12e60e029..938d4b5984 100644 --- a/cmd/ateapi/internal/authz/registry_test.go +++ b/cmd/ateapi/internal/authz/registry_test.go @@ -274,6 +274,40 @@ func TestDefaultRPCPermissions(t *testing.T) { want: []check{{RelationCanListActorAssignments, "worker:w-1"}}, }, + // CSI drivers. + { + name: "CreateCsiDriver", + fullMethod: ateapi.Control_CreateCsiDriver_FullMethodName, + req: &ateapi.CreateCsiDriverRequest{}, + want: []check{{relation: RelationCanCreateCSIDriver, object: GlobalRootObject}}, + }, + { + name: "ListCsiDrivers", + fullMethod: ateapi.Control_ListCsiDrivers_FullMethodName, + req: &ateapi.ListCsiDriversRequest{}, + want: []check{{relation: RelationCanListCSIDrivers, object: GlobalRootObject}}, + }, + { + name: "GetCsiDriver", + fullMethod: ateapi.Control_GetCsiDriver_FullMethodName, + req: &ateapi.GetCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}}, + want: []check{{relation: RelationCanGet, object: "csi_driver:csi-nfs"}}, + }, + { + name: "UpdateCsiDriver", + fullMethod: ateapi.Control_UpdateCsiDriver_FullMethodName, + req: &ateapi.UpdateCsiDriverRequest{CsiDriver: &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, + }}, + want: []check{{relation: RelationCanUpdate, object: "csi_driver:csi-nfs"}}, + }, + { + name: "DeleteCsiDriver", + fullMethod: ateapi.Control_DeleteCsiDriver_FullMethodName, + req: &ateapi.DeleteCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}}, + want: []check{{relation: RelationCanDelete, object: "csi_driver:csi-nfs"}}, + }, + // Actor identity credentials. { name: "MintActorJWT", @@ -282,6 +316,20 @@ func TestDefaultRPCPermissions(t *testing.T) { want: []check{{RelationCanMintActorJWT, "actor:team-a/runner"}}, }, + // External volumes. + { + name: "GetExternalVolume", + fullMethod: ateapi.Control_GetExternalVolume_FullMethodName, + req: &ateapi.GetExternalVolumeRequest{ExternalVolume: &ateapi.ObjectRef{Atespace: "team-a", Name: "ctx"}}, + want: []check{{RelationCanGet, "external_volume:team-a/ctx"}}, + }, + { + name: "ListExternalVolumes across all atespaces", + fullMethod: ateapi.Control_ListExternalVolumes_FullMethodName, + req: &ateapi.ListExternalVolumesRequest{}, + want: []check{{RelationCanListExternalVolumes, GlobalRootObject}}, + }, + // Tags. { name: "CreateTag checks its source actor's atespace", @@ -591,6 +639,32 @@ func TestDefaultRPCPermissions_MalformedIdentifierFailsClosed(t *testing.T) { req: &ateapi.ListWorkerActorAssignmentsRequest{Worker: &ateapi.ObjectRef{}}, wantField: "worker.name", }, + { + name: "GetCsiDriver without a driver", + fullMethod: ateapi.Control_GetCsiDriver_FullMethodName, + req: &ateapi.GetCsiDriverRequest{}, + wantField: "csi_driver.name", + }, + { + name: "UpdateCsiDriver without metadata", + fullMethod: ateapi.Control_UpdateCsiDriver_FullMethodName, + req: &ateapi.UpdateCsiDriverRequest{CsiDriver: &ateapi.CsiDriver{}}, + wantField: "csi_driver.metadata.name", + }, + { + name: "UpdateCsiDriver with an invalid name", + fullMethod: ateapi.Control_UpdateCsiDriver_FullMethodName, + req: &ateapi.UpdateCsiDriverRequest{CsiDriver: &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi/nfs"}, + }}, + wantField: "csi_driver.metadata.name", + }, + { + name: "DeleteCsiDriver with an invalid name", + fullMethod: ateapi.Control_DeleteCsiDriver_FullMethodName, + req: &ateapi.DeleteCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: "csi/nfs"}}, + wantField: "csi_driver.name", + }, { name: "MintActorJWT without an actor", fullMethod: ateapi.Control_MintActorJwt_FullMethodName, diff --git a/cmd/ateapi/internal/controlapi/access_policy.go b/cmd/ateapi/internal/controlapi/access_policy.go index d0dac32b8f..6bbd9bd96f 100644 --- a/cmd/ateapi/internal/controlapi/access_policy.go +++ b/cmd/ateapi/internal/controlapi/access_policy.go @@ -35,7 +35,7 @@ func (s *RPCService) CreateGlobalAccessPolicy(ctx context.Context, req *ateapi.C scrubResourceMetadataForCreate(policy.Metadata) defaults.Apply(policy) } - if errs := apivalidation.ValidateCreateGlobalAccessPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateCreateGlobalAccessPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } return s.impl.CreateGlobalAccessPolicy(ctx, policy) @@ -47,7 +47,7 @@ func (s *ServiceImpl) CreateGlobalAccessPolicy(ctx context.Context, policy *atea } func (s *RPCService) GetGlobalAccessPolicy(ctx context.Context, req *ateapi.GetGlobalAccessPolicyRequest) (*ateapi.AccessPolicy, error) { - if errs := apivalidation.ValidateGetGlobalAccessPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateGetGlobalAccessPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } return s.impl.GetGlobalAccessPolicy(ctx) @@ -57,7 +57,7 @@ func (s *ServiceImpl) GetGlobalAccessPolicy(ctx context.Context) (*ateapi.Access policy, err := s.store.GetGlobalAccessPolicy(ctx) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Global AccessPolicy not found") + return nil, apierror.NotFound("Global AccessPolicy not found").WithCause(err) } return nil, fmt.Errorf("while getting Global access policy: %w", err) } @@ -69,7 +69,7 @@ func (s *RPCService) UpdateGlobalAccessPolicy(ctx context.Context, req *ateapi.U if policy != nil { scrubResourceMetadataForUpdate(policy.Metadata) } - if errs := apivalidation.ValidateUpdateGlobalAccessPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateUpdateGlobalAccessPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } return s.impl.UpdateGlobalAccessPolicy(ctx, store.PreconditionFrom(policy), replaceAccessPolicy(policy)) @@ -81,7 +81,7 @@ func (s *ServiceImpl) UpdateGlobalAccessPolicy(ctx context.Context, precondition if err := mutate(toUpdate); err != nil { return err } - errs := apivalidation.ValidateGlobalAccessPolicyUpdate(ctx, field.NewPath("access_policy"), toUpdate, oldVal) + errs := apivalidation.ValidateGlobalAccessPolicyUpdate(ctx, s.gates, field.NewPath("access_policy"), toUpdate, oldVal) return resources.ToAPIError(errs) }) return mapAccessPolicyWrite(updated, err) @@ -93,7 +93,7 @@ func (s *RPCService) CreateAtespaceAccessPolicy(ctx context.Context, req *ateapi scrubResourceMetadataForCreate(policy.Metadata) defaults.Apply(policy) } - if errs := apivalidation.ValidateCreateAtespaceAccessPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateCreateAtespaceAccessPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } return s.impl.CreateAtespaceAccessPolicy(ctx, req.GetAtespace().GetName(), policy) @@ -105,7 +105,7 @@ func (s *ServiceImpl) CreateAtespaceAccessPolicy(ctx context.Context, name strin } func (s *RPCService) GetAtespaceAccessPolicy(ctx context.Context, req *ateapi.GetAtespaceAccessPolicyRequest) (*ateapi.AccessPolicy, error) { - if errs := apivalidation.ValidateGetAtespaceAccessPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateGetAtespaceAccessPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } return s.impl.GetAtespaceAccessPolicy(ctx, req.GetAtespace().GetName()) @@ -115,7 +115,7 @@ func (s *ServiceImpl) GetAtespaceAccessPolicy(ctx context.Context, name string) policy, err := s.store.GetAtespaceAccessPolicy(ctx, name) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("AccessPolicy for atespace %s not found", name) + return nil, apierror.NotFound("AccessPolicy for atespace %s not found", name).WithCause(err) } return nil, fmt.Errorf("while getting Atespace access policy: %w", err) } @@ -127,7 +127,7 @@ func (s *RPCService) UpdateAtespaceAccessPolicy(ctx context.Context, req *ateapi if policy != nil { scrubResourceMetadataForUpdate(policy.Metadata) } - if errs := apivalidation.ValidateUpdateAtespaceAccessPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateUpdateAtespaceAccessPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } return s.impl.UpdateAtespaceAccessPolicy(ctx, req.GetAtespace().GetName(), store.PreconditionFrom(policy), replaceAccessPolicy(policy)) @@ -139,20 +139,20 @@ func (s *ServiceImpl) UpdateAtespaceAccessPolicy(ctx context.Context, name strin if err := mutate(toUpdate); err != nil { return err } - errs := apivalidation.ValidateAtespaceAccessPolicyUpdate(ctx, field.NewPath("access_policy"), toUpdate, oldVal) + errs := apivalidation.ValidateAtespaceAccessPolicyUpdate(ctx, s.gates, field.NewPath("access_policy"), toUpdate, oldVal) return resources.ToAPIError(errs) }) return mapAccessPolicyWrite(updated, err) } func (s *RPCService) DeleteAtespaceAccessPolicy(ctx context.Context, req *ateapi.DeleteAtespaceAccessPolicyRequest) (*ateapi.AccessPolicy, error) { - if errs := apivalidation.ValidateDeleteAtespaceAccessPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateDeleteAtespaceAccessPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } - return s.impl.DeleteAtespaceAccessPolicy(ctx, req.GetAtespace().GetName(), toDeletePreconditions(req.GetOptions())) + return s.impl.DeleteAtespaceAccessPolicy(ctx, req.GetAtespace().GetName(), toPreconditions(req.GetOptions())) } -func (s *ServiceImpl) DeleteAtespaceAccessPolicy(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.AccessPolicy, error) { +func (s *ServiceImpl) DeleteAtespaceAccessPolicy(ctx context.Context, name string, precondition store.Precondition) (*ateapi.AccessPolicy, error) { deleted, err := s.store.DeleteAtespaceAccessPolicy(ctx, name, precondition) return mapAccessPolicyWrite(deleted, err) } @@ -173,17 +173,17 @@ func mapAccessPolicyWrite(policy *ateapi.AccessPolicy, err error) (*ateapi.Acces case err == nil: return policy, nil case errors.Is(err, store.ErrNotFound): - return nil, apierror.NotFound("AccessPolicy not found") + return nil, apierror.NotFound("AccessPolicy not found").WithCause(err) case errors.Is(err, store.ErrAlreadyExists): - return nil, apierror.AlreadyExists("AccessPolicy already exists") + return nil, apierror.AlreadyExists("AccessPolicy already exists").WithCause(err) case errors.Is(err, store.ErrVersionConflict): - return nil, apierror.Aborted("AccessPolicy version conflict") + return nil, apierror.Aborted("AccessPolicy version conflict").WithCause(err) case errors.Is(err, store.ErrUIDConflict): - return nil, apierror.Aborted("AccessPolicy UID conflict") + return nil, apierror.Aborted("AccessPolicy UID conflict").WithCause(err) case errors.Is(err, store.ErrPreconditionRequired): - return nil, apierror.InvalidArgument("AccessPolicy UID and version are required") + return nil, apierror.InvalidArgument("AccessPolicy UID and version are required").WithCause(err) case errors.Is(err, store.ErrFailedPrecondition): - return nil, apierror.FailedPrecondition("parent Atespace does not exist") + return nil, apierror.FailedPrecondition("parent Atespace does not exist").WithCause(err) default: return nil, fmt.Errorf("while writing AccessPolicy: %w", err) } diff --git a/cmd/ateapi/internal/controlapi/access_policy_test.go b/cmd/ateapi/internal/controlapi/access_policy_test.go index 3c225534c7..88d755f8de 100644 --- a/cmd/ateapi/internal/controlapi/access_policy_test.go +++ b/cmd/ateapi/internal/controlapi/access_policy_test.go @@ -48,7 +48,7 @@ func TestAccessPolicy_GlobalAndAtespaceGovernance(t *testing.T) { } persistence.SetPolicyManager(policyManager) - svc := NewRPCService(persistence, nil, nil, nil, nil, nil, "", 0, nil, nil, "", nil, "") + svc, _ := NewRPCService(persistence, nil, nil, nil, nil, nil, "", 0, nil, nil, "", nil, "", testGates) interceptor := authz.UnaryServerInterceptor(authorizer) userCtx := func(id string) context.Context { diff --git a/cmd/ateapi/internal/controlapi/actor.go b/cmd/ateapi/internal/controlapi/actor.go index 9b690a9f12..b68d2b510c 100644 --- a/cmd/ateapi/internal/controlapi/actor.go +++ b/cmd/ateapi/internal/controlapi/actor.go @@ -48,7 +48,7 @@ func (s *RPCService) CreateActor(ctx context.Context, req *ateapi.CreateActorReq } // Validate the request, including the object within it. - if errs := apivalidation.ValidateCreateActorRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateCreateActorRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -108,10 +108,10 @@ func (s *ServiceImpl) CreateActor(ctx context.Context, inActor *ateapi.Actor) (* name := inActor.GetMetadata().GetName() // Volume creation is completed asynchronously after the actor is recorded. - var initVols []*ateapi.ExternalVolumeStatus + var initVols []*ateapi.ActorExternalVolumeStatus if iv, err := initialExternalVolumes(ctx, s.storageClassLister, template); err != nil { return nil, err - } else if preview.IsEnabledFor(ctx, preview.GateExternalVolumes) { + } else if s.gates.IsEnabledFor(ctx, preview.GateExternalVolumes) { initVols = iv } else if len(iv) > 0 { errs := field.ErrorList{ @@ -142,7 +142,7 @@ func (s *ServiceImpl) CreateActor(ctx context.Context, inActor *ateapi.Actor) (* outActor.Status.Snapshots = []*ateapi.Snapshot{snap} outActor.Status.LastAssignedGeneration = 1 } - if errs := apivalidation.ValidateActorUpdate(ctx, field.NewPath("actor"), outActor, inActor, true); len(errs) > 0 { + if errs := apivalidation.ValidateActorUpdate(ctx, s.gates, field.NewPath("actor"), outActor, inActor, true); len(errs) > 0 { return nil, resources.ToInternalError(errs) } @@ -150,10 +150,10 @@ func (s *ServiceImpl) CreateActor(ctx context.Context, inActor *ateapi.Actor) (* stored, err := s.store.CreateActor(ctx, outActor) if err != nil { if errors.Is(err, store.ErrAlreadyExists) { - return nil, apierror.AlreadyExists("Actor %s already exists", name) + return nil, apierror.AlreadyExists("Actor %s already exists", name).WithCause(err) } if errors.Is(err, store.ErrFailedPrecondition) { - return nil, apierror.FailedPrecondition("Atespace %s not found", atespace) + return nil, apierror.FailedPrecondition("Atespace %s not found", atespace).WithCause(err) } return nil, fmt.Errorf("while recording actor: %w", err) } @@ -171,7 +171,7 @@ func (s *ServiceImpl) CreateActor(ctx context.Context, inActor *ateapi.Actor) (* func (s *ServiceImpl) resolveTagSource(ctx context.Context, actorAtespace string, tagRef *ateapi.ObjectRef, template *ateapi.ActorTemplate) (*ateapi.Tag, error) { tag, err := s.store.GetTag(ctx, resources.TagRefFromObjectRef(tagRef)) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.FailedPrecondition("Tag not found") + return nil, apierror.FailedPrecondition("Tag not found").WithCause(err) } if err != nil { return nil, fmt.Errorf("while getting tag: %w", err) @@ -202,13 +202,13 @@ func (s *ServiceImpl) resolveTagSource(ctx context.Context, actorAtespace string } func (s *RPCService) GetActor(ctx context.Context, req *ateapi.GetActorRequest) (*ateapi.Actor, error) { - if errs := apivalidation.ValidateGetActorRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateGetActorRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } actorRef := resources.ActorRefFromObjectRef(req.GetActor()) actor, err := s.impl.GetActor(ctx, actorRef) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Actor %s not found", actorRef) + return nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } else if err != nil { return nil, fmt.Errorf("while getting actor from DB: %w", err) } @@ -220,7 +220,7 @@ func (s *ServiceImpl) GetActor(ctx context.Context, actorRef resources.ActorRef) } func (s *RPCService) ListActors(ctx context.Context, req *ateapi.ListActorsRequest) (*ateapi.ListActorsResponse, error) { - if errs := apivalidation.ValidateListActorsRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateListActorsRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -247,7 +247,7 @@ func (s *RPCService) UpdateActor(ctx context.Context, req *ateapi.UpdateActorReq } // Validate the request. - if errs := apivalidation.ValidateUpdateActorRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateUpdateActorRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -289,7 +289,7 @@ func (s *RPCService) UpdateActor(ctx context.Context, req *ateapi.UpdateActorReq func (s *ServiceImpl) UpdateActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { storedActor, err := s.store.UpdateActor(ctx, actorRef, precondition, s.validatedActorMutation(ctx, mutate)) if err != nil { - if mapped := actorWriteError(actorRef, err); mapped != err { + if mapped := actorWriteError(actorRef, precondition.UID, err); mapped != err { return nil, mapped } return nil, fmt.Errorf("while updating actor: %w", err) @@ -298,15 +298,18 @@ func (s *ServiceImpl) UpdateActor(ctx context.Context, actorRef resources.ActorR } // actorWriteError maps the store's errors for a write to the Actor actorRef to -// API errors, and returns any other error unchanged. -func actorWriteError(actorRef resources.ActorRef, err error) error { +// API errors, and returns any other error unchanged. expectedUID is the UID +// guard on the write. +func actorWriteError(actorRef resources.ActorRef, expectedUID string, err error) error { switch { - case errors.Is(err, store.ErrVersionConflict), errors.Is(err, store.ErrUIDConflict): - return apierror.Aborted("concurrent update conflict, please retry") + case errors.Is(err, store.ErrUIDConflict): + return actorUIDConflictError(actorRef, expectedUID, err) + case errors.Is(err, store.ErrVersionConflict): + return apierror.Aborted("concurrent update conflict, please retry").WithCause(err) case errors.Is(err, store.ErrNotFound): - return apierror.NotFound("actor %s not found", actorRef) + return apierror.NotFound("actor %s not found", actorRef).WithCause(err) case errors.Is(err, store.ErrPreconditionRequired): - return apierror.InvalidArgument("while updating actor %s: %v", actorRef, err) + return apierror.InvalidArgument("while updating actor %s: %w", actorRef, err) } return err } @@ -317,13 +320,15 @@ func (s *ServiceImpl) validatedActorMutation(ctx context.Context, mutate func(*a return func(toUpdate *ateapi.Actor) error { // Apply the mutation function to the stored value. oldVal := proto.CloneOf(toUpdate) - if err := mutate(toUpdate); err != nil { - return err + if mutate != nil { + if err := mutate(toUpdate); err != nil { + return err + } } newVal := toUpdate // Validate the user's input before doing any further work. - if errs := apivalidation.ValidateActorUpdate(ctx, field.NewPath("actor"), newVal, oldVal, false); len(errs) > 0 { + if errs := apivalidation.ValidateActorUpdate(ctx, s.gates, field.NewPath("actor"), newVal, oldVal, false); len(errs) > 0 { return resources.ToAPIError(errs) } @@ -362,7 +367,7 @@ func (s *ServiceImpl) validatedActorMutation(ctx context.Context, mutate func(*a } // Validate the final value before storing it. - if errs := apivalidation.ValidateActorUpdate(ctx, field.NewPath("actor"), newVal, oldVal, true); len(errs) > 0 { + if errs := apivalidation.ValidateActorUpdate(ctx, s.gates, field.NewPath("actor"), newVal, oldVal, true); len(errs) > 0 { return resources.ToInternalError(errs) } @@ -427,7 +432,7 @@ func (s *ServiceImpl) validateSnapshotLocationUnchanged(actor *ateapi.Actor, new } // Compared as prefixes, so a newLocation spelled with and without a // trailing slash counts as the same. - newLocation, err := resolveSnapshotLocation(s.clusterSnapshotLocation, newTemplate) + newLocation, err := resolveSnapshotLocation(s.gates, s.clusterSnapshotLocation, newTemplate) if err != nil { return err } @@ -445,7 +450,7 @@ func (s *ServiceImpl) validateSnapshotLocationUnchanged(actor *ateapi.Actor, new } func (s *RPCService) DeleteActor(ctx context.Context, req *ateapi.DeleteActorRequest) (deleted *ateapi.Actor, err error) { - if errs := apivalidation.ValidateDeleteActorRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateDeleteActorRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } start := time.Now() @@ -465,7 +470,7 @@ func (s *RPCService) DeleteActor(ctx context.Context, req *ateapi.DeleteActorReq actorRef := resources.ActorRefFromObjectRef(req.GetActor()) setSpanActorRefAttributes(ctx, actorRef) - deleted, err = s.actorWorkflow.DeleteActor(ctx, actorRef, toDeletePreconditions(req.GetOptions())) + deleted, err = s.actorWorkflow.DeleteActor(ctx, actorRef, toPreconditions(req.GetOptions())) if err != nil { return nil, err } @@ -473,30 +478,25 @@ func (s *RPCService) DeleteActor(ctx context.Context, req *ateapi.DeleteActorReq return deleted, nil } -func (s *ServiceImpl) MarkActorForDeletion(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { - return s.store.MarkActorForDeletion(ctx, actorRef, precondition, mutate) +func (s *ServiceImpl) MarkActorForDeletion(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { + return s.store.MarkActorForDeletion(ctx, actorRef, precondition, s.validatedActorMutation(ctx, mutate)) } -func (s *ServiceImpl) DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions) (*ateapi.Actor, error) { +func (s *ServiceImpl) DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (*ateapi.Actor, error) { return s.store.DeleteActor(ctx, actorRef, precondition) } func (s *RPCService) ResumeActor(ctx context.Context, req *ateapi.ResumeActorRequest) (*ateapi.ResumeActorResponse, error) { - if errs := apivalidation.ValidateResumeActorRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateResumeActorRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } actorRef := resources.ActorRefFromObjectRef(req.GetActor()) setSpanActorRefAttributes(ctx, actorRef) - actor, resumed, err := s.actorWorkflow.ResumeActor(ctx, actorRef) + precondition := toPreconditions(req.GetOptions()) + actor, resumed, err := s.actorWorkflow.ResumeActor(ctx, actorRef, precondition) if err != nil { - if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") - } - if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Actor %s not found", actorRef) - } - return nil, err + return nil, actorWriteError(actorRef, precondition.UID, err) } setSpanActorAttributes(ctx, actor) @@ -504,21 +504,16 @@ func (s *RPCService) ResumeActor(ctx context.Context, req *ateapi.ResumeActorReq } func (s *RPCService) SuspendActor(ctx context.Context, req *ateapi.SuspendActorRequest) (*ateapi.SuspendActorResponse, error) { - if errs := apivalidation.ValidateSuspendActorRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateSuspendActorRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } actorRef := resources.ActorRefFromObjectRef(req.GetActor()) setSpanActorRefAttributes(ctx, actorRef) - actor, err := s.actorWorkflow.SuspendActor(ctx, actorRef, suspendModeFromOptions(req.GetOptions())) + precondition := toPreconditions(req.GetOptions()) + actor, err := s.actorWorkflow.SuspendActor(ctx, actorRef, precondition, suspendModeFromOptions(req.GetOptions())) if err != nil { - if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") - } - if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Actor %s not found", actorRef) - } - return nil, err + return nil, actorWriteError(actorRef, precondition.UID, err) } setSpanActorAttributes(ctx, actor) return &ateapi.SuspendActorResponse{Actor: actor}, nil @@ -531,7 +526,7 @@ func (s *RPCService) CrashActorReportedByWorker(ctx context.Context, actorRef re actor, err := s.actorWorkflow.CrashActorReportedByWorker(ctx, actorRef, actorUID, workerName, message) if err != nil { if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } return nil, err } @@ -540,28 +535,23 @@ func (s *RPCService) CrashActorReportedByWorker(ctx context.Context, actorRef re } func (s *RPCService) RevertActor(ctx context.Context, req *ateapi.RevertActorRequest) (*ateapi.RevertActorResponse, error) { - if errs := apivalidation.ValidateRevertActorRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateRevertActorRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } actorRef := resources.ActorRefFromObjectRef(req.GetActor()) setSpanActorRefAttributes(ctx, actorRef) - actor, err := s.actorWorkflow.RevertActor(ctx, actorRef) + precondition := toPreconditions(req.GetOptions()) + actor, err := s.actorWorkflow.RevertActor(ctx, actorRef, precondition) if err != nil { - if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") - } - if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Actor %s not found", actorRef) - } - return nil, err + return nil, actorWriteError(actorRef, precondition.UID, err) } setSpanActorAttributes(ctx, actor) return &ateapi.RevertActorResponse{Actor: actor}, nil } func (s *RPCService) MintActorJwt(ctx context.Context, req *ateapi.MintActorJwtRequest) (*ateapi.MintActorJwtResponse, error) { - if errs := apivalidation.ValidateMintActorJWTRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateMintActorJWTRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -572,7 +562,7 @@ func (s *RPCService) MintActorJwt(ctx context.Context, req *ateapi.MintActorJwtR // running, since we may need to issue JWTs during actor boot / resume. dbActor, err := s.impl.GetActor(ctx, resources.ActorRefFromObjectRef(req.GetActor())) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("actor not found") + return nil, apierror.NotFound("actor not found").WithCause(err) } else if err != nil { return nil, fmt.Errorf("while retrieving actor: %w", err) } diff --git a/cmd/ateapi/internal/controlapi/actor_template.go b/cmd/ateapi/internal/controlapi/actor_template.go index 68d1f8ee34..bb2144af5f 100644 --- a/cmd/ateapi/internal/controlapi/actor_template.go +++ b/cmd/ateapi/internal/controlapi/actor_template.go @@ -24,6 +24,7 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/defaults" "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "google.golang.org/protobuf/proto" "k8s.io/apimachinery/pkg/util/validation/field" @@ -40,7 +41,7 @@ func (s *RPCService) CreateActorTemplate(ctx context.Context, req *ateapi.Create } // Validate the request, including the object within it. - if errs := apivalidation.ValidateCreateActorTemplateRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateCreateActorTemplateRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -49,7 +50,7 @@ func (s *RPCService) CreateActorTemplate(ctx context.Context, req *ateapi.Create stored, err := s.impl.CreateActorTemplate(ctx, in) if err != nil { if errors.Is(err, store.ErrAlreadyExists) { - return nil, apierror.AlreadyExists("ActorTemplate %s already exists", templateRef) + return nil, apierror.AlreadyExists("ActorTemplate %s already exists", templateRef).WithCause(err) } if errors.Is(err, store.ErrFailedPrecondition) { return nil, apierror.FailedPrecondition("%v", err) @@ -66,13 +67,13 @@ func (s *ServiceImpl) CreateActorTemplate(ctx context.Context, inTemplate *ateap outTemplate.Status = &ateapi.ActorTemplateStatus{} // Validate the final value before storing it. - if errs := apivalidation.ValidateActorTemplateUpdate(ctx, field.NewPath("actor_template"), outTemplate, inTemplate); len(errs) > 0 { + if errs := apivalidation.ValidateActorTemplateUpdate(ctx, s.gates, field.NewPath("actor_template"), outTemplate, inTemplate); len(errs) > 0 { return nil, resources.ToInternalError(errs) } // Reject a template whose actors could never be snapshotted, rather than // failing their first suspend or tag. - if _, err := resolveSnapshotLocation(s.clusterSnapshotLocation, outTemplate); err != nil { + if _, err := resolveSnapshotLocation(s.gates, s.clusterSnapshotLocation, outTemplate); err != nil { return nil, err } @@ -80,14 +81,14 @@ func (s *ServiceImpl) CreateActorTemplate(ctx context.Context, inTemplate *ateap } func (s *RPCService) GetActorTemplate(ctx context.Context, req *ateapi.GetActorTemplateRequest) (*ateapi.ActorTemplate, error) { - if errs := apivalidation.ValidateGetActorTemplateRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateGetActorTemplateRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } templateRef := resources.ActorTemplateRefFromObjectRef(req.GetActorTemplate()) template, err := s.impl.GetActorTemplate(ctx, templateRef) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("ActorTemplate %s not found", templateRef) + return nil, apierror.NotFound("ActorTemplate %s not found", templateRef).WithCause(err) } else if err != nil { return nil, fmt.Errorf("while getting actor template from DB: %w", err) } @@ -101,7 +102,7 @@ func (s *ServiceImpl) GetActorTemplate(ctx context.Context, templateRef resource } func (s *RPCService) ListActorTemplates(ctx context.Context, req *ateapi.ListActorTemplatesRequest) (*ateapi.ListActorTemplatesResponse, error) { - if errs := apivalidation.ValidateListActorTemplatesRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateListActorTemplatesRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -121,27 +122,42 @@ func (s *ServiceImpl) ListActorTemplates(ctx context.Context, atespace string, o } func (s *RPCService) DeleteActorTemplate(ctx context.Context, req *ateapi.DeleteActorTemplateRequest) (*ateapi.ActorTemplate, error) { - if errs := apivalidation.ValidateDeleteActorTemplateRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateDeleteActorTemplateRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } - return s.actorWorkflow.DeleteActorTemplate(ctx, resources.ActorTemplateRefFromObjectRef(req.GetActorTemplate()), toDeletePreconditions(req.GetOptions())) + return s.actorWorkflow.DeleteActorTemplate(ctx, resources.ActorTemplateRefFromObjectRef(req.GetActorTemplate()), toPreconditions(req.GetOptions())) } -func (s *ServiceImpl) MarkActorTemplateForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions, mutate func(*ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) { - return s.store.MarkActorTemplateForDeletion(ctx, templateRef, precondition, mutate) +func (s *ServiceImpl) MarkActorTemplateForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition, mutate func(*ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) { + return s.store.MarkActorTemplateForDeletion(ctx, templateRef, precondition, validatedActorTemplateMutation(ctx, s.gates, mutate)) } -func (s *ServiceImpl) DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions) (*ateapi.ActorTemplate, error) { +func (s *ServiceImpl) DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition) (*ateapi.ActorTemplate, error) { // TODO: implement this return s.store.DeleteActorTemplate(ctx, templateRef, precondition) } func (s *ServiceImpl) UpdateActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition, mutate func(dbTemplate *ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) { - // ActorTemplates are immutable to clients: there is no update RPC, and - // the only writer is the template reconciler, which updates status - // against the store directly. The store enforces metadata immutability, - // so this layer has nothing to add. - return s.store.UpdateActorTemplate(ctx, templateRef, precondition, mutate) + return s.store.UpdateActorTemplate(ctx, templateRef, precondition, validatedActorTemplateMutation(ctx, s.gates, mutate)) +} + +// validatedActorTemplateMutation wraps mutate so the ActorTemplate it writes is +// validated as an update of the stored ActorTemplate. There is no update RPC +// for ActorTemplates, so only the server mutates them, and a validation +// failure is an internal error. +func validatedActorTemplateMutation(ctx context.Context, gates *preview.Gates, mutate func(*ateapi.ActorTemplate) error) func(*ateapi.ActorTemplate) error { + return func(toUpdate *ateapi.ActorTemplate) error { + oldVal := proto.CloneOf(toUpdate) + if mutate != nil { + if err := mutate(toUpdate); err != nil { + return err + } + } + if errs := apivalidation.ValidateActorTemplateUpdate(ctx, gates, field.NewPath("actor_template"), toUpdate, oldVal); len(errs) > 0 { + return resources.ToInternalError(errs) + } + return nil + } } // actorTemplateGetter is the storage subset template resolution needs. diff --git a/cmd/ateapi/internal/controlapi/actor_template_test.go b/cmd/ateapi/internal/controlapi/actor_template_test.go index 66aa77778a..3976184417 100644 --- a/cmd/ateapi/internal/controlapi/actor_template_test.go +++ b/cmd/ateapi/internal/controlapi/actor_template_test.go @@ -56,9 +56,9 @@ func validActorTemplate(mutations ...func(*ateapi.ActorTemplate)) *ateapi.ActorT // while the atespace is missing, and succeeds once the atespace exists. func TestCreateActorTemplate(t *testing.T) { persistence := newTestPersistence(t) - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, testGates) impl.clusterSnapshotLocation = "gs://cluster-bucket/" - s := &RPCService{impl: impl} + s := &RPCService{gates: testGates, impl: impl} ctx := context.Background() req := func(atespace, name string) *ateapi.CreateActorTemplateRequest { return &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { @@ -123,11 +123,11 @@ func TestCreateActorTemplate_RequiresSnapshotLocation(t *testing.T) { }} for i, tt := range tests { t.Run(tt.name, func(t *testing.T) { - preview.InitForTest(t, tt.gates...) + gates := preview.NewForTest(t, tt.gates...) persistence := newTestPersistence(t) - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, gates) impl.clusterSnapshotLocation = tt.clusterSnapshotLocation - s := &RPCService{impl: impl} + s := &RPCService{gates: gates, impl: impl} ctx := context.Background() if _, err := persistence.CreateAtespace(ctx, &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "ns1"}}); err != nil { t.Fatalf("CreateAtespace failed: %v", err) @@ -152,9 +152,9 @@ func TestCreateActorTemplate_RequiresSnapshotLocation(t *testing.T) { // the only guard. func TestCreateActorTemplateIgnoresServerOwnedFields(t *testing.T) { persistence := newTestPersistence(t) - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, testGates) impl.clusterSnapshotLocation = "gs://cluster-bucket/" - s := &RPCService{impl: impl} + s := &RPCService{gates: testGates, impl: impl} ctx := context.Background() if _, err := persistence.CreateAtespace(ctx, &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "ns1"}}); err != nil { @@ -199,9 +199,9 @@ func TestCreateActorTemplateIgnoresServerOwnedFields(t *testing.T) { // snapshot_config is optional: create fills an omitted one with every default. func TestCreateActorTemplateDefaultsOmittedSnapshotConfig(t *testing.T) { persistence := newTestPersistence(t) - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, testGates) impl.clusterSnapshotLocation = "gs://cluster-bucket/" - s := &RPCService{impl: impl} + s := &RPCService{gates: testGates, impl: impl} ctx := context.Background() if _, err := persistence.CreateAtespace(ctx, &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "ns1"}}); err != nil { t.Fatalf("CreateAtespace failed: %v", err) @@ -276,18 +276,19 @@ func TestDeleteActorTemplate(t *testing.T) { tagRef := resources.TagRefFromTag(tag) tagURI := mustReservedTagSnapshotURI(t, tag) objects.PutSnapshot(t, tagURI, "manifest.json") - svc := &RPCService{impl: newServiceImpl(persistence, nil), actorWorkflow: workflow, objectStorePlugin: objectstoreplugintest.ControlClient(objects)} + svc := &RPCService{gates: testGates, impl: newServiceImpl(persistence, nil, testGates), actorWorkflow: workflow, objectStorePlugin: objectstoreplugintest.ControlClient(objects)} // The handler must clean up an active golden actor. mustUpdateActorStatus(t, ctx, persistence, actor, func(s *ateapi.ActorStatus) { s.State = ateapi.ActorState_ACTOR_STATE_RUNNING }) if tt.actorDeleted { - if _, err := workflow.DeleteActor(ctx, goldenRef, store.DeletePreconditions{}); err != nil { + if _, err := workflow.DeleteActor(ctx, goldenRef, store.Precondition{}); err != nil { t.Fatal(err) } } if tt.tagDeleted { - if _, err := svc.DeleteTag(ctx, &ateapi.DeleteTagRequest{Tag: tagRef.ToObjectRef()}); err != nil { + // DeleteTag refuses the golden tag of a live template. + if _, err := workflow.DeleteTag(ctx, tagRef, store.Precondition{}); err != nil { t.Fatal(err) } } @@ -304,7 +305,7 @@ func TestDeleteActorTemplate(t *testing.T) { if err != nil { t.Fatal(err) } - stale := store.DeletePreconditions{UID: current.GetMetadata().GetUid(), Version: current.GetMetadata().GetVersion() + 1} + stale := store.Precondition{UID: current.GetMetadata().GetUid(), Version: current.GetMetadata().GetVersion() + 1} if _, err := workflow.DeleteActorTemplate(ctx, templateRef, stale); apierror.Code(err) != codes.Aborted { t.Fatalf("DeleteActorTemplate with a stale version = %v, want code Aborted", err) } @@ -463,11 +464,12 @@ func TestResolveActorTemplate_NotFound(t *testing.T) { } } -// TestUpdateActorTemplateMetadata pins the store's update behavior: the -// server-assigned metadata is recomputed in place, and metadata identity is -// immutable. +// TestUpdateActorTemplateMetadata checks that a server-owned status write +// bumps the version, and that an update or mark for deletion that changes +// metadata is rejected. func TestUpdateActorTemplateMetadata(t *testing.T) { persistence := newTestPersistence(t) + impl := newServiceImpl(persistence, nil, testGates) ctx := context.Background() if _, err := persistence.CreateAtespace(ctx, &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "ns1"}}); err != nil { @@ -479,8 +481,7 @@ func TestUpdateActorTemplateMetadata(t *testing.T) { } ref := resources.ActorTemplateRefFromActorTemplate(created) - // A server-owned status write passes validation and bumps the version. - updated, err := persistence.UpdateActorTemplate(ctx, ref, store.PreconditionFrom(created), func(tmpl *ateapi.ActorTemplate) error { + updated, err := impl.UpdateActorTemplate(ctx, ref, store.PreconditionFrom(created), func(tmpl *ateapi.ActorTemplate) error { tmpl.Status = &ateapi.ActorTemplateStatus{GoldenSnapshotStatus: &ateapi.GoldenSnapshotStatus{ GoldenTag: &ateapi.ObjectRef{Atespace: "ns1", Name: "golden-tag"}, }} @@ -493,27 +494,19 @@ func TestUpdateActorTemplateMetadata(t *testing.T) { t.Errorf("updated version = %d, want %d", got, want) } - // A mutation that touches an immutable field is a server bug, rejected by - // the store. for name, mutate := range map[string]func(*ateapi.ActorTemplate) error{ "atespace": func(tmpl *ateapi.ActorTemplate) error { tmpl.Metadata.Atespace = "ns2"; return nil }, "name": func(tmpl *ateapi.ActorTemplate) error { tmpl.Metadata.Name = "tmpl-b"; return nil }, + "uid": func(tmpl *ateapi.ActorTemplate) error { + tmpl.Metadata.Uid = "1e186271-b829-4085-b2b1-6b665c1a4f42" + return nil + }, } { - if _, err := persistence.UpdateActorTemplate(ctx, ref, store.PreconditionFrom(updated), mutate); err == nil { - t.Errorf("mutating %s succeeded, want error", name) + if _, err := impl.UpdateActorTemplate(ctx, ref, store.PreconditionFrom(updated), mutate); apierror.Code(err) != codes.Internal { + t.Errorf("UpdateActorTemplate mutating %s: error = %v, want an Internal error", name, err) + } + if _, err := impl.MarkActorTemplateForDeletion(ctx, ref, store.Precondition{UID: updated.GetMetadata().GetUid(), Version: updated.GetMetadata().GetVersion()}, mutate); apierror.Code(err) != codes.Internal { + t.Errorf("MarkActorTemplateForDeletion mutating %s: error = %v, want an Internal error", name, err) } - } - - // Server-assigned metadata edits are overwritten, not errors: the store - // restores them from the stored value. - reverted, err := persistence.UpdateActorTemplate(ctx, ref, store.PreconditionFrom(updated), func(tmpl *ateapi.ActorTemplate) error { - tmpl.Metadata.Uid = "1e186271-b829-4085-b2b1-6b665c1a4f42" - return nil - }) - if err != nil { - t.Fatalf("UpdateActorTemplate with uid edit failed: %v", err) - } - if got, want := reverted.GetMetadata().GetUid(), created.GetMetadata().GetUid(); got != want { - t.Errorf("uid after update = %q, want %q", got, want) } } diff --git a/cmd/ateapi/internal/controlapi/actor_test.go b/cmd/ateapi/internal/controlapi/actor_test.go index 4787e0f2d5..99df48030e 100644 --- a/cmd/ateapi/internal/controlapi/actor_test.go +++ b/cmd/ateapi/internal/controlapi/actor_test.go @@ -30,6 +30,7 @@ import ( "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" + "go.opentelemetry.io/otel/sdk/metric/metricdata" "google.golang.org/grpc/codes" "google.golang.org/protobuf/proto" "google.golang.org/protobuf/testing/protocmp" @@ -115,7 +116,7 @@ func TestValidateActorStatusCrash(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - assertValidateErr(t, apivalidation.ValidateActorUpdate(context.Background(), nil, tt.newVal, tt.oldVal, true), tt.want) + assertValidateErr(t, apivalidation.ValidateActorUpdate(context.Background(), testGates, nil, tt.newVal, tt.oldVal, true), tt.want) }) } } @@ -306,7 +307,7 @@ func TestUpdateActor_RepointTemplate(t *testing.T) { ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl-a"}, Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, }) - svc := &RPCService{impl: newServiceImpl(persistence, nil)} + svc := &RPCService{gates: testGates, impl: newServiceImpl(persistence, nil, testGates)} // Repointing at a template that does not exist is rejected. _, err := svc.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: &ateapi.Actor{ @@ -592,12 +593,13 @@ func TestUpdateActor_RepointTemplateStorageLocation(t *testing.T) { } for i, tt := range tests { t.Run(tt.name, func(t *testing.T) { + gates := testGates if tt.gateOff { - preview.InitForTest(t) + gates = preview.NewForTest(t) } - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, gates) impl.clusterSnapshotLocation = tt.clusterSnapshotLocation - svc := &RPCService{impl: impl} + svc := &RPCService{gates: gates, impl: impl} actor := storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: fmt.Sprintf("actor-%d", i)}, ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: tt.template}, @@ -768,13 +770,13 @@ func TestUpdateActor_DeleteRecreateRace(t *testing.T) { Interface: persistence, inject: func() { // A delete releases the Actor's worker before removing it. - if _, err := persistence.MarkActorForDeletion(ctx, actorRef, store.DeletePreconditions{}, func(a *ateapi.Actor) error { + if _, err := persistence.MarkActorForDeletion(ctx, actorRef, store.Precondition{}, func(a *ateapi.Actor) error { a.Status.WorkerAssignment = nil return nil }); err != nil { t.Fatalf("racing writer: mark for deletion: %v", err) } - if _, err := persistence.DeleteActor(ctx, actorRef, store.DeletePreconditions{}); err != nil { + if _, err := persistence.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatalf("racing writer: DeleteActor: %v", err) } recreated, err = persistence.CreateActor(ctx, &ateapi.Actor{ @@ -787,7 +789,7 @@ func TestUpdateActor_DeleteRecreateRace(t *testing.T) { } }, } - svc := &RPCService{impl: newServiceImpl(racing, nil)} + svc := &RPCService{gates: testGates, impl: newServiceImpl(racing, nil, testGates)} // The client asserts "only update the actor with uid A". original.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "paid"}} @@ -796,6 +798,10 @@ func TestUpdateActor_DeleteRecreateRace(t *testing.T) { t.Errorf("UpdateActor error = %v (code %v), want code Aborted: the actor holding uid %s was deleted mid-update", err, code, original.GetMetadata().GetUid()) } + wantUIDMsg := fmt.Sprintf("Actor %s does not have uid %s", actorRef, original.GetMetadata().GetUid()) + if err == nil || !strings.Contains(err.Error(), wantUIDMsg) { + t.Errorf("UpdateActor error = %v, want substring %q", err, wantUIDMsg) + } stored, err := persistence.GetActor(ctx, actorRef) if err != nil { @@ -848,7 +854,7 @@ func TestUpdateActor_ConcurrentDisjointUpdates(t *testing.T) { } }, } - svc := &RPCService{impl: newServiceImpl(racing, nil)} + svc := &RPCService{gates: testGates, impl: newServiceImpl(racing, nil, testGates)} // Update operation is changing the worker_selector field, not the actor's state (like the concurrent op) // This update must fail: the racing update bumped the version. @@ -904,11 +910,11 @@ func rpcServiceWithActor(t *testing.T, actor *ateapi.Actor) (*RPCService, *ateap t.Cleanup(cleanup) created := storetest.MustCreateActor(t, context.Background(), persistence, actor) - return &RPCService{impl: newServiceImpl(persistence, nil)}, created + return &RPCService{gates: testGates, impl: newServiceImpl(persistence, nil, testGates)}, created } func TestCreateActor_DoesNotInheritGoldenEgressPolicy(t *testing.T) { - preview.InitForTest(t, "GoldenEgressPolicy") + gates := preview.NewForTest(t, "GoldenEgressPolicy") for _, tt := range []struct { name string policy *ateapi.EgressPolicyTemplate @@ -922,9 +928,9 @@ func TestCreateActor_DoesNotInheritGoldenEgressPolicy(t *testing.T) { t.Run(tt.name, func(t *testing.T) { ctx := t.Context() persistence := newTestPersistence(t) - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, gates) impl.clusterSnapshotLocation = "gs://cluster-bucket/" - svc := &RPCService{impl: impl} + svc := &RPCService{gates: gates, impl: impl} storetest.MustCreateAtespace(t, ctx, persistence, "templates") storetest.MustCreateAtespace(t, ctx, persistence, "actors") tmpl, err := svc.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { @@ -936,7 +942,8 @@ func TestCreateActor_DoesNotInheritGoldenEgressPolicy(t *testing.T) { } tmplRef := resources.ActorTemplateRefFromActorTemplate(tmpl).ToObjectRef() // Existing templates remain usable without the preview gate. - preview.InitForTest(t) + impl.gates = preview.NewForTest(t) + svc.gates = impl.gates for _, target := range []resources.ActorRef{ {Atespace: "actors", Name: "alpha"}, {Atespace: "actors", Name: tmpl.GetMetadata().GetUid()}, @@ -1021,7 +1028,7 @@ func TestCreateActor_GoldenTagDefault(t *testing.T) { } actor.SourceTag = &ateapi.ObjectRef{Atespace: ref.Atespace, Name: "explicit"} } - svc := &ServiceImpl{store: persistence} + svc := &ServiceImpl{gates: testGates, store: persistence} created, err := svc.CreateActor(ctx, actor) if apierror.Code(err) != wantCode { t.Fatalf("CreateActor = %v, want %v", err, wantCode) @@ -1051,9 +1058,9 @@ func TestCreateActor_GoldenTagDefault(t *testing.T) { t.Fatal(err) } } - workflow := &ActorWorkflow{store: persistence} + workflow := &ActorWorkflow{gates: testGates, store: persistence} actorRef := resources.ActorRefFromActor(created) - loaded, _, err := workflow.loadActorForResume(ctx, actorRef) + loaded, _, err := workflow.loadActorForResume(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatal(err) } @@ -1063,3 +1070,186 @@ func TestCreateActor_GoldenTagDefault(t *testing.T) { }) } } + +// TestMarkActorForDeletion checks that ServiceImpl validates the Actor a +// mark-for-deletion writes, as it does for an update. +func TestMarkActorForDeletion(t *testing.T) { + ctx := context.Background() + persistence, cleanup := storetest.SetupTestStore(t) + t.Cleanup(cleanup) + impl := newServiceImpl(persistence, nil, testGates) + + actor := storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: testActorID}, + ActorTemplate: &ateapi.ObjectRef{Atespace: "ns1", Name: "tmpl1"}, + Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, + }) + ref := resources.ActorRefFromActor(actor) + precondition := store.PreconditionFrom(actor) + + if _, err := impl.MarkActorForDeletion(ctx, ref, precondition, func(toUpdate *ateapi.Actor) error { + toUpdate.SourceTag = &ateapi.ObjectRef{Atespace: testAtespace, Name: "tag-a"} + return nil + }); apierror.Code(err) != codes.InvalidArgument { + t.Errorf("MarkActorForDeletion setting source_tag: error = %v, want code InvalidArgument", err) + } + + marked, err := impl.MarkActorForDeletion(ctx, ref, precondition, func(toUpdate *ateapi.Actor) error { + toUpdate.Status.State = ateapi.ActorState_ACTOR_STATE_DELETING + return nil + }) + if err != nil { + t.Fatalf("MarkActorForDeletion failed: %v", err) + } + if marked.GetMetadata().GetDeleteTime() == nil || marked.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_DELETING { + t.Errorf("marked actor = %v, want delete_time set and state DELETING", marked) + } + + if _, err := impl.MarkActorForDeletion(ctx, ref, store.PreconditionFrom(marked), nil); err != nil { + t.Errorf("MarkActorForDeletion with a nil mutate failed: %v", err) + } +} + +// TestActorCustomMethods_Preconditions checks that Suspend, Resume and Revert +// refuse an actor that no longer matches the caller's guards with ABORTED, and +// leave it untouched. The refused calls' lifecycle metric carries no labels +// from the stored actor. Each seed state completes without atelet, so the +// matching call succeeds. +func TestActorCustomMethods_Preconditions(t *testing.T) { + const foreignUID = "1a7e4c83-6d20-4f95-b3c8-9e0a2f6d4b17" + actorRef := resources.ActorRef{Atespace: testAtespace, Name: testActorID} + ref := &ateapi.ObjectRef{Atespace: actorRef.Atespace, Name: actorRef.Name} + + methods := []struct { + name string + state ateapi.ActorState + call func(ctx context.Context, svc *RPCService, p store.Precondition) error + }{ + { + // SUSPENDED takes the shortcut that reports success without writing. + name: "SuspendActor", + state: ateapi.ActorState_ACTOR_STATE_SUSPENDED, + call: func(ctx context.Context, svc *RPCService, p store.Precondition) error { + _, err := svc.SuspendActor(ctx, &ateapi.SuspendActorRequest{ + Actor: ref, + Options: &ateapi.SuspendOptions{ + Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS, + Uid: p.UID, + Version: p.Version, + }, + }) + return err + }, + }, + { + // RUNNING takes the fast path that returns before the lease. + name: "ResumeActor", + state: ateapi.ActorState_ACTOR_STATE_RUNNING, + call: func(ctx context.Context, svc *RPCService, p store.Precondition) error { + _, err := svc.ResumeActor(ctx, &ateapi.ResumeActorRequest{ + Actor: ref, + Options: &ateapi.ResumeActorRequest_Options{Uid: p.UID, Version: p.Version}, + }) + return err + }, + }, + { + // A CRASHED actor with no node reverts without atelet. + name: "RevertActor", + state: ateapi.ActorState_ACTOR_STATE_CRASHED, + call: func(ctx context.Context, svc *RPCService, p store.Precondition) error { + _, err := svc.RevertActor(ctx, &ateapi.RevertActorRequest{ + Actor: ref, + Options: &ateapi.RevertActorRequest_Options{Uid: p.UID, Version: p.Version}, + }) + return err + }, + }, + } + for _, m := range methods { + t.Run(m.name, func(t *testing.T) { + ctx := context.Background() + st, cleanup := storetest.SetupTestStore(t) + t.Cleanup(cleanup) + w := newTestActorWorkflow(t, st, "ns", "tmpl1") + inst, reader := newTestInstruments(t) + w.instruments = inst + svc := &RPCService{gates: testGates, impl: newServiceImpl(st, nil, testGates), actorWorkflow: w} + seedWorkflowActor(t, ctx, st, actorRef, "ns", "tmpl1", m.state) + seeded := mustReadActor(t, ctx, st, actorRef) + md := seeded.GetMetadata() + + for _, tc := range []struct { + name string + p store.Precondition + }{ + {"stale version", store.Precondition{Version: md.GetVersion() + 7}}, + {"foreign uid", store.Precondition{UID: foreignUID}}, + {"foreign uid, matching version", store.Precondition{UID: foreignUID, Version: md.GetVersion()}}, + } { + if err := m.call(ctx, svc, tc.p); apierror.Code(err) != codes.Aborted { + t.Errorf("%s: code = %v (err %v), want %v", tc.name, apierror.Code(err), err, codes.Aborted) + } + } + if diff := cmp.Diff(seeded, mustReadActor(t, ctx, st, actorRef), protocmp.Transform()); diff != "" { + t.Errorf("refused calls changed the actor (-seeded +stored):\n%s", diff) + } + for _, dp := range mustMetric(t, reader, lifecycleOpDurationMetric).Data.(metricdata.Histogram[float64]).DataPoints { + if name, ok := attrString(dp, ateattr.TemplateNameKey); ok { + t.Errorf("refused call recorded template %q, want no template label", name) + } + } + + if err := m.call(ctx, svc, store.Precondition{UID: md.GetUid(), Version: md.GetVersion()}); err != nil { + t.Errorf("matching preconditions failed: %v", err) + } + }) + } +} + +// replacingLeaseStore runs replace once, just before the first lease is taken. +type replacingLeaseStore struct { + store.Interface + replace func() +} + +func (s *replacingLeaseStore) AcquireLease(ctx context.Context, key string) (*store.Lease, error) { + if s.replace != nil { + s.replace() + s.replace = nil + } + return s.Interface.AcquireLease(ctx, key) +} + +// TestResumeActor_PreconditionCheckedUnderLease covers an actor deleted and +// recreated between ResumeActor's read before the lease and its read under it. +func TestResumeActor_PreconditionCheckedUnderLease(t *testing.T) { + ctx := context.Background() + persistence, cleanup := storetest.SetupTestStore(t) + t.Cleanup(cleanup) + actorRef := resources.ActorRef{Atespace: testAtespace, Name: testActorID} + st := &replacingLeaseStore{Interface: persistence} + w := newTestActorWorkflow(t, st, "ns", "tmpl1") + seedWorkflowActor(t, ctx, persistence, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_SUSPENDED) + original := mustReadActor(t, ctx, persistence, actorRef) + + var recreated *ateapi.Actor + st.replace = func() { + if _, err := persistence.MarkActorForDeletion(ctx, actorRef, store.Precondition{}, nil); err != nil { + t.Fatalf("MarkActorForDeletion: %v", err) + } + if _, err := persistence.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + seedWorkflowActor(t, ctx, persistence, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_SUSPENDED) + recreated = mustReadActor(t, ctx, persistence, actorRef) + } + + _, _, err := w.ResumeActor(ctx, actorRef, store.Precondition{UID: original.GetMetadata().GetUid()}) + if apierror.Code(err) != codes.Aborted { + t.Fatalf("ResumeActor code = %v (err %v), want %v", apierror.Code(err), err, codes.Aborted) + } + if diff := cmp.Diff(recreated, mustReadActor(t, ctx, persistence, actorRef), protocmp.Transform()); diff != "" { + t.Errorf("ResumeActor changed the recreated actor (-recreated +stored):\n%s", diff) + } +} diff --git a/cmd/ateapi/internal/controlapi/atespace.go b/cmd/ateapi/internal/controlapi/atespace.go index 65c11691e7..9b3b67a06d 100644 --- a/cmd/ateapi/internal/controlapi/atespace.go +++ b/cmd/ateapi/internal/controlapi/atespace.go @@ -38,7 +38,7 @@ func (s *RPCService) CreateAtespace(ctx context.Context, req *ateapi.CreateAtesp } // Validate the request, including the object within it. - if errs := apivalidation.ValidateCreateAtespaceRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateCreateAtespaceRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -53,7 +53,7 @@ func (s *ServiceImpl) CreateAtespace(ctx context.Context, inAtespace *ateapi.Ate stored, err := s.store.CreateAtespace(ctx, inAtespace) if err != nil { if errors.Is(err, store.ErrAlreadyExists) { - return nil, apierror.AlreadyExists("Atespace %s already exists", inAtespace.Metadata.Name) + return nil, apierror.AlreadyExists("Atespace %s already exists", inAtespace.Metadata.Name).WithCause(err) } return nil, fmt.Errorf("while recording atespace: %w", err) } @@ -62,7 +62,7 @@ func (s *ServiceImpl) CreateAtespace(ctx context.Context, inAtespace *ateapi.Ate } func (s *RPCService) GetAtespace(ctx context.Context, req *ateapi.GetAtespaceRequest) (*ateapi.Atespace, error) { - if errs := apivalidation.ValidateGetAtespaceRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateGetAtespaceRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -72,7 +72,7 @@ func (s *RPCService) GetAtespace(ctx context.Context, req *ateapi.GetAtespaceReq func (s *ServiceImpl) GetAtespace(ctx context.Context, name string) (*ateapi.Atespace, error) { atespace, err := s.store.GetAtespace(ctx, name) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Atespace %s not found", name) + return nil, apierror.NotFound("Atespace %s not found", name).WithCause(err) } else if err != nil { return nil, fmt.Errorf("while getting atespace from DB: %w", err) } @@ -81,7 +81,7 @@ func (s *ServiceImpl) GetAtespace(ctx context.Context, name string) (*ateapi.Ate } func (s *RPCService) ListAtespaces(ctx context.Context, req *ateapi.ListAtespacesRequest) (*ateapi.ListAtespacesResponse, error) { - if errs := apivalidation.ValidateListAtespacesRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateListAtespacesRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -104,27 +104,27 @@ func (s *ServiceImpl) ListAtespaces(ctx context.Context, opts store.ListOptions) } func (s *RPCService) DeleteAtespace(ctx context.Context, req *ateapi.DeleteAtespaceRequest) (*ateapi.Atespace, error) { - if errs := apivalidation.ValidateDeleteAtespaceRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateDeleteAtespaceRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } - return s.impl.DeleteAtespace(ctx, req.Atespace.Name, toDeletePreconditions(req.GetOptions())) + return s.impl.DeleteAtespace(ctx, req.Atespace.Name, toPreconditions(req.GetOptions())) } -func (s *ServiceImpl) DeleteAtespace(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.Atespace, error) { +func (s *ServiceImpl) DeleteAtespace(ctx context.Context, name string, precondition store.Precondition) (*ateapi.Atespace, error) { deleted, err := s.store.DeleteAtespace(ctx, name, precondition) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Atespace %s not found", name) + return nil, apierror.NotFound("Atespace %s not found", name).WithCause(err) } if errors.Is(err, store.ErrFailedPrecondition) { - return nil, apierror.FailedPrecondition("Atespace %s is not empty", name) + return nil, apierror.FailedPrecondition("Atespace %s is not empty", name).WithCause(err) } if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("Atespace %s does not have uid %s", name, precondition.UID) + return nil, apierror.Aborted("Atespace %s does not have uid %s", name, precondition.UID).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } return nil, fmt.Errorf("while deleting atespace from DB: %w", err) } diff --git a/cmd/ateapi/internal/controlapi/atespace_test.go b/cmd/ateapi/internal/controlapi/atespace_test.go index ad6296de2c..bceb62db11 100644 --- a/cmd/ateapi/internal/controlapi/atespace_test.go +++ b/cmd/ateapi/internal/controlapi/atespace_test.go @@ -71,7 +71,8 @@ func TestAtespace_EndToEndOpenFGAScenarios(t *testing.T) { storeID := storesResp.GetStores()[0].GetId() svc := &RPCService{ - impl: newServiceImpl(persistence, nil), + gates: testGates, + impl: newServiceImpl(persistence, nil, testGates), } interceptor := authz.UnaryServerInterceptor(authorizer) @@ -198,7 +199,7 @@ func TestAtespace_EndToEndOpenFGAScenarios(t *testing.T) { } // --- Scenario 3: Atomic rollback if DeleteAtespacePolicies fails after DELETE FROM atespaces --- - if _, err := persistence.DeleteActorTemplate(ctx, resources.ActorTemplateRefFromActorTemplate(tmpl), store.DeletePreconditions{}); err != nil { + if _, err := persistence.DeleteActorTemplate(ctx, resources.ActorTemplateRefFromActorTemplate(tmpl), store.Precondition{}); err != nil { t.Fatalf("DeleteActorTemplate failed: %v", err) } // Install a temporary PostgreSQL BEFORE DELETE trigger on OpenFGA's `tuple` table diff --git a/cmd/ateapi/internal/controlapi/crash.go b/cmd/ateapi/internal/controlapi/crash.go index e8d6607c0a..a94cf6ce28 100644 --- a/cmd/ateapi/internal/controlapi/crash.go +++ b/cmd/ateapi/internal/controlapi/crash.go @@ -150,7 +150,7 @@ func crashActor(ctx context.Context, st crashActorStore, actorRef resources.Acto toUpdate.Status.WorkerAssignment = nil return nil }); err != nil { - return fmt.Errorf("while marking actor crashed: %w", actorWriteError(actorRef, err)) + return fmt.Errorf("while marking actor crashed: %w", actorWriteError(actorRef, actor.GetMetadata().GetUid(), err)) } // Count the crash only once it has committed. diff --git a/cmd/ateapi/internal/controlapi/crash_test.go b/cmd/ateapi/internal/controlapi/crash_test.go index eff57b601c..b94a02224c 100644 --- a/cmd/ateapi/internal/controlapi/crash_test.go +++ b/cmd/ateapi/internal/controlapi/crash_test.go @@ -35,9 +35,9 @@ import ( "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/resources" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" otellog "go.opentelemetry.io/otel/log" - "go.opentelemetry.io/otel/log/global" sdklog "go.opentelemetry.io/otel/sdk/log" sdkmetric "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/metric/metricdata" @@ -794,7 +794,7 @@ func otlpEvents(t *testing.T) func() []otlpEvent { t.Helper() otlpSinkOnce.Do(func() { - global.SetLoggerProvider(sdklog.NewLoggerProvider( + otel.SetLoggerProvider(sdklog.NewLoggerProvider( sdklog.WithProcessor(switchProcessor{sdklog.NewSimpleProcessor(otlpSinkExporter{})}))) }) diff --git a/cmd/ateapi/internal/controlapi/csi_driver.go b/cmd/ateapi/internal/controlapi/csi_driver.go new file mode 100644 index 0000000000..c2ac4749e1 --- /dev/null +++ b/cmd/ateapi/internal/controlapi/csi_driver.go @@ -0,0 +1,166 @@ +// Copyright 2026 The Agent Substrate 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 controlapi + +import ( + "context" + "errors" + "fmt" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/apivalidation" + "go.ate.dev/substrate/cmd/ateapi/internal/defaults" + "go.ate.dev/substrate/cmd/ateapi/internal/store" + "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/resources" + "google.golang.org/protobuf/proto" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +func (s *RPCService) CreateCsiDriver(ctx context.Context, req *ateapi.CreateCsiDriverRequest) (*ateapi.CsiDriver, error) { + in := proto.CloneOf(req.GetCsiDriver()) + if in != nil { + scrubResourceMetadataForCreate(in.Metadata) + defaults.Apply(in) + } + if errs := apivalidation.ValidateCreateCSIDriverRequest(ctx, s.gates, &ateapi.CreateCsiDriverRequest{CsiDriver: in}); len(errs) > 0 { + return nil, resources.ToAPIError(errs) + } + return s.impl.CreateCSIDriver(ctx, in) +} + +func (s *ServiceImpl) CreateCSIDriver(ctx context.Context, driver *ateapi.CsiDriver) (*ateapi.CsiDriver, error) { + stored, err := s.store.CreateCSIDriver(ctx, driver) + if errors.Is(err, store.ErrDriverNameAlreadyExists) { + return nil, apierror.FailedPrecondition("CsiDriver for driver_name %q already exists", driver.GetDriverName()) + } + if errors.Is(err, store.ErrAlreadyExists) { + return nil, apierror.AlreadyExists("CsiDriver %q already exists", driver.GetMetadata().GetName()) + } + if err != nil { + return nil, fmt.Errorf("while recording csi driver: %w", err) + } + return stored, nil +} + +func (s *RPCService) GetCsiDriver(ctx context.Context, req *ateapi.GetCsiDriverRequest) (*ateapi.CsiDriver, error) { + if errs := apivalidation.ValidateGetCSIDriverRequest(ctx, s.gates, req); len(errs) > 0 { + return nil, resources.ToAPIError(errs) + } + return s.impl.GetCSIDriver(ctx, req.GetCsiDriver().GetName()) +} + +func (s *ServiceImpl) GetCSIDriver(ctx context.Context, name string) (*ateapi.CsiDriver, error) { + driver, err := s.store.GetCSIDriver(ctx, name) + if errors.Is(err, store.ErrNotFound) { + return nil, apierror.NotFound("CsiDriver %s not found", name) + } + if err != nil { + return nil, fmt.Errorf("while getting csi driver from DB: %w", err) + } + return driver, nil +} + +func (s *RPCService) ListCsiDrivers(ctx context.Context, req *ateapi.ListCsiDriversRequest) (*ateapi.ListCsiDriversResponse, error) { + if errs := apivalidation.ValidateListCSIDriversRequest(ctx, s.gates, req); len(errs) > 0 { + return nil, resources.ToAPIError(errs) + } + page, err := s.impl.ListCSIDrivers(ctx, toStoreListOptions(req.GetOptions())) + if err != nil { + return nil, err + } + return &ateapi.ListCsiDriversResponse{ + CsiDrivers: page.Items, + NextPageToken: page.NextPageToken, + }, nil +} + +func (s *ServiceImpl) ListCSIDrivers(ctx context.Context, opts store.ListOptions) (store.ListResponse[*ateapi.CsiDriver], error) { + page, err := s.store.ListCSIDrivers(ctx, opts) + if err != nil { + return page, mapListError(fmt.Errorf("while listing csi drivers in db: %w", err)) + } + return page, nil +} + +func (s *RPCService) UpdateCsiDriver(ctx context.Context, req *ateapi.UpdateCsiDriverRequest) (*ateapi.CsiDriver, error) { + in := proto.CloneOf(req.GetCsiDriver()) + if in != nil { + scrubResourceMetadataForUpdate(in.Metadata) + } + if errs := apivalidation.ValidateUpdateCSIDriverRequest(ctx, s.gates, &ateapi.UpdateCsiDriverRequest{CsiDriver: in}); len(errs) > 0 { + return nil, resources.ToAPIError(errs) + } + return s.impl.UpdateCSIDriver(ctx, in.GetMetadata().GetName(), store.PreconditionFrom(in), func(toUpdate *ateapi.CsiDriver) error { + metadata := toUpdate.GetMetadata() + proto.Reset(toUpdate) + proto.Merge(toUpdate, in) + toUpdate.Metadata = metadata + defaults.Apply(toUpdate) + return nil + }) +} + +func (s *ServiceImpl) UpdateCSIDriver(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapi.CsiDriver) error) (*ateapi.CsiDriver, error) { + updated, err := s.store.UpdateCSIDriver(ctx, name, precondition, func(toUpdate *ateapi.CsiDriver) error { + oldVal := proto.CloneOf(toUpdate) + if mutate != nil { + if err := mutate(toUpdate); err != nil { + return err + } + } + if errs := apivalidation.ValidateCSIDriverUpdate(ctx, s.gates, field.NewPath("csi_driver"), toUpdate, oldVal); len(errs) > 0 { + return resources.ToAPIError(errs) + } + return nil + }) + switch { + case err == nil: + return updated, nil + case errors.Is(err, store.ErrNotFound): + return nil, apierror.NotFound("CsiDriver %s not found", name) + case errors.Is(err, store.ErrPreconditionRequired): + return nil, apierror.InvalidArgument("while updating csi driver %s: %v", name, err) + case errors.Is(err, store.ErrUIDConflict): + return nil, apierror.Aborted("CsiDriver %s does not have uid %s", name, precondition.UID) + case errors.Is(err, store.ErrVersionConflict): + return nil, apierror.Aborted("concurrent update conflict, please retry") + default: + return nil, fmt.Errorf("while updating csi driver: %w", err) + } +} + +func (s *RPCService) DeleteCsiDriver(ctx context.Context, req *ateapi.DeleteCsiDriverRequest) (*ateapi.CsiDriver, error) { + if errs := apivalidation.ValidateDeleteCSIDriverRequest(ctx, s.gates, req); len(errs) > 0 { + return nil, resources.ToAPIError(errs) + } + return s.impl.DeleteCSIDriver(ctx, req.GetCsiDriver().GetName(), toPreconditions(req.GetOptions())) +} + +func (s *ServiceImpl) DeleteCSIDriver(ctx context.Context, name string, precondition store.Precondition) (*ateapi.CsiDriver, error) { + deleted, err := s.store.DeleteCSIDriver(ctx, name, precondition) + switch { + case err == nil: + return deleted, nil + case errors.Is(err, store.ErrNotFound): + return nil, apierror.NotFound("CsiDriver %s not found", name) + case errors.Is(err, store.ErrUIDConflict): + return nil, apierror.Aborted("CsiDriver %s does not have uid %s", name, precondition.UID) + case errors.Is(err, store.ErrVersionConflict): + return nil, apierror.Aborted("concurrent update conflict, please retry") + default: + return nil, fmt.Errorf("while deleting csi driver from DB: %w", err) + } +} diff --git a/cmd/ateapi/internal/controlapi/delete_options.go b/cmd/ateapi/internal/controlapi/delete_options.go deleted file mode 100644 index c4beb04cb4..0000000000 --- a/cmd/ateapi/internal/controlapi/delete_options.go +++ /dev/null @@ -1,24 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 controlapi - -import ( - "go.ate.dev/substrate/api/ateapi/v1" - "go.ate.dev/substrate/cmd/ateapi/internal/store" -) - -func toDeletePreconditions(opts *ateapi.DeleteOptions) store.DeletePreconditions { - return store.DeletePreconditions{UID: opts.GetUid(), Version: opts.GetVersion()} -} diff --git a/cmd/ateapi/internal/controlapi/dialer.go b/cmd/ateapi/internal/controlapi/dialer.go index d06112695d..7fd522698a 100644 --- a/cmd/ateapi/internal/controlapi/dialer.go +++ b/cmd/ateapi/internal/controlapi/dialer.go @@ -68,6 +68,9 @@ type AteletDialer struct { // atelet, keyed on the atelet's expected pod UID. Production wires this to // per-atelet mTLS; tests can override it with insecure credentials. dialCredentials func(expectedPodUID string) (credentials.TransportCredentials, error) + // contextDialer, when set, opens the connection to an atelet's address in + // place of a TCP dial. + contextDialer func(ctx context.Context, addr string) (net.Conn, error) } // DialerOption customizes an AteletDialer built by NewAteletDialer. @@ -109,6 +112,13 @@ func (d *AteletDialer) NodeGone(ctx context.Context, nodeName string) (bool, err return len(atelets) == 0, nil } +// WithContextDialer replaces the TCP dial to an atelet's address. Tests use it +// to serve each node's fake atelet in memory while still exercising the real +// lookup, dial and connection-cache path. +func WithContextDialer(dial func(ctx context.Context, addr string) (net.Conn, error)) DialerOption { + return func(d *AteletDialer) { d.contextDialer = dial } +} + // NewAteletDialer creates a new AteletDialer. clientBundlePath and serverCAPath // are used to build the per-atelet mTLS credentials used for every atelet // connection, and ateletSPIFFEID is the identity those credentials expect on @@ -189,10 +199,16 @@ func (d *AteletDialer) DialForAteletOnNode(nodeName string) (*grpc.ClientConn, e return nil, fmt.Errorf("while building atelet credentials: %w", err) } - conn, err := grpc.NewClient( - net.JoinHostPort(ateletIP, strconv.Itoa(atelet.DefaultPort)), + dialOpts := []grpc.DialOption{ grpc.WithTransportCredentials(creds), grpc.WithStatsHandler(otelgrpc.NewClientHandler()), + } + if d.contextDialer != nil { + dialOpts = append(dialOpts, grpc.WithContextDialer(d.contextDialer)) + } + conn, err := grpc.NewClient( + net.JoinHostPort(ateletIP, strconv.Itoa(atelet.DefaultPort)), + dialOpts..., ) if err != nil { return nil, fmt.Errorf("while creating atelet gRPC client connection: %w", err) diff --git a/cmd/ateapi/internal/controlapi/dialer_test.go b/cmd/ateapi/internal/controlapi/dialer_test.go index 69cc5368b9..8927426b77 100644 --- a/cmd/ateapi/internal/controlapi/dialer_test.go +++ b/cmd/ateapi/internal/controlapi/dialer_test.go @@ -24,6 +24,7 @@ import ( "crypto/x509/pkix" "errors" "math/big" + "net" "net/url" "slices" "strconv" @@ -510,6 +511,37 @@ func TestDialForAteletOnNode(t *testing.T) { } }) + t.Run("dials through the context dialer", func(t *testing.T) { + dialed := make(chan string, 1) + d := NewAteletDialer(newTestAteletIndexer(t, + ateletPod("atelet-1", "uid-1", "node1", "10.0.0.1"), + ), installdefaults.AteletSPIFFEID(installdefaults.SystemNamespace), "", "", WithDialCredentials(func(string) (credentials.TransportCredentials, error) { + return insecure.NewCredentials(), nil + }), WithContextDialer(func(_ context.Context, addr string) (net.Conn, error) { + select { + case dialed <- addr: + default: + } + return nil, errors.New("refused by test") + })) + + conn, err := d.DialForAteletOnNode("node1") + if err != nil { + t.Fatalf("DialForAteletOnNode: %v", err) + } + t.Cleanup(func() { conn.Close() }) + conn.Connect() + + select { + case got := <-dialed: + if want := "10.0.0.1:" + ateletPort; got != want { + t.Errorf("context dialer got address %q, want %q", got, want) + } + case <-time.After(5 * time.Second): + t.Fatal("context dialer was never called") + } + }) + t.Run("closes conns evicted from the cache", func(t *testing.T) { d := NewAteletDialer(newTestAteletIndexer(t, ateletPod("atelet-1", "uid-1", "node1", "10.0.0.1"), diff --git a/cmd/ateapi/internal/controlapi/egress_policy.go b/cmd/ateapi/internal/controlapi/egress_policy.go index 2776414f12..0b78827a15 100644 --- a/cmd/ateapi/internal/controlapi/egress_policy.go +++ b/cmd/ateapi/internal/controlapi/egress_policy.go @@ -37,7 +37,7 @@ func (s *RPCService) CreateActorEgressPolicy(ctx context.Context, req *ateapi.Cr scrubResourceMetadataForCreate(policy.Metadata) defaults.Apply(policy) } - if errs := apivalidation.ValidateCreateActorEgressPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateCreateActorEgressPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } actorRef := resources.ActorRefFromObjectRef(req.GetActor()) @@ -50,7 +50,7 @@ func (s *ServiceImpl) CreateEgressPolicy(ctx context.Context, actorRef resources } func (s *RPCService) GetActorEgressPolicy(ctx context.Context, req *ateapi.GetActorEgressPolicyRequest) (*ateapi.EgressPolicy, error) { - if errs := apivalidation.ValidateGetActorEgressPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateGetActorEgressPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -60,7 +60,7 @@ func (s *RPCService) GetActorEgressPolicy(ctx context.Context, req *ateapi.GetAc func (s *ServiceImpl) GetEgressPolicy(ctx context.Context, actorRef resources.ActorRef) (*ateapi.EgressPolicy, error) { policy, err := s.store.GetEgressPolicy(ctx, actorRef) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("EgressPolicy for actor %s not found", actorRef) + return nil, apierror.NotFound("EgressPolicy for actor %s not found", actorRef).WithCause(err) } if err != nil { return nil, fmt.Errorf("while getting Actor egress policy: %w", err) @@ -73,7 +73,7 @@ func (s *RPCService) UpdateActorEgressPolicy(ctx context.Context, req *ateapi.Up if policy != nil { scrubResourceMetadataForUpdate(policy.Metadata) } - if errs := apivalidation.ValidateUpdateActorEgressPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateUpdateActorEgressPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } actorRef := resources.ActorRefFromObjectRef(req.GetActor()) @@ -93,7 +93,7 @@ func (s *ServiceImpl) UpdateEgressPolicy(ctx context.Context, actorRef resources if err := mutate(toUpdate); err != nil { return err } - if errs := apivalidation.ValidateEgressPolicyUpdate(ctx, field.NewPath("egress_policy"), toUpdate, oldVal); len(errs) > 0 { + if errs := apivalidation.ValidateEgressPolicyUpdate(ctx, s.gates, field.NewPath("egress_policy"), toUpdate, oldVal); len(errs) > 0 { return resources.ToAPIError(errs) } // EgressPolicy has no status or other server-derived fields to verify. @@ -103,14 +103,14 @@ func (s *ServiceImpl) UpdateEgressPolicy(ctx context.Context, actorRef resources } func (s *RPCService) DeleteActorEgressPolicy(ctx context.Context, req *ateapi.DeleteActorEgressPolicyRequest) (*ateapi.EgressPolicy, error) { - if errs := apivalidation.ValidateDeleteActorEgressPolicyRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateDeleteActorEgressPolicyRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } - return s.impl.DeleteEgressPolicy(ctx, resources.ActorRefFromObjectRef(req.GetActor()), toDeletePreconditions(req.GetOptions())) + return s.impl.DeleteEgressPolicy(ctx, resources.ActorRefFromObjectRef(req.GetActor()), toPreconditions(req.GetOptions())) } -func (s *ServiceImpl) DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions) (*ateapi.EgressPolicy, error) { +func (s *ServiceImpl) DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (*ateapi.EgressPolicy, error) { deleted, err := s.store.DeleteEgressPolicy(ctx, actorRef, precondition) return mapEgressPolicyWrite(deleted, err) } @@ -120,17 +120,17 @@ func mapEgressPolicyWrite(policy *ateapi.EgressPolicy, err error) (*ateapi.Egres case err == nil: return policy, nil case errors.Is(err, store.ErrNotFound): - return nil, apierror.NotFound("EgressPolicy not found") + return nil, apierror.NotFound("EgressPolicy not found").WithCause(err) case errors.Is(err, store.ErrAlreadyExists): - return nil, apierror.AlreadyExists("EgressPolicy already exists") + return nil, apierror.AlreadyExists("EgressPolicy already exists").WithCause(err) case errors.Is(err, store.ErrVersionConflict): - return nil, apierror.Aborted("EgressPolicy version conflict") + return nil, apierror.Aborted("EgressPolicy version conflict").WithCause(err) case errors.Is(err, store.ErrUIDConflict): - return nil, apierror.Aborted("EgressPolicy UID conflict") + return nil, apierror.Aborted("EgressPolicy UID conflict").WithCause(err) case errors.Is(err, store.ErrPreconditionRequired): - return nil, apierror.InvalidArgument("EgressPolicy UID and version are required") + return nil, apierror.InvalidArgument("EgressPolicy UID and version are required").WithCause(err) case errors.Is(err, store.ErrFailedPrecondition): - return nil, apierror.FailedPrecondition("parent Actor does not exist") + return nil, apierror.FailedPrecondition("parent Actor does not exist").WithCause(err) default: return nil, fmt.Errorf("while writing EgressPolicy: %w", err) } diff --git a/cmd/ateapi/internal/controlapi/egress_policy_test.go b/cmd/ateapi/internal/controlapi/egress_policy_test.go index 649af744f9..eb28206e9d 100644 --- a/cmd/ateapi/internal/controlapi/egress_policy_test.go +++ b/cmd/ateapi/internal/controlapi/egress_policy_test.go @@ -29,7 +29,7 @@ import ( func TestActorEgressPolicy(t *testing.T) { persistence, cleanup := storetest.SetupTestStore(t) defer cleanup() - service := &RPCService{impl: &ServiceImpl{store: persistence}} + service := &RPCService{gates: testGates, impl: &ServiceImpl{gates: testGates, store: persistence}} if _, err := persistence.CreateAtespace(t.Context(), &ateapi.Atespace{ Metadata: &ateapi.ResourceMetadata{Name: testAtespace}, }); err != nil { diff --git a/cmd/ateapi/internal/controlapi/export_test.go b/cmd/ateapi/internal/controlapi/export_test.go index e9537c0a78..9eb614efa4 100644 --- a/cmd/ateapi/internal/controlapi/export_test.go +++ b/cmd/ateapi/internal/controlapi/export_test.go @@ -87,7 +87,7 @@ func ReleasingWorkflows() []ReleasingWorkflow { // and its first actor update is the finalize commit. Finalize: func(t *testing.T, ctx context.Context, st store.Interface, actorRef resources.ActorRef, _ *ateapi.Actor) error { w, _ := newWireCaptureWorkflow(t, st) - _, err := w.SuspendActor(ctx, actorRef, suspendAsync) + _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendAsync) return err }, WantRetry: codes.OK, @@ -102,7 +102,7 @@ func ReleasingWorkflows() []ReleasingWorkflow { // As for the async suspend, the finalize commit is the first actor update. Finalize: func(t *testing.T, ctx context.Context, st store.Interface, actorRef resources.ActorRef, _ *ateapi.Actor) error { w, _ := newWireCaptureWorkflow(t, st) - _, err := w.SuspendActor(ctx, actorRef, suspendSync) + _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync) return err }, WantRetry: codes.OK, @@ -123,7 +123,7 @@ func ReleasingWorkflows() []ReleasingWorkflow { Name: "resume onto an ineligible worker", State: ateapi.ActorState_ACTOR_STATE_RESUMING, Finalize: func(_ *testing.T, ctx context.Context, st store.Interface, actorRef resources.ActorRef, actor *ateapi.Actor) error { - _, err := (&ActorWorkflow{store: st, scheduler: scheduling.New(nil)}).validateAssignedWorker(ctx, actorRef, actor, ineligibleTemplate) + _, err := (&ActorWorkflow{gates: testGates, store: st, scheduler: scheduling.New(nil)}).validateAssignedWorker(ctx, actorRef, actor, ineligibleTemplate) return err }, WantRetry: codes.Aborted, diff --git a/cmd/ateapi/internal/controlapi/external_volume.go b/cmd/ateapi/internal/controlapi/external_volume.go new file mode 100644 index 0000000000..faeb3cee0e --- /dev/null +++ b/cmd/ateapi/internal/controlapi/external_volume.go @@ -0,0 +1,74 @@ +// Copyright 2026 The Agent Substrate 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 controlapi + +import ( + "context" + "errors" + "fmt" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/apivalidation" + "go.ate.dev/substrate/cmd/ateapi/internal/store" + "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/resources" +) + +func (s *RPCService) GetExternalVolume(ctx context.Context, req *ateapi.GetExternalVolumeRequest) (*ateapi.ExternalVolume, error) { + if errs := apivalidation.ValidateGetExternalVolumeRequest(ctx, s.gates, req); len(errs) > 0 { + return nil, resources.ToAPIError(errs) + } + + volumeRef := resources.ExternalVolumeRefFromObjectRef(req.GetExternalVolume()) + volume, err := s.impl.GetExternalVolume(ctx, volumeRef) + if err != nil { + if errors.Is(err, store.ErrNotFound) { + return nil, apierror.NotFound("ExternalVolume %s not found", volumeRef).WithCause(err) + } + return nil, fmt.Errorf("while getting external volume from DB: %w", err) + } + return volume, nil +} + +func (s *ServiceImpl) GetExternalVolume(ctx context.Context, volumeRef resources.ExternalVolumeRef) (*ateapi.ExternalVolume, error) { + return s.store.GetExternalVolume(ctx, volumeRef) +} + +func (s *RPCService) ListExternalVolumes(ctx context.Context, req *ateapi.ListExternalVolumesRequest) (*ateapi.ListExternalVolumesResponse, error) { + if errs := apivalidation.ValidateListExternalVolumesRequest(ctx, s.gates, req); len(errs) > 0 { + return nil, resources.ToAPIError(errs) + } + + page, err := s.impl.ListExternalVolumes(ctx, req.GetAtespace(), toStoreListOptions(req.GetOptions())) + if err != nil { + return nil, mapListError(fmt.Errorf("while listing external volumes in db: %w", err)) + } + return &ateapi.ListExternalVolumesResponse{ + ExternalVolumes: page.Items, + NextPageToken: page.NextPageToken, + }, nil +} + +func (s *ServiceImpl) ListExternalVolumes(ctx context.Context, atespace string, opts store.ListOptions) (store.ListResponse[*ateapi.ExternalVolume], error) { + return s.store.ListExternalVolumes(ctx, atespace, opts) +} + +func (s *ServiceImpl) CreateExternalVolume(ctx context.Context, volume *ateapi.ExternalVolume) (*ateapi.ExternalVolume, error) { + return s.store.CreateExternalVolume(ctx, volume) +} + +func (s *ServiceImpl) DeleteExternalVolume(ctx context.Context, volumeRef resources.ExternalVolumeRef, precondition store.Precondition) (*ateapi.ExternalVolume, error) { + return s.store.DeleteExternalVolume(ctx, volumeRef, precondition) +} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/access_policy_test.go b/cmd/ateapi/internal/controlapi/functionaltest/access_policy_test.go deleted file mode 100644 index d3d6dc07f7..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/access_policy_test.go +++ /dev/null @@ -1,164 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "testing" - - "github.com/google/go-cmp/cmp" - "go.ate.dev/substrate/api/ateapi/v1" - "go.ate.dev/substrate/internal/resources" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/testing/protocmp" -) - -func wantCode(t *testing.T, op string, err error, want codes.Code) { - t.Helper() - if got := status.Code(err); got != want { - t.Fatalf("%s: code = %v, want %v (err: %v)", op, got, want, err) - } -} - -func TestGlobalAccessPolicy_CRUD(t *testing.T) { - tc := setupTest(t, namespaceForTest("ns-global-access-policy")) - defer tc.cleanup() - ctx := context.Background() - - _, err := tc.client.GetGlobalAccessPolicy(ctx, &ateapi.GetGlobalAccessPolicyRequest{Name: resources.SingletonName}) - wantCode(t, "Get before create", err, codes.NotFound) - - created, err := tc.client.CreateGlobalAccessPolicy(ctx, &ateapi.CreateGlobalAccessPolicyRequest{ - AccessPolicy: &ateapi.AccessPolicy{ - Metadata: &ateapi.ResourceMetadata{Name: "default"}, - Bindings: []*ateapi.Binding{{Role: "owner", Members: []string{"user:alice"}}}, - }, - }) - if err != nil { - t.Fatalf("Create failed: %v", err) - } - if md := created.GetMetadata(); md.GetName() != "default" || md.GetUid() == "" || md.GetVersion() != 1 { - t.Errorf("created metadata = %v, want name default, a uid and version 1", md) - } - - _, err = tc.client.CreateGlobalAccessPolicy(ctx, &ateapi.CreateGlobalAccessPolicyRequest{ - AccessPolicy: &ateapi.AccessPolicy{ - Metadata: &ateapi.ResourceMetadata{Name: "default"}, - Bindings: []*ateapi.Binding{{Role: "owner", Members: []string{"user:alice"}}}, - }, - }) - wantCode(t, "second Create", err, codes.AlreadyExists) - - got, err := tc.client.GetGlobalAccessPolicy(ctx, &ateapi.GetGlobalAccessPolicyRequest{Name: resources.SingletonName}) - if err != nil { - t.Fatalf("Get failed: %v", err) - } - if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { - t.Errorf("Get mismatch (-created +got):\n%s", diff) - } - - update := proto.Clone(created).(*ateapi.AccessPolicy) - update.Bindings = []*ateapi.Binding{ - {Role: "owner", Members: []string{"user:alice"}}, - {Role: "viewer", Members: []string{"user:bob"}}, - } - updated, err := tc.client.UpdateGlobalAccessPolicy(ctx, &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: update}) - if err != nil { - t.Fatalf("Update failed: %v", err) - } - if updated.GetMetadata().GetVersion() != created.GetMetadata().GetVersion()+1 { - t.Errorf("updated version = %d, want %d", updated.GetMetadata().GetVersion(), created.GetMetadata().GetVersion()+1) - } - if diff := cmp.Diff(update.GetBindings(), updated.GetBindings(), protocmp.Transform()); diff != "" { - t.Errorf("updated bindings mismatch (-want +got):\n%s", diff) - } - - // The update above consumed created's version. - _, err = tc.client.UpdateGlobalAccessPolicy(ctx, &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: update}) - wantCode(t, "stale Update", err, codes.Aborted) -} - -func TestAtespaceAccessPolicy_CRUD(t *testing.T) { - tc := setupTest(t, namespaceForTest("ns-atespace-access-policy")) - defer tc.cleanup() - ctx := context.Background() - createAtespace(t, tc, "team-a") - ref := &ateapi.ObjectRef{Name: "team-a"} - policy := &ateapi.AccessPolicy{ - Metadata: &ateapi.ResourceMetadata{Name: "default"}, - Bindings: []*ateapi.Binding{{Role: "editor", Members: []string{"user:alice"}}}, - } - - _, err := tc.client.CreateAtespaceAccessPolicy(ctx, &ateapi.CreateAtespaceAccessPolicyRequest{ - Atespace: &ateapi.ObjectRef{Name: "missing"}, - AccessPolicy: policy, - }) - wantCode(t, "Create on missing atespace", err, codes.FailedPrecondition) - - _, err = tc.client.GetAtespaceAccessPolicy(ctx, &ateapi.GetAtespaceAccessPolicyRequest{Atespace: ref, Name: resources.SingletonName}) - wantCode(t, "Get before create", err, codes.NotFound) - - created, err := tc.client.CreateAtespaceAccessPolicy(ctx, &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: ref, AccessPolicy: policy}) - if err != nil { - t.Fatalf("Create failed: %v", err) - } - _, err = tc.client.CreateAtespaceAccessPolicy(ctx, &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: ref, AccessPolicy: policy}) - wantCode(t, "second Create", err, codes.AlreadyExists) - - got, err := tc.client.GetAtespaceAccessPolicy(ctx, &ateapi.GetAtespaceAccessPolicyRequest{Atespace: ref, Name: resources.SingletonName}) - if err != nil { - t.Fatalf("Get failed: %v", err) - } - if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { - t.Errorf("Get mismatch (-created +got):\n%s", diff) - } - - update := proto.Clone(created).(*ateapi.AccessPolicy) - update.Bindings = []*ateapi.Binding{{Role: "viewer", Members: []string{"user:bob"}}} - updated, err := tc.client.UpdateAtespaceAccessPolicy(ctx, &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: ref, AccessPolicy: update}) - if err != nil { - t.Fatalf("Update failed: %v", err) - } - if diff := cmp.Diff(update.GetBindings(), updated.GetBindings(), protocmp.Transform()); diff != "" { - t.Errorf("updated bindings mismatch (-want +got):\n%s", diff) - } - - _, err = tc.client.DeleteAtespaceAccessPolicy(ctx, &ateapi.DeleteAtespaceAccessPolicyRequest{ - Atespace: ref, - Name: resources.SingletonName, - Options: &ateapi.DeleteOptions{Version: created.GetMetadata().GetVersion()}, - }) - wantCode(t, "Delete with stale version", err, codes.Aborted) - - if _, err := tc.client.DeleteAtespaceAccessPolicy(ctx, &ateapi.DeleteAtespaceAccessPolicyRequest{Atespace: ref, Name: resources.SingletonName}); err != nil { - t.Fatalf("Delete failed: %v", err) - } - _, err = tc.client.GetAtespaceAccessPolicy(ctx, &ateapi.GetAtespaceAccessPolicyRequest{Atespace: ref, Name: resources.SingletonName}) - wantCode(t, "Get after delete", err, codes.NotFound) - _, err = tc.client.DeleteAtespaceAccessPolicy(ctx, &ateapi.DeleteAtespaceAccessPolicyRequest{Atespace: ref, Name: resources.SingletonName}) - wantCode(t, "second Delete", err, codes.NotFound) - - // Deleting the atespace removes its policy with it. - if _, err := tc.client.CreateAtespaceAccessPolicy(ctx, &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: ref, AccessPolicy: policy}); err != nil { - t.Fatalf("re-Create failed: %v", err) - } - if _, err := tc.client.DeleteAtespace(ctx, &ateapi.DeleteAtespaceRequest{Atespace: ref}); err != nil { - t.Fatalf("DeleteAtespace failed: %v", err) - } - _, err = tc.client.GetAtespaceAccessPolicy(ctx, &ateapi.GetAtespaceAccessPolicyRequest{Atespace: ref, Name: resources.SingletonName}) - wantCode(t, "Get after DeleteAtespace", err, codes.NotFound) -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/actor_template_test.go b/cmd/ateapi/internal/controlapi/functionaltest/actor_template_test.go deleted file mode 100644 index 4d8f20a469..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/actor_template_test.go +++ /dev/null @@ -1,535 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "fmt" - "testing" - "time" - - "go.ate.dev/substrate/cmd/ateapi/internal/controlapi" - "go.ate.dev/substrate/internal/preview" - "go.ate.dev/substrate/internal/resources" - "google.golang.org/grpc/status" - "google.golang.org/protobuf/proto" - "k8s.io/apimachinery/pkg/util/wait" - - "github.com/google/go-cmp/cmp" - "go.ate.dev/substrate/api/ateapi/v1" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/metadata" - "google.golang.org/protobuf/testing/protocmp" -) - -func TestActorTemplateCRUD(t *testing.T) { - ns := namespaceForTest("ns-template-crud") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - - created, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tmpl-a"}, - Containers: []*ateapi.Container{{Name: "main", Image: "example.com/app:v1@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}}, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 1<<30)}, - // Server-owned status on the request is ignored. - Status: &ateapi.ActorTemplateStatus{ - GoldenSnapshotStatus: &ateapi.GoldenSnapshotStatus{ - GoldenTag: &ateapi.ObjectRef{Atespace: testAtespace, Name: "golden-tag"}, - }, - }, - }, - }) - if err != nil { - t.Fatalf("CreateActorTemplate failed: %v", err) - } - want := &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tmpl-a", Version: 1}, - Containers: []*ateapi.Container{{Name: "main", Image: "example.com/app:v1@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}}, - SnapshotConfig: &ateapi.SnapshotConfig{ - PreferredFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, - GoldenSnapshotConfig: &ateapi.GoldenSnapshotConfig{Mode: ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_ENABLED}, - }, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 1<<30)}, - Status: &ateapi.ActorTemplateStatus{}, - } - if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreUID, ignoreTimestamps); diff != "" { - t.Errorf("CreateActorTemplate response mismatch (-want +got):\n%s", diff) - } - - _, err = tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tmpl-a"}, - Containers: []*ateapi.Container{{Name: "main", Image: "example.com/app:v1@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}}, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 512<<20)}, - }, - }) - assertGrpcError(t, err, codes.AlreadyExists, "ActorTemplate "+testAtespace+"/tmpl-a already exists") - - got, err := tc.client.GetActorTemplate(ctx, &ateapi.GetActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl-a"}}) - if err != nil { - t.Fatalf("GetActorTemplate failed: %v", err) - } - if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { - t.Errorf("GetActorTemplate response mismatch (-created +got):\n%s", diff) - } - - list, err := tc.client.ListActorTemplates(ctx, &ateapi.ListActorTemplatesRequest{}) - if err != nil { - t.Fatalf("ListActorTemplates failed: %v", err) - } - if len(list.GetActorTemplates()) != 1 || list.GetActorTemplates()[0].GetMetadata().GetName() != "tmpl-a" { - t.Errorf("ListActorTemplates = %v, want [tmpl-a]", list.GetActorTemplates()) - } - - // The atespace filter scopes the listing: a match returns the template, a - // different atespace returns nothing. - list, err = tc.client.ListActorTemplates(ctx, &ateapi.ListActorTemplatesRequest{Atespace: testAtespace}) - if err != nil { - t.Fatalf("ListActorTemplates(atespace) failed: %v", err) - } - if len(list.GetActorTemplates()) != 1 { - t.Errorf("ListActorTemplates(atespace=%s) = %v, want [tmpl-a]", testAtespace, list.GetActorTemplates()) - } - list, err = tc.client.ListActorTemplates(ctx, &ateapi.ListActorTemplatesRequest{Atespace: "other-atespace"}) - if err != nil { - t.Fatalf("ListActorTemplates(other atespace) failed: %v", err) - } - if len(list.GetActorTemplates()) != 0 { - t.Errorf("ListActorTemplates(atespace=other-atespace) = %v, want []", list.GetActorTemplates()) - } - - deleted, err := tc.client.DeleteActorTemplate(ctx, &ateapi.DeleteActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl-a"}}) - if err != nil { - t.Fatalf("DeleteActorTemplate failed: %v", err) - } - if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreVersion, ignoreTimestamps); diff != "" { - t.Errorf("DeleteActorTemplate response mismatch (-created +deleted):\n%s", diff) - } - if deleted.GetMetadata().GetDeleteTime() == nil { - t.Errorf("the deleted template carries no delete_time") - } - _, err = tc.client.GetActorTemplate(ctx, &ateapi.GetActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl-a"}}) - assertGrpcError(t, err, codes.NotFound, "ActorTemplate "+testAtespace+"/tmpl-a not found") - _, err = tc.client.DeleteActorTemplate(ctx, &ateapi.DeleteActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl-a"}}) - assertGrpcError(t, err, codes.NotFound, "ActorTemplate "+testAtespace+"/tmpl-a not found") -} - -func TestGoldenTagLifecycle(t *testing.T) { - ns := namespaceForTest("golden-tag") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - createWorkerPool(t, tc, ns, "pool1", map[string]string{poolLabelKey: ns}) - tmpl := createTemplateWithSelector(t, tc, "golden-template", &ateapi.Selector{MatchLabels: map[string]string{poolLabelKey: ns}}) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - templateRef := resources.ActorTemplateRefFromActorTemplate(tmpl) - // Created before readiness: a later golden tag must not change its source. - early, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "early"}, ActorTemplate: templateRef.ToObjectRef(), - }}) - if err != nil { - t.Fatal(err) - } - controlapi.NewActorTemplateReconciler(tc.persistence, tc.service, 7*time.Second).Start(ctx) - var goldenRef *ateapi.ObjectRef - err = wait.PollUntilContextTimeout(ctx, 50*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) { - current, err := tc.client.GetActorTemplate(ctx, &ateapi.GetActorTemplateRequest{ActorTemplate: templateRef.ToObjectRef()}) - goldenRef = current.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag() - return goldenRef != nil, err - }) - if err != nil { - t.Fatalf("waiting for golden tag: %v", err) - } - golden, err := tc.client.GetTag(ctx, &ateapi.GetTagRequest{Tag: goldenRef}) - if err != nil { - t.Fatal(err) - } - uri := tagSnapshotURI(golden) - parsed, err := resources.ParseSnapshotURI(uri) - if err != nil { - t.Fatal(err) - } - if !parsed.OwnedBy(resources.TagSnapshotOwner(testAtespace, golden.GetMetadata().GetUid())) { - t.Fatalf("golden snapshot %q is not under the golden tag's own prefix", uri) - } - assertSnapshotPresent(t, tc, uri) - _, err = tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: goldenRef}) - if status.Code(err) != codes.NotFound { - t.Fatalf("golden actor was not deleted: %v", err) - } - late, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "late"}, ActorTemplate: templateRef.ToObjectRef(), - }}) - if err != nil { - t.Fatal(err) - } - if durableSnapshotURI(late.GetStatus()) != uri || durableSnapshot(late.GetStatus()).GetActorTemplateUid() != tmpl.GetMetadata().GetUid() { - t.Fatal("actor did not inherit golden tag snapshot and template UID") - } - waitForWorkerAvailable(t, tc, workerName) - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.RunCalled = false - tc.fakeAtelet.Lock.Unlock() - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: resources.ActorRefFromActor(early).ToObjectRef()}); err != nil { - t.Fatal(err) - } - if !tc.fakeAtelet.RunCalled { - t.Fatal("actor created before golden readiness did not cold boot") - } - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: resources.ActorRefFromActor(early).ToObjectRef()}); err != nil { - t.Fatal(err) - } - waitForWorkerAvailable(t, tc, workerName) - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: resources.ActorRefFromActor(late).ToObjectRef()}); err != nil { - t.Fatal(err) - } - if !tc.fakeAtelet.RestoreCalled { - t.Fatal("actor did not restore golden tag") - } - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: resources.ActorRefFromActor(late).ToObjectRef(), - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }); err != nil { - t.Fatal(err) - } - assertSnapshotPresent(t, tc, uri) - for _, actor := range []*ateapi.Actor{early, late} { - if _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: resources.ActorRefFromActor(actor).ToObjectRef()}); err != nil { - t.Fatal(err) - } - } - if _, err := tc.client.DeleteActorTemplate(ctx, &ateapi.DeleteActorTemplateRequest{ActorTemplate: templateRef.ToObjectRef()}); err != nil { - t.Fatal(err) - } - assertSnapshotCollected(t, tc, uri) - _, err = tc.client.GetTag(ctx, &ateapi.GetTagRequest{Tag: goldenRef}) - if status.Code(err) != codes.NotFound { - t.Fatalf("golden tag was not deleted: %v", err) - } -} - -func TestActorLifecycleWithoutGoldenSnapshot(t *testing.T) { - ns := namespaceForTest("no-golden") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx, cancel := context.WithCancel(t.Context()) - defer cancel() - createWorkerPool(t, tc, ns, "pool1", map[string]string{poolLabelKey: ns}) - tmpl, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "no-golden"}, - SnapshotConfig: &ateapi.SnapshotConfig{ - GoldenSnapshotConfig: &ateapi.GoldenSnapshotConfig{Mode: ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_DISABLED}, - }, - Containers: []*ateapi.Container{{Name: "main", Image: "main@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Command: []string{"/main"}}}, - WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{poolLabelKey: ns}}, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 512<<20)}, - }}) - if err != nil { - t.Fatal(err) - } - if tmpl.GetSnapshotConfig().GetGoldenSnapshotConfig().GetMode() != ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_DISABLED { - t.Fatal("CreateActorTemplate did not preserve the golden snapshot opt-out") - } - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - controlTemplate := createTemplateWithSelector(t, tc, "golden-control", &ateapi.Selector{MatchLabels: map[string]string{poolLabelKey: ns}}) - goldenRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: tmpl.GetMetadata().GetUid()} - assertNoGolden := func(ctx context.Context) error { - if _, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: goldenRef}); status.Code(err) != codes.NotFound { - return fmt.Errorf("disabled template's golden actor: got %v, want NotFound", err) - } - if _, err := tc.client.GetTag(ctx, &ateapi.GetTagRequest{Tag: goldenRef}); status.Code(err) != codes.NotFound { - return fmt.Errorf("disabled template's golden tag: got %v, want NotFound", err) - } - return nil - } - controlapi.NewActorTemplateReconciler(tc.persistence, tc.service, 7*time.Second).Start(ctx) - // The enabled template proves the same reconciler is making progress. - err = wait.PollUntilContextTimeout(ctx, 50*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) { - if err := assertNoGolden(ctx); err != nil { - return false, err - } - current, err := tc.client.GetActorTemplate(ctx, &ateapi.GetActorTemplateRequest{ - ActorTemplate: resources.ActorTemplateRefFromActorTemplate(controlTemplate).ToObjectRef(), - }) - return current.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag() != nil, err - }) - if err != nil { - t.Fatalf("waiting for enabled template's golden tag: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - actor, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "actor"}, - ActorTemplate: resources.ActorTemplateRefFromActorTemplate(tmpl).ToObjectRef(), - }}) - if err != nil { - t.Fatal(err) - } - if durableSnapshot(actor.GetStatus()) != nil { - t.Fatal("new actor unexpectedly inherited a snapshot") - } - ref := resources.ActorRefFromActor(actor).ToObjectRef() - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.RunCalled, tc.fakeAtelet.RestoreCalled = false, false - tc.fakeAtelet.Lock.Unlock() - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatal(err) - } - tc.fakeAtelet.Lock.Lock() - ran, restored := tc.fakeAtelet.RunCalled, tc.fakeAtelet.RestoreCalled - tc.fakeAtelet.Lock.Unlock() - if !ran || restored { - t.Fatal("first resume did not cold boot") - } - suspended, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: ref, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatal(err) - } - snapshotURI := durableSnapshotURI(suspended.GetActor().GetStatus()) - if snapshotURI == "" { - t.Fatal("suspend did not produce the actor's own snapshot") - } - assertSnapshotPresent(t, tc, snapshotURI) - waitForWorkerAvailable(t, tc, workerName) - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatal(err) - } - if got := tc.fakeAtelet.lastRestoreRequest().GetSnapshot().GetObject().GetSnapshotUri(); got != snapshotURI { - t.Fatalf("restored snapshot = %q, want actor's snapshot %q", got, snapshotURI) - } - if err := assertNoGolden(ctx); err != nil { - t.Fatal(err) - } - if _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref}); err != nil { - t.Fatal(err) - } - if _, err := tc.client.DeleteActorTemplate(ctx, &ateapi.DeleteActorTemplateRequest{ActorTemplate: resources.ActorTemplateRefFromActorTemplate(tmpl).ToObjectRef()}); err != nil { - t.Fatal(err) - } - if _, err := tc.client.DeleteActorTemplate(ctx, &ateapi.DeleteActorTemplateRequest{ActorTemplate: resources.ActorTemplateRefFromActorTemplate(controlTemplate).ToObjectRef()}); err != nil { - t.Fatal(err) - } -} - -func TestListActorTemplates_InvalidPageToken(t *testing.T) { - ns := namespaceForTest("ns-template-invalid-token") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.ListActorTemplates(context.Background(), - &ateapi.ListActorTemplatesRequest{Options: &ateapi.ListOptions{PageToken: "%%%"}}) - assertGrpcError(t, err, codes.InvalidArgument, "invalid page_token") -} - -func TestDeleteActorTemplate_Preconditions(t *testing.T) { - ns := namespaceForTest("ns-delete-template-preconditions") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - tmpl := createTemplateWithSelector(t, tc, "tmpl1", nil) - templateRef := resources.ActorTemplateRefFromActorTemplate(tmpl) - ref := templateRef.ToObjectRef() - del := func(opts *ateapi.DeleteOptions) error { - _, err := tc.client.DeleteActorTemplate(ctx, &ateapi.DeleteActorTemplateRequest{ActorTemplate: ref, Options: opts}) - return err - } - - uid, version := tmpl.GetMetadata().GetUid(), tmpl.GetMetadata().GetVersion() - - assertGrpcError(t, del(&ateapi.DeleteOptions{Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: uid, Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID}), codes.Aborted, "ActorTemplate "+templateRef.String()+" does not have uid "+foreignUID) - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID, Version: version}), codes.Aborted, "ActorTemplate "+templateRef.String()+" does not have uid "+foreignUID) - if _, err := tc.client.GetActorTemplate(ctx, &ateapi.GetActorTemplateRequest{ActorTemplate: ref}); err != nil { - t.Fatalf("a refused delete removed the template: %v", err) - } - - if err := del(&ateapi.DeleteOptions{Version: version}); err != nil { - t.Fatalf("DeleteActorTemplate with the matching version: %v", err) - } - tmpl = createTemplateWithSelector(t, tc, "tmpl1", nil) - if err := del(&ateapi.DeleteOptions{Uid: tmpl.GetMetadata().GetUid()}); err != nil { - t.Fatalf("DeleteActorTemplate with the matching uid: %v", err) - } - tmpl = createTemplateWithSelector(t, tc, "tmpl1", nil) - if err := del(&ateapi.DeleteOptions{Uid: tmpl.GetMetadata().GetUid(), Version: tmpl.GetMetadata().GetVersion()}); err != nil { - t.Fatalf("DeleteActorTemplate with both guards: %v", err) - } - _, err := tc.client.GetActorTemplate(ctx, &ateapi.GetActorTemplateRequest{ActorTemplate: ref}) - assertGrpcError(t, err, codes.NotFound, "ActorTemplate "+templateRef.String()+" not found") -} - -// TestCreateActorTemplate_ExternalVolumesPreview checks that external volumes -// are accepted only when the server enables the gate and the client opts in -// to preview features. -func TestCreateActorTemplate_ExternalVolumesPreview(t *testing.T) { - ns := namespaceForTest("ns-template-ext-vol-preview") - tc := setupTest(t, ns) - defer tc.cleanup() - - for i, tt := range []struct { - name string - gates []string - optIn bool - wantCode codes.Code - }{ - {name: "gate off", gates: nil, optIn: true, wantCode: codes.InvalidArgument}, - {name: "no opt-in", gates: []string{"ExternalVolumes"}, optIn: false, wantCode: codes.InvalidArgument}, - {name: "gate on and opt-in", gates: []string{"ExternalVolumes"}, optIn: true, wantCode: codes.OK}, - } { - t.Run(tt.name, func(t *testing.T) { - preview.InitForTest(t, tt.gates...) - ctx := context.Background() - if tt.optIn { - ctx = metadata.AppendToOutgoingContext(ctx, preview.Header, "true") - } - _, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: fmt.Sprintf("tmpl-ext-%d", i)}, - Containers: []*ateapi.Container{{ - Name: "main", - Image: "example.com/app:v1@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - VolumeMounts: []*ateapi.VolumeMount{{Name: "data", MountPath: "/data"}}, - }}, - Volumes: []*ateapi.Volume{{ - Name: "data", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{StorageClassName: "standard", CapacityBytes: 1 << 30}}, - }}, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 1<<30)}, - }, - }) - if status.Code(err) != tt.wantCode { - t.Fatalf("CreateActorTemplate error = %v, want %v", err, tt.wantCode) - } - }) - } -} - -// TestCreateActorTemplate_PerTemplateSnapshotLocationPreview pins how -// snapshotConfig.storageLocation combines the PerTemplateSnapshotLocation gate -// with the client's preview opt-in. Only a client that opts in may set it, and -// only with the gate on. A template that leaves it empty uses the server's -// --snapshot-location. -func TestCreateActorTemplate_PerTemplateSnapshotLocationPreview(t *testing.T) { - ns := namespaceForTest("ns-template-storage-location-preview") - tc := setupTest(t, ns) - defer tc.cleanup() - - for i, tt := range []struct { - name string - gates []string - optIn bool - location string - wantCode codes.Code - }{ - {name: "gate off, no opt-in, location set", optIn: false, location: "gs://my-bucket/snapshots", wantCode: codes.InvalidArgument}, - {name: "gate off, opt-in, location set", optIn: true, location: "gs://my-bucket/snapshots", wantCode: codes.InvalidArgument}, - {name: "gate off, opt-in, no location", optIn: true, wantCode: codes.OK}, - {name: "gate on, no opt-in, location set", gates: []string{"PerTemplateSnapshotLocation"}, optIn: false, location: "gs://my-bucket/snapshots", wantCode: codes.InvalidArgument}, - {name: "gate on, no opt-in, no location", gates: []string{"PerTemplateSnapshotLocation"}, optIn: false, wantCode: codes.OK}, - {name: "gate on, opt-in, location set", gates: []string{"PerTemplateSnapshotLocation"}, optIn: true, location: "gs://my-bucket/snapshots", wantCode: codes.OK}, - {name: "gate on, opt-in, no location", gates: []string{"PerTemplateSnapshotLocation"}, optIn: true, wantCode: codes.OK}, - } { - t.Run(tt.name, func(t *testing.T) { - preview.InitForTest(t, tt.gates...) - ctx := context.Background() - if tt.optIn { - ctx = metadata.AppendToOutgoingContext(ctx, preview.Header, "true") - } - _, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: fmt.Sprintf("tmpl-loc-%d", i)}, - Containers: []*ateapi.Container{{ - Name: "main", - Image: "example.com/app:v1@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - }}, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 1<<30)}, - SnapshotConfig: &ateapi.SnapshotConfig{StorageLocation: tt.location}, - }, - }) - if status.Code(err) != tt.wantCode { - t.Fatalf("CreateActorTemplate error = %v, want %v", err, tt.wantCode) - } - }) - } -} - -func TestCreateActorTemplate_GoldenEgressPolicyPreview(t *testing.T) { - tc := setupPreviewTest(t, namespaceForTest("ns-template-golden-egress-preview")) - t.Cleanup(tc.cleanup) - base := createTemplateWithSelector(t, tc, "base", nil) - - for i, tt := range []struct { - name string - gates []string - optIn bool - snapshotsDisabled bool - wantCode codes.Code - }{ - {name: "gate off", optIn: true, wantCode: codes.InvalidArgument}, - {name: "no opt-in", gates: []string{"GoldenEgressPolicy"}, wantCode: codes.InvalidArgument}, - {name: "unrelated gate", gates: []string{"ExternalVolumes"}, optIn: true, wantCode: codes.InvalidArgument}, - {name: "gate on and opt-in", gates: []string{"GoldenEgressPolicy"}, optIn: true, wantCode: codes.OK}, - {name: "all gates and opt-in", gates: []string{"ALL"}, optIn: true, wantCode: codes.OK}, - {name: "golden snapshots disabled", gates: []string{"GoldenEgressPolicy"}, optIn: true, snapshotsDisabled: true, wantCode: codes.InvalidArgument}, - } { - t.Run(tt.name, func(t *testing.T) { - preview.InitForTest(t, tt.gates...) - client := tc.noOptInClient - if tt.optIn { - client = tc.client - } - tmpl := proto.Clone(base).(*ateapi.ActorTemplate) - tmpl.Metadata = &ateapi.ResourceMetadata{Atespace: testAtespace, Name: fmt.Sprintf("golden-egress-%d", i)} - tmpl.Status = nil - tmpl.GoldenEgressPolicy = &ateapi.EgressPolicyTemplate{Rules: functionalEgressPolicy().Rules} - if tt.snapshotsDisabled { - tmpl.SnapshotConfig.GoldenSnapshotConfig = &ateapi.GoldenSnapshotConfig{Mode: ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_DISABLED} - } - ref := resources.ActorTemplateRefFromActorTemplate(tmpl).ToObjectRef() - created, err := client.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}) - if tt.wantCode != codes.OK { - assertGrpcErrorRegex(t, err, tt.wantCode, "golden_egress_policy") - _, err = client.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: ref}) - assertGrpcErrorRegex(t, err, codes.NotFound, "not found") - return - } - if err != nil { - t.Fatalf("CreateActorTemplate: %v", err) - } - wantPolicy := &ateapi.EgressPolicyTemplate{Rules: []*ateapi.EgressRule{{ - Http: &ateapi.HttpRule{Hostnames: []string{"api.example.com"}, Ports: &ateapi.Ports{Numbers: []int32{80}}}, - }}} - if diff := cmp.Diff(wantPolicy, created.GetGoldenEgressPolicy(), protocmp.Transform()); diff != "" { - t.Fatalf("golden policy (-want +got):\n%s", diff) - } - - // Opting out or disabling the gate must not strand existing templates. - preview.InitForTest(t) - got, err := tc.noOptInClient.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: ref}) - if err != nil { - t.Fatalf("GetActorTemplate with gate disabled: %v", err) - } - if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { - t.Fatalf("template changed with gate disabled (-want +got):\n%s", diff) - } - if _, err := tc.noOptInClient.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: ref}); err != nil { - t.Fatalf("DeleteActorTemplate with gate disabled: %v", err) - } - }) - } -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/actor_test.go b/cmd/ateapi/internal/controlapi/functionaltest/actor_test.go deleted file mode 100644 index 0cb3eddeeb..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/actor_test.go +++ /dev/null @@ -1,7304 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "encoding/base64" - "encoding/json" - "errors" - "fmt" - "slices" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - "cloud.google.com/go/storage" - "github.com/aws/aws-sdk-go-v2/service/s3/types" - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "go.ate.dev/substrate/api/ateapi/v1" - "go.ate.dev/substrate/cmd/ateapi/internal/store" - "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" - "go.ate.dev/substrate/internal/actoridjwt" - "go.ate.dev/substrate/internal/apierror" - "go.ate.dev/substrate/internal/ateattr" - "go.ate.dev/substrate/internal/installdefaults" - "go.ate.dev/substrate/internal/objectstore" - "go.ate.dev/substrate/internal/preview" - "go.ate.dev/substrate/internal/proto/ateletpb" - "go.ate.dev/substrate/internal/resources" - "go.ate.dev/substrate/internal/volume" - "go.opentelemetry.io/otel/attribute" - "go.opentelemetry.io/otel/sdk/metric/metricdata" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" - "google.golang.org/protobuf/encoding/protowire" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/testing/protocmp" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/utils/ptr" -) - -// TestCreateActor_Success tests the happy path for creating an actor. -// Workflow: -// 1. Creates a mock ActorTemplate in the test atespace. -// 2. Calls CreateActor RPC. -// 3. Verifies that the actor is successfully created and returned in the response with a generated ID. -func TestCreateActor_Success(t *testing.T) { - ns := namespaceForTest("ns-create-success") - tc := setupTest(t, ns) - defer tc.cleanup() - - tmpl := createTemplate(t, tc, ns) - - createResp, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "id1", - }, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"tier": "free"}}, - Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_RUNNING}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - want := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Name: "id1", Atespace: testAtespace, Version: 1}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{ - State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, - LastAssignedGeneration: 1, - Snapshots: []*ateapi.Snapshot{ - newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, tmpl.GetMetadata().GetUid(), goldenSnapshotName, goldenSnapshotURI(t)), - }, - }, - WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"tier": "free"}}, - } - - // The diff below ignores the server-assigned uid/timestamps (non-deterministic), - // so assert they are populated separately — and that uid is server-generated, - // not the caller-supplied value. - md := createResp.GetMetadata() - if md.GetUid() == "" { - t.Errorf("CreateActor response missing server-assigned uid") - } - if md.GetUid() == "caller-supplied-uid" { - t.Errorf("CreateActor echoed caller-supplied uid instead of generating one") - } - if md.GetCreateTime() == nil { - t.Errorf("CreateActor response missing create_time") - } - if md.GetUpdateTime() == nil { - t.Errorf("CreateActor response missing update_time") - } - - if diff := cmp.Diff(want, createResp, protocmp.Transform(), ignoreUID, ignoreTimestamps); diff != "" { - t.Errorf("CreateActor response mismatch (-want +got):\n%s", diff) - } -} - -func TestCreateActor_WithExternalVolumes(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-create-ext-vols") - tc := setupPreviewTest(t, ns) - defer tc.cleanup() - - volumes := []*ateapi.Volume{ - { - Name: "ext-vol-1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - { - Name: "ext-vol-1", - MountPath: "/data", - }, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - - createResp, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "vol-actor-1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - if len(createResp.GetStatus().GetExternalVolumes().GetVolumes()) != 1 { - t.Fatalf("expected 1 volume in CreateActor response, got %d", len(createResp.GetStatus().GetExternalVolumes().GetVolumes())) - } - vol := createResp.GetStatus().GetExternalVolumes().GetVolumes()[0] - if vol.GetName() != "ext-vol-1" { - t.Errorf("volume name = %q, want %q", vol.GetName(), "ext-vol-1") - } - if vol.GetStorageVolumeId() != "" { - t.Errorf("expected empty storageVolumeId before resume, got %q", vol.GetStorageVolumeId()) - } - - // Verify GetActor returns the same external volume state - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "vol-actor-1"}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if len(getResp.GetStatus().GetExternalVolumes().GetVolumes()) != 1 { - t.Fatalf("expected 1 volume in GetActor response, got %d", len(getResp.GetStatus().GetExternalVolumes().GetVolumes())) - } - if got := getResp.GetStatus().GetExternalVolumes().GetVolumes()[0].GetStorageVolumeId(); got != "" { - t.Errorf("GetActor storageVolumeId = %q, want empty before resume", got) - } -} - -// TestCreateActor_ExternalVolumesWithoutOptIn checks that a client which did -// not opt in to preview features cannot create an Actor whose template has -// external volumes, even though the server enables the gate. -func TestCreateActor_ExternalVolumesWithoutOptIn(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-create-ext-vols-no-opt-in") - tc := setupPreviewTest(t, ns) - defer tc.cleanup() - - createTemplateWithVolumes(t, tc, ns, - []*ateapi.Volume{{ - Name: "ext-vol-1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{StorageClassName: "standard", CapacityBytes: 10 << 30}}, - }}, - []*ateapi.VolumeMount{{Name: "ext-vol-1", MountPath: "/data"}}) - - _, err := tc.noOptInClient.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "vol-actor-1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if status.Code(err) != codes.InvalidArgument { - t.Fatalf("CreateActor error = %v, want InvalidArgument", err) - } - if !strings.Contains(err.Error(), preview.Header) { - t.Errorf("CreateActor error = %v, want it to mention %s", err, preview.Header) - } -} - -// TestActorLifecycle_ExternalVolumesWithoutOptIn checks that a client which -// did not opt in to preview features can still resume, suspend and delete an -// Actor with external volumes: those requests carry no preview fields, and the -// volume state they change is written by workflows on the system's behalf. -func TestActorLifecycle_ExternalVolumesWithoutOptIn(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-lifecycle-ext-vols-no-opt-in") - tc := setupPreviewTest(t, ns) - defer tc.cleanup() - - createTemplateWithVolumes(t, tc, ns, - []*ateapi.Volume{{ - Name: "data-vol", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{StorageClassName: "fast", CapacityBytes: 20 << 30}}, - }}, - []*ateapi.VolumeMount{{Name: "data-vol", MountPath: "/mnt/data"}}) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-vol-no-opt-in"} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: actorRef.Name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - _, err := tc.noOptInClient.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - if _, err := tc.noOptInClient.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - - if _, err := tc.noOptInClient.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - _, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: actorRef}) - if status.Code(err) != codes.NotFound { - t.Errorf("GetActor after delete err = %v, want NotFound", err) - } -} - -// TestCreateActor_TemplateNotFound tests that creating an actor with a non-existent template fails with FailedPrecondition. -func TestCreateActor_TemplateNotFound(t *testing.T) { - ns := namespaceForTest("ns-create-notfound") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "non-existent"}, - }}) - if got := status.Code(err); got != codes.FailedPrecondition { - t.Fatalf("CreateActor with a missing template = %v, want FailedPrecondition (err: %v)", got, err) - } -} - -// TestCreateActor_SubstrateTemplateRef covers creation against a template -// with no golden snapshot yet: the actor names its template with an -// actor_template ObjectRef resolved from the store at create time. -func TestCreateActor_SubstrateTemplateRef(t *testing.T) { - ns := namespaceForTest("ns-create-sub-ref") - tc := setupTest(t, ns) - defer tc.cleanup() - - ctx := context.Background() - if _, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "sub-tmpl"}, - Containers: []*ateapi.Container{{Name: "main", Image: "example.com/app:v1@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}}, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 512<<20)}, - }, - }); err != nil { - t.Fatalf("CreateActorTemplate failed: %v", err) - } - - created, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "ref-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "sub-tmpl"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - want := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "ref-actor", Version: 1}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "sub-tmpl"}, - Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, - } - if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreUID, ignoreTimestamps); diff != "" { - t.Errorf("CreateActor response mismatch (-want +got):\n%s", diff) - } - - // A reference to a template that does not exist fails. - _, err = tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "ref-actor-2"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "absent"}, - }}) - if got := status.Code(err); got != codes.FailedPrecondition { - t.Fatalf("CreateActor with an absent template ref = %v, want FailedPrecondition (err: %v)", got, err) - } -} - -// TestCreateActor_Duplicate tests that creating an actor with an existing ID fails. -func TestCreateActor_Duplicate(t *testing.T) { - ns := namespaceForTest("ns-create-dup") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("first CreateActor failed: %v", err) - } - - _, err = tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - assertGrpcError(t, err, codes.AlreadyExists, "Actor id1 already exists") -} - -// CreateActor is the only lifecycle op with the full identity (incl. version) -// available in the request, so the whole ate.* set should land on its span. -func TestCreateActor_StampsFullSpanIdentity(t *testing.T) { - ns := namespaceForTest("ns-span-create") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - - attrs := recordRootSpanAttrs(t, func(ctx context.Context) { - if _, err := tc.service.CreateActor(ctx, &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: testActorID}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }); err != nil { - t.Fatalf("CreateActor: %v", err) - } - }) - - assertSpanStr(t, attrs, ateattr.AtespaceKey, testAtespace) - assertSpanStr(t, attrs, ateattr.ActorNameKey, testActorID) - assertSpanStr(t, attrs, ateattr.TemplateNameKey, "tmpl1") - assertSpanStr(t, attrs, ateattr.TemplateAtespaceKey, testAtespace) - // uid is server-assigned on create, so assert it is present and non-empty - // rather than a fixed value. - if v, ok := attrs[ateattr.ActorUIDKey]; !ok || v.Type() != attribute.STRING || v.AsString() == "" { - t.Errorf("%s = %v, want non-empty server-assigned uid", ateattr.ActorUIDKey, v.String()) - } - if v, ok := attrs[ateattr.ActorVersionKey]; !ok || v.Type() != attribute.INT64 || v.AsInt64() != 1 { - t.Errorf("%s = %v, want int64 1", ateattr.ActorVersionKey, v.String()) - } -} - -func TestCreateActor_RejectsDifferentTemplateForDataSnapshot(t *testing.T) { - ns := namespaceForTest("ns-data-snapshot-template") - tc := setupTest(t, ns) - defer tc.cleanup() - tmpl := createTemplate(t, tc, ns) - createTemplateWithSelector(t, tc, "tmpl2", nil) - - seedTag(t, tc, "data-source", "data-snapshot", func(tag *ateapi.Tag) { - tag.Status.Snapshot.Fidelity = ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES - tag.Status.ActorTemplateUid = tmpl.GetMetadata().GetUid() - }) - - _, err := tc.service.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "clone"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl2"}, - SourceTag: &ateapi.ObjectRef{Atespace: testAtespace, Name: "data-snapshot"}, - }, - }) - if apierror.Code(err) != codes.FailedPrecondition { - t.Fatalf("CreateActor status = %v, want FailedPrecondition", apierror.Code(err)) - } -} - -func TestCreateActor_RejectsSnapshotWithExternalVolumes(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-snapshot-external-volume") - tc := setupPreviewTest(t, ns) - defer tc.cleanup() - template, err := tc.client.CreateActorTemplate(context.Background(), &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tmpl1"}, - Containers: []*ateapi.Container{{ - Name: "main", Image: "main@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", VolumeMounts: []*ateapi.VolumeMount{{Name: "data", MountPath: "/data"}}, - }}, - Volumes: []*ateapi.Volume{{ - Name: "data", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - CapacityBytes: 1 << 30, StorageClassName: "standard", - }}, - }}, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 512<<20)}, - }, - }) - if err != nil { - t.Fatalf("Create ActorTemplate: %v", err) - } - seedTag(t, tc, "external-volume-source", "external-volume-snapshot", func(tag *ateapi.Tag) { - tag.Status.ActorTemplateUid = template.GetMetadata().GetUid() - }) - tagRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "external-volume-snapshot"} - - _, err = tc.service.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "clone"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - SourceTag: tagRef, - }, - }) - if apierror.Code(err) != codes.FailedPrecondition { - t.Fatalf("CreateActor status = %v, want FailedPrecondition", apierror.Code(err)) - } -} - -// TestCreateActor_PendingTag verifies an Actor cannot be created from a -// tag whose create never finished: the tag names a copy that may be partial, so -// it only becomes a source once the create completes. -func TestCreateActor_PendingTag(t *testing.T) { - ns := namespaceForTest("ns-pending-tag") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - tmpl := createTemplate(t, tc, ns) - - // Simulates a tag creation that failed while writing the snapshot to - // external storage. - pending := seedTag(t, tc, "pending-source", "pending", func(tag *ateapi.Tag) { - tag.Status.Snapshot.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING - tag.Status.ActorTemplateUid = tmpl.GetMetadata().GetUid() - }) - tagRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "pending"} - - // seeding an actor from the pending tag must fail. - _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "clone"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - SourceTag: tagRef, - }}) - assertGrpcError(t, err, codes.FailedPrecondition, "source Tag is still being created or failed creation") - - // Finishing the tag creation, so now the tag is qualified to be a tag source. - snapshotURI := pending.GetStatus().GetSnapshot().GetDurableSnapshot().GetObject().GetSnapshotUri() - if _, err := tc.persistence.UpdateTag(ctx, - resources.TagRefFromTag(pending), store.PreconditionFrom(pending), - func(toUpdate *ateapi.Tag) error { - toUpdate.Status.Snapshot.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED - return nil - }); err != nil { - t.Fatalf("finalizing the tag: %v", err) - } - - // The tag was finalized. Now, actor creation should succeed. - clone, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "clone"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - SourceTag: tagRef, - }}) - if err != nil { - t.Fatalf("CreateActor from the finished tag failed: %v", err) - } - // The clone points at the tag's snapshot, under the tag's own prefix: the - // tag still owns those objects. - if got := durableSnapshotURI(clone.GetStatus()); got != snapshotURI { - t.Errorf("clone external snapshot = %q, want the tag's %q", got, snapshotURI) - } -} - -// TestCreateActor_FromDeletingTag verifies an Actor cannot be created from a tag -// with delete_time set, since DeleteTag may already have collected its snapshot. -func TestCreateActor_FromDeletingTag(t *testing.T) { - ns := namespaceForTest("ns-deleting-tag") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - tmpl := createTemplate(t, tc, ns) - - tag := seedTag(t, tc, "deleting-source", "deleting", func(tag *ateapi.Tag) { - tag.Status.ActorTemplateUid = tmpl.GetMetadata().GetUid() - }) - if _, err := tc.persistence.MarkTagForDeletion(ctx, resources.TagRefFromTag(tag), store.DeletePreconditions{}, nil); err != nil { - t.Fatalf("MarkTagForDeletion: %v", err) - } - - _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "clone"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - SourceTag: resources.TagRefFromTag(tag).ToObjectRef(), - }}) - assertGrpcError(t, err, codes.FailedPrecondition, "source Tag "+testAtespace+"/deleting is being deleted") -} - -// TestCreateActor_FromDeletingGoldenTag verifies an Actor created without a source -// tag is refused while its template's golden tag has delete_time set. -func TestCreateActor_FromDeletingGoldenTag(t *testing.T) { - ns := namespaceForTest("ns-deleting-golden-tag") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - tmpl := createTemplate(t, tc, ns) - - golden := seedTag(t, tc, "golden-source", "golden", func(tag *ateapi.Tag) { - tag.Status.ActorTemplateUid = tmpl.GetMetadata().GetUid() - }) - goldenRef := resources.TagRefFromTag(golden) - if _, err := tc.persistence.UpdateActorTemplate(ctx, resources.ActorTemplateRefFromActorTemplate(tmpl), store.PreconditionFrom(tmpl), func(toUpdate *ateapi.ActorTemplate) error { - toUpdate.Status = &ateapi.ActorTemplateStatus{GoldenSnapshotStatus: &ateapi.GoldenSnapshotStatus{GoldenTag: goldenRef.ToObjectRef()}} - return nil - }); err != nil { - t.Fatalf("recording the golden tag: %v", err) - } - if _, err := tc.persistence.MarkTagForDeletion(ctx, goldenRef, store.DeletePreconditions{}, nil); err != nil { - t.Fatalf("MarkTagForDeletion: %v", err) - } - - _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - assertGrpcError(t, err, codes.FailedPrecondition, "source Tag "+testAtespace+"/golden is being deleted") -} - -// TestGetActor_Found tests that an existing actor can be retrieved. -func TestGetActor_Found(t *testing.T) { - ns := namespaceForTest("ns-get-found") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - name := "id1" - - createResp, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - - want := createResp - - if diff := cmp.Diff(want, getResp, protocmp.Transform()); diff != "" { - t.Errorf("GetActor response mismatch (-want +got):\n%s", diff) - } -} - -// TestGetActor_NotFound tests that retrieving a non-existent actor fails. -// Workflow: -// 1. Calls GetActor RPC with a non-existent ID. -// 2. Verifies that it returns an error (NotFound). -func TestGetActor_NotFound(t *testing.T) { - ns := namespaceForTest("ns-get-notfound") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "non-existent"}, - }) - assertGrpcError(t, err, codes.NotFound, "Actor test-atespace/non-existent not found") -} - -// TestListActors tests that all created actors can be listed. -// Workflow: -// 1. Creates a mock ActorTemplate. -// 2. Calls CreateActor twice to create two actors. -// 3. Calls ListActors RPC. -// 4. Verifies that both actors are returned in the list. -func TestListActors(t *testing.T) { - ns := namespaceForTest("ns-list-actors") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - resp1, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor 1 failed: %v", err) - } - resp2, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id2"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor 2 failed: %v", err) - } - - listResp, err := tc.client.ListActors(context.Background(), &ateapi.ListActorsRequest{Atespace: testAtespace}) - if err != nil { - t.Fatalf("ListActors failed: %v", err) - } - - if len(listResp.Actors) != 2 { - t.Fatalf("expected 2 actors, got %d", len(listResp.Actors)) - } - - want := []*ateapi.Actor{ - resp1, - resp2, - } - - opts := []cmp.Option{ - protocmp.Transform(), - cmpopts.SortSlices(func(a, b *ateapi.Actor) bool { - return a.GetMetadata().GetName() < b.GetMetadata().GetName() - }), - } - - if diff := cmp.Diff(want, listResp.Actors, opts...); diff != "" { - t.Errorf("ListActors response mismatch (-want +got):\n%s", diff) - } -} - -// TestListActors_ByAtespace verifies create + list are scoped by atespace end to -// end through the RPC surface: an actor created with a given atespace is only -// returned by ListActors(atespace=X) and only fetched by GetActor(atespace=X). -func TestListActors_ByAtespace(t *testing.T) { - ns := namespaceForTest("ns-list-by-atespace") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createAtespace(t, tc, "team-a") - createAtespace(t, tc, "team-b") - - create := func(atespace, name string) *ateapi.Actor { - resp, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor(%s, atespace=%q) failed: %v", name, atespace, err) - } - return resp - } - a1 := create("team-a", "id1") - a2 := create("team-a", "id2") - b1 := create("team-b", "id3") - - sortByID := []cmp.Option{ - protocmp.Transform(), - cmpopts.SortSlices(func(a, b *ateapi.Actor) bool { return a.GetMetadata().GetName() < b.GetMetadata().GetName() }), - } - - // List scoped to team-a returns only its actors. - listA, err := tc.client.ListActors(context.Background(), &ateapi.ListActorsRequest{Atespace: "team-a"}) - if err != nil { - t.Fatalf("ListActors(team-a) failed: %v", err) - } - if diff := cmp.Diff([]*ateapi.Actor{a1, a2}, listA.GetActors(), sortByID...); diff != "" { - t.Errorf("ListActors(team-a) mismatch (-want +got):\n%s", diff) - } - - // List scoped to team-b returns only its actor. - listB, err := tc.client.ListActors(context.Background(), &ateapi.ListActorsRequest{Atespace: "team-b"}) - if err != nil { - t.Fatalf("ListActors(team-b) failed: %v", err) - } - if diff := cmp.Diff([]*ateapi.Actor{b1}, listB.GetActors(), sortByID...); diff != "" { - t.Errorf("ListActors(team-b) mismatch (-want +got):\n%s", diff) - } - - // Get is scoped: the right atespace hits, the empty atespace misses (deny-across by key). - if _, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: "team-a", Name: "id1"}}); err != nil { - t.Errorf("GetActor(id1, team-a) failed: %v", err) - } - _, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}}) - assertGrpcError(t, err, codes.NotFound, "Actor test-atespace/id1 not found") -} - -// TestListActors_AllAtespaces verifies that an empty atespace lists actors across -// all atespaces (the `-A` / admin view), unlike the scoped single-atespace listing. -func TestListActors_AllAtespaces(t *testing.T) { - ns := namespaceForTest("ns-list-all-atespaces") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createAtespace(t, tc, "team-a") - createAtespace(t, tc, "team-b") - - create := func(atespace, name string) { - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor(%s, atespace=%q) failed: %v", name, atespace, err) - } - } - create("team-a", "id1") - create("team-b", "id2") - - // Empty atespace lists across all atespaces; returned actors carry their atespace. - resp, err := tc.client.ListActors(context.Background(), &ateapi.ListActorsRequest{}) - if err != nil { - t.Fatalf("ListActors(all) failed: %v", err) - } - got := map[string]string{} - for _, a := range resp.GetActors() { - got[a.GetMetadata().GetName()] = a.GetMetadata().GetAtespace() - } - if got["id1"] != "team-a" { - t.Errorf("ListActors(all): got[id1]=%q, want team-a", got["id1"]) - } - if got["id2"] != "team-b" { - t.Errorf("ListActors(all): got[id2]=%q, want team-b", got["id2"]) - } -} - -// TestListActors_Pagination tests that ListActors correctly paginates results. -func TestListActors_Pagination(t *testing.T) { - ns := namespaceForTest("ns-list-actors-pagination") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - var want []*ateapi.Actor - for i := 0; i < 5; i++ { - resp, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: fmt.Sprintf("name%d", i)}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor %d failed: %v", i, err) - } - want = append(want, resp) - } - - var allActors []*ateapi.Actor - pageToken := "" - - for { - listResp, err := tc.client.ListActors(context.Background(), &ateapi.ListActorsRequest{ - Atespace: testAtespace, - Options: &ateapi.ListOptions{PageSize: 2, PageToken: pageToken}, - }) - if err != nil { - t.Fatalf("ListActors failed: %v", err) - } - - allActors = append(allActors, listResp.Actors...) - pageToken = listResp.GetNextPageToken() - if pageToken == "" { - break - } - } - - if len(allActors) != 5 { - t.Fatalf("expected 5 actors total, got %d", len(allActors)) - } - - opts := []cmp.Option{ - protocmp.Transform(), - cmpopts.SortSlices(func(a, b *ateapi.Actor) bool { - return a.GetMetadata().GetName() < b.GetMetadata().GetName() - }), - } - - if diff := cmp.Diff(want, allActors, opts...); diff != "" { - t.Errorf("ListActors pagination response mismatch (-want +got):\n%s", diff) - } -} - -// TestUpdateActor_Success verifies UpdateActor replaces the actor's -// worker_selector and that the change is durably persisted. -func TestUpdateActor_Success(t *testing.T) { - ns := namespaceForTest("ns-update-actor") - tc := setupTest(t, ns) - defer tc.cleanup() - - tmpl := createTemplate(t, tc, ns) - - toUpdate, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{"tier": "free"}, - }, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - toUpdate.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "paid"}} - - updateResp, err := tc.client.UpdateActor(context.Background(), &ateapi.UpdateActorRequest{ - Actor: toUpdate, - }) - if err != nil { - t.Fatalf("UpdateActor failed: %v", err) - } - - wantActor := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Name: "id1", Atespace: testAtespace, Version: 2}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{ - State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, - LastAssignedGeneration: 1, - Snapshots: []*ateapi.Snapshot{ - newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, tmpl.GetMetadata().GetUid(), goldenSnapshotName, goldenSnapshotURI(t)), - }, - }, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{"tier": "paid"}, - }, - } - if diff := cmp.Diff(wantActor, updateResp, protocmp.Transform(), ignoreUID, ignoreTimestamps); diff != "" { - t.Errorf("UpdateActor response mismatch (-want +got):\n%s", diff) - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - wantGetResp := wantActor - if diff := cmp.Diff(wantGetResp, getResp, protocmp.Transform(), ignoreUID, ignoreTimestamps); diff != "" { - t.Errorf("GetActor response mismatch after UpdateActor (-want +got):\n%s", diff) - } -} - -// TestUpdateActor_RepointTemplate verifies UpdateActor can point an actor at -// a different substrate ActorTemplate (effective on the next ResumeActor), -// and that a ref to an absent template, or to one with different volumes or -// volume mounts, is rejected. -func TestUpdateActor_RepointTemplate(t *testing.T) { - tests := []struct { - name string - template string - wantCode codes.Code - }{ - {name: "absent-template", template: "absent", wantCode: codes.FailedPrecondition}, - {name: "different-mounts", template: "tmpl-c", wantCode: codes.FailedPrecondition}, - {name: "different-volumes", template: "tmpl-d", wantCode: codes.FailedPrecondition}, - {name: "same-volumes", template: "tmpl-b", wantCode: codes.OK}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-update-repoint-" + tt.name) - tc := setupTest(t, ns) - defer tc.cleanup() - - ctx := context.Background() - // tmpl-a and tmpl-b are volume-compatible; tmpl-c mounts the data - // volume elsewhere, and tmpl-d declares an extra volume. - dataVolume := &ateapi.Volume{Name: "data", DurableDir: &ateapi.DurableDirVolumeSource{}} - scratchVolume := &ateapi.Volume{Name: "scratch", DurableDir: &ateapi.DurableDirVolumeSource{}} - templates := map[string]struct { - mountPath string - volumes []*ateapi.Volume - }{ - "tmpl-a": {"/data", []*ateapi.Volume{dataVolume}}, - "tmpl-b": {"/data", []*ateapi.Volume{dataVolume}}, - "tmpl-c": {"/mnt/data", []*ateapi.Volume{dataVolume}}, - "tmpl-d": {"/data", []*ateapi.Volume{dataVolume, scratchVolume}}, - } - for name, tmpl := range templates { - if _, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - Containers: []*ateapi.Container{{ - Name: "main", - Image: "example.com/app:v1@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - VolumeMounts: []*ateapi.VolumeMount{{Name: "data", MountPath: tmpl.mountPath}}, - }}, - Volumes: tmpl.volumes, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 512<<20)}, - }, - }); err != nil { - t.Fatalf("CreateActorTemplate %s failed: %v", name, err) - } - } - - created, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "repoint-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl-a"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - updated, err := tc.client.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: &ateapi.Actor{ - Metadata: created.GetMetadata(), - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: tt.template}, - }}) - if got := status.Code(err); got != tt.wantCode { - t.Fatalf("UpdateActor repointing at %s = %v, want %v (err: %v)", tt.template, got, tt.wantCode, err) - } - if tt.wantCode != codes.OK { - return - } - - want := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "repoint-actor", Version: 2}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: tt.template}, - Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, - } - if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreUID, ignoreTimestamps); diff != "" { - t.Errorf("UpdateActor response mismatch (-want +got):\n%s", diff) - } - }) - } -} - -// TestUpdateActor verifies a typical RMW UpdateActor flow: a -// client reads an actor, modifies it and send an UpdateActor request. -// Output-only fields it sets are ignored, and the mutable actor_template ref -// can repoint the actor at another template. -func TestUpdateActor(t *testing.T) { - ns := namespaceForTest("ns-update-replace") - tc := setupTest(t, ns) - defer tc.cleanup() - - tmpl := createTemplate(t, tc, ns) - - created, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{"tier": "free"}, - }, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Mutable field - created.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "paid"}} - // Output-only: server-owned, so this is ignored rather than applied. - created.Status = &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_RUNNING} - updatedActor, err := tc.client.UpdateActor(context.Background(), &ateapi.UpdateActorRequest{Actor: created}) - if err != nil { - t.Fatalf("UpdateActor failed: %v", err) - } - - wantActor := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Name: "id1", Atespace: testAtespace, Version: 2}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{ - State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, - LastAssignedGeneration: 1, - Snapshots: []*ateapi.Snapshot{ - newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, tmpl.GetMetadata().GetUid(), goldenSnapshotName, goldenSnapshotURI(t)), - }, - }, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{"tier": "paid"}, - }, - } - if diff := cmp.Diff(wantActor, updatedActor, protocmp.Transform(), ignoreUID, ignoreTimestamps); diff != "" { - t.Errorf("UpdateActor response mismatch (-want +got):\n%s", diff) - } - - // Mutable template ref: repoint the actor at a second template. - tmpl2 := proto.Clone(tmpl).(*ateapi.ActorTemplate) - tmpl2.Metadata = &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tmpl2"} - tmpl2.Status = nil - if _, err := tc.client.CreateActorTemplate(context.Background(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl2}); err != nil { - t.Fatalf("CreateActorTemplate failed: %v", err) - } - - updatedActor.ActorTemplate = &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl2"} - repointed, err := tc.client.UpdateActor(context.Background(), &ateapi.UpdateActorRequest{Actor: updatedActor}) - if err != nil { - t.Fatalf("UpdateActor failed: %v", err) - } - wantActor.Metadata.Version = 3 - wantActor.ActorTemplate = &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl2"} - if diff := cmp.Diff(wantActor, repointed, protocmp.Transform(), ignoreUID, ignoreTimestamps); diff != "" { - t.Errorf("UpdateActor response mismatch after template repoint (-want +got):\n%s", diff) - } -} - -// TestUpdateActor_Preconditions verifies the required version and uid guards -// carried in the embedded resource's metadata. -func TestUpdateActor_Preconditions(t *testing.T) { - ns := namespaceForTest("ns-update-preconditions") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - ctx := context.Background() - createActor := func() *ateapi.Actor { - t.Helper() - actor, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: testActorID}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - return actor - } - - update := func(observed *ateapi.Actor, tier string) (*ateapi.Actor, error) { - actor := proto.Clone(observed).(*ateapi.Actor) - actor.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": tier}} - return tc.client.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: actor}) - } - // Delete and recreate the same atespace/name actor, so the first lifecycle's uid - // becomes stale. - staleUID := createActor().GetMetadata().GetUid() - if _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: testActorID}, - }); err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - - created := createActor() - staleVersion := created.GetMetadata().GetVersion() - uid := created.GetMetadata().GetUid() - if uid == staleUID { - t.Fatalf("recreated actor reused uid %s, want a fresh one", uid) - } - // No preconditions - unguarded := proto.Clone(created).(*ateapi.Actor) - unguarded.Metadata.Uid, unguarded.Metadata.Version = "", 0 - _, err := update(unguarded, "blind") - assertGrpcError(t, err, codes.InvalidArgument, "while updating actor test-atespace/id1: persistence: precondition required: uid") - - // The uid from the deleted lifecycle must be rejected, even though the - // atespace/name it was observed under still resolves and the version it - // guards on matches the recreated actor's. - otherLifecycle := proto.Clone(created).(*ateapi.Actor) - otherLifecycle.Metadata.Uid = staleUID - _, err = update(otherLifecycle, "other-lifecycle") - assertGrpcError(t, err, codes.Aborted, "concurrent update conflict, please retry") - - // Both guards matching the observed state: the update goes through, and - // moves the resource past the version observed above. - first, err := update(created, "free") - if err != nil { - t.Fatalf("UpdateActor(matching guards) failed: %v", err) - } - currentVersion := first.GetMetadata().GetVersion() - if currentVersion <= staleVersion { - t.Fatalf("version = %d, want greater than %d after an update", currentVersion, staleVersion) - } - if got := first.GetWorkerSelector().GetMatchLabels()["tier"]; got != "free" { - t.Errorf("worker_selector[tier] = %q, want free", got) - } - - // The version observed before that write is now stale: rejected rather than - // silently overwriting the concurrent change. - _, err = update(created, "stale") - assertGrpcError(t, err, codes.Aborted, "concurrent update conflict, please retry") - - // Guarding on the version the last write produced succeeds again. - updated, err := update(first, "paid") - if err != nil { - t.Fatalf("UpdateActor(matching guards) failed: %v", err) - } - if got := updated.GetWorkerSelector().GetMatchLabels()["tier"]; got != "paid" { - t.Errorf("worker_selector[tier] = %q, want paid", got) - } - if updated.GetMetadata().GetVersion() <= currentVersion { - t.Errorf("version = %d, want greater than %d", updated.GetMetadata().GetVersion(), currentVersion) - } - - // The guard the client just satisfied is now stale in turn. - _, err = update(first, "free") - assertGrpcError(t, err, codes.Aborted, "concurrent update conflict, please retry") -} - -func TestUpdateActor_NotFound(t *testing.T) { - ns := namespaceForTest("ns-update-actor-notfound") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.UpdateActor(context.Background(), &ateapi.UpdateActorRequest{ - Actor: &ateapi.Actor{Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "does-not-exist", - // Well-formed guards to pass preconditions validation - Uid: "9a2b1c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d", - Version: 1, - }}, - }) - assertGrpcError(t, err, codes.NotFound, "actor test-atespace/does-not-exist not found") -} - -func TestUpdateActor_FailsIfDeleting(t *testing.T) { - ns := namespaceForTest("ns-update-actor-deleting") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - - ctx := context.Background() - actorRef := resources.ActorRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.persistence.CreateActor(ctx, &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_DELETING}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }); err != nil { - t.Fatalf("CreateActor: %v", err) - } - marked, err := tc.persistence.MarkActorForDeletion(ctx, actorRef, store.DeletePreconditions{}, nil) - if err != nil { - t.Fatalf("MarkActorForDeletion: %v", err) - } - - _, err = tc.client.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: &ateapi.Actor{ - Metadata: marked.GetMetadata(), - ActorTemplate: marked.GetActorTemplate(), - WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"tier": "paid"}}, - }}) - assertGrpcError(t, err, codes.FailedPrecondition, "Actor test-atespace/id1 is being deleted") -} - -func TestUpdateActor_StampsFullSpanIdentity(t *testing.T) { - ns := namespaceForTest("ns-span-update") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - - toUpdate, err := tc.service.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: testActorID}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("seed CreateActor: %v", err) - } - toUpdate.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"env": "prod"}} - - attrs := recordRootSpanAttrs(t, func(ctx context.Context) { - if _, err := tc.service.UpdateActor(ctx, &ateapi.UpdateActorRequest{ - Actor: toUpdate, - }); err != nil { - t.Fatalf("UpdateActor: %v", err) - } - }) - - assertSpanStr(t, attrs, ateattr.AtespaceKey, testAtespace) - assertSpanStr(t, attrs, ateattr.ActorNameKey, testActorID) - assertSpanStr(t, attrs, ateattr.TemplateNameKey, "tmpl1") - assertSpanStr(t, attrs, ateattr.TemplateAtespaceKey, testAtespace) - if v, ok := attrs[ateattr.ActorUIDKey]; !ok || v.Type() != attribute.STRING || v.AsString() == "" { - t.Errorf("%s = %v, want non-empty server-assigned uid", ateattr.ActorUIDKey, v.String()) - } - if v, ok := attrs[ateattr.ActorVersionKey]; !ok || v.Type() != attribute.INT64 || v.AsInt64() != 2 { - t.Errorf("%s = %v, want int64 2 (updated version)", ateattr.ActorVersionKey, v.String()) - } -} - -func TestUpdateActor_FailedLookupStampsRefIdentityOnly(t *testing.T) { - ns := namespaceForTest("ns-span-update-err") - tc := setupTest(t, ns) - defer tc.cleanup() - - attrs := recordRootSpanAttrs(t, func(ctx context.Context) { - if _, err := tc.service.UpdateActor(ctx, &ateapi.UpdateActorRequest{ - Actor: &ateapi.Actor{Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: testActorID, - // Well-formed guards to pass preconditions validation - Uid: "9a2b1c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d", - Version: 1, - }}, - }); apierror.Code(err) != codes.NotFound { - t.Fatalf("UpdateActor(missing) error = %v, want code NotFound", err) - } - }) - - assertSpanStr(t, attrs, ateattr.AtespaceKey, testAtespace) - assertSpanStr(t, attrs, ateattr.ActorNameKey, testActorID) - for _, k := range []attribute.Key{ateattr.ActorUIDKey, ateattr.TemplateNameKey, ateattr.TemplateAtespaceKey, ateattr.ActorVersionKey} { - if _, ok := attrs[k]; ok { - t.Errorf("unexpected %s on failed-update span", k) - } - } -} - -func TestDeleteActor_Success(t *testing.T) { - ns := namespaceForTest("ns-delete-success") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - deleted, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - // DeleteActor returns the deleted resource. - if got := deleted.GetMetadata().GetName(); got != "id1" { - t.Errorf("deleted actor name = %q, want id1", got) - } - if deleted.GetMetadata().GetDeleteTime() == nil { - t.Errorf("the deleted actor carries no delete_time") - } - if got := deleted.GetMetadata().GetAtespace(); got != testAtespace { - t.Errorf("deleted actor atespace = %q, want %q", got, testAtespace) - } - - _, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}, - }) - assertGrpcError(t, err, codes.NotFound, "Actor test-atespace/id1 not found") -} - -func TestDeleteActor_MissingSnapshotBucket(t *testing.T) { - for _, provider := range []struct { - name string - err error - }{ - {name: "S3", err: &types.NoSuchBucket{}}, - {name: "GCS", err: storage.ErrBucketNotExist}, - } { - for _, state := range []ateapi.ActorState{ - ateapi.ActorState_ACTOR_STATE_SUSPENDED, - ateapi.ActorState_ACTOR_STATE_DELETING, - } { - t.Run(provider.name+"/"+state.String(), func(t *testing.T) { - ns := namespaceForTest("ns-delete-missing-bucket") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - ctx := t.Context() - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: testActorID} - actor, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: ref.GetAtespace(), Name: ref.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor: %v", err) - } - uri, err := resources.NewActorSnapshotURI(testStorageLocation, testAtespace, actor.GetMetadata().GetUid(), "snapshot") - if err != nil { - t.Fatal(err) - } - if _, err := tc.persistence.UpdateActor(ctx, resources.ActorRefFromActor(actor), store.PreconditionFrom(actor), func(toUpdate *ateapi.Actor) error { - toUpdate.Status.State = state - snap := newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, "", uri.Name(), uri.String()) - if state != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - // A failed upload leaves only the in-progress URI, even - // when a prior deletion already marked the actor DELETING. - snap.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING - } - toUpdate.Status.Snapshots = []*ateapi.Snapshot{snap} - return nil - }); err != nil { - t.Fatalf("UpdateActor: %v", err) - } - bucket, prefix, err := objectstore.BucketPrefix(uri.OwnerPrefix()) - if err != nil { - t.Fatal(err) - } - var listCalls atomic.Int32 - tc.objectStore.OnList = func(gotBucket, gotPrefix string) error { - listCalls.Add(1) - if gotBucket != bucket || gotPrefix != prefix { - return fmt.Errorf("unexpected cleanup prefix: %s/%s", gotBucket, gotPrefix) - } - return fmt.Errorf("snapshot bucket removed: %w", provider.err) - } - deleted, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("DeleteActor with missing snapshot bucket: %v", err) - } - if deleted.GetMetadata().GetUid() != actor.GetMetadata().GetUid() { - t.Errorf("DeleteActor returned a different actor: %v", deleted) - } - if got := listCalls.Load(); got != 1 { - t.Errorf("snapshot cleanup list calls = %d, want 1", got) - } - _, err = tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - assertGrpcError(t, err, codes.NotFound, "Actor test-atespace/id1 not found") - }) - } - } -} - -// TestDeleteActor_Running deletes a running actor that owns an external -// snapshot and an external volume. The delete terminates the workload, detaches -// and deletes the volume, collects the snapshot, and releases the worker. -func TestDeleteActor_Running(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-delete-running") - plugin := &attachFailVolumePlugin{} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - createTemplateWithVolumes(t, tc, ns, []*ateapi.Volume{ - { - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - }, []*ateapi.VolumeMount{ - {Name: "vol1", MountPath: "/mnt/vol1"}, - }) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Suspend once so the actor owns an external snapshot, then resume it. - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: actorRef, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }); err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("second ResumeActor failed: %v", err) - } - running, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := running.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Fatalf("actor state = %v, want ACTOR_STATE_RUNNING", got) - } - actorUID := running.GetMetadata().GetUid() - snapshotURI := durableSnapshotURI(running.GetStatus()) - if snapshotURI == "" { - t.Fatal("running actor has no external snapshot") - } - assertSnapshotPresent(t, tc, snapshotURI) - - tc.fakeAtelet.Reset() - plugin.mu.Lock() - plugin.detachedNodes = nil - plugin.deleted = nil - plugin.mu.Unlock() - - if _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("DeleteActor of a running actor failed: %v", err) - } - if !tc.fakeAtelet.TerminateCalled { - t.Error("expected atelet Terminate on the running actor's node") - } - if diff := cmp.Diff([]string{"node1"}, plugin.detachedNodes); diff != "" { - t.Errorf("detached nodes mismatch (-want +got):\n%s", diff) - } - if diff := cmp.Diff([]string{"storage-substrate-" + actorUID + "-vol1"}, plugin.deleted); diff != "" { - t.Errorf("deleted volume IDs mismatch (-want +got):\n%s", diff) - } - assertSnapshotCollected(t, tc, snapshotURI) - if worker := storetest.WorkerHostingActor(t, ctx, tc.persistence, actorUID); worker != "" { - t.Errorf("worker %q holds the actor after delete, want none", worker) - } - _, err = tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: actorRef}) - assertGrpcError(t, err, codes.NotFound, "Actor test-atespace/id1 not found") -} - -func TestDeleteActor_Crashed(t *testing.T) { - ns := namespaceForTest("ns-delete-crashed") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Resume onto worker-1 so AssignedNode is set to "node1", then delete - // worker-1 so the actor crashes and loses its WorkerAssignment. - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - deleteWorkerPod(t, tc, ns, "worker-1") - - crashed, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := crashed.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Fatalf("state = %v, want CRASHED", got) - } - if got := crashed.GetStatus().GetAssignedNode(); got != "node1" { - t.Fatalf("assigned node = %q, want node1", got) - } - if got := crashed.GetStatus().GetWorkerAssignment(); got != nil { - t.Fatalf("worker assignment = %v, want nil", got) - } - - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.TerminateCalled = false - tc.fakeAtelet.Lock.Unlock() - - deleted, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{ - Actor: actorRef, - }) - if err != nil { - t.Fatalf("DeleteActor of crashed actor failed: %v", err) - } - if got := deleted.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_DELETING { - t.Errorf("deleted actor state = %v, want %v", got, ateapi.ActorState_ACTOR_STATE_DELETING) - } - if !tc.fakeAtelet.TerminateCalled { - t.Errorf("expected Terminate call to clean up assigned node for crashed actor") - } else if gotUID := tc.fakeAtelet.TerminateRequest.GetWorkerPodUid(); gotUID != "" { - t.Errorf("TerminateRequest.WorkerPodUid = %q, want empty for crashed actor", gotUID) - } - - _, err = tc.client.GetActor(ctx, &ateapi.GetActorRequest{ - Actor: actorRef, - }) - assertGrpcError(t, err, codes.NotFound, "Actor test-atespace/id1 not found") -} - -// A delete that fails partway leaves the actor DELETING. Losing its worker -// before the retry must keep it DELETING, since a CRASHED actor can be -// reverted and resumed, and the retry must still finish the delete. -func TestDeleteActor_RetryAfterWorkerDelete(t *testing.T) { - ns := namespaceForTest("ns-delete-retry-worker-gone") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailTerminate = status.Error(codes.Unavailable, "node unavailable") - tc.fakeAtelet.Lock.Unlock() - if _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: actorRef}); err == nil { - t.Fatal("DeleteActor succeeded, want it to fail on Terminate") - } - - // This would crash a RUNNING Actor. But, should keep a DELETING actor - // unchanged. - deleteWorkerPod(t, tc, ns, "worker-1") - actor, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := actor.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_DELETING { - t.Fatalf("state after worker delete = %v, want DELETING", got) - } - - // Retry deleting the actor after its worker is gone. - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailTerminate = nil - tc.fakeAtelet.TerminateRequest = nil - tc.fakeAtelet.Lock.Unlock() - if _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("retried DeleteActor failed: %v", err) - } - - // The worker is gone, so the retry must not name its pod. - tc.fakeAtelet.Lock.Lock() - terminate := tc.fakeAtelet.TerminateRequest - tc.fakeAtelet.Lock.Unlock() - if terminate == nil { - t.Error("retried DeleteActor did not call atelet Terminate") - } else if gotUID := terminate.GetWorkerPodUid(); gotUID != "" { - t.Errorf("TerminateRequest.WorkerPodUid = %q, want empty", gotUID) - } - _, err = tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: actorRef}) - assertGrpcError(t, err, codes.NotFound, "Actor test-atespace/id1 not found") -} - -func TestDeleteActor_NotFound(t *testing.T) { - ns := namespaceForTest("ns-delete-notfound") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "non-existent"}, - }) - assertGrpcError(t, err, codes.NotFound, "Actor test-atespace/non-existent not found") -} - -// Delete addresses the actor by ref (atespace + id) and does not resolve the -// template/version, so only the ref identity is stamped. -func TestDeleteActor_StampsRefSpanIdentity(t *testing.T) { - ns := namespaceForTest("ns-span-delete") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - if _, err := tc.service.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: testActorID}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }); err != nil { - t.Fatalf("seed CreateActor: %v", err) - } - - attrs := recordRootSpanAttrs(t, func(ctx context.Context) { - if _, err := tc.service.DeleteActor(ctx, &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: testActorID}, - }); err != nil { - t.Fatalf("DeleteActor: %v", err) - } - }) - - assertSpanStr(t, attrs, ateattr.AtespaceKey, testAtespace) - assertSpanStr(t, attrs, ateattr.ActorNameKey, testActorID) -} - -func TestDeleteActor_StateDeleting(t *testing.T) { - ns := namespaceForTest("ns-delete-deleting") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - - deletingActor := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "deleting-actor", - }, - Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_DELETING}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - } - if _, err := tc.persistence.CreateActor(context.Background(), deletingActor); err != nil { - t.Fatalf("CreateActor: %v", err) - } - if _, err := tc.persistence.MarkActorForDeletion(context.Background(), resources.ActorRef{Atespace: testAtespace, Name: "deleting-actor"}, store.DeletePreconditions{}, nil); err != nil { - t.Fatalf("MarkActorForDeletion: %v", err) - } - - if _, err := tc.service.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "deleting-actor"}, - }); err != nil { - t.Fatalf("DeleteActor on ACTOR_STATE_DELETING actor failed: %v", err) - } - - if _, err := tc.persistence.GetActor(context.Background(), resources.ActorRef{Atespace: testAtespace, Name: "deleting-actor"}); err == nil { - t.Errorf("expected actor to be deleted, but it still exists") - } -} - -// TestDeleteActor_Paused deletes an asynchronously suspended actor: it is -// SUSPENDED (holding a node-local snapshot), and the delete terminates it on -// its assigned node so the local snapshot is removed. -func TestDeleteActor_Paused(t *testing.T) { - ns := namespaceForTest("ns-delete-paused") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - if _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}}); err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - paused, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := paused.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Fatalf("actor state after pause = %v, want ACTOR_STATE_SUSPENDED", got) - } - if localSnapshot(paused.GetStatus()) == nil { - t.Fatal("paused actor has no local snapshot") - } - tc.fakeAtelet.Reset() - - if _, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("DeleteActor of a paused actor failed: %v", err) - } - if !tc.fakeAtelet.TerminateCalled { - t.Error("expected atelet Terminate on the paused actor's node to remove its local snapshot") - } else if got, want := tc.fakeAtelet.TerminateRequest.GetActorUid(), paused.GetMetadata().GetUid(); got != want { - t.Errorf("Terminate actor_uid = %q, want %q", got, want) - } - if _, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: actorRef}); status.Code(err) != codes.NotFound { - t.Errorf("GetActor after DeleteActor err = %v, want NotFound", err) - } -} - -type failingVolumePlugin struct { - volume.VolumePluginControlPlane - deletedIDs []string -} - -func (f *failingVolumePlugin) DeleteVolume(ctx context.Context, volumeID string) error { - f.deletedIDs = append(f.deletedIDs, volumeID) - return fmt.Errorf("simulated delete error for %s", volumeID) -} - -func TestDeleteActor_MultipleVolumeDeletionFailures(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-delete-multivol-fail") - plugin := &failingVolumePlugin{} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - createTemplate(t, tc, ns) - - actor := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "multi-vol-actor", - }, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{ - State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ - {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "substrate.io/mock"}, - {Name: "vol2", StorageVolumeId: "storage-vol-2", VolumeType: "substrate.io/mock"}, - }}, - }, - } - if _, err := tc.persistence.CreateActor(context.Background(), actor); err != nil { - t.Fatalf("CreateActor: %v", err) - } - - _, err := tc.service.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "multi-vol-actor"}, - }) - if err == nil { - t.Fatalf("expected DeleteActor to fail when volume deletion fails, but it succeeded") - } - - wantDeleted := []string{"storage-vol-1", "storage-vol-2"} - if diff := cmp.Diff(wantDeleted, plugin.deletedIDs); diff != "" { - t.Errorf("deletedIDs mismatch (-want +got):\n%s", diff) - } - - errMsg := err.Error() - if !strings.Contains(errMsg, "storage-vol-1") || !strings.Contains(errMsg, "storage-vol-2") { - t.Errorf("expected error message to contain both volume failure details, got: %v", errMsg) - } -} - -// retryDeleteVolumePlugin simulates a CSI control-plane plugin that fails DeleteVolume -// until failDelete is cleared, recording all deleted volume IDs for assertions. -type retryDeleteVolumePlugin struct { - volume.VolumePluginControlPlane - mu sync.Mutex - failDelete bool - deletedIDs []string -} - -func (r *retryDeleteVolumePlugin) DeleteVolume(ctx context.Context, volumeID string) error { - r.mu.Lock() - defer r.mu.Unlock() - r.deletedIDs = append(r.deletedIDs, volumeID) - if r.failDelete { - return fmt.Errorf("simulated temporary delete error for %s", volumeID) - } - return nil -} - -// TestDeleteActor_VolumeDeletionFailure_RetrySuccess tests that when volume deletion fails -// during DeleteActor, the actor transitions to ACTOR_STATE_DELETING keeping its volumes, -// and a subsequent retry of DeleteActor cleanly finalizes deletion. -// -// Workflow: -// 1. Creates a suspended actor with a provisioned external volume. -// 2. Calls DeleteActor, which fails because the CSI plugin returns an error on DeleteVolume. -// 3. Verifies that the actor is persisted in ACTOR_STATE_DELETING and still records the volume. -// 4. Clears the plugin error to simulate backend recovery. -// 5. Retries DeleteActor, which re-attempts volume deletion and cleans up the actor from the store. -// 6. Confirms GetActor returns NotFound. -func TestDeleteActor_VolumeDeletionFailure_RetrySuccess(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-delete-vol-retry") - plugin := &retryDeleteVolumePlugin{failDelete: true} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - createTemplate(t, tc, ns) - - // 1. Create suspended actor with a provisioned external volume. - actor := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "delete-retry-actor", - }, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{ - State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ - {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "substrate.io/mock"}, - }}, - }, - } - if _, err := tc.persistence.CreateActor(context.Background(), actor); err != nil { - t.Fatalf("CreateActor: %v", err) - } - - // 2. First DeleteActor call should fail due to DeleteVolume error. - _, err := tc.service.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "delete-retry-actor"}, - }) - if err == nil { - t.Fatalf("expected DeleteActor to fail, but got nil") - } - - // 3. Verify actor is persisted in ACTOR_STATE_DELETING with its volume still recorded. - getResp, err := tc.service.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "delete-retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after failed delete: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_DELETING { - t.Errorf("actor state = %v, want ACTOR_STATE_DELETING", getResp.GetStatus().GetState()) - } - if len(getResp.GetStatus().GetExternalVolumes().GetVolumes()) != 1 { - t.Errorf("actor volumes = %v, want the volume still recorded", getResp.GetStatus().GetExternalVolumes().GetVolumes()) - } - - // 4. Recover the CSI plugin to simulate backend recovery. - plugin.mu.Lock() - plugin.failDelete = false - plugin.mu.Unlock() - - // 5. Second DeleteActor call (retry) re-attempts deletion and should succeed. - _, err = tc.service.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "delete-retry-actor"}, - }) - if err != nil { - t.Fatalf("expected retry DeleteActor to succeed, got: %v", err) - } - - // 6. Verify actor is removed from store. - _, err = tc.service.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "delete-retry-actor"}, - }) - if apierror.Code(err) != codes.NotFound { - t.Errorf("GetActor after successful delete retry = %v, want NotFound", err) - } -} - -func TestCreateActor_AtespaceNotFound(t *testing.T) { - ns := namespaceForTest("ns-create-actor-no-atespace") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - - // The template exists, but "missing-as" was never created. The template - // check fires first, so reaching this error proves the atespace check ran. - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: "missing-as", Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - assertGrpcError(t, err, codes.FailedPrecondition, "Atespace missing-as not found") -} - -func TestValidation_Actor(t *testing.T) { - ns := namespaceForTest("ns-validation-actor") - tc := setupTest(t, ns) - defer tc.cleanup() - - t.Run("CreateActor", func(t *testing.T) { - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - }) - - t.Run("GetActor", func(t *testing.T) { - _, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - }) - - t.Run("ResumeActor", func(t *testing.T) { - _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - }) - - t.Run("SuspendActor", func(t *testing.T) { - _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - }) - - t.Run("UpdateActor", func(t *testing.T) { - _, err := tc.client.UpdateActor(context.Background(), &ateapi.UpdateActorRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - }) - - t.Run("DeleteActor", func(t *testing.T) { - _, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - }) - - t.Run("ListActors", func(t *testing.T) { - _, err := tc.client.ListActors(context.Background(), &ateapi.ListActorsRequest{Options: &ateapi.ListOptions{PageSize: -1}}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "page_size: Invalid value") - }) - - t.Run("ListActors invalid token", func(t *testing.T) { - _, err := tc.client.ListActors(context.Background(), &ateapi.ListActorsRequest{Options: &ateapi.ListOptions{PageToken: "%%%"}}) - assertGrpcError(t, err, codes.InvalidArgument, "invalid page_token") - }) - - t.Run("ListTags invalid token", func(t *testing.T) { - _, err := tc.client.ListTags(context.Background(), &ateapi.ListTagsRequest{Options: &ateapi.ListOptions{PageToken: "%%%"}}) - assertGrpcError(t, err, codes.InvalidArgument, "invalid page_token") - }) -} - -func TestActorLifecycle_WithExternalVolumes(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-lifecycle-ext-vols") - tc := setupPreviewTest(t, ns) - defer tc.cleanup() - - volumes := []*ateapi.Volume{ - { - Name: "data-vol", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "fast", - CapacityBytes: 20 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - { - Name: "data-vol", - MountPath: "/mnt/data", - }, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // 1. CreateActor - createResp, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "actor-vol-lc"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if createResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Fatalf("expected initial state ACTOR_STATE_SUSPENDED, got %v", createResp.GetStatus().GetState()) - } - if len(createResp.GetStatus().GetExternalVolumes().GetVolumes()) != 1 || createResp.GetStatus().GetExternalVolumes().GetVolumes()[0].GetStorageVolumeId() != "" { - t.Fatalf("expected 1 unprovisioned volume after CreateActor, got %v", createResp.GetStatus().GetExternalVolumes().GetVolumes()) - } - - // 2. ResumeActor - resumeResp, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-vol-lc"}, - }) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - if resumeResp.GetActor().GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Fatalf("expected state ACTOR_STATE_RUNNING after resume, got %v", resumeResp.GetActor().GetStatus().GetState()) - } - if len(resumeResp.GetActor().GetStatus().GetExternalVolumes().GetVolumes()) != 1 { - t.Fatalf("expected 1 volume after ResumeActor, got %v", resumeResp.GetActor().GetStatus().GetExternalVolumes().GetVolumes()) - } - if resumeResp.GetActor().GetStatus().GetExternalVolumes().GetVolumes()[0].GetStorageVolumeId() == "" { - t.Fatalf("expected non-empty storageVolumeId after ResumeActor") - } - - // 3. Async SuspendActor - pauseResp, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-vol-lc"}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - if pauseResp.GetActor().GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Fatalf("expected state ACTOR_STATE_SUSPENDED after pause, got %v", pauseResp.GetActor().GetStatus().GetState()) - } - if localSnapshot(pauseResp.GetActor().GetStatus()) == nil { - t.Fatal("expected a local snapshot on the paused actor") - } - waitForWorkerAvailable(t, tc, workerName) - - // 4. ResumeActor from node-local snapshot - waitForWorkerAvailable(t, tc, workerName) - resumeResp2, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-vol-lc"}, - }) - if err != nil { - t.Fatalf("ResumeActor from paused failed: %v", err) - } - if resumeResp2.GetActor().GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Fatalf("expected state ACTOR_STATE_RUNNING after second resume, got %v", resumeResp2.GetActor().GetStatus().GetState()) - } - - // 5. Sync SuspendActor - suspendResp, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-vol-lc"}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - if suspendResp.GetActor().GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Fatalf("expected state ACTOR_STATE_SUSPENDED after suspend, got %v", suspendResp.GetActor().GetStatus().GetState()) - } - - // 6. DeleteActor - deleteResp, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-vol-lc"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - if deleteResp.GetMetadata().GetName() != "actor-vol-lc" { - t.Errorf("deleted actor name = %q, want %q", deleteResp.GetMetadata().GetName(), "actor-vol-lc") - } - - // Confirm GetActor returns NotFound after deletion - _, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-vol-lc"}, - }) - if status.Code(err) != codes.NotFound { - t.Errorf("GetActor after delete err = %v, want NotFound", err) - } -} - -type partialFailVolumePlugin struct { - volume.VolumePluginControlPlane - deleted []string -} - -func (f *partialFailVolumePlugin) CreateVolume(ctx context.Context, req volume.CreateVolumeRequest) (volume.CreateVolumeResponse, error) { - if strings.HasSuffix(req.Name, "fail-vol2") { - return volume.CreateVolumeResponse{}, fmt.Errorf("simulated volume creation failure") - } - return volume.CreateVolumeResponse{VolumeID: "storage-" + req.Name, VolumeContext: req.Parameters}, nil -} - -func (f *partialFailVolumePlugin) AttachVolume(ctx context.Context, req volume.AttachVolumeRequest) (volume.AttachVolumeResponse, error) { - return volume.AttachVolumeResponse{}, nil -} - -func (f *partialFailVolumePlugin) DetachVolume(ctx context.Context, volumeID, node string) error { - return nil -} - -func (f *partialFailVolumePlugin) DeleteVolume(ctx context.Context, volumeID string) error { - f.deleted = append(f.deleted, volumeID) - return nil -} - -// TestResumeActor_VolumeCreationFailure tests that when volume provisioning fails during ResumeActor, -// successfully created volumes are saved, the actor remains in ACTOR_STATE_SUSPENDED, -// and that calling DeleteActor on the suspended actor cleans up all partially created volumes. -func TestResumeActor_VolumeCreationFailure(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-resume-vol-fail") - plugin := &partialFailVolumePlugin{} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - volumes := []*ateapi.Volume{ - { - Name: "succ-vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - { - Name: "fail-vol2", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - {Name: "succ-vol1", MountPath: "/mnt/vol1"}, - {Name: "fail-vol2", MountPath: "/mnt/vol2"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - - // Call CreateActor RPC directly - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "fail-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("expected CreateActor to succeed, got: %v", err) - } - - // Call ResumeActor RPC, which should trigger volume provisioning and fail on fail-vol2 - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "fail-actor"}, - }) - if err == nil { - t.Fatalf("expected ResumeActor to fail due to volume creation error, but it succeeded") - } - - // Verify GetActor returns the actor in ACTOR_STATE_SUSPENDED state - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "fail-actor"}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("actor state = %v, want %v", getResp.GetStatus().GetState(), ateapi.ActorState_ACTOR_STATE_SUSPENDED) - } - - actorUID := getResp.GetMetadata().GetUid() - if actorUID == "" { - t.Fatalf("expected non-empty UID on actor") - } - - // Verify that succ-vol1 was given a storageVolumeId, and fail-vol2 still has none - if len(getResp.GetStatus().GetExternalVolumes().GetVolumes()) != 2 { - t.Fatalf("expected 2 volumes on actor, got %d", len(getResp.GetStatus().GetExternalVolumes().GetVolumes())) - } - volsByName := make(map[string]*ateapi.ExternalVolumeStatus) - for _, v := range getResp.GetStatus().GetExternalVolumes().GetVolumes() { - volsByName[v.GetName()] = v - } - if v1, ok := volsByName["succ-vol1"]; !ok || v1.GetStorageVolumeId() == "" { - t.Errorf("succ-vol1 unexpected state: %v", v1) - } - if v2, ok := volsByName["fail-vol2"]; !ok || v2.GetStorageVolumeId() != "" { - t.Errorf("fail-vol2 unexpected state: %v", v2) - } - - // Call DeleteActor on the actor in ACTOR_STATE_SUSPENDED - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "fail-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - - // Verify both volumes were deleted (succ-vol1 via storageID, fail-vol2 via fallback actorVolumeID) - wantDeleted := []string{ - "storage-substrate-" + actorUID + "-succ-vol1", - "substrate-" + actorUID + "-fail-vol2", - } - if diff := cmp.Diff(wantDeleted, plugin.deleted); diff != "" { - t.Errorf("deleted volume IDs mismatch (-want +got):\n%s", diff) - } - - // Confirm GetActor returns NotFound after deletion - _, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "fail-actor"}, - }) - if status.Code(err) != codes.NotFound { - t.Errorf("GetActor after DeleteActor err = %v, want NotFound", err) - } -} - -type retrySuccessVolumePlugin struct { - volume.VolumePluginControlPlane - mu sync.Mutex - attempts int - deleted []string -} - -func (r *retrySuccessVolumePlugin) CreateVolume(ctx context.Context, req volume.CreateVolumeRequest) (volume.CreateVolumeResponse, error) { - r.mu.Lock() - defer r.mu.Unlock() - if strings.HasSuffix(req.Name, "retry-vol2") { - r.attempts++ - if r.attempts == 1 { - return volume.CreateVolumeResponse{}, fmt.Errorf("simulated temporary volume creation failure") - } - } - return volume.CreateVolumeResponse{VolumeID: "storage-" + req.Name, VolumeContext: req.Parameters}, nil -} - -func (r *retrySuccessVolumePlugin) AttachVolume(ctx context.Context, req volume.AttachVolumeRequest) (volume.AttachVolumeResponse, error) { - return volume.AttachVolumeResponse{}, nil -} - -func (r *retrySuccessVolumePlugin) DetachVolume(ctx context.Context, volumeID, node string) error { - return nil -} - -func (r *retrySuccessVolumePlugin) DeleteVolume(ctx context.Context, volumeID string) error { - r.mu.Lock() - defer r.mu.Unlock() - r.deleted = append(r.deleted, volumeID) - return nil -} - -// TestResumeActor_VolumeCreationRetrySuccess tests that when volume provisioning fails on the first ResumeActor call, -// a subsequent call to ResumeActor retries provisioning only the pending volumes and succeeds. -func TestResumeActor_VolumeCreationRetrySuccess(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-resume-vol-retry") - plugin := &retrySuccessVolumePlugin{} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - volumes := []*ateapi.Volume{ - { - Name: "succ-vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - { - Name: "retry-vol2", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - retryMounts := []*ateapi.VolumeMount{ - {Name: "succ-vol1", MountPath: "/mnt/vol1"}, - {Name: "retry-vol2", MountPath: "/mnt/vol2"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, retryMounts) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // Call CreateActor RPC directly - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "retry-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("expected CreateActor to succeed, got: %v", err) - } - - // First call to ResumeActor RPC, which should fail on retry-vol2 (attempt 1) - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "retry-actor"}, - }) - if err == nil { - t.Fatalf("expected first ResumeActor to fail due to temporary volume creation error, but it succeeded") - } - - // Verify GetActor returns the actor in ACTOR_STATE_SUSPENDED state with succ-vol1 created and retry-vol2 pending - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after first resume failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("actor state after first resume = %v, want %v", getResp.GetStatus().GetState(), ateapi.ActorState_ACTOR_STATE_SUSPENDED) - } - - volsByName := make(map[string]*ateapi.ExternalVolumeStatus) - for _, v := range getResp.GetStatus().GetExternalVolumes().GetVolumes() { - volsByName[v.GetName()] = v - } - if v1, ok := volsByName["succ-vol1"]; !ok || v1.GetStorageVolumeId() == "" { - t.Errorf("succ-vol1 unexpected state after first resume: %v", v1) - } - if v2, ok := volsByName["retry-vol2"]; !ok || v2.GetStorageVolumeId() != "" { - t.Errorf("retry-vol2 unexpected state after first resume: %v", v2) - } - - // Second call to ResumeActor RPC, which should succeed on retry-vol2 (attempt 2) - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "retry-actor"}, - }) - if err != nil { - t.Fatalf("expected second ResumeActor to succeed, got: %v", err) - } - - // Verify GetActor returns the actor in ACTOR_STATE_RUNNING state with both volumes CREATED - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after second resume failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("actor state after second resume = %v, want %v", getResp.GetStatus().GetState(), ateapi.ActorState_ACTOR_STATE_RUNNING) - } - for _, v := range getResp.GetStatus().GetExternalVolumes().GetVolumes() { - if v.GetStorageVolumeId() == "" { - t.Errorf("volume %s unexpected state after second resume: %v", v.GetName(), v) - } - } - - // Clean up by suspending and deleting the actor - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "retry-actor"}, - }) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "retry-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } -} - -type attachFailVolumePlugin struct { - volume.VolumePluginControlPlane - mu sync.Mutex - attachAttempts int - failUntil int - attachedNodes []string - detachedNodes []string - deleted []string -} - -func (a *attachFailVolumePlugin) CreateVolume(ctx context.Context, req volume.CreateVolumeRequest) (volume.CreateVolumeResponse, error) { - return volume.CreateVolumeResponse{VolumeID: "storage-" + req.Name, VolumeContext: req.Parameters}, nil -} - -func (a *attachFailVolumePlugin) AttachVolume(ctx context.Context, req volume.AttachVolumeRequest) (volume.AttachVolumeResponse, error) { - a.mu.Lock() - defer a.mu.Unlock() - a.attachAttempts++ - if a.attachAttempts <= a.failUntil { - return volume.AttachVolumeResponse{}, fmt.Errorf("simulated volume attach failure on attempt %d", a.attachAttempts) - } - a.attachedNodes = append(a.attachedNodes, req.Node) - return volume.AttachVolumeResponse{ - PublishContext: map[string]string{ - "mock.substrate.io/attached-node": req.Node, - "mock.substrate.io/device-path": "/dev/mock-" + req.VolumeID, - }, - }, nil -} - -func (a *attachFailVolumePlugin) DetachVolume(ctx context.Context, volumeID, node string) error { - a.mu.Lock() - defer a.mu.Unlock() - a.detachedNodes = append(a.detachedNodes, node) - return nil -} - -func (a *attachFailVolumePlugin) DeleteVolume(ctx context.Context, volumeID string) error { - a.mu.Lock() - defer a.mu.Unlock() - a.deleted = append(a.deleted, volumeID) - return nil -} - -// TestResumeActor_VolumeAttachFailureAndRetry tests that when volume attachment to a worker node -// fails during ResumeActor, the actor is left in ACTOR_STATE_RESUMING with its worker assignment -// and provisioned volumes intact, and that a subsequent call to ResumeActor re-attempts volume attachment -// and successfully transitions the actor to ACTOR_STATE_RUNNING. -func TestResumeActor_VolumeAttachFailureAndRetry(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-resume-vol-attach-retry") - plugin := &attachFailVolumePlugin{failUntil: 1} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - volumes := []*ateapi.Volume{ - { - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - {Name: "vol1", MountPath: "/mnt/vol1"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // Call CreateActor RPC directly - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "attach-retry-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("expected CreateActor to succeed, got: %v", err) - } - - // First call to ResumeActor: provisioning succeeds, worker is assigned, but AttachVolume fails (attempt 1) - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-retry-actor"}, - }) - if err == nil { - t.Fatalf("expected first ResumeActor to fail due to attach failure, but it succeeded") - } - if !strings.Contains(err.Error(), "simulated volume attach failure on attempt 1") { - t.Errorf("expected error containing simulated volume attach failure, got: %v", err) - } - - // Verify actor status after failed attach: in ACTOR_STATE_RESUMING, worker assigned, volume CREATED - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after failed attach: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RESUMING { - t.Errorf("actor state after failed attach = %v, want ACTOR_STATE_RESUMING", getResp.GetStatus().GetState()) - } - if getResp.GetStatus().GetWorkerAssignment() == nil || getResp.GetStatus().GetWorkerAssignment().GetWorkerPod() != "worker-1" { - t.Errorf("worker assignment = %v, want worker-1", getResp.GetStatus().GetWorkerAssignment()) - } - if len(getResp.GetStatus().GetExternalVolumes().GetVolumes()) != 1 { - t.Fatalf("expected 1 volume on actor, got %d", len(getResp.GetStatus().GetExternalVolumes().GetVolumes())) - } - vol := getResp.GetStatus().GetExternalVolumes().GetVolumes()[0] - if vol.GetStorageVolumeId() == "" { - t.Errorf("vol1 unexpected state after failed attach: %v", vol) - } - - // Second call to ResumeActor: reuses assigned worker, re-attempts volume attach, succeeds (attempt 2), transitions to RUNNING - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-retry-actor"}, - }) - if err != nil { - t.Fatalf("expected second ResumeActor to succeed, got: %v", err) - } - - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after successful retry: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("actor state after retry = %v, want ACTOR_STATE_RUNNING", getResp.GetStatus().GetState()) - } - - // Clean up by suspending and deleting the actor - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-retry-actor"}, - }) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-retry-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } -} - -// TestResumeActor_VolumeAttachFailure_DeleteActor tests that when volume attachment fails during ResumeActor, -// leaving the actor in ACTOR_STATE_RESUMING, DeleteActor succeeds, cleaning up worker assignment and volumes. -func TestResumeActor_VolumeAttachFailure_DeleteActor(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-resume-vol-attach-del") - plugin := &attachFailVolumePlugin{failUntil: 100} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - volumes := []*ateapi.Volume{ - { - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - {Name: "vol1", MountPath: "/mnt/vol1"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // Call CreateActor RPC - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "attach-fail-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("expected CreateActor to succeed, got: %v", err) - } - - // Call ResumeActor RPC, which assigns worker-1 and fails on AttachVolume - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-fail-actor"}, - }) - if err == nil { - t.Fatalf("expected ResumeActor to fail due to attach failure, but it succeeded") - } - - // Verify actor is in ACTOR_STATE_RESUMING - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-fail-actor"}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RESUMING { - t.Fatalf("actor state = %v, want ACTOR_STATE_RESUMING", getResp.GetStatus().GetState()) - } - actorUID := getResp.GetMetadata().GetUid() - - // DeleteActor on the RESUMING actor should succeed and cleanly tear down - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-fail-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - - // Verify volume was detached and deleted - expectedVolumeID := "storage-substrate-" + actorUID + "-vol1" - if diff := cmp.Diff([]string{"node1"}, plugin.detachedNodes); diff != "" { - t.Errorf("detached nodes mismatch (-want +got):\n%s", diff) - } - if diff := cmp.Diff([]string{expectedVolumeID}, plugin.deleted); diff != "" { - t.Errorf("deleted volume IDs mismatch (-want +got):\n%s", diff) - } - - // Confirm GetActor returns NotFound after deletion - _, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "attach-fail-actor"}, - }) - if status.Code(err) != codes.NotFound { - t.Errorf("GetActor after DeleteActor err = %v, want NotFound", err) - } -} - -// multiVolAttachPlugin simulates a CSI control-plane plugin that selectively fails -// volume attachment for a specified volume up to a configured number of attempts. -type multiVolAttachPlugin struct { - volume.VolumePluginControlPlane - mu sync.Mutex - attachAttempts map[string]int - failVol string - failUntil int - attachedNodes map[string][]string - detachedNodes map[string][]string - deleted []string -} - -func newMultiVolAttachPlugin(failVol string, failUntil int) *multiVolAttachPlugin { - return &multiVolAttachPlugin{ - attachAttempts: make(map[string]int), - failVol: failVol, - failUntil: failUntil, - attachedNodes: make(map[string][]string), - detachedNodes: make(map[string][]string), - } -} - -func (m *multiVolAttachPlugin) CreateVolume(ctx context.Context, req volume.CreateVolumeRequest) (volume.CreateVolumeResponse, error) { - return volume.CreateVolumeResponse{VolumeID: "storage-" + req.Name, VolumeContext: req.Parameters}, nil -} - -func (m *multiVolAttachPlugin) AttachVolume(ctx context.Context, req volume.AttachVolumeRequest) (volume.AttachVolumeResponse, error) { - m.mu.Lock() - defer m.mu.Unlock() - m.attachAttempts[req.VolumeID]++ - if strings.Contains(req.VolumeID, m.failVol) && m.attachAttempts[req.VolumeID] <= m.failUntil { - return volume.AttachVolumeResponse{}, fmt.Errorf("simulated volume attach failure for %s on attempt %d", req.VolumeID, m.attachAttempts[req.VolumeID]) - } - m.attachedNodes[req.VolumeID] = append(m.attachedNodes[req.VolumeID], req.Node) - return volume.AttachVolumeResponse{}, nil -} - -func (m *multiVolAttachPlugin) DetachVolume(ctx context.Context, volumeID, node string) error { - m.mu.Lock() - defer m.mu.Unlock() - m.detachedNodes[volumeID] = append(m.detachedNodes[volumeID], node) - return nil -} - -func (m *multiVolAttachPlugin) DeleteVolume(ctx context.Context, volumeID string) error { - m.mu.Lock() - defer m.mu.Unlock() - m.deleted = append(m.deleted, volumeID) - return nil -} - -// TestResumeActor_MultiVolumePartialAttachFailure_Retry tests scenario B: -// when an actor has multiple external volumes and one fails to attach during ResumeActor: -// 1. ResumeActor fails, leaving the actor in ACTOR_STATE_RESUMING. -// 2. The successfully attached volume remains attached; the failing volume is not attached. -// 3. The worker assignment remains held by the actor. -// 4. A subsequent retry of ResumeActor re-attempts attachment, succeeds, and transitions the actor to ACTOR_STATE_RUNNING. -// -// Workflow: -// 1. Creates a template with two external volumes (vol1, vol2) and creates a mock worker pod on node1. -// 2. Creates an actor referencing the template. -// 3. Calls ResumeActor; plugin is configured to fail vol2 on attempt 1. -// 4. Verifies ResumeActor returns an error, actor is in ACTOR_STATE_RESUMING, worker assignment is held, and vol1 is attached while vol2 is not. -// 5. Calls ResumeActor a second time (retry). -// 6. Verifies ResumeActor succeeds and actor transitions to ACTOR_STATE_RUNNING. -// 7. Cleans up by suspending and deleting the actor. -func TestResumeActor_MultiVolumePartialAttachFailure_Retry(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-resume-multivol-attach-retry") - plugin := newMultiVolAttachPlugin("vol2", 1) - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - // 1. Create a template with two external volumes and a worker pod. - volumes := []*ateapi.Volume{ - { - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - { - Name: "vol2", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - {Name: "vol1", MountPath: "/mnt/vol1"}, - {Name: "vol2", MountPath: "/mnt/vol2"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // 2. Create the actor. - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "multi-attach-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // 3. Attempt 1: vol1 attaches, vol2 fails attach. - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "multi-attach-actor"}, - }) - if err == nil { - t.Fatalf("expected ResumeActor to fail due to partial attach failure, got nil") - } - if !strings.Contains(err.Error(), "simulated volume attach failure for") { - t.Errorf("expected error containing simulated attach failure, got: %v", err) - } - - // 4. Verify actor state is ACTOR_STATE_RESUMING, worker assignment is held, and partial attachment state. - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "multi-attach-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after failed attach: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RESUMING { - t.Errorf("actor state = %v, want ACTOR_STATE_RESUMING", getResp.GetStatus().GetState()) - } - if getResp.GetStatus().GetWorkerAssignment() == nil || getResp.GetStatus().GetWorkerAssignment().GetWorkerPod() != "worker-1" { - t.Errorf("worker assignment = %v, want worker-1", getResp.GetStatus().GetWorkerAssignment()) - } - - // Verify vol1 was attached, vol2 was not attached on attempt 1. - actorUID := getResp.GetMetadata().GetUid() - vol1ID := "storage-substrate-" + actorUID + "-vol1" - vol2ID := "storage-substrate-" + actorUID + "-vol2" - plugin.mu.Lock() - if len(plugin.attachedNodes[vol1ID]) != 1 || plugin.attachedNodes[vol1ID][0] != "node1" { - t.Errorf("vol1 attached nodes = %v, want [node1]", plugin.attachedNodes[vol1ID]) - } - if len(plugin.attachedNodes[vol2ID]) != 0 { - t.Errorf("vol2 attached nodes = %v, want empty on attempt 1", plugin.attachedNodes[vol2ID]) - } - plugin.mu.Unlock() - - // 5. Attempt 2 (retry): re-attempts attach, both succeed, actor reaches RUNNING. - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "multi-attach-actor"}, - }) - if err != nil { - t.Fatalf("expected second ResumeActor to succeed, got: %v", err) - } - - // 6. Verify actor state is RUNNING. - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "multi-attach-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after second resume: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("actor state after retry = %v, want ACTOR_STATE_RUNNING", getResp.GetStatus().GetState()) - } - - // 7. Clean up by suspending and deleting. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "multi-attach-actor"}, - }) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "multi-attach-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } -} - -// detachFailVolumePlugin simulates a CSI control-plane plugin that fails DetachVolume -// for a configured number of attempts, tracking attached and detached nodes. -type detachFailVolumePlugin struct { - volume.VolumePluginControlPlane - mu sync.Mutex - detachAttempts int - failUntil int - attachedNodes []string - detachedNodes []string - deleted []string -} - -func (d *detachFailVolumePlugin) CreateVolume(ctx context.Context, req volume.CreateVolumeRequest) (volume.CreateVolumeResponse, error) { - return volume.CreateVolumeResponse{VolumeID: "storage-" + req.Name, VolumeContext: req.Parameters}, nil -} - -func (d *detachFailVolumePlugin) AttachVolume(ctx context.Context, req volume.AttachVolumeRequest) (volume.AttachVolumeResponse, error) { - d.mu.Lock() - defer d.mu.Unlock() - d.attachedNodes = append(d.attachedNodes, req.Node) - return volume.AttachVolumeResponse{}, nil -} - -func (d *detachFailVolumePlugin) DetachVolume(ctx context.Context, volumeID, node string) error { - d.mu.Lock() - defer d.mu.Unlock() - d.detachAttempts++ - if d.detachAttempts <= d.failUntil { - return fmt.Errorf("simulated volume detach failure on attempt %d", d.detachAttempts) - } - d.detachedNodes = append(d.detachedNodes, node) - return nil -} - -func (d *detachFailVolumePlugin) DeleteVolume(ctx context.Context, volumeID string) error { - d.mu.Lock() - defer d.mu.Unlock() - d.deleted = append(d.deleted, volumeID) - return nil -} - -// TestSuspendActor_VolumeDetachFailure_RetrySuccess tests scenario C: -// when volume detachment fails during SuspendActor: -// 1. SuspendActor fails, leaving the actor in ACTOR_STATE_SUSPENDING. -// 2. The worker assignment is preserved (worker is not released). -// 3. A subsequent retry of SuspendActor succeeds, detaches the volume, releases the worker, and transitions the actor to ACTOR_STATE_SUSPENDED. -// -// Workflow: -// 1. Creates a template with an external volume and creates a mock worker pod on node1. -// 2. Creates and resumes an actor to ACTOR_STATE_RUNNING (attaching the volume). -// 3. Calls SuspendActor; plugin is configured to fail DetachVolume on attempt 1. -// 4. Verifies SuspendActor returns an error, actor state is ACTOR_STATE_SUSPENDING, and worker assignment is preserved. -// 5. Calls SuspendActor a second time (retry); detachment succeeds. -// 6. Verifies actor transitions to ACTOR_STATE_SUSPENDED and worker assignment is cleared. -// 7. Cleans up by deleting the actor. -func TestSuspendActor_VolumeDetachFailure_RetrySuccess(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-suspend-vol-detach-retry") - plugin := &detachFailVolumePlugin{failUntil: 1} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - // 1. Create template with external volume and a mock worker pod. - volumes := []*ateapi.Volume{ - { - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - {Name: "vol1", MountPath: "/mnt/vol1"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // 2. Create and resume actor to ACTOR_STATE_RUNNING. - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "suspend-detach-retry-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-detach-retry-actor"}, - }) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - // 3. Attempt 1: SuspendActor fails on DetachVolume. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-detach-retry-actor"}, - }) - if err == nil { - t.Fatalf("expected first SuspendActor to fail, got nil") - } - if !strings.Contains(err.Error(), "simulated volume detach failure on attempt 1") { - t.Errorf("expected error containing simulated detach failure, got: %v", err) - } - - // 4. Verify actor state after failed detach: left in ACTOR_STATE_SUSPENDING, worker assignment preserved. - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-detach-retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after failed detach: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDING { - t.Errorf("actor state = %v, want ACTOR_STATE_SUSPENDING", getResp.GetStatus().GetState()) - } - if getResp.GetStatus().GetWorkerAssignment() == nil || getResp.GetStatus().GetWorkerAssignment().GetWorkerPod() != "worker-1" { - t.Errorf("worker assignment = %v, want worker-1", getResp.GetStatus().GetWorkerAssignment()) - } - - // 5. Attempt 2 (retry): SuspendActor retry succeeds, volume is detached. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-detach-retry-actor"}, - }) - if err != nil { - t.Fatalf("expected retry SuspendActor to succeed, got: %v", err) - } - - // 6. Verify actor state transitions to ACTOR_STATE_SUSPENDED and worker is released. - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-detach-retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after successful suspend retry: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("actor state = %v, want ACTOR_STATE_SUSPENDED", getResp.GetStatus().GetState()) - } - if getResp.GetStatus().GetWorkerAssignment() != nil && getResp.GetStatus().GetWorkerAssignment().GetWorkerPod() != "" { - t.Errorf("worker assignment = %v, want worker released", getResp.GetStatus().GetWorkerAssignment()) - } - - // 7. Clean up by deleting actor. - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-detach-retry-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } -} - -// TestSuspendActor_VolumeDetachFailure_DeleteActor tests scenario C: -// when volume detachment fails during SuspendActor and leaves the actor in ACTOR_STATE_SUSPENDING, -// DeleteActor succeeds, tearing down the actor and its volumes. -// -// Workflow: -// 1. Creates a template with an external volume and creates a mock worker pod on node1. -// 2. Creates and resumes an actor to ACTOR_STATE_RUNNING. -// 3. Calls SuspendActor, which fails due to simulated volume detachment failure, leaving the actor in ACTOR_STATE_SUSPENDING. -// 4. Resets the plugin to allow detachment, then calls DeleteActor. -// 5. Verifies the actor is deleted and GetActor returns NotFound. -func TestSuspendActor_VolumeDetachFailure_DeleteActor(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-suspend-vol-detach-del") - plugin := &detachFailVolumePlugin{failUntil: 100} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - // 1. Create template with external volume and a mock worker pod. - volumes := []*ateapi.Volume{ - { - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - {Name: "vol1", MountPath: "/mnt/vol1"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // 2. Create and resume actor to ACTOR_STATE_RUNNING. - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "suspend-del-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-del-actor"}, - }); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - // 3. Attempt SuspendActor; fails on volume detachment, leaving actor in ACTOR_STATE_SUSPENDING. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-del-actor"}, - }) - if err == nil { - t.Fatalf("expected SuspendActor to fail, got nil") - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-del-actor"}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDING { - t.Fatalf("actor state = %v, want ACTOR_STATE_SUSPENDING", getResp.GetStatus().GetState()) - } - - // 4. Allow detach to succeed and call DeleteActor. - plugin.mu.Lock() - plugin.failUntil = 0 - plugin.mu.Unlock() - - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-del-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - - // 5. Verify actor is NotFound. - _, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "suspend-del-actor"}, - }) - if status.Code(err) != codes.NotFound { - t.Errorf("GetActor after delete err = %v, want NotFound", err) - } -} - -// TestSuspendActorAsync_VolumeLifecycle_DetachResumeAndMigrate tests external volume -// attachment, publishContext delivery, detachment, cross-node migration, and -// deletion across async SuspendActor, ResumeActor, SuspendActor, and DeleteActor: -// 1. Creates a template with an external volume and a mock worker pod on node1. -// 2. Creates and resumes an actor to ACTOR_STATE_RUNNING; verifies volume is attached to node1 and restore request carries node1 publishContext. -// 3. Calls async SuspendActor; verifies volume is detached from node1 and actor transitions to ACTOR_STATE_SUSPENDED with a local snapshot. -// 4. Calls ResumeActor from local snapshot; verifies volume is re-attached to node1 and restore request carries node1 publishContext. -// 5. Calls SuspendActor, replaces worker-1 (node1) with worker-2 (node2), and calls ResumeActor; verifies volume is attached to node2 and restore request carries node2 publishContext. -// 6. Calls SuspendActor and DeleteActor; verifies volume is detached from node2 and deleted. -func TestSuspendActorAsync_VolumeLifecycle_DetachResumeAndMigrate(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-pause-vol-lifecycle") - plugin := &attachFailVolumePlugin{} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - // 1. Create template with external volume and a mock worker pod. - volumes := []*ateapi.Volume{ - { - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - {Name: "vol1", MountPath: "/mnt/vol1"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // 2. Create actor and resume to RUNNING; volume is attached to node1. - createResp, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "pause-vol-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - actorUID := createResp.GetMetadata().GetUid() - - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - }) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - plugin.mu.Lock() - if diff := cmp.Diff([]string{"node1"}, plugin.attachedNodes); diff != "" { - t.Errorf("attached nodes after resume mismatch (-want +got):\n%s", diff) - } - plugin.mu.Unlock() - if got := tc.fakeAtelet.lastRestoreVolumePublishContext("vol1"); got["mock.substrate.io/attached-node"] != "node1" { - t.Errorf("atelet restore publishContext after first resume = %v, want attached-node=node1", got) - } - - // 3. Async SuspendActor: volume is detached from node1 and actor transitions to ACTOR_STATE_SUSPENDED with a local snapshot. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("actor state = %v, want ACTOR_STATE_SUSPENDED", getResp.GetStatus().GetState()) - } - if localSnapshot(getResp.GetStatus()) == nil { - t.Error("expected a local snapshot on the paused actor") - } - plugin.mu.Lock() - if diff := cmp.Diff([]string{"node1"}, plugin.detachedNodes); diff != "" { - t.Errorf("detached nodes after pause mismatch (-want +got):\n%s", diff) - } - plugin.mu.Unlock() - waitForWorkerAvailable(t, tc, workerName) - - // 4. ResumeActor from local snapshot: volume is re-attached to node1 and actor transitions to ACTOR_STATE_RUNNING. - tc.fakeAtelet.Reset() - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - }) - if err != nil { - t.Fatalf("ResumeActor from pause failed: %v", err) - } - - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after second resume: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("actor state after retry = %v, want ACTOR_STATE_RUNNING", getResp.GetStatus().GetState()) - } - plugin.mu.Lock() - // Should have attached twice: first resume + resume from local snapshot - if diff := cmp.Diff([]string{"node1", "node1"}, plugin.attachedNodes); diff != "" { - t.Errorf("attached nodes after resume from pause mismatch (-want +got):\n%s", diff) - } - plugin.mu.Unlock() - if got := tc.fakeAtelet.lastRestoreVolumePublishContext("vol1"); got["mock.substrate.io/attached-node"] != "node1" { - t.Errorf("atelet restore publishContext after resume from pause = %v, want attached-node=node1", got) - } - - // 5. Suspend to detach from node1 and clear local snapshot, then migrate to node2. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor before migration failed: %v", err) - } - plugin.mu.Lock() - if diff := cmp.Diff([]string{"node1", "node1"}, plugin.detachedNodes); diff != "" { - t.Errorf("detached nodes after suspend before migration mismatch (-want +got):\n%s", diff) - } - plugin.mu.Unlock() - - setupAteletOnNode(t, tc, "atelet-node2", "node2") - createWorkerPod(t, tc, ns, "worker-2", "node2", "pool1") - deleteWorkerPod(t, tc, ns, "worker-1") - tc.fakeAtelet.Reset() - - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - }) - if err != nil { - t.Fatalf("ResumeActor on migration failed: %v", err) - } - plugin.mu.Lock() - if diff := cmp.Diff([]string{"node1", "node1", "node2"}, plugin.attachedNodes); diff != "" { - t.Errorf("attached nodes after migration mismatch (-want +got):\n%s", diff) - } - plugin.mu.Unlock() - if got := tc.fakeAtelet.lastRestoreVolumePublishContext("vol1"); got["mock.substrate.io/attached-node"] != "node2" { - t.Errorf("atelet restore publishContext after migration = %v, want attached-node=node2", got) - } - - // 6. Suspend and delete the actor on node2. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor after migration failed: %v", err) - } - plugin.mu.Lock() - if diff := cmp.Diff([]string{"node1", "node1", "node2"}, plugin.detachedNodes); diff != "" { - t.Errorf("detached nodes after final suspend mismatch (-want +got):\n%s", diff) - } - plugin.mu.Unlock() - - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-vol-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - expectedVolumeID := "storage-substrate-" + actorUID + "-vol1" - plugin.mu.Lock() - if diff := cmp.Diff([]string{"node1", "node1", "node2"}, plugin.detachedNodes); diff != "" { - t.Errorf("detached nodes after delete mismatch (-want +got):\n%s", diff) - } - if diff := cmp.Diff([]string{expectedVolumeID}, plugin.deleted); diff != "" { - t.Errorf("deleted volume IDs mismatch (-want +got):\n%s", diff) - } - plugin.mu.Unlock() - if _, err := tc.persistence.GetActor(context.Background(), resources.ActorRef{Atespace: testAtespace, Name: "pause-vol-actor"}); !errors.Is(err, store.ErrNotFound) { - t.Errorf("GetActor from store after delete: err = %v, want %v", err, store.ErrNotFound) - } -} - -// TestSuspendActorAsync_VolumeDetachFailure_RetrySuccess tests scenario D: -// when volume detachment fails during async SuspendActor: -// 1. Async SuspendActor fails, leaving the actor in ACTOR_STATE_SUSPENDING. -// 2. A subsequent retry of async SuspendActor re-attempts volume detachment and succeeds, transitioning the actor to ACTOR_STATE_SUSPENDED. -// -// Workflow: -// 1. Creates a template with an external volume and creates a mock worker pod on node1. -// 2. Creates and resumes an actor to ACTOR_STATE_RUNNING. -// 3. Calls async SuspendActor; plugin is configured to fail DetachVolume on attempt 1. -// 4. Verifies async SuspendActor returns an error and actor state is left in ACTOR_STATE_SUSPENDING. -// 5. Calls async SuspendActor a second time (retry); detachment succeeds. -// 6. Verifies actor state transitions to ACTOR_STATE_SUSPENDED with a local snapshot. -// 7. Cleans up by deleting the actor. -func TestSuspendActorAsync_VolumeDetachFailure_RetrySuccess(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") - - ns := namespaceForTest("ns-pause-vol-detach-retry") - plugin := &detachFailVolumePlugin{failUntil: 1} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - // 1. Create template with external volume and a mock worker pod. - volumes := []*ateapi.Volume{ - { - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }, - } - mounts := []*ateapi.VolumeMount{ - {Name: "vol1", MountPath: "/mnt/vol1"}, - } - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // 2. Create and resume actor to ACTOR_STATE_RUNNING. - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "pause-detach-retry-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-detach-retry-actor"}, - }); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - // 3. Attempt 1: async SuspendActor fails on DetachVolume. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-detach-retry-actor"}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }) - if err == nil { - t.Fatalf("expected first async SuspendActor to fail, got nil") - } - if !strings.Contains(err.Error(), "simulated volume detach failure on attempt 1") { - t.Errorf("expected error containing simulated detach failure, got: %v", err) - } - - // 4. Verify actor state is ACTOR_STATE_SUSPENDING. - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-detach-retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after failed pause: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDING { - t.Errorf("actor state = %v, want ACTOR_STATE_SUSPENDING", getResp.GetStatus().GetState()) - } - - // 5. Attempt 2 (retry): async SuspendActor retry succeeds, detaching volume. - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-detach-retry-actor"}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("expected retry async SuspendActor to succeed, got: %v", err) - } - - // 6. Verify actor state transitions to ACTOR_STATE_SUSPENDED with a local snapshot. - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-detach-retry-actor"}, - }) - if err != nil { - t.Fatalf("GetActor after successful pause retry: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("actor state = %v, want ACTOR_STATE_SUSPENDED", getResp.GetStatus().GetState()) - } - if localSnapshot(getResp.GetStatus()) == nil { - t.Error("expected a local snapshot on the paused actor") - } - - // 7. Clean up by deleting the actor. - _, err = tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "pause-detach-retry-actor"}, - }) - if err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } -} - -// TestResumeActor tests the full workflow of resuming a suspended actor. -// Workflow: -// 1. Creates a mock ActorTemplate. -// 2. Creates a mock Atelet Pod in 'ate-system' namespace on 'node1'. -// 3. Creates a mock worker Pod in the test namespace on 'node1'. -// 4. Waits for the WorkerPoolSyncer to mirror the worker to the store. -// 5. Creates an actor (starts as SUSPENDED). -// 6. Calls ResumeActor RPC. -// 7. Verifies that the fake Atelet received the Restore call. -// 8. Verifies that the actor state is updated to RUNNING. -func TestResumeActor(t *testing.T) { - ns := namespaceForTest("ns-resume") - tc := setupTest(t, ns) - defer tc.cleanup() - - tmpl := createTemplate(t, tc, ns) - - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "id1" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - if !tc.fakeAtelet.RestoreCalled { - t.Errorf("expected Restore to be called") - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - want := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Name: name, Atespace: testAtespace}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{ - State: ateapi.ActorState_ACTOR_STATE_RUNNING, - AssignedNode: "node1", - LastAssignedGeneration: 1, - Snapshots: []*ateapi.Snapshot{ - newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, tmpl.GetMetadata().GetUid(), goldenSnapshotName, goldenSnapshotURI(t)), - }, - WorkerAssignment: &ateapi.WorkerAssignment{ - Worker: &ateapi.ObjectRef{Name: podUID}, - WorkerNamespace: ns, - WorkerPool: "pool1", - WorkerPod: "worker-1", - WorkerPodUid: podUID, - WorkerPodIps: []string{"127.0.0.1"}, - NodeName: "node1", - WorkerEpoch: reportedEpoch, - SandboxRuntime: defaultWorkerRuntime("gvisor"), - }, - }, - } - if diff := cmp.Diff(want, getResp, protocmp.Transform(), ignoreUID, ignoreVersion, ignoreTimestamps); diff != "" { - t.Errorf("GetActor response mismatch (-want +got):\n%s", diff) - } - - // Verify that the worker record also has the assigned actor details - listWorkersResp, err := tc.client.ListWorkers(context.Background(), &ateapi.ListWorkersRequest{}) - if err != nil { - t.Fatalf("ListWorkers failed: %v", err) - } - var actorWorker *ateapi.Worker - for _, w := range listWorkersResp.GetWorkers() { - if w.GetWorkerNamespace() == ns && w.GetWorkerPod() == "worker-1" { - actorWorker = w - break - } - } - if actorWorker == nil { - t.Fatalf("expected worker-1 in namespace %s not found in ListWorkers", ns) - } - - wantWorker := &ateapi.Worker{ - Metadata: &ateapi.ResourceMetadata{Name: podUID}, - WorkerNamespace: ns, - WorkerPool: "pool1", - WorkerPod: "worker-1", - WorkerPodUid: podUID, - NodeName: "node1", - Labels: map[string]string{poolLabelKey: ns}, - Status: &ateapi.WorkerStatus{ - State: ateapi.WorkerState_WORKER_STATE_ACTIVE, - RegisteredEpoch: reportedEpoch, - Ips: []string{"127.0.0.1"}, - // Only the ceiling the worker reported. - Capacity: &ateapi.WorkerResources{Actors: 1, CpuMillicores: 1000, MemoryBytes: 512 << 20}, - // All a listing reports of the assignments: one actor and the - // compute its template declares. - Allocated: &ateapi.WorkerResources{Actors: 1, CpuMillicores: 1000, MemoryBytes: 512 << 20}, - SandboxClasses: workerSandboxClasses(defaultWorkerRuntime("gvisor")), - }, - } - - if diff := cmp.Diff(wantWorker, actorWorker, protocmp.Transform(), ignoreUID, ignoreVersion, ignoreTimestamps); diff != "" { - t.Errorf("Worker state mismatch (-want +got):\n%s", diff) - } -} - -func TestResumeActorPassesLiteralEnv(t *testing.T) { - ns := namespaceForTest("ns-resume-literal-env") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplateWithContainers(t, tc, ns, []*ateapi.Container{ - { - Name: "main", - Image: "main@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - Command: []string{"/main"}, - Env: []*ateapi.EnvVar{ - { - Name: "LITERAL", - Value: "plain", - }, - }, - }, - }) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}, - }) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - restoreReq := tc.fakeAtelet.lastRestoreRequest() - if restoreReq == nil { - t.Fatalf("expected Restore to be called") - } - if len(restoreReq.GetSpec().GetContainers()) != 1 { - t.Fatalf("expected one container in restore request, got %d", len(restoreReq.GetSpec().GetContainers())) - } - gotEnv := map[string]string{} - for _, env := range restoreReq.GetSpec().GetContainers()[0].GetEnv() { - gotEnv[env.GetName()] = env.GetValue() - } - wantEnv := map[string]string{ - "LITERAL": "plain", - } - if diff := cmp.Diff(wantEnv, gotEnv); diff != "" { - t.Errorf("env mismatch (-want +got):\n%s", diff) - } -} - -// createDataFidelityTemplate creates "tmpl1" like createTemplate, but with -// preferredFidelity DATA, so a resumed-after-suspend actor restores from a DATA -// snapshot while the template also has a golden snapshot. -func createDataFidelityTemplate(t *testing.T, tc *testContext, ns string) *ateapi.ActorTemplate { - t.Helper() - createWorkerPool(t, tc, ns, "pool1", map[string]string{poolLabelKey: ns}) - - created, err := tc.client.CreateActorTemplate(context.Background(), &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "tmpl1", - }, - SnapshotConfig: &ateapi.SnapshotConfig{ - PreferredFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES, - }, - Containers: []*ateapi.Container{{ - Name: "main", - Image: "main@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - Command: []string{"/main"}, - }}, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{poolLabelKey: ns}, - }, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 512<<20)}, - }, - }) - if err != nil { - t.Fatalf("failed to create actor template: %v", err) - } - - // Publish the golden snapshot as a tag and point the template at it, as - // createTemplateWithContainersAndVolumes does. - tag, err := tc.persistence.CreateTag(context.Background(), &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: created.GetMetadata().GetUid()}, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: created.GetMetadata().GetUid()}, - Scope: ateapi.TagScope_TAG_SCOPE_PUBLISHED, - Status: &ateapi.TagStatus{ - Snapshot: newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES, created.GetMetadata().GetUid(), goldenSnapshotName, goldenSnapshotURI(t)), - ActorTemplateUid: created.GetMetadata().GetUid(), - }, - }) - if err != nil { - t.Fatalf("create golden tag: %v", err) - } - updated, err := tc.persistence.UpdateActorTemplate(context.Background(), - resources.ActorTemplateRefFromActorTemplate(created), store.PreconditionFrom(created), - func(dbTemplate *ateapi.ActorTemplate) error { - dbTemplate.Status = &ateapi.ActorTemplateStatus{ - GoldenSnapshotStatus: &ateapi.GoldenSnapshotStatus{ - GoldenTag: resources.TagRefFromTag(tag).ToObjectRef(), - }, - } - return nil - }) - if err != nil { - t.Fatalf("failed to record the template's golden snapshot: %v", err) - } - return updated -} - -// TestResumeActor_DataSnapshotIgnoresGolden drives a resume from a DATA -// snapshot end to end and pins the wire request: a plain DATA restore of the -// actor's own snapshot, even though the template has a golden snapshot. -func TestResumeActor_DataSnapshotIgnoresGolden(t *testing.T) { - ns := namespaceForTest("ns-resume-data") - tc := setupTest(t, ns) - defer tc.cleanup() - - createDataFidelityTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - const name = "id1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // First resume runs fresh from the golden; the suspend then commits a - // DATA snapshot per preferredFidelity. - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor (first) failed: %v", err) - } - suspended, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - actorSnapshotURI := durableSnapshotURI(suspended.GetActor().GetStatus()) - if actorSnapshotURI == "" { - t.Fatal("SuspendActor recorded no external snapshot") - } - - // Second resume restores the actor's DATA snapshot on its own. - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor (second) failed: %v", err) - } - restoreReq := tc.fakeAtelet.lastRestoreRequest() - if restoreReq == nil { - t.Fatal("second resume sent no Restore request to atelet") - } - if got := restoreReq.GetSnapshot().GetFidelity(); got != ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES { - t.Fatalf("restore scope = %v, want SNAPSHOT_FIDELITY_VOLUMES", got) - } - if got := restoreReq.GetSnapshot().GetObject().GetSnapshotUri(); got != actorSnapshotURI { - t.Errorf("restore config snapshot uri = %q, want the actor's data snapshot %q", got, actorSnapshotURI) - } - // The actor's own snapshot is replaced by its next suspend: atelet must - // not cache it. - if got := restoreReq.GetSnapshot().GetObject().GetSharing(); got != ateletpb.SnapshotSharing_SNAPSHOT_SHARING_PRIVATE { - t.Errorf("restore of the actor's own snapshot declared sharing %v, want PRIVATE", got) - } -} - -// TestSuspendActor_ReplacedSnapshotReleaseFailure verifies that object storage -// failing to delete the snapshot a suspend replaces does not fail the suspend. -// By then the new snapshot is written and the worker released, so the actor -// must still reach SUSPENDED and stay resumable; the replaced snapshot is left -// behind rather than the actor wedged in SUSPENDING. -func TestSuspendActor_ReplacedSnapshotReleaseFailure(t *testing.T) { - ns := namespaceForTest("ns-suspend-release-failure") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - const name = "id1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // A first suspend gives the actor an external snapshot of its own for the - // second one to replace. - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor (first) failed: %v", err) - } - first, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor (first) failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - replacedURI := durableSnapshotURI(first.GetActor().GetStatus()) - assertSnapshotOwnedByActor(t, first.GetActor(), replacedURI) - - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor (second) failed: %v", err) - } - tc.objectStore.OnDelete = func(string, string) error { - return status.Error(codes.Unavailable, "object storage is unavailable") - } - second, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - tc.objectStore.OnDelete = nil - if err != nil { - t.Fatalf("SuspendActor (second) failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - if got := second.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state after the second suspend = %v, want SUSPENDED", got) - } - freshURI := durableSnapshotURI(second.GetActor().GetStatus()) - if freshURI == "" || freshURI == replacedURI { - t.Errorf("external snapshot after the second suspend = %q, want a new one replacing %q", freshURI, replacedURI) - } - assertSnapshotPresent(t, tc, freshURI) - assertSnapshotPresent(t, tc, replacedURI) - - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor after the release failure failed: %v", err) - } - if got := tc.fakeAtelet.lastRestoreRequest().GetSnapshot().GetObject().GetSnapshotUri(); got != freshURI { - t.Errorf("restore snapshot uri = %q, want the second suspend's %q", got, freshURI) - } - - // A later suspend releases only the snapshot it replaces; the one the - // failed release left behind stays until the actor is deleted, which - // collects everything under the actor's prefix. - third, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor (third) failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - lastURI := durableSnapshotURI(third.GetActor().GetStatus()) - assertSnapshotCollected(t, tc, freshURI) - assertSnapshotPresent(t, tc, replacedURI) - - if _, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - assertSnapshotCollected(t, tc, replacedURI) - assertSnapshotCollected(t, tc, lastURI) -} - -// TestResumeActor_NoWorkers tests that resuming an actor fails when no worker has room for it. -// Workflow: -// 1. Creates a mock ActorTemplate. -// 2. Creates an actor. -// 3. Calls ResumeActor RPC without creating any workers. -// 4. Verifies that ResumeActor fails with FailedPrecondition status. -func TestResumeActor_NoWorkers(t *testing.T) { - ns := namespaceForTest("ns-resume-no-workers") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - createResp, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - name := createResp.GetMetadata().GetName() - - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - assertGrpcError(t, err, codes.ResourceExhausted, "no worker has room for the actor") -} - -// TestResumeActor_MultiPoolSelector exercises the AND-of-two-selectors path -// end to end: a template's WorkerSelector gates two pools, and the actor's -// worker_selector narrows to just one of them. -func TestResumeActor_MultiPoolSelector(t *testing.T) { - ns := namespaceForTest("ns-multi-pool") - tc := setupTest(t, ns) - defer tc.cleanup() - - createWorkerPool(t, tc, ns, "pool-a", map[string]string{"group": ns, "tier": "a"}) - createWorkerPool(t, tc, ns, "pool-b", map[string]string{"group": ns, "tier": "b"}) - createTemplateWithSelector(t, tc, "tmpl1", &ateapi.Selector{ - MatchLabels: map[string]string{"group": ns}, - }) - - createWorkerPod(t, tc, ns, "worker-a", "node1", "pool-a") - createWorkerPod(t, tc, ns, "worker-b", "node1", "pool-b") - - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{"tier": "b"}, - }, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}}) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := getResp.GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-b" { - t.Errorf("expected actor to be assigned to worker-b (pool-b, matching narrowed selector), got %q", got) - } - if got := getResp.GetStatus().GetWorkerAssignment().GetWorkerPool(); got != "pool-b" { - t.Errorf("expected actor's worker_assignment.worker_pool to be pool-b, got %q", got) - } -} - -// TestResumeActor_RequiresBothSelectorsToMatch proves eligibility is the AND -// of the template's WorkerSelector and the actor's worker_selector, not -// either one alone: a pool matching only the template selector and a pool -// matching only the actor selector must both be rejected, end to end -// through CreateActor/ResumeActor (not just the eligibleWorkerPools unit -// test), while a pool matching both is the one actually used. -func TestResumeActor_RequiresBothSelectorsToMatch(t *testing.T) { - ns := namespaceForTest("ns-resume-and-selectors") - tc := setupTest(t, ns) - defer tc.cleanup() - - createWorkerPool(t, tc, ns, "pool-both", map[string]string{"group": ns, "tier": "b"}) - createWorkerPool(t, tc, ns, "pool-template-only", map[string]string{"group": ns, "tier": "a"}) - createWorkerPool(t, tc, ns, "pool-actor-only", map[string]string{"tier": "b"}) - createTemplateWithSelector(t, tc, "tmpl1", &ateapi.Selector{ - MatchLabels: map[string]string{"group": ns}, - }) - - createWorkerPod(t, tc, ns, "worker-both", "node1", "pool-both") - createWorkerPod(t, tc, ns, "worker-template-only", "node1", "pool-template-only") - createWorkerPod(t, tc, ns, "worker-actor-only", "node1", "pool-actor-only") - - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{"tier": "b"}, - }, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := getResp.GetStatus().GetWorkerAssignment().GetWorkerPool(); got != "pool-both" { - t.Errorf("expected actor to be assigned to pool-both (the only pool matching both selectors), got worker_assignment.worker_pool=%q", got) - } -} - -// TestResumeActor_AteletFailureCrashesActor verifies the default crash -// behavior: an atelet error a retry cannot clear crashes the actor during -// resume and releases its worker, and the crashed actor cannot be resumed -// again. -func TestResumeActor_AteletFailureCrashesActor(t *testing.T) { - ns := namespaceForTest("ns-resume-atelet-crash") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "id1" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - // STEP 1: Make Atelet FAIL on Restore! - tc.fakeAtelet.FailRestore = status.Error(codes.Internal, "mock atelet failure") - - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err == nil { - t.Fatal("expected ResumeActor to fail due to atelet error") - } - // Atelet's code does not reach the caller. - if got := status.Code(err); got != codes.Internal { - t.Errorf("status code = %v, want %v (err: %v)", got, codes.Internal, err) - } - - // Verify actor state is CRASHED in the store. - actor, err := tc.persistence.GetActor(context.Background(), resources.ActorRef{Atespace: testAtespace, Name: name}) - if err != nil { - t.Fatalf("failed to get actor from store: %v", err) - } - if actor.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Errorf("expected state CRASHED, got %v", actor.GetStatus().GetState()) - } - if actor.GetStatus().GetWorkerAssignment() != nil { - t.Errorf("expected worker assignment to be cleared, got %v", actor.GetStatus().GetWorkerAssignment()) - } - assertActorCrashStatus(t, tc, name, "resume failed: atelet Restore: mock atelet failure") - - worker, err := tc.persistence.GetWorker(context.Background(), podUID) - if err != nil { - t.Fatalf("GetWorker(%s) failed: %v", podUID, err) - } - if n := worker.GetStatus().GetAllocated().GetActors(); n != 0 { - t.Errorf("expected worker to be released after crash, still holds %d actors", n) - } -} - -// A transient atelet failure, or a caller whose deadline passes during the -// restore, leaves the actor RESUMING on its worker, and the next resume finishes. -// Only Unavailable and the caller's own deadline reach the caller with their -// code. Atelet's own Canceled or DeadlineExceeded reach it as Internal. -func TestResumeActor_AteletTransportErrorLeavesActorResuming(t *testing.T) { - for _, tt := range []struct { - name string - fail error - delay time.Duration - deadline time.Duration - wantCode codes.Code - }{ - {name: "Unavailable", fail: status.Error(codes.Unavailable, "restore reply lost"), wantCode: codes.Unavailable}, - {name: "atelet Canceled", fail: status.Error(codes.Canceled, "restore reply lost"), wantCode: codes.Internal}, - {name: "atelet DeadlineExceeded", fail: status.Error(codes.DeadlineExceeded, "restore reply lost"), wantCode: codes.Internal}, - {name: "caller deadline", delay: time.Second, deadline: 200 * time.Millisecond, wantCode: codes.DeadlineExceeded}, - } { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-resume-atelet-" + strings.ReplaceAll(strings.ToLower(tt.name), " ", "-")) - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "id1" - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - actorRef := resources.ActorRef{Atespace: testAtespace, Name: name} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - tc.fakeAtelet.FailRestore = tt.fail - tc.fakeAtelet.RestoreDelay = tt.delay - ctx := context.Background() - if tt.deadline > 0 { - var cancel context.CancelFunc - ctx, cancel = context.WithTimeout(ctx, tt.deadline) - defer cancel() - } - _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}) - if got := status.Code(err); got != tt.wantCode { - t.Fatalf("ResumeActor status code = %v, want %v (err: %v)", got, tt.wantCode, err) - } - - actor, err := tc.persistence.GetActor(context.Background(), actorRef) - if err != nil { - t.Fatalf("failed to get actor from store: %v", err) - } - if got := actor.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RESUMING { - t.Fatalf("state after %s = %v, want RESUMING", tt.name, got) - } - if crash := actor.GetStatus().GetCrash(); crash != nil { - t.Errorf("crash recorded after %s: %v", tt.name, crash) - } - if got := actor.GetStatus().GetWorkerAssignment().GetWorker().GetName(); got != podUID { - t.Errorf("assigned worker = %q, want %q kept for the retry", got, podUID) - } - - // The fake still holds its lock while a delayed restore sleeps. - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailRestore = nil - tc.fakeAtelet.RestoreDelay = 0 - tc.fakeAtelet.Lock.Unlock() - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("retried ResumeActor failed: %v", err) - } - actor, err = tc.persistence.GetActor(context.Background(), actorRef) - if err != nil { - t.Fatalf("failed to get actor from store: %v", err) - } - if got := actor.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("state after retry = %v, want RUNNING", got) - } - if got := actor.GetStatus().GetWorkerAssignment().GetWorker().GetName(); got != podUID { - t.Errorf("assigned worker after retry = %q, want %q", got, podUID) - } - }) - } -} - -// TestResumeActor_LocalRestoreFailureCrashesActor: an atelet error restoring a -// suspended actor from its local snapshot crashes it and releases its worker. -func TestResumeActor_LocalRestoreFailureCrashesActor(t *testing.T) { - ns := namespaceForTest("ns-resume-local-crash") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "id1" - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - pauseResp, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: ref, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - paused := localSnapshot(pauseResp.GetActor().GetStatus()) - if paused.GetDurableSnapshot().GetObject().GetSnapshotUri() == "" { - t.Fatalf("pause left no local snapshot naming its upload: %v", pauseResp.GetActor().GetStatus()) - } - - tc.fakeAtelet.Reset() - tc.fakeAtelet.FailRestore = status.Error(codes.Internal, "injected restore failure") - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: ref}); status.Code(err) != codes.Internal { - t.Fatalf("ResumeActor status code = %v, want Internal (err: %v)", status.Code(err), err) - } - if got := tc.fakeAtelet.RestoreRequest.GetSnapshot(); got.GetSnapshotUuid() != paused.GetUuid() || got.GetObject().GetSnapshotUri() != paused.GetDurableSnapshot().GetObject().GetSnapshotUri() { - t.Fatalf("restore snapshot = %v, want the local snapshot %v, naming its upload", got, paused) - } - - actor, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if actor.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Fatalf("state after failed restore = %v, want CRASHED", actor.GetStatus().GetState()) - } - if actor.GetStatus().GetWorkerAssignment() != nil { - t.Errorf("expected worker assignment to be cleared, got %v", actor.GetStatus().GetWorkerAssignment()) - } - assertActorCrashStatus(t, tc, name, "resume failed: atelet Restore: injected restore failure") - - worker, err := tc.persistence.GetWorker(context.Background(), podUID) - if err != nil { - t.Fatalf("GetWorker(%s) failed: %v", podUID, err) - } - if n := worker.GetStatus().GetAllocated().GetActors(); n != 0 { - t.Errorf("expected worker to be released after crash, still holds %d actors", n) - } -} - -// The early ref stamp must land on the span even when the op fails, so a failed -// resume is still attributable to who/where. -func TestResumeActor_ErrorStillStampsRefSpanIdentity(t *testing.T) { - ns := namespaceForTest("ns-span-resume-err") - tc := setupTest(t, ns) - defer tc.cleanup() - - attrs := recordRootSpanAttrs(t, func(ctx context.Context) { - if _, err := tc.service.ResumeActor(ctx, &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "missing"}, - }); err == nil { - t.Fatal("expected error resuming missing actor") - } - }) - - assertSpanStr(t, attrs, ateattr.AtespaceKey, testAtespace) - assertSpanStr(t, attrs, ateattr.ActorNameKey, "missing") -} - -// TestSuspendActor tests the full workflow of suspending a running actor. -// Workflow: -// 1. Creates a mock ActorTemplate. -// 2. Creates a mock Atelet Pod on 'node1'. -// 3. Creates a mock worker Pod on 'node1'. -// 4. Waits for the WorkerPoolSyncer to mirror the worker to the store. -// 5. Creates an actor. -// 6. Calls ResumeActor to transition it to RUNNING. -// 7. Calls SuspendActor RPC. -// 8. Verifies that the fake Atelet received the Suspend call. -func TestSuspendActor(t *testing.T) { - ns := namespaceForTest("ns-suspend") - tc := setupTest(t, ns) - defer tc.cleanup() - - tmpl := createTemplate(t, tc, ns) - - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - name := "id1" - - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Resume first to make it running - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - // Suspend - suspended, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - - if !tc.fakeAtelet.CheckpointCalled { - t.Errorf("expected atelet Checkpoint to be called") - } - - sourceActor := suspended.GetActor() - snapshotURI := durableSnapshotURI(sourceActor.GetStatus()) - if snapshotURI == "" { - t.Fatalf("SuspendActor wrote no external snapshot: %v", suspended) - } - // The snapshot lands under the Actor's own prefix: it owns what it wrote. - assertSnapshotOwnedByActor(t, sourceActor, snapshotURI) - - // Tagging is a separate call over whatever snapshot the Actor holds by then, - // which here is the one the suspend above left behind. - const tagName = "before-upgrade" - tagRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: tagName} - tagged, err := tc.client.CreateTag(context.Background(), &ateapi.CreateTagRequest{ - Tag: &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: tagName}, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }, - }) - if err != nil { - t.Fatalf("CreateTag failed: %v", err) - } - - // The tag owns a copy of its own, so the Actor's later suspends and its - // deletion cannot collect the tag's snapshot copy. - taggedSnapshotURI := tagSnapshotURI(tagged) - if taggedSnapshotURI == snapshotURI || taggedSnapshotURI == "" { - t.Fatalf("tag snapshot uri = %q, want an external snapshot of its own", taggedSnapshotURI) - } - assertSnapshotPresent(t, tc, snapshotURI) - assertSnapshotPresent(t, tc, taggedSnapshotURI) - - wantTagSnap := newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, durableSnapshot(sourceActor.GetStatus()).GetFidelity(), "", snapshotName(t, taggedSnapshotURI), taggedSnapshotURI) - wantTagSnap.SandboxRuntime = defaultWorkerRuntime("gvisor") - wantTag := &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: tagName}, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - Status: &ateapi.TagStatus{ - Snapshot: wantTagSnap, - ActorTemplateUid: tmpl.GetMetadata().GetUid(), - }, - } - stored, err := tc.client.GetTag(context.Background(), &ateapi.GetTagRequest{Tag: tagRef}) - if err != nil { - t.Fatalf("GetTag failed: %v", err) - } - if diff := cmp.Diff(wantTag, stored, protocmp.Transform(), ignoreUID, ignoreVersion, ignoreTimestamps); diff != "" { - t.Errorf("stored tag mismatch (-want +got):\n%s", diff) - } - listed, err := tc.client.ListTags(context.Background(), &ateapi.ListTagsRequest{Atespace: testAtespace, Options: &ateapi.ListOptions{PageSize: 1}}) - if err != nil || len(listed.GetTags()) != 1 { - t.Fatalf("ListTags = (%v, %v), want one", listed, err) - } - - // A tag is born ATESPACE-scoped, so it cannot seed an Actor elsewhere until - // it is published. - createAtespace(t, tc, "other") - crossAtespaceClone := &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: "other", Name: "cross-atespace"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - SourceTag: tagRef, - }, - } - if _, err := tc.client.CreateActor(context.Background(), crossAtespaceClone); status.Code(err) != codes.FailedPrecondition { - t.Fatalf("cross-atespace CreateActor status = %v, want FailedPrecondition", status.Code(err)) - } - tagged.Scope = ateapi.TagScope_TAG_SCOPE_PUBLISHED - updated, err := tc.client.UpdateTag(context.Background(), &ateapi.UpdateTagRequest{ - Tag: tagged, - }) - if err != nil || updated.GetScope() != ateapi.TagScope_TAG_SCOPE_PUBLISHED { - t.Fatalf("UpdateTag = (%v, %v), want published", updated, err) - } - if tagSnapshotURI(updated) != taggedSnapshotURI { - t.Errorf("tag snapshot uri after publication = %q, want %q", tagSnapshotURI(updated), taggedSnapshotURI) - } - if _, err := tc.client.CreateActor(context.Background(), crossAtespaceClone); err != nil { - t.Fatalf("CreateActor from published tag failed: %v", err) - } - - // A clone borrows the tag's external snapshot rather than copying it. The - // snapshot stays under the tag's prefix, which is what keeps the clone's own - // lifecycle from ever releasing it. - clone, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "clone"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - SourceTag: tagRef, - }, - }) - if err != nil { - t.Fatalf("CreateActor from tag failed: %v", err) - } - if got := durableSnapshotURI(clone.GetStatus()); got != taggedSnapshotURI { - t.Errorf("clone snapshot uri = %q, want the tag's %q", got, taggedSnapshotURI) - } - if snapshotOwnedByActor(t, clone, taggedSnapshotURI) { - t.Errorf("clone snapshot %s sits under the clone's own prefix, want it left under the tag's", taggedSnapshotURI) - } - if !proto.Equal(clone.GetSourceTag(), tagRef) { - t.Errorf("clone source tag = %v, want %v", clone.GetSourceTag(), tagRef) - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "clone"}}); err != nil { - t.Fatalf("ResumeActor clone failed: %v", err) - } - if !tc.fakeAtelet.RestoreCalled { - t.Error("resuming clone did not restore its source external snapshot") - } - - // The clone's first suspend writes a snapshot of its own and stops - // borrowing, which is what makes the tag's snapshot collectable later. - cloneSuspended, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "clone"}, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor clone failed: %v", err) - } - cloneSnapshotURI := durableSnapshotURI(cloneSuspended.GetActor().GetStatus()) - if cloneSnapshotURI == taggedSnapshotURI || cloneSnapshotURI == "" { - t.Errorf("clone snapshot uri after suspension = %q, want an external snapshot of its own", cloneSnapshotURI) - } - assertSnapshotOwnedByActor(t, cloneSuspended.GetActor(), cloneSnapshotURI) - // It stopped borrowing without releasing what it had borrowed. - assertSnapshotPresent(t, tc, taggedSnapshotURI) - assertSnapshotPresent(t, tc, cloneSnapshotURI) - // The untagged suspend created no tag: only the golden and explicit tag remain. - listed, err = tc.client.ListTags(context.Background(), &ateapi.ListTagsRequest{Atespace: testAtespace}) - if err != nil || len(listed.GetTags()) != 2 { - t.Fatalf("ListTags after clone suspension = (%v, %v), want golden and explicit tags", listed, err) - } - for _, tag := range listed.GetTags() { - if ref := resources.TagRefFromTag(tag).ToObjectRef(); !proto.Equal(ref, tagRef) && !proto.Equal(ref, tmpl.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag()) { - t.Errorf("unexpected tag after clone suspension: %v", ref) - } - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - wantActorSnap := newDurableSnapshot(2, ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR, durableSnapshot(sourceActor.GetStatus()).GetFidelity(), tmpl.GetMetadata().GetUid(), snapshotName(t, snapshotURI), snapshotURI) - wantActorSnap.SandboxRuntime = defaultWorkerRuntime("gvisor") - want := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Name: name, Atespace: testAtespace}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{ - State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, - LastAssignedGeneration: 2, - Snapshots: []*ateapi.Snapshot{ - wantActorSnap, - }, - }, - } - - if diff := cmp.Diff(want, getResp, - protocmp.Transform(), - ignoreUID, - ignoreVersion, - ignoreTimestamps, - ); diff != "" { - t.Errorf("GetActor response mismatch (-want +got):\n%s", diff) - } - // The tag outlives the Actor it was taken from: it holds the snapshot on its - // own, and deleting it is what ends that snapshot's life. - if _, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}); err != nil { - t.Fatalf("DeleteActor source failed: %v", err) - } - if _, err := tc.client.GetTag(context.Background(), &ateapi.GetTagRequest{Tag: tagRef}); err != nil { - t.Fatalf("source tag disappeared with source Actor: %v", err) - } - // The Actor took only what it owned with it. - assertSnapshotCollected(t, tc, snapshotURI) - assertSnapshotPresent(t, tc, taggedSnapshotURI) - - if deleted, err := tc.client.DeleteTag(context.Background(), &ateapi.DeleteTagRequest{Tag: tagRef}); err != nil || deleted.GetMetadata().GetName() != tagRef.GetName() { - t.Fatalf("DeleteTag = (%v, %v)", deleted, err) - } - if _, err := tc.client.GetTag(context.Background(), &ateapi.GetTagRequest{Tag: tagRef}); status.Code(err) != codes.NotFound { - t.Fatalf("deleted tag status = %v, want NotFound", status.Code(err)) - } - // Deleting the tag is what ends its snapshot's life. The clone that - // borrowed it has one of its own by now and is unaffected. - assertSnapshotCollected(t, tc, taggedSnapshotURI) - assertSnapshotPresent(t, tc, cloneSnapshotURI) -} - -func TestResumeActor_SyncSuspendKeepsLocalCopy(t *testing.T) { - for _, tt := range []struct { - name string - repoint bool - relocate bool - wantNode string - wantTemplate string - wantFidelity ateletpb.SnapshotFidelity - }{ - { - name: "same template on the original node", - wantNode: "node1", - wantTemplate: "tmpl1", - wantFidelity: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, - }, - { - name: "new template on the original node", - repoint: true, - wantNode: "node1", - wantTemplate: "tmpl2", - wantFidelity: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES, - }, - { - name: "new template on another node", - repoint: true, - relocate: true, - wantNode: "node2", - wantTemplate: "tmpl2", - wantFidelity: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES, - }, - } { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-sync-local-resume") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - resumeKinds := func() map[string]uint64 { - var rm metricdata.ResourceMetrics - if err := tc.metricReader.Collect(ctx, &rm); err != nil { - t.Fatal(err) - } - counts := make(map[string]uint64) - for _, scope := range rm.ScopeMetrics { - for _, metric := range scope.Metrics { - if metric.Name != "ate.actor.lifecycle.operation.duration" { - continue - } - hist, ok := metric.Data.(metricdata.Histogram[float64]) - if !ok { - t.Fatalf("%s data = %T, want float64 histogram", metric.Name, metric.Data) - } - for _, point := range hist.DataPoints { - op, _ := point.Attributes.Value(ateattr.ActorOperationNameKey) - kind, present := point.Attributes.Value(ateattr.SnapshotKindKey) - if op.AsString() == ateattr.OperationResume && present { - counts[kind.AsString()] += point.Count - } - } - } - } - return counts - } - tmpl := createTemplate(t, tc, ns) - if tt.repoint { - replacement := proto.CloneOf(tmpl) - replacement.Metadata = &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tmpl2"} - replacement.Status = nil - if _, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ActorTemplate: replacement}); err != nil { - t.Fatalf("CreateActorTemplate(tmpl2): %v", err) - } - } - worker := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.KeepCheckpointLocal = true - tc.fakeAtelet.Lock.Unlock() - - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: actorRef.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("initial ResumeActor: %v", err) - } - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: actorRef, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }); err != nil { - t.Fatalf("sync SuspendActor: %v", err) - } - suspended, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("GetActor after suspend: %v", err) - } - if got := suspended.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Fatalf("state after suspend = %v, want SUSPENDED", got) - } - if got := suspended.GetStatus().GetAssignedNode(); got != "node1" { - t.Fatalf("AssignedNode after sync suspend = %q, want node1", got) - } - if got := suspended.GetStatus().GetWorkerAssignment(); got != nil { - t.Fatalf("WorkerAssignment after sync suspend = %v, want none", got) - } - snap := localSnapshot(suspended.GetStatus()) - if snap == nil || snap.GetLocality() != "node1" { - t.Fatalf("sync snapshot = %v, want its local copy on node1 recorded", snap) - } - if got := snap.GetDurableSnapshot().GetState(); got != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED { - t.Fatalf("sync snapshot durable state = %v, want COMPLETED", got) - } - if got := snap.GetActorTemplateUid(); got != tmpl.GetMetadata().GetUid() { - t.Fatalf("snapshot template UID = %q, want original template %q", got, tmpl.GetMetadata().GetUid()) - } - if snap.GetUuid() == "" || snap.GetGeneration() == 0 || snap.GetDurableSnapshot().GetObject().GetSnapshotUri() == "" { - t.Fatalf("snapshot has incomplete identity: %v", snap) - } - assertSnapshotPresent(t, tc, snap.GetDurableSnapshot().GetObject().GetSnapshotUri()) - waitForWorkerAvailable(t, tc, worker) - - if tt.repoint { - toUpdate := proto.CloneOf(suspended) - toUpdate.ActorTemplate = &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl2"} - updated, err := tc.client.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: toUpdate}) - if err != nil { - t.Fatalf("UpdateActor with durable local snapshot: %v", err) - } - if got := localSnapshot(updated.GetStatus()); !proto.Equal(got, snap) { - t.Fatalf("snapshot after template update = %v, want unchanged %v", got, snap) - } - } - if tt.relocate { - // Fill node1 so resume must detach before moving to node2. - squatterRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "squatter"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: squatterRef.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor(squatter): %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: squatterRef}); err != nil { - t.Fatalf("ResumeActor(squatter): %v", err) - } - createWorkerPod(t, tc, ns, "worker-2", "node2", "pool1") - setupAteletOnNode(t, tc, "atelet-node2", "node2") - } - - before := resumeKinds() - resumed, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("ResumeActor with durable local snapshot: %v", err) - } - if got := resumed.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("state after resume = %v, want RUNNING", got) - } - if got := resumed.GetActor().GetStatus().GetWorkerAssignment().GetNodeName(); got != tt.wantNode { - t.Errorf("resumed on node %q, want %q", got, tt.wantNode) - } - restore := tc.fakeAtelet.lastRestoreRequest() - if restore == nil || restore.GetActorName() != actorRef.GetName() { - t.Fatalf("Restore request = %v, want actor-1", restore) - } - if got := restore.GetWorkerPodUid(); got != resumed.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPodUid() { - t.Errorf("Restore worker UID = %q, want the assigned worker", got) - } - if got := restore.GetActorTemplateName(); got != tt.wantTemplate { - t.Errorf("Restore template = %q, want %q", got, tt.wantTemplate) - } - if got := restore.GetSnapshot().GetFidelity(); got != tt.wantFidelity { - t.Errorf("Restore fidelity = %v, want %v", got, tt.wantFidelity) - } - if got := restore.GetSnapshot(); got.GetSnapshotUuid() != snap.GetUuid() || - got.GetGeneration() != snap.GetGeneration() || - got.GetObject().GetSnapshotUri() != snap.GetDurableSnapshot().GetObject().GetSnapshotUri() { - t.Errorf("Restore snapshot = %v, want original checkpoint identity %v", got, snap) - } - wantLocality := "node1" - wantKind := ateattr.SnapshotKindLocal - if tt.relocate { - wantLocality = "" - wantKind = ateattr.SnapshotKindLatest - } - if got := localSnapshot(resumed.GetActor().GetStatus()).GetLocality(); got != wantLocality { - t.Errorf("locality after resume = %q, want %q", got, wantLocality) - } - tc.fakeAtelet.Lock.Lock() - detached := tc.fakeAtelet.DetachCalled - tc.fakeAtelet.Lock.Unlock() - if detached != tt.relocate { - t.Errorf("detach called = %v, want %v", detached, tt.relocate) - } - - counts := resumeKinds() - for kind, count := range before { - counts[kind] -= count - if counts[kind] == 0 { - delete(counts, kind) - } - } - if diff := cmp.Diff(map[string]uint64{wantKind: 1}, counts); diff != "" { - t.Errorf("restore snapshot kinds (-want +got):\n%s", diff) - } - }) - } -} - -// TestResumeActor_RepointTemplateBeforeResume checks what an Actor cloned from -// a tag asks atelet to restore on its first resume. -// -// The clone borrows a snapshot taken under the tag's template. Left on that -// template, it restores in Full: memory and filesystem come back as they were. -// Moved to another template first, it must drop to Data: the new template's -// image boots fresh and only the volume data carries over. -func TestResumeActor_RepointTemplateBeforeResume(t *testing.T) { - tests := []struct { - name string - // moveActorToAnotherTemplate moves the clone to a volume-compatible replacement template - // after it is created but before its first resume. - moveActorToAnotherTemplate bool - wantTemplate string - wantScope ateletpb.SnapshotFidelity - }{ - { - name: "clone left on the tag's template", - moveActorToAnotherTemplate: false, - wantTemplate: "tmpl1", - wantScope: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, - }, - { - name: "clone repointed before its first resume", - moveActorToAnotherTemplate: true, - wantTemplate: "tmpl2", - wantScope: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-clone-repoint") - tc := setupTest(t, ns) - defer tc.cleanup() - - ctx := context.Background() - tmpl := createTemplate(t, tc, ns) - // The tmpl2 copies tmpl1 so the repoint clears the sandbox - // class and volume compatibility checks; only the name differs. - tmpl2 := proto.Clone(tmpl).(*ateapi.ActorTemplate) - tmpl2.Metadata = &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tmpl2"} - tmpl2.Status = nil - if _, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl2}); err != nil { - t.Fatalf("CreateActorTemplate(tmpl2) failed: %v", err) - } - worker := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // Run and suspend a source Actor, so we have an external snapshot we can tag - const sourceActorName = "source-actor" - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: sourceActorName}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor(%s) failed: %v", sourceActorName, err) - } - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: sourceActorName} - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor(%s) failed: %v", sourceActorName, err) - } - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}); err != nil { - t.Fatalf("SuspendActor(%s) failed: %v", sourceActorName, err) - } - waitForWorkerAvailable(t, tc, worker) - - const tagName = "before-upgrade" - if _, err := tc.client.CreateTag(ctx, &ateapi.CreateTagRequest{ - Tag: &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: tagName}, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - SourceActor: actorRef, - }, - }); err != nil { - t.Fatalf("CreateTag failed: %v", err) - } - - const cloneActorName = "clone" - cloneActor, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: cloneActorName}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - // Seeded from the tag. - SourceTag: &ateapi.ObjectRef{Atespace: testAtespace, Name: tagName}, - }}) - if err != nil { - t.Fatalf("CreateActor from tag failed: %v", err) - } - if tt.moveActorToAnotherTemplate { - // Change clonetActor's template - toUpdate := proto.Clone(cloneActor).(*ateapi.Actor) - toUpdate.ActorTemplate = &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl2"} - if _, err := tc.client.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: toUpdate}); err != nil { - t.Fatalf("UpdateActor repointing the clone at tmpl2 failed: %v", err) - } - } - - cloneRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: cloneActorName} - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: cloneRef}); err != nil { - t.Fatalf("ResumeActor(%s) failed: %v", cloneActorName, err) - } - - restoreReq := tc.fakeAtelet.lastRestoreRequest() - if restoreReq == nil { - t.Fatal("resuming the clone sent no Restore request to atelet") - } - if got := restoreReq.GetActorName(); got != cloneActorName { - t.Fatalf("last restore request to atelet was for actor %q, want the clone %q", got, cloneActorName) - } - if got := restoreReq.GetActorTemplateName(); got != tt.wantTemplate { - t.Errorf("restore request to atelet had actor template = %q, want %q", got, tt.wantTemplate) - } - if got := restoreReq.GetSnapshot().GetFidelity(); got != tt.wantScope { - t.Errorf("restore request to atelet had scope = %v, want %v", got, tt.wantScope) - } - // Either way the restore reads the snapshot the clone borrowed - // from the tag, not the template's golden image. - if got := restoreReq.GetSnapshot().GetObject().GetSnapshotUri(); got != durableSnapshotURI(cloneActor.GetStatus()) { - t.Errorf("restore request to atelet had snapshot uri = %q, want the clone's borrowed %q", got, durableSnapshotURI(cloneActor.GetStatus())) - } - }) - } -} - -// TestResumeActor_PausedAfterRepointUsesLocalProvenance verifies that an actor -// suspended after a template repoint restores from its local checkpoint in -// FULL, not DATA. At that point the actor holds an external snapshot captured -// on v1 and a local checkpoint captured on v2; judging the local restore by the -// external snapshot's provenance would wrongly discard the v2 memory image. -func TestResumeActor_PausedAfterRepointUsesLocalProvenance(t *testing.T) { - ns := namespaceForTest("ns-repoint-pause") - tc := setupTest(t, ns) - defer tc.cleanup() - - ctx := context.Background() - tmpl := createTemplate(t, tc, ns) - tmpl2 := proto.Clone(tmpl).(*ateapi.ActorTemplate) - tmpl2.Metadata = &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tmpl2"} - tmpl2.Status = nil - if _, err := tc.client.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl2}); err != nil { - t.Fatalf("CreateActorTemplate(tmpl2) failed: %v", err) - } - worker := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - const name = "actor-1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor(v1) failed: %v", err) - } - suspended, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor(v1) failed: %v", err) - } - waitForWorkerAvailable(t, tc, worker) - - // Repoint at v2 while suspended; the external snapshot stays on v1. - toUpdate := proto.Clone(suspended.GetActor()).(*ateapi.Actor) - toUpdate.ActorTemplate = &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl2"} - if _, err := tc.client.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: toUpdate}); err != nil { - t.Fatalf("UpdateActor(tmpl2) failed: %v", err) - } - - // Resume on v2 (this restore is DATA, from the v1 external snapshot), then - // suspend asynchronously; the local checkpoint is captured on v2 while the - // external snapshot still says v1. - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor(v2 from v1 snapshot) failed: %v", err) - } - if got := tc.fakeAtelet.lastRestoreRequest().GetSnapshot().GetFidelity(); got != ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES { - t.Fatalf("first resume on v2 had scope = %v, want DATA", got) - } - pauseResp, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - paused := localSnapshot(pauseResp.GetActor().GetStatus()) - if paused.GetDurableSnapshot().GetObject().GetSnapshotUri() == "" { - t.Fatalf("pause left no local snapshot naming its upload: %v", pauseResp.GetActor().GetStatus()) - } - waitForWorkerAvailable(t, tc, worker) - - // Resume from local snapshot: the local checkpoint was captured on v2 and - // the actor's template is v2, so the restore must be FULL. - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor(from v2 pause) failed: %v", err) - } - restoreReq := tc.fakeAtelet.lastRestoreRequest() - if got := restoreReq.GetSnapshot(); got.GetSnapshotUuid() != paused.GetUuid() || got.GetObject().GetSnapshotUri() != paused.GetDurableSnapshot().GetObject().GetSnapshotUri() { - t.Errorf("restore request snapshot = %v, want the local snapshot %v, naming its upload", got, paused) - } - if got := restoreReq.GetSnapshot().GetFidelity(); got != ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY { - t.Errorf("restore request scope = %v, want FULL (local checkpoint was captured on v2)", got) - } -} - -func TestResumeActor_PausedLocalSnapshotRuntimeFallback(t *testing.T) { - rtA := &ateapi.ActorSandboxRuntime{ - SandboxClass: "gvisor", - Version: &ateapi.VersionedSandboxCompat{ - SchemaVersion: "v1", - Attributes: []*ateapi.AttributeEntry{ - {Key: "architecture", Value: "amd64"}, - {Key: "sandbox_bundle_hash", Value: "hash-a"}, - }, - }, - } - rtB := proto.CloneOf(rtA) - rtB.Version.Attributes[1].Value = "hash-b" - - for _, tt := range []struct { - name string - compatibleNode bool - failDetach bool - wantWorker string - wantNode string - wantRuntime *ateapi.ActorSandboxRuntime - wantFidelity ateletpb.SnapshotFidelity - }{ - { - name: "compatible worker on another node preserves memory", - compatibleNode: true, - wantWorker: "worker-2", - wantNode: "node2", - wantRuntime: rtA, - wantFidelity: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, - }, - { - name: "no compatible worker falls back after detach", - wantWorker: "worker-1", - wantNode: "node1", - wantRuntime: rtB, - wantFidelity: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, - }, - { - name: "unreachable node uses the uploaded checkpoint", - compatibleNode: true, - failDetach: true, - wantWorker: "worker-2", - wantNode: "node2", - wantRuntime: rtA, - wantFidelity: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, - }, - } { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-paused-runtime-fallback") - tc := setupTest(t, ns) - t.Cleanup(tc.cleanup) - ctx := context.Background() - createTemplate(t, tc, ns) - - workerPod := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - reportWorkerRuntime(t, tc, workerPod, rtA) - - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: actorRef.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("initial ResumeActor: %v", err) - } - pauseResp, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: actorRef, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor: %v", err) - } - paused := localSnapshot(pauseResp.GetActor().GetStatus()) - if paused == nil || !proto.Equal(paused.GetSandboxRuntime(), rtA) { - t.Fatalf("pause snapshot = %v, want runtime A", paused) - } - waitForWorkerAvailable(t, tc, workerPod) - - upload := &ateapi.SnapshotReport{ - Uuid: paused.GetUuid(), - Generation: paused.GetGeneration(), - Fidelity: paused.GetFidelity(), - Object: paused.GetDurableSnapshot().GetObject(), - } - if err := tc.service.ApplyActorSnapshotState(ctx, resources.ActorRefFromActor(pauseResp.GetActor()), pauseResp.GetActor().GetMetadata().GetUid(), "node1", &ateapi.ActorSnapshotState{ - LatestLocal: upload, - LatestDurable: upload, - }); err != nil { - t.Fatalf("ApplyActorSnapshotState(upload): %v", err) - } - reportWorkerRuntime(t, tc, workerPod, rtB) - if tt.compatibleNode { - other := createWorkerPod(t, tc, ns, "worker-2", "node2", "pool1") - reportWorkerRuntime(t, tc, other, rtA) - setupAteletOnNode(t, tc, "atelet-node2", "node2") - } - if tt.failDetach { - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailDetach = status.Error(codes.Unavailable, "node unavailable") - tc.fakeAtelet.Lock.Unlock() - } - - resumed, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("ResumeActor after runtime change: %v", err) - } - assignment := resumed.GetActor().GetStatus().GetWorkerAssignment() - if assignment.GetWorkerPod() != tt.wantWorker || assignment.GetNodeName() != tt.wantNode { - t.Errorf("assignment = %v, want %s on %s", assignment, tt.wantWorker, tt.wantNode) - } - if !proto.Equal(assignment.GetSandboxRuntime(), tt.wantRuntime) { - t.Errorf("assigned runtime = %v, want %v", assignment.GetSandboxRuntime(), tt.wantRuntime) - } - tc.fakeAtelet.Lock.Lock() - detached := tc.fakeAtelet.DetachCalled - tc.fakeAtelet.Lock.Unlock() - if !detached { - t.Error("resume did not detach the incompatible local checkpoint") - } - if snap := localSnapshot(resumed.GetActor().GetStatus()); snap != nil { - t.Errorf("local snapshot after detach = %v, want none", snap) - } - - restore := tc.fakeAtelet.lastRestoreRequest().GetSnapshot() - if restore.GetSnapshotUuid() != paused.GetUuid() || restore.GetGeneration() != paused.GetGeneration() || - restore.GetObject().GetSnapshotUri() != paused.GetDurableSnapshot().GetObject().GetSnapshotUri() { - t.Errorf("restore snapshot = %v, want the paused checkpoint's identity", restore) - } - if restore.GetFidelity() != tt.wantFidelity { - t.Errorf("restore fidelity = %v, want %v", restore.GetFidelity(), tt.wantFidelity) - } - }) - } -} - -// An older upload cannot authorize fallback for a newer checkpoint. -func TestResumeActor_PausedPendingSnapshotRefusesRuntimeFallback(t *testing.T) { - ns := namespaceForTest("ns-paused-pending-refusal") - tc := setupTest(t, ns) - defer tc.cleanup() - - ctx := context.Background() - createTemplate(t, tc, ns) - - rtA := &ateapi.ActorSandboxRuntime{ - SandboxClass: "gvisor", - Version: &ateapi.VersionedSandboxCompat{ - SchemaVersion: "v1", - Attributes: []*ateapi.AttributeEntry{ - {Key: "architecture", Value: "amd64"}, - {Key: "sandbox_bundle_hash", Value: "hash-a"}, - }, - }, - } - rtB := &ateapi.ActorSandboxRuntime{ - SandboxClass: "gvisor", - Version: &ateapi.VersionedSandboxCompat{ - SchemaVersion: "v1", - Attributes: []*ateapi.AttributeEntry{ - {Key: "architecture", Value: "amd64"}, - {Key: "sandbox_bundle_hash", Value: "hash-b"}, - }, - }, - } - - workerPod := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - reportWorkerRuntime(t, tc, workerPod, rtA) - - const name = "actor-1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - // Keep an older durable generation beside the pending checkpoint. - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: actorRef, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }); err != nil { - t.Fatalf("sync SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerPod) - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor from the durable snapshot failed: %v", err) - } - pauseResp, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: actorRef, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("pause SuspendActor failed: %v", err) - } - paused := localSnapshot(pauseResp.GetActor().GetStatus()) - if paused == nil { - t.Fatalf("pause left no local snapshot: %v", pauseResp.GetActor().GetStatus()) - } - if got := paused.GetDurableSnapshot().GetState(); got != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING { - t.Fatalf("pause checkpoint durable state = %v, want PENDING (not yet uploaded)", got) - } - durable := durableSnapshot(pauseResp.GetActor().GetStatus()) - if durable == nil || durable.GetGeneration() >= paused.GetGeneration() { - t.Fatalf("want an older COMPLETED durable snapshot beside the pause checkpoint, got %v", pauseResp.GetActor().GetStatus().GetSnapshots()) - } - waitForWorkerAvailable(t, tc, workerPod) - - // The pending checkpoint still needs upload before runtime fallback. - reportWorkerRuntime(t, tc, workerPod, rtB) - tc.fakeAtelet.Reset() - tc.fakeAtelet.FailDetach = status.Error(codes.Unavailable, "checkpoint upload unavailable") - - _, err = tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}) - assertGrpcError(t, err, codes.Unavailable, "while calling atelet DetachActor: rpc error: code = Unavailable desc = checkpoint upload unavailable") - tc.fakeAtelet.Lock.Lock() - detachCalled := tc.fakeAtelet.DetachCalled - tc.fakeAtelet.Lock.Unlock() - if !detachCalled { - t.Error("ResumeActor did not attempt to detach the pending checkpoint") - } - - if restore := tc.fakeAtelet.lastRestoreRequest(); restore != nil { - t.Errorf("ResumeActor sent a Restore request: %v, want none (neither the checkpoint nor the older generation)", restore) - } - after, err := tc.persistence.GetActor(ctx, resources.ActorRefFromActor(pauseResp.GetActor())) - if err != nil { - t.Fatalf("GetActor: %v", err) - } - if got := after.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state after the refused resume = %v, want SUSPENDED", got) - } - if got := after.GetStatus().GetWorkerAssignment(); got != nil { - t.Errorf("WorkerAssignment after the refused resume = %v, want none", got) - } - stillLocal := localSnapshot(after.GetStatus()) - if stillLocal == nil || stillLocal.GetUuid() != paused.GetUuid() || - stillLocal.GetDurableSnapshot().GetState() != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING { - t.Errorf("pause checkpoint after the refused resume = %v, want %v still PENDING", stillLocal, paused) - } - if got := durableSnapshotURI(after.GetStatus()); got != durable.GetDurableSnapshot().GetObject().GetSnapshotUri() { - t.Errorf("older durable snapshot = %q, want it untouched at %q", got, durable.GetDurableSnapshot().GetObject().GetSnapshotUri()) - } -} - -func TestResumeActor_RetryRelaxedPauseAssignmentRestoresSameSnapshot(t *testing.T) { - ns := namespaceForTest("ns-paused-relaxed-retry") - tc := setupTest(t, ns) - defer tc.cleanup() - - ctx := context.Background() - createTemplate(t, tc, ns) - - rtA := &ateapi.ActorSandboxRuntime{ - SandboxClass: "gvisor", - Version: &ateapi.VersionedSandboxCompat{ - SchemaVersion: "v1", - Attributes: []*ateapi.AttributeEntry{ - {Key: "architecture", Value: "amd64"}, - {Key: "sandbox_bundle_hash", Value: "hash-a"}, - }, - }, - } - rtB := &ateapi.ActorSandboxRuntime{ - SandboxClass: "gvisor", - Version: &ateapi.VersionedSandboxCompat{ - SchemaVersion: "v1", - Attributes: []*ateapi.AttributeEntry{ - {Key: "architecture", Value: "amd64"}, - {Key: "sandbox_bundle_hash", Value: "hash-b"}, - }, - }, - } - - workerPod := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - reportWorkerRuntime(t, tc, workerPod, rtA) - - const name = "actor-1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - pauseResp, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: actorRef, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - paused := localSnapshot(pauseResp.GetActor().GetStatus()) - if paused == nil { - t.Fatalf("pause left no local snapshot: %v", pauseResp.GetActor().GetStatus()) - } - waitForWorkerAvailable(t, tc, workerPod) - - // Finish the upload before changing the worker's runtime. - upload := &ateapi.SnapshotReport{ - Uuid: paused.GetUuid(), - Generation: paused.GetGeneration(), - Fidelity: paused.GetFidelity(), - Object: paused.GetDurableSnapshot().GetObject(), - } - if err := tc.service.ApplyActorSnapshotState(ctx, resources.ActorRefFromActor(pauseResp.GetActor()), pauseResp.GetActor().GetMetadata().GetUid(), "node1", &ateapi.ActorSnapshotState{ - LatestLocal: upload, - LatestDurable: upload, - }); err != nil { - t.Fatalf("ApplyActorSnapshotState(upload) failed: %v", err) - } - reportWorkerRuntime(t, tc, workerPod, rtB) - - // Interrupt restore after detach and worker assignment. - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailRestore = status.Error(codes.Unavailable, "restore reply lost") - tc.fakeAtelet.Lock.Unlock() - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); status.Code(err) != codes.Unavailable { - t.Fatalf("first ResumeActor status code = %v, want Unavailable (err: %v)", status.Code(err), err) - } - interrupted, err := tc.persistence.GetActor(ctx, resources.ActorRefFromActor(pauseResp.GetActor())) - if err != nil { - t.Fatalf("GetActor after the interrupted resume: %v", err) - } - if got := interrupted.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RESUMING { - t.Fatalf("state after the interrupted resume = %v, want RESUMING", got) - } - if got := interrupted.GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-1" { - t.Fatalf("assigned worker after the interrupted resume = %q, want worker-1", got) - } - if crash := interrupted.GetStatus().GetCrash(); crash != nil { - t.Fatalf("crash recorded after the interrupted resume: %v", crash) - } - - // Re-entry keeps the assignment and restores the same snapshot. - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailRestore = nil - tc.fakeAtelet.Lock.Unlock() - resumed, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("retried ResumeActor failed: %v", err) - } - if got := resumed.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("state after the retry = %v, want RUNNING", got) - } - if got := resumed.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-1" { - t.Errorf("retried resume moved to worker %q, want the kept assignment on worker-1", got) - } - restoreReq := tc.fakeAtelet.lastRestoreRequest() - if got := restoreReq.GetSnapshot().GetSnapshotUuid(); got != paused.GetUuid() { - t.Errorf("RestoreRequest.SnapshotUuid = %q, want the pause checkpoint's %q", got, paused.GetUuid()) - } - if got := restoreReq.GetSnapshot().GetObject().GetSnapshotUri(); got != paused.GetDurableSnapshot().GetObject().GetSnapshotUri() { - t.Errorf("RestoreRequest.SnapshotUri = %q, want the pause checkpoint's upload %q", got, paused.GetDurableSnapshot().GetObject().GetSnapshotUri()) - } - if got := restoreReq.GetSnapshot().GetFidelity(); got != ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS { - t.Errorf("RestoreRequest.Fidelity = %v, want ROOTFS (assigned worker cannot run the checkpoint's runtime)", got) - } -} - -// TestSuspendActorAsynchronous tests the full workflow of suspending a running -// actor asynchronously. -// Workflow: -// 1. Creates a mock ActorTemplate. -// 2. Creates a mock Atelet Pod on 'node1'. -// 3. Creates a mock worker Pod on 'node1'. -// 4. Waits for the WorkerPoolSyncer to mirror the worker to the store. -// 5. Creates an actor. -// 6. Calls ResumeActor to transition it to RUNNING. -// 7. Suspends it asynchronously. -// 8. Verifies that the fake Atelet received the Checkpoint call and the -// actor holds a node-local snapshot. -func TestSuspendActorAsynchronous(t *testing.T) { - tests := []struct { - name string - suspend func(ctx context.Context, client ateapi.ControlClient, ref *ateapi.ObjectRef) error - }{ - { - name: "SuspendActor asynchronous", - suspend: func(ctx context.Context, client ateapi.ControlClient, ref *ateapi.ObjectRef) error { - _, err := client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: ref, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }) - return err - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-pause") - tc := setupTest(t, ns) - defer tc.cleanup() - - tmpl := createTemplate(t, tc, ns) - - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "id1" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Resume first to make it running - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - if err := tt.suspend(context.Background(), tc.client, &ateapi.ObjectRef{Atespace: testAtespace, Name: name}); err != nil { - t.Fatalf("suspend failed: %v", err) - } - - if !tc.fakeAtelet.CheckpointCalled { - t.Errorf("expected atelet Checkpoint to be called") - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - ls := localSnapshot(getResp.GetStatus()) - if ls.GetUuid() == "" { - t.Error("Snapshot.Uuid is empty, want the name the pause checkpointed under") - } - wantPausedSnap := newPausedSnapshot(t, 2, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, tmpl.GetMetadata().GetUid(), getResp.GetMetadata().GetUid(), ls.GetUuid(), "node1") - wantPausedSnap.SandboxRuntime = defaultWorkerRuntime("gvisor") - want := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Name: name, Atespace: testAtespace}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{ - State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, - AssignedNode: "node1", - LastAssignedGeneration: 2, - Snapshots: []*ateapi.Snapshot{ - newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, tmpl.GetMetadata().GetUid(), goldenSnapshotName, goldenSnapshotURI(t)), - wantPausedSnap, - }, - }, - } - - if diff := cmp.Diff(want, getResp, - protocmp.Transform(), - ignoreUID, - ignoreVersion, - ignoreTimestamps, - ); diff != "" { - t.Errorf("GetActor response mismatch (-want +got):\n%s", diff) - } - }) - } -} - -// TestResumeActor_PausedLocalSnapshotMissing_Crashes tests that if the local checkpoint -// files on the worker node are missing (e.g. node reboot, /tmp wipe) when resuming a -// suspended actor from its local snapshot, atelet returns a terminal file system error -// and ateapi marks the actor ACTOR_STATE_CRASHED while releasing the assigned worker pod. -func TestResumeActor_PausedLocalSnapshotMissing_Crashes(t *testing.T) { - ns := namespaceForTest("ns-resume-paused-missing") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "paused-missing-actor" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - if _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }); err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Fatalf("actor state = %v, want ACTOR_STATE_SUSPENDED", getResp.GetStatus().GetState()) - } - if ls := localSnapshot(getResp.GetStatus()); ls == nil { - t.Fatal("expected local snapshot to be present on paused actor") - } - waitForWorkerAvailable(t, tc, workerName) - - // Simulate node-local files missing: atelet reports the restore as NotFound. - tc.fakeAtelet.Reset() - tc.fakeAtelet.FailRestore = status.Error(codes.NotFound, "local checkpoint files missing on node: directory not found") - - // A failed restore crashes the actor, and atelet's code does not reach the - // caller. - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err == nil { - t.Fatal("expected ResumeActor to fail due to missing local snapshot, but it succeeded") - } - if got := status.Code(err); got != codes.Internal { - t.Errorf("ResumeActor err code = %v, want %v", got, codes.Internal) - } - - // Assert actor transitioned to ACTOR_STATE_CRASHED - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Errorf("actor state after failed restore = %v, want ACTOR_STATE_CRASHED", getResp.GetStatus().GetState()) - } - - // Worker assignment must be released so the worker is not leaked - if getResp.GetStatus().GetWorkerAssignment() != nil && getResp.GetStatus().GetWorkerAssignment().GetWorkerPod() != "" { - t.Errorf("worker assignment = %v, want worker released", getResp.GetStatus().GetWorkerAssignment()) - } - - // Subsequent ResumeActor call on CRASHED actor must be rejected - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - assertGrpcErrorRegex(t, err, codes.FailedPrecondition, "ACTOR_STATE_CRASHED") -} - -// Suspend stamps the ref identity before resolving the Actor record, so a failed -// lookup still carries who/where; it must not invent template/version, which are -// known only once the record resolves (and stamped on success). -func TestSuspendActor_FailedLookupStampsRefIdentityOnly(t *testing.T) { - ns := namespaceForTest("ns-span-suspend-err") - tc := setupTest(t, ns) - defer tc.cleanup() - - attrs := recordRootSpanAttrs(t, func(ctx context.Context) { - if _, err := tc.service.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: testActorID}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }); apierror.Code(err) != codes.NotFound { - t.Fatalf("SuspendActor(missing) error = %v, want code NotFound", err) - } - }) - - assertSpanStr(t, attrs, ateattr.AtespaceKey, testAtespace) - assertSpanStr(t, attrs, ateattr.ActorNameKey, testActorID) - for _, k := range []attribute.Key{ateattr.ActorUIDKey, ateattr.TemplateNameKey, ateattr.TemplateAtespaceKey, ateattr.ActorVersionKey} { - if _, ok := attrs[k]; ok { - t.Errorf("unexpected %s on failed-suspend span", k) - } - } -} - -// TestResumeActor_ReleasesStaleWorkerWhenPoolBecomesIneligible verifies that -// a worker claimed by a failed resume attempt is released back to the free -// pool if, by the next resume attempt, the actor's worker_selector has -// changed such that the worker's pool is no longer eligible. The actor -// itself is crashed rather than transparently migrated to another pool. -// Workflow: -// 1. Creates pool-a (tier=a) and pool-b (tier=b), and an actor narrowed to -// tier=a. -// 2. Makes the fake atelet fail Run, then resumes: the actor gets assigned -// to worker-a (the only eligible pool) and the resume fails after the -// worker is claimed, leaving worker-a's actor assignment set and the actor -// stuck in RESUMING. -// 3. Updates the actor's selector to tier=b, making pool-a ineligible. -// 4. Resumes again; asserts it fails and the actor is CRASHED, that worker-a -// has been released (actor assignment cleared) rather than left dangling, -// and that worker-b remains free (the crashed actor must not claim it). -func TestResumeActor_ReleasesStaleWorkerWhenPoolBecomesIneligible(t *testing.T) { - ns := namespaceForTest("ns-resume-release-stale") - tc := setupTest(t, ns) - defer tc.cleanup() - - createWorkerPool(t, tc, ns, "pool-a", map[string]string{"group": ns, "tier": "a"}) - createWorkerPool(t, tc, ns, "pool-b", map[string]string{"group": ns, "tier": "b"}) - createTemplateWithSelector(t, tc, "tmpl1", &ateapi.Selector{ - MatchLabels: map[string]string{"group": ns}, - }) - createWorkerPod(t, tc, ns, "worker-a", "node1", "pool-a") - createWorkerPod(t, tc, ns, "worker-b", "node1", "pool-b") - - name := "id1" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"tier": "a"}}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - tc.fakeAtelet.FailRun = fmt.Errorf("mock atelet failure") - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}) - if err == nil { - t.Fatalf("expected first ResumeActor (onto worker-a) to fail") - } - tc.fakeAtelet.FailRun = nil - - current, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - current.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "b"}} - if _, err := tc.client.UpdateActor(context.Background(), &ateapi.UpdateActorRequest{ - Actor: current, - }); err != nil { - t.Fatalf("UpdateActor failed: %v", err) - } - - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}); err == nil { - t.Fatalf("expected second ResumeActor to fail: the assigned worker's pool is no longer eligible") - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := getResp.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Errorf("expected actor state CRASHED, got %v", got) - } - // The failed Run already crashed the actor, so the crash it records is - // that one, not the later eligibility check. - assertActorCrashStatus(t, tc, name, "resume failed: atelet Run: mock atelet failure") - - listResp, err := tc.client.ListWorkers(context.Background(), &ateapi.ListWorkersRequest{}) - if err != nil { - t.Fatalf("ListWorkers failed: %v", err) - } - for _, w := range listResp.GetWorkers() { - if w.GetWorkerNamespace() != ns { - continue - } - switch w.GetWorkerPool() { - case "pool-a": - if n := w.GetStatus().GetAllocated().GetActors(); n != 0 { - t.Errorf("expected worker-a (now-ineligible pool-a) to be released, still holds %d actors", n) - } - case "pool-b": - if n := w.GetStatus().GetAllocated().GetActors(); n != 0 { - t.Errorf("expected worker-b to stay free (actor crashed, not migrated), holds %d actors", n) - } - } - } -} - -// TestResumeActor_ReleasesDrainingWorkerFromPriorAttempt exercises the reuse-loop -// change in AssignWorkerStep.Execute: a worker still assigned to the actor from a -// previous (failed) attempt that has since entered DRAINING must not be reused — -// it is released and the actor is crashed. -func TestResumeActor_CrashesIfAssignedWorkerIsDraining(t *testing.T) { - ns := namespaceForTest("ns-resume-release-draining") - tc := setupTest(t, ns) - defer tc.cleanup() - - // createTemplate sets up pool1 (labeled pool=) + tmpl1 (selecting it) with - // a golden snapshot, so resume drives Restore. Two workers share the pool. - createTemplate(t, tc, ns) - podA := createWorkerPod(t, tc, ns, "worker-a", "node1", "pool1") - createWorkerPod(t, tc, ns, "worker-b", "node1", "pool1") - - id := "id1" - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: id, - }, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }, - }); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // An interrupted attempt left the actor RESUMING on worker-a (fabricated - // directly: an atelet error no longer leaves this state, it crashes the - // actor); the worker then went DRAINING, as the syncer records when its - // pod enters Terminating. - actorRef := resources.ActorRef{Atespace: testAtespace, Name: id} - suspended, err := tc.persistence.GetActor(context.Background(), actorRef) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if _, err := tc.persistence.BindActorToWorker(context.Background(), podA, &ateapi.ActorAssignment{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: id}, - ActorUid: suspended.GetMetadata().GetUid(), - }, nil, actorRef, store.PreconditionFrom(suspended), func(toUpdate *ateapi.Actor) error { - toUpdate.Status.State = ateapi.ActorState_ACTOR_STATE_RESUMING - toUpdate.Status.WorkerAssignment = &ateapi.WorkerAssignment{ - Worker: &ateapi.ObjectRef{Name: podA}, - WorkerNamespace: ns, - WorkerPool: "pool1", - WorkerPod: "worker-a", - WorkerPodUid: podA, - WorkerPodIps: []string{"127.0.0.1"}, - } - return nil - }); err != nil { - t.Fatalf("BindActorToWorker failed: %v", err) - } - - // Learn which worker got assigned through the API, then mark it DRAINING - // as the syncer would when its pod enters Terminating. - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: id}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - assignedPod := getResp.GetStatus().GetWorkerAssignment().GetWorkerPod() - if assignedPod == "" { - t.Fatalf("expected actor to be bound to a worker after the interrupted attempt") - } - - assigned, err := tc.persistence.GetWorker(context.Background(), getResp.GetStatus().GetWorkerAssignment().GetWorker().GetName()) - if err != nil { - t.Fatalf("GetWorker(%s) failed: %v", assignedPod, err) - } - if _, err := tc.persistence.UpdateWorker(context.Background(), assigned.GetMetadata().GetName(), store.PreconditionFrom(assigned), func(toUpdate *ateapi.Worker) error { - toUpdate.Status.State = ateapi.WorkerState_WORKER_STATE_DRAINING - return nil - }); err != nil { - t.Fatalf("marking worker %s draining failed: %v", assignedPod, err) - } - - // Wait until the DRAINING state is observable, which also gives the store - // watch time to propagate it into the scheduler's worker cache. - if err := wait.PollUntilContextTimeout(context.Background(), 100*time.Millisecond, 5*time.Second, true, func(ctx context.Context) (bool, error) { - resp, err := tc.client.ListWorkers(ctx, &ateapi.ListWorkersRequest{}) - if err != nil { - return false, nil - } - for _, w := range resp.GetWorkers() { - if w.GetWorkerNamespace() == ns && w.GetWorkerPod() == assignedPod { - return w.GetStatus().GetState() == ateapi.WorkerState_WORKER_STATE_DRAINING, nil - } - } - return false, nil - }); err != nil { - t.Fatalf("worker %s did not reach DRAINING: %v", assignedPod, err) - } - - // The resume must fail and crash the actor because its worker is draining. - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: id}}) - if err == nil { - t.Fatalf("expected ResumeActor to fail") - } - if status.Code(err) != codes.Aborted || !strings.Contains(err.Error(), "crashed") { - t.Errorf("expected Aborted/crashed error, got %v", err) - } - - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: id}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := getResp.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Errorf("expected actor state CRASHED, got %v", got) - } - if got := getResp.GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "" { - t.Errorf("expected actor pod name to be empty, got %q", got) - } - assertActorCrashStatus(t, tc, id, "resume failed: assigned worker is draining") - - // The draining worker must have been released. - listResp, err := tc.client.ListWorkers(context.Background(), &ateapi.ListWorkersRequest{}) - if err != nil { - t.Fatalf("ListWorkers failed: %v", err) - } - for _, w := range listResp.GetWorkers() { - if w.GetWorkerNamespace() != ns { - continue - } - if w.GetWorkerPod() == assignedPod { - if n := w.GetStatus().GetAllocated().GetActors(); n != 0 { - t.Errorf("expected draining worker %q to be released, still holds %d actors", assignedPod, n) - } - } - } -} - -// TestUpdateActor_ReassignsPoolAcrossSuspendResume verifies that updating an -// actor's worker_selector moves it onto a different eligible pool not just -// on the next fresh resume, but also across a full suspend/resume cycle of -// an already-running actor. -// Workflow: -// 1. Creates two WorkerPools, pool-a (tier=a) and pool-b (tier=b), both -// under the template's gating selector. -// 2. Creates an actor narrowed to tier=a and resumes it; asserts it lands on -// pool-a/worker-a. -// 3. Updates the actor's selector to tier=b while it's still running. -// 4. Suspends then resumes the actor; asserts it now lands on -// pool-b/worker-b, proving the updated selector — not the one in effect -// when it was first scheduled — governs the new placement. -func TestUpdateActor_ReassignsPoolAcrossSuspendResume(t *testing.T) { - ns := namespaceForTest("ns-update-actor-suspend-resume") - tc := setupTest(t, ns) - defer tc.cleanup() - - createWorkerPool(t, tc, ns, "pool-a", map[string]string{"group": ns, "tier": "a"}) - createWorkerPool(t, tc, ns, "pool-b", map[string]string{"group": ns, "tier": "b"}) - createTemplateWithSelector(t, tc, "tmpl1", &ateapi.Selector{ - MatchLabels: map[string]string{"group": ns}, - }) - - createWorkerPod(t, tc, ns, "worker-a", "node1", "pool-a") - createWorkerPod(t, tc, ns, "worker-b", "node1", "pool-b") - - name := "id1" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{"tier": "a"}, - }, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}); err != nil { - t.Fatalf("first ResumeActor failed: %v", err) - } - - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := getResp.GetStatus().GetWorkerAssignment().GetWorkerPool(); got != "pool-a" { - t.Fatalf("expected actor to first resume onto pool-a, got worker_assignment.worker_pool=%q", got) - } - if got := getResp.GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-a" { - t.Fatalf("expected actor to first resume onto worker-a, got worker_assignment.worker_pod=%q", got) - } - - getResp.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "b"}} - if _, err := tc.client.UpdateActor(context.Background(), &ateapi.UpdateActorRequest{ - Actor: getResp, - }); err != nil { - t.Fatalf("UpdateActor failed: %v", err) - } - - if _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}); err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}); err != nil { - t.Fatalf("second ResumeActor failed: %v", err) - } - - getResp, err = tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if got := getResp.GetStatus().GetWorkerAssignment().GetWorkerPool(); got != "pool-b" { - t.Errorf("expected actor to resume onto pool-b after selector update, got worker_assignment.worker_pool=%q", got) - } - if got := getResp.GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-b" { - t.Errorf("expected actor to resume onto worker-b after selector update, got worker_assignment.worker_pod=%q", got) - } - if got := getResp.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("expected actor state RUNNING after second resume, got %v", got) - } -} - -func TestResumeActor_LeaseConflict(t *testing.T) { - ns := namespaceForTest("ns-resume-conflict") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "id1" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Set a delay on the fake Atelet to hold the lease - tc.fakeAtelet.RestoreDelay = 1 * time.Second - - // Launch Request A in a goroutine - errChan := make(chan error, 1) - go func() { - _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - errChan <- err - }() - - // Sleep a bit to ensure Request A acquired the lease - time.Sleep(200 * time.Millisecond) - - // Launch Request B (should fail due to lease conflict) - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - assertGrpcError(t, err, codes.Aborted, "another operation is in progress for this actor") - - // Wait for Request A to finish - if errA := <-errChan; errA != nil { - t.Fatalf("Request A failed: %v", errA) - } -} - -func TestResumeActor_DanglingWorker(t *testing.T) { - ns := namespaceForTest("ns-resume-dangling") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - podA := createWorkerPod(t, tc, ns, "worker-a", "node1", "pool1") - - name := "id1" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // An interrupted attempt left the actor RESUMING on worker-a (fabricated - // directly: an atelet error no longer leaves this state, it crashes the - // actor). - actorRef := resources.ActorRef{Atespace: testAtespace, Name: name} - suspended, err := tc.persistence.GetActor(context.Background(), actorRef) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if _, err := tc.persistence.BindActorToWorker(context.Background(), podA, &ateapi.ActorAssignment{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - ActorUid: suspended.GetMetadata().GetUid(), - }, nil, actorRef, store.PreconditionFrom(suspended), func(toUpdate *ateapi.Actor) error { - toUpdate.Status.State = ateapi.ActorState_ACTOR_STATE_RESUMING - toUpdate.Status.WorkerAssignment = &ateapi.WorkerAssignment{ - Worker: &ateapi.ObjectRef{Name: podA}, - WorkerNamespace: ns, - WorkerPool: "pool1", - WorkerPod: "worker-a", - WorkerPodUid: podA, - WorkerPodIps: []string{"127.0.0.1"}, - } - return nil - }); err != nil { - t.Fatalf("BindActorToWorker failed: %v", err) - } - - // Verify actor state is RESUMING with worker A assigned - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - actor := getResp - if actor.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RESUMING { - t.Fatalf("expected state RESUMING, got %v", actor.GetStatus().GetState()) - } - if actor.GetStatus().GetWorkerAssignment().GetWorkerPod() != "worker-a" { - t.Fatalf("expected worker-a assigned, got %v", actor.GetStatus().GetWorkerAssignment().GetWorkerPod()) - } - - deleteWorkerPod(t, tc, ns, "worker-a") - - // Create Worker Pod B - createWorkerPod(t, tc, ns, "worker-b", "node1", "pool1") - - // Call ResumeActor again -> Expect it to fail because it is already CRASHED - // by the worker delete. - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err == nil { - t.Fatalf("expected ResumeActor to fail because worker is gone") - } - if status.Code(err) != codes.FailedPrecondition || !strings.Contains(err.Error(), "ACTOR_STATE_CRASHED") { - t.Errorf("expected FailedPrecondition/ACTOR_STATE_CRASHED error, got %v", err) - } - - // Verify actor state is CRASHED and worker assignment is empty - actor, err = tc.persistence.GetActor(context.Background(), resources.ActorRef{Atespace: testAtespace, Name: name}) - if err != nil { - t.Fatalf("failed to get actor from store: %v", err) - } - if actor.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Errorf("expected state CRASHED, got %v", actor.GetStatus().GetState()) - } - if actor.GetStatus().GetWorkerAssignment().GetWorkerPod() != "" { - t.Errorf("expected worker to be unassigned, got %v", actor.GetStatus().GetWorkerAssignment().GetWorkerPod()) - } -} - -func TestSuspendActor_DanglingWorker(t *testing.T) { - ns := namespaceForTest("ns-sd") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - // 1. Create Worker Pod - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "id1" - _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Resume first to make it running - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - deleteWorkerPod(t, tc, ns, "worker-1") - - // 3. Call SuspendActor -> Expect it to fail because it is already CRASHED by background syncer - _, err = tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err == nil { - t.Fatalf("expected SuspendActor to fail because worker is gone") - } - if status.Code(err) != codes.FailedPrecondition || !strings.Contains(err.Error(), "ACTOR_STATE_CRASHED") { - t.Errorf("expected FailedPrecondition error, got %v", err) - } - - // 4. Verify it becomes CRASHED in the store. - getResp, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if getResp.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Errorf("expected status CRASHED, got %v", getResp.GetStatus()) - } - if getResp.GetStatus().GetWorkerAssignment() != nil { - t.Errorf("expected worker_assignment to be cleared, got %v", getResp.GetStatus().GetWorkerAssignment()) - } -} - -// TestSuspendActor_FromPaused verifies SuspendActor, in either mode, returns a -// suspended actor as it is: atelet is not called, and the actor keeps its -// node-local snapshot on its node. -func TestSuspendActor_FromPaused(t *testing.T) { - tests := []struct { - name string - opts *ateapi.SuspendOptions - }{ - {name: "sync", opts: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}, - {name: "async", opts: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-suspend-paused-" + tt.name) - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: ref.GetAtespace(), Name: ref.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - if _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: ref, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }); err != nil { - t.Fatalf("pause failed: %v", err) - } - paused, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if localSnapshot(paused.GetStatus()) == nil { - t.Fatal("paused actor has no local snapshot") - } - // Drop the first suspend's Checkpoint call so the second suspend's - // atelet traffic is observable in isolation. - tc.fakeAtelet.Reset() - - suspended, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: ref, Options: tt.opts}) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - if tc.fakeAtelet.CheckpointCalled || tc.fakeAtelet.PromoteCalled { - t.Errorf("atelet called (Checkpoint %t, PromoteSnapshot %t), want neither for a paused actor", tc.fakeAtelet.CheckpointCalled, tc.fakeAtelet.PromoteCalled) - } - if diff := cmp.Diff(paused, suspended.GetActor(), protocmp.Transform()); diff != "" { - t.Errorf("SuspendActor changed the paused actor (-paused +returned):\n%s", diff) - } - }) - } -} - -// TestSuspendActor_Mode verifies the snapshot a running actor's suspend leaves -// in each mode. An unset mode suspends asynchronously. -func TestSuspendActor_Mode(t *testing.T) { - tests := []struct { - name string - opts *ateapi.SuspendOptions - wantUploadMode ateletpb.UploadMode - wantLocal bool - // wantNode is the node an async suspend keeps the actor pinned to. - wantNode string - }{ - {name: "unset", opts: nil, wantUploadMode: ateletpb.UploadMode_UPLOAD_MODE_DEFERRED, wantLocal: true, wantNode: "node1"}, - {name: "unspecified", opts: &ateapi.SuspendOptions{}, wantUploadMode: ateletpb.UploadMode_UPLOAD_MODE_DEFERRED, wantLocal: true, wantNode: "node1"}, - {name: "async", opts: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, wantUploadMode: ateletpb.UploadMode_UPLOAD_MODE_DEFERRED, wantLocal: true, wantNode: "node1"}, - {name: "sync", opts: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, wantUploadMode: ateletpb.UploadMode_UPLOAD_MODE_IMMEDIATE, wantLocal: false}, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-suspend-mode-" + tt.name) - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: ref.GetAtespace(), Name: ref.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - suspended, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: ref, Options: tt.opts}) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - tc.fakeAtelet.Lock.Lock() - gotUploadMode := tc.fakeAtelet.CheckpointRequest.GetUploadConfig().GetMode() - tc.fakeAtelet.Lock.Unlock() - if gotUploadMode != tt.wantUploadMode { - t.Errorf("Checkpoint upload mode = %v, want %v", gotUploadMode, tt.wantUploadMode) - } - status := suspended.GetActor().GetStatus() - if got := status.GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state = %v, want %v", got, ateapi.ActorState_ACTOR_STATE_SUSPENDED) - } - // A sync suspend leaves a durable snapshot, an async one a node-local - // snapshot whose upload is still pending. - if gotLocal := localSnapshot(status) != nil; gotLocal != tt.wantLocal { - t.Errorf("has local snapshot = %t, want %t", gotLocal, tt.wantLocal) - } - if gotDurable := durableSnapshot(status).GetOwner() == ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR; gotDurable == tt.wantLocal { - t.Errorf("has completed durable snapshot = %t, want %t", gotDurable, !tt.wantLocal) - } - if got := status.GetAssignedNode(); got != tt.wantNode { - t.Errorf("assigned node = %q, want %q", got, tt.wantNode) - } - }) - } -} - -// TestSuspendActor_SnapshotConflictPreservesState verifies that checkpoint -// conflicts preserve the actor's worker and last completed snapshot, and that -// retries send the same pending snapshot until atelet accepts it. -func TestSuspendActor_SnapshotConflictPreservesState(t *testing.T) { - for _, mode := range []ateapi.DurabilityMode{ - ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS, - ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS, - } { - t.Run(mode.String(), func(t *testing.T) { - ctx := context.Background() - ns := namespaceForTest("ns-suspend-snapshot-conflict") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - workerUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: ref.GetAtespace(), Name: ref.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("first ResumeActor: %v", err) - } - saved, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: ref, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("first SuspendActor: %v", err) - } - waitForWorkerAvailable(t, tc, workerUID) - savedURI := durableSnapshotURI(saved.GetActor().GetStatus()) - assertSnapshotPresent(t, tc, savedURI) - running, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("second ResumeActor: %v", err) - } - - tc.fakeAtelet.Reset() - tc.fakeAtelet.SetObjectStore(tc.objectStore) - tc.fakeAtelet.FailCheckpoint = status.Error(codes.Aborted, "stale snapshot generation") - req := &ateapi.SuspendActorRequest{Actor: ref, Options: &ateapi.SuspendOptions{Mode: mode}} - _, err = tc.client.SuspendActor(ctx, req) - if got := status.Code(err); got != codes.Aborted { - t.Fatalf("SuspendActor error = %v, want Aborted", err) - } - stored, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("GetActor: %v", err) - } - st := stored.GetStatus() - if st.GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDING || st.GetCrash() != nil { - t.Fatalf("status after conflict = %v, want SUSPENDING without a crash", st) - } - if !proto.Equal(st.GetWorkerAssignment(), running.GetActor().GetStatus().GetWorkerAssignment()) { - t.Error("snapshot conflict changed the worker assignment") - } - if got := durableSnapshotURI(st); got != savedURI { - t.Errorf("completed snapshot = %q, want %q", got, savedURI) - } - assertSnapshotPresent(t, tc, savedURI) - worker, err := tc.persistence.GetWorker(ctx, workerUID) - if err != nil { - t.Fatalf("GetWorker: %v", err) - } - if got := worker.GetStatus().GetAllocated().GetActors(); got != 1 { - t.Errorf("allocated actors = %d, want 1", got) - } - var pending *ateapi.Snapshot - for _, snap := range st.GetSnapshots() { - if snap.GetGeneration() == st.GetLastAssignedGeneration() { - pending = snap - } - } - if pending.GetDurableSnapshot().GetState() != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING || pending.GetLocality() != "" { - t.Fatalf("in-progress snapshot = %v, want PENDING without locality", pending) - } - assertSnapshotCollected(t, tc, pending.GetDurableSnapshot().GetObject().GetSnapshotUri()) - - // A repeated conflict must not finalize or allocate another generation. - tc.fakeAtelet.Reset() - tc.fakeAtelet.SetObjectStore(tc.objectStore) - tc.fakeAtelet.FailCheckpoint = status.Error(codes.Aborted, "stale snapshot generation") - _, err = tc.client.SuspendActor(ctx, req) - if status.Code(err) != codes.Aborted { - t.Fatalf("repeated SuspendActor error = %v, want Aborted", err) - } - if !tc.fakeAtelet.CheckpointCalled { - t.Fatal("repeated conflict did not call atelet Checkpoint") - } - conflicted := tc.fakeAtelet.CheckpointRequest.GetSnapshot() - if conflicted.GetSnapshotUuid() != pending.GetUuid() || conflicted.GetGeneration() != pending.GetGeneration() { - t.Errorf("repeated Checkpoint snapshot = %v, want pending snapshot %v", conflicted, pending) - } - repeated, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("GetActor after repeated conflict: %v", err) - } - if !proto.Equal(repeated.GetStatus(), st) { - t.Error("repeated conflict changed the actor's status") - } - assertSnapshotPresent(t, tc, savedURI) - - // Once atelet accepts the request, retry the same persisted snapshot. - tc.fakeAtelet.Reset() - tc.fakeAtelet.SetObjectStore(tc.objectStore) - finished, err := tc.client.SuspendActor(ctx, req) - if err != nil { - t.Fatalf("SuspendActor after conflict cleared: %v", err) - } - if !tc.fakeAtelet.CheckpointCalled { - t.Fatal("retry did not call atelet Checkpoint") - } - retried := tc.fakeAtelet.CheckpointRequest.GetSnapshot() - if got := retried.GetSnapshotUuid(); got != pending.GetUuid() { - t.Errorf("retry snapshot UUID = %q, want %q", got, pending.GetUuid()) - } - if got := retried.GetGeneration(); got != pending.GetGeneration() { - t.Errorf("retry snapshot generation = %d, want %d", got, pending.GetGeneration()) - } - if got := finished.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state after retry = %v, want SUSPENDED", got) - } - if got := finished.GetActor().GetStatus().GetLastAssignedGeneration(); got != pending.GetGeneration() { - t.Errorf("generation after retry = %d, want %d", got, pending.GetGeneration()) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor after retry: %v", err) - } - }) - } -} - -// TestCheckpointFailureCrashes: an atelet Checkpoint error while suspending a -// running actor (in either mode) crashes it, records atelet's error text, and -// releases its worker. -func TestCheckpointFailureCrashes(t *testing.T) { - tests := []struct { - name string - call func(tc *testContext, ref *ateapi.ObjectRef) error - wantMessage string - }{ - { - name: "pause", - call: func(tc *testContext, ref *ateapi.ObjectRef) error { - _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: ref, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}}) - return err - }, - wantMessage: "suspend failed: atelet Checkpoint: injected checkpoint failure", - }, - { - name: "suspend", - call: func(tc *testContext, ref *ateapi.ObjectRef) error { - _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: ref, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - return err - }, - wantMessage: "suspend failed: atelet Checkpoint: injected checkpoint failure", - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-checkpoint-crash-" + tt.name) - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - name := "id1" - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - tc.fakeAtelet.Reset() - tc.fakeAtelet.FailCheckpoint = status.Error(codes.Internal, "injected checkpoint failure") - err := tt.call(tc, ref) - if err == nil { - t.Fatalf("%s succeeded despite failing checkpoint", tt.name) - } - if !tc.fakeAtelet.CheckpointCalled { - t.Error("expected atelet Checkpoint to be called") - } - - crashed, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if crashed.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Fatalf("state after failed checkpoint = %v, want CRASHED", crashed.GetStatus().GetState()) - } - if crashed.GetStatus().GetWorkerAssignment() != nil { - t.Errorf("expected worker assignment to be cleared, got %v", crashed.GetStatus().GetWorkerAssignment()) - } - assertActorCrashStatus(t, tc, name, tt.wantMessage) - - worker, err := tc.persistence.GetWorker(context.Background(), podUID) - if err != nil { - t.Fatalf("GetWorker(%s) failed: %v", podUID, err) - } - if n := worker.GetStatus().GetAllocated().GetActors(); n != 0 { - t.Errorf("expected worker to be released after crash, still holds %d actors", n) - } - }) - } -} - -// TestResumeActor_RelocatesAfterDetach covers the capacity-recovery flow: a -// suspended actor with a local snapshot is placed on the node holding its -// local snapshot. Once atelet reports the snapshot uploaded and detached from -// the node, the node placement is cleared and the actor is scheduled onto a -// worker on a different node. -func TestResumeActor_RelocatesAfterDetach(t *testing.T) { - ns := namespaceForTest("ns-resume-relocate") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - const pinned, relocated = "actor-pinned", "actor-squatter" - for _, name := range []string{pinned, relocated} { - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor(%s) failed: %v", name, err) - } - } - - // The actor under test runs on node1's only worker, then suspends - // asynchronously — which frees that worker but pins the actor to node1 via - // the local snapshot. - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - }); err != nil { - t.Fatalf("ResumeActor(%s) failed: %v", pinned, err) - } - if _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }); err != nil { - t.Fatalf("SuspendActor(%s) failed: %v", pinned, err) - } - paused, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - }) - if err != nil { - t.Fatalf("GetActor(%s) failed: %v", pinned, err) - } - if got := paused.GetStatus().GetAssignedNode(); got != "node1" { - t.Fatalf("paused actor pinned to %q, want node1", got) - } - waitForWorkerAvailable(t, tc, workerName) - - // Another actor takes node1's only worker, so the pinned actor's node is full - // while free capacity exists elsewhere. - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: relocated}, - }); err != nil { - t.Fatalf("ResumeActor(%s) failed: %v", relocated, err) - } - // With no room on any node, the resume fails with ResourceExhausted. - _, err = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - }) - assertGrpcError(t, err, codes.ResourceExhausted, "no worker has room for the actor") - createWorkerPod(t, tc, ns, "worker-2", "node2", "pool1") - setupAteletOnNode(t, tc, "atelet-node2", "node2") - - // node1's atelet reports the local snapshot uploaded and detached: a report - // with only latest_durable. - ls := localSnapshot(paused.GetStatus()) - if err := tc.service.ApplyActorSnapshotState(context.Background(), resources.ActorRefFromActor(paused), paused.GetMetadata().GetUid(), "node1", &ateapi.ActorSnapshotState{ - LatestDurable: &ateapi.SnapshotReport{ - Uuid: ls.GetUuid(), - Generation: ls.GetGeneration(), - Fidelity: ls.GetFidelity(), - Object: ls.GetDurableSnapshot().GetObject(), - }, - }); err != nil { - t.Fatalf("ApplyActorSnapshotState(%s) failed: %v", pinned, err) - } - detached, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - }) - if err != nil { - t.Fatalf("GetActor(%s) failed: %v", pinned, err) - } - if ls := localSnapshot(detached.GetStatus()); ls != nil { - t.Fatalf("local snapshot = %v, want cleared so the actor can be scheduled anywhere", ls) - } - if got := detached.GetStatus().GetAssignedNode(); got != "" { - t.Fatalf("detached actor pinned to %q, want no node", got) - } - - // Resume should succeed now and the actor scheduled on node2. - resumed, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - }) - if err != nil { - t.Fatalf("ResumeActor(%s) after detach failed: %v", pinned, err) - } - if got := resumed.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-2" { - t.Errorf("resumed onto worker %q, want worker-2 (the worker on node2)", got) - } - worker, err := tc.persistence.GetWorker(context.Background(), resumed.GetActor().GetStatus().GetWorkerAssignment().GetWorker().GetName()) - if err != nil { - t.Fatalf("GetWorker(worker-2) failed: %v", err) - } - if got := worker.GetNodeName(); got != "node2" { - t.Errorf("worker-2 node = %q, want node2", got) - } -} - -// TestResumeActor_DetachesFromFullNode resumes a suspended actor whose node is -// full while another has room: it is detached and restored on the other node. -func TestResumeActor_DetachesFromFullNode(t *testing.T) { - ns := namespaceForTest("ns-resume-detach") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - const pinned, squatter = "actor-pinned", "actor-squatter" - for _, name := range []string{pinned, squatter} { - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor(%s) failed: %v", name, err) - } - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - }); err != nil { - t.Fatalf("ResumeActor(%s) failed: %v", pinned, err) - } - if _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }); err != nil { - t.Fatalf("SuspendActor(%s) failed: %v", pinned, err) - } - paused, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - }) - if err != nil { - t.Fatalf("GetActor(%s) failed: %v", pinned, err) - } - ls := localSnapshot(paused.GetStatus()) - if ls == nil || paused.GetStatus().GetAssignedNode() != "node1" { - t.Fatalf("paused actor = %v, want a local snapshot on node1", paused.GetStatus()) - } - waitForWorkerAvailable(t, tc, workerName) - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: squatter}, - }); err != nil { - t.Fatalf("ResumeActor(%s) failed: %v", squatter, err) - } - createWorkerPod(t, tc, ns, "worker-2", "node2", "pool1") - setupAteletOnNode(t, tc, "atelet-node2", "node2") - - resumed, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: pinned}, - }) - if err != nil { - t.Fatalf("ResumeActor(%s) on a full node failed: %v", pinned, err) - } - if got := resumed.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-2" { - t.Errorf("resumed onto worker %q, want worker-2 (the worker on node2)", got) - } - tc.fakeAtelet.Lock.Lock() - detach := proto.CloneOf(tc.fakeAtelet.DetachRequest) - tc.fakeAtelet.Lock.Unlock() - if got := detach.GetActorUid(); got != paused.GetMetadata().GetUid() { - t.Errorf("DetachActor actor_uid = %q, want %q", got, paused.GetMetadata().GetUid()) - } - restore := tc.fakeAtelet.lastRestoreRequest() - if got := restore.GetSnapshot().GetSnapshotUuid(); got != ls.GetUuid() { - t.Errorf("Restore snapshot = %q, want the detached snapshot %q", got, ls.GetUuid()) - } - if got := restore.GetSnapshot().GetObject().GetSnapshotUri(); got != ls.GetDurableSnapshot().GetObject().GetSnapshotUri() { - t.Errorf("Restore snapshot URI = %q, want %q", got, ls.GetDurableSnapshot().GetObject().GetSnapshotUri()) - } -} - -// TestLifecycleOpPoolAttributesOnSuccess is the regression test for #957: a -// successful sync or async suspend must stamp the pool it ran on. Both recorded -// the histogram from a defer that read the finalized record, whose assignment -// the finalize step had already cleared, so the pair landed only on failures. -func TestLifecycleOpPoolAttributesOnSuccess(t *testing.T) { - tests := []struct { - name string - op string - // run performs the operation on an actor that is already RUNNING. - run func(t *testing.T, tc *testContext, actor *ateapi.ObjectRef) - }{ - { - name: "suspend", - op: ateattr.OperationSuspend, - run: func(t *testing.T, tc *testContext, actor *ateapi.ObjectRef) { - t.Helper() - if _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: actor, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}); err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - }, - }, - { - name: "pause", - op: ateattr.OperationSuspend, - run: func(t *testing.T, tc *testContext, actor *ateapi.ObjectRef) { - t.Helper() - if _, err := tc.client.SuspendActor(context.Background(), &ateapi.SuspendActorRequest{Actor: actor, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}}); err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - }, - }, - } - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-lifecycle-pool-" + tt.name) - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: actorRef.GetAtespace(), Name: actorRef.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - tt.run(t, tc, actorRef) - - attrs := lifecycleOpAttributes(t, tc, tt.op) - if got, ok := attrs.Value(ateattr.WorkerPoolNamespaceKey); !ok || got.AsString() != ns { - t.Errorf("%s = %q (present: %v), want %q", ateattr.WorkerPoolNamespaceKey, got.AsString(), ok, ns) - } - if got, ok := attrs.Value(ateattr.WorkerPoolNameKey); !ok || got.AsString() != "pool1" { - t.Errorf("%s = %q (present: %v), want %q", ateattr.WorkerPoolNameKey, got.AsString(), ok, "pool1") - } - // error.type's absence marks a success, so its presence would mean the - // datapoint under test is not the happy path. - if _, ok := attrs.Value(ateattr.ErrorTypeKey); ok { - t.Errorf("%s is set on the %s datapoint, want the successful operation", ateattr.ErrorTypeKey, tt.op) - } - }) - } -} - -// lifecycleOpAttributes returns the attribute set of the single -// ate.actor.lifecycle.operation.duration datapoint recorded for op. -func lifecycleOpAttributes(t *testing.T, tc *testContext, op string) attribute.Set { - t.Helper() - var rm metricdata.ResourceMetrics - if err := tc.metricReader.Collect(context.Background(), &rm); err != nil { - t.Fatalf("collect metrics: %v", err) - } - var got []attribute.Set - for _, sm := range rm.ScopeMetrics { - for _, m := range sm.Metrics { - if m.Name != "ate.actor.lifecycle.operation.duration" { - continue - } - hist, ok := m.Data.(metricdata.Histogram[float64]) - if !ok { - t.Fatalf("%s data type = %T, want a float64 histogram", m.Name, m.Data) - } - for _, dp := range hist.DataPoints { - if v, ok := dp.Attributes.Value(ateattr.ActorOperationNameKey); ok && v.AsString() == op { - got = append(got, dp.Attributes) - } - } - } - } - if len(got) != 1 { - t.Fatalf("datapoints for %s = %d (%v), want exactly one", op, len(got), got) - } - return got[0] -} - -// TestCreateActor_RejectsUnknownRequestFields checks that a request carrying a -// field this binary has no descriptor for is refused by the server-wide -// interceptor before it reaches the handler. -func TestCreateActor_RejectsUnknownRequestFields(t *testing.T) { - ns := namespaceForTest("ns-create-unknown-field") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - req := &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }} - unknown := protowire.AppendTag(nil, 9999, protowire.VarintType) - req.ProtoReflect().SetUnknown(protowire.AppendVarint(unknown, 42)) - - _, err := tc.client.CreateActor(context.Background(), req) - assertGrpcError(t, err, codes.InvalidArgument, "request: Invalid value: unknown field with protobuf tag 9999") -} - -func TestMintActorJWT_Success(t *testing.T) { - ns := namespaceForTest("ns-mintactorjwt-success") - - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - createResp, err := tc.client.CreateActor(t.Context(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "id1", - }, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"tier": "free"}}, - Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_RUNNING}, - }, - }) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - mintResp, err := tc.client.MintActorJwt(t.Context(), &ateapi.MintActorJwtRequest{ - Actor: &ateapi.ObjectRef{ - Atespace: createResp.GetMetadata().GetAtespace(), - Name: createResp.GetMetadata().GetName(), - }, - Audiences: []string{"foo"}, - ExpirationSeconds: 1800, - }) - if err != nil { - t.Fatalf("Error while calling MintActorJwt: %v", err) - } - - segments := strings.Split(mintResp.GetActorJwt(), ".") - if len(segments) != 3 { - t.Fatalf("actor JWT has %d segments, want 3", len(segments)) - } - var header struct { - Type string `json:"typ"` - } - decodeJWTSegment(t, segments[0], &header) - if header.Type != "JWT" { - t.Errorf("header typ = %q, want %q", header.Type, "JWT") - } - var claims actoridjwt.WireClaims - decodeJWTSegment(t, segments[1], &claims) - if claims.Issuer != testActorJWTIssuer { - t.Errorf("iss = %q, want %q", claims.Issuer, testActorJWTIssuer) - } - if want := "actor/" + testAtespace + "/id1"; claims.Subject != want { - t.Errorf("sub = %q, want %q", claims.Subject, want) - } - kind, substrate, ok := claims.Substrate() - if !ok || kind != actoridjwt.KindActor { - t.Fatalf("token kind = %v (ok %v), want KindActor under actor.ate.dev", kind, ok) - } - if want := createResp.GetMetadata().GetUid(); substrate.ActorUID != want { - t.Errorf("actor.ate.dev.actorUID = %q, want the stored actor's %q", substrate.ActorUID, want) - } - assertActorJWTLifetime(t, mintResp, claims, 30*time.Minute) -} - -// assertActorJWTLifetime checks that expire_time matches the exp claim and that -// the token is valid for want after it was issued. -func assertActorJWTLifetime(t *testing.T, resp *ateapi.MintActorJwtResponse, claims actoridjwt.WireClaims, want time.Duration) { - t.Helper() - if got, exp := resp.GetExpireTime().AsTime(), time.Unix(int64(claims.Expiration), 0); !got.Equal(exp) { - t.Errorf("expire_time = %v, want the exp claim %v", got, exp) - } - if got := time.Duration(claims.Expiration-claims.IssuedAt) * time.Second; got != want { - t.Errorf("exp - iat = %v, want %v", got, want) - } -} - -// decodeJWTSegment base64url-decodes one JWT segment and unmarshals its JSON into v. -func decodeJWTSegment(t *testing.T, segment string, v any) { - t.Helper() - raw, err := base64.RawURLEncoding.DecodeString(segment) - if err != nil { - t.Fatalf("decoding JWT segment: %v", err) - } - if err := json.Unmarshal(raw, v); err != nil { - t.Fatalf("unmarshaling JWT segment: %v", err) - } -} - -// TestRevertActor returns a running actor to the snapshot its last suspend -// wrote, without taking a new one. -func TestRevertActor(t *testing.T) { - ns := namespaceForTest("ns-revert") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - const name = "id1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Run and suspend once, so the revert has a snapshot to return the actor to. - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - suspended, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - snapshotURI := durableSnapshotURI(suspended.GetActor().GetStatus()) - if snapshotURI == "" { - t.Fatalf("SuspendActor wrote no external snapshot: %v", suspended) - } - - // Run it again, then throw that second execution away. - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("second ResumeActor failed: %v", err) - } - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.CheckpointCalled = false - tc.fakeAtelet.Lock.Unlock() - - reverted, err := tc.client.RevertActor(ctx, &ateapi.RevertActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("RevertActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - - got := reverted.GetActor().GetStatus() - if got.GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state = %v, want SUSPENDED", got.GetState()) - } - if uri := durableSnapshotURI(got); uri != snapshotURI { - t.Errorf("external snapshot = %q, want it untouched at %q", uri, snapshotURI) - } - assertSnapshotPresent(t, tc, snapshotURI) - if got.GetWorkerAssignment() != nil { - t.Errorf("worker assignment = %v, want nil", got.GetWorkerAssignment()) - } - if !tc.fakeAtelet.TerminateCalled { - t.Errorf("expected atelet Terminate to be called, the workload was still running") - } - // The difference from suspend: the execution is discarded, not captured. - if tc.fakeAtelet.CheckpointCalled { - t.Errorf("RevertActor checkpointed the workload, want the execution discarded") - } -} - -func TestRevertActor_UnreachableNode(t *testing.T) { - const sourceNode = "node-revert-source" - const sourceAtelet = "atelet-revert-source" - for _, tt := range []struct { - name string - missing bool - pending bool - }{ - {name: "missing atelet", missing: true}, - {name: "unavailable atelet"}, - {name: "pending checkpoint remains pinned", pending: true}, - } { - t.Run(tt.name, func(t *testing.T) { - ns := namespaceForTest("ns-revert-unreachable") - tc := setupTest(t, ns) - t.Cleanup(tc.cleanup) - ctx := context.Background() - createTemplate(t, tc, ns) - worker := createWorkerPod(t, tc, ns, "worker-1", sourceNode, "pool1") - setupAteletOnNode(t, tc, sourceAtelet, sourceNode) - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.KeepCheckpointLocal = true - tc.fakeAtelet.Lock.Unlock() - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: ref.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatal(err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatal(err) - } - mode := ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS - if tt.pending { - mode = ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS - } - suspended, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: ref, Options: &ateapi.SuspendOptions{Mode: mode}, - }) - if err != nil { - t.Fatal(err) - } - snap := proto.CloneOf(localSnapshot(suspended.GetActor().GetStatus())) - if snap == nil || suspended.GetActor().GetStatus().GetAssignedNode() != sourceNode { - t.Fatalf("suspended actor has no retained checkpoint: %v", suspended.GetActor().GetStatus()) - } - waitForWorkerAvailable(t, tc, worker) - deleteWorkerPod(t, tc, ns, "worker-1") - if tt.missing { - if err := tc.k8sClient.CoreV1().Pods(installdefaults.SystemNamespace).Delete(ctx, sourceAtelet, metav1.DeleteOptions{GracePeriodSeconds: ptr.To[int64](0)}); err != nil { - t.Fatal(err) - } - if err := wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 5*time.Second, true, func(context.Context) (bool, error) { - pods, err := tc.ateletIndexer.ByIndex(byNode, sourceNode) - return len(pods) == 0, err - }); err != nil { - t.Fatal(err) - } - } else { - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailTerminate = status.Error(codes.Unavailable, "node unavailable") - tc.fakeAtelet.Lock.Unlock() - } - reverted, err := tc.client.RevertActor(ctx, &ateapi.RevertActorRequest{Actor: ref}) - if tt.pending { - if status.Code(err) != codes.Unavailable { - t.Fatalf("RevertActor = %v, want Unavailable", err) - } - stored, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatal(err) - } - if stored.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_REVERTING || - stored.GetStatus().GetAssignedNode() != sourceNode || !proto.Equal(localSnapshot(stored.GetStatus()), snap) { - t.Fatalf("pending checkpoint changed: %v", stored.GetStatus()) - } - return - } - if err != nil { - t.Fatalf("RevertActor on unreachable node: %v", err) - } - got := reverted.GetActor().GetStatus() - if got.GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED || got.GetAssignedNode() != "" || - got.GetWorkerAssignment() != nil || localSnapshot(got) != nil { - t.Fatalf("reverted status = %v, want unbound SUSPENDED", got) - } - createWorkerPod(t, tc, ns, "worker-2", "node2", "pool1") - setupAteletOnNode(t, tc, "atelet-node2", "node2") - resumed, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("ResumeActor after revert: %v", err) - } - if resumed.GetActor().GetStatus().GetAssignedNode() != "node2" { - t.Fatalf("resumed on wrong node: %v", resumed.GetActor().GetStatus()) - } - restore := tc.fakeAtelet.lastRestoreRequest().GetSnapshot() - if restore.GetSnapshotUuid() != snap.GetUuid() || restore.GetGeneration() != snap.GetGeneration() || - restore.GetObject().GetSnapshotUri() != snap.GetDurableSnapshot().GetObject().GetSnapshotUri() { - t.Fatalf("restored snapshot = %v, want retained checkpoint %v", restore, snap) - } - assertSnapshotPresent(t, tc, snap.GetDurableSnapshot().GetObject().GetSnapshotUri()) - }) - } -} - -// TestRevertActor_FromPaused reverts a suspended actor with a local snapshot -// back to its external snapshot, discarding the local snapshot info on the -// actor record. -func TestRevertActor_FromPaused(t *testing.T) { - ns := namespaceForTest("ns-revert-paused") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - const name = "id1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - suspended, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - snapshotURI := durableSnapshotURI(suspended.GetActor().GetStatus()) - if snapshotURI == "" { - t.Fatalf("SuspendActor wrote no external snapshot: %v", suspended) - } - - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("second ResumeActor failed: %v", err) - } - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}}); err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.TerminateCalled = false - tc.fakeAtelet.CheckpointCalled = false - tc.fakeAtelet.Lock.Unlock() - - reverted, err := tc.client.RevertActor(ctx, &ateapi.RevertActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("RevertActor failed: %v", err) - } - - got := reverted.GetActor().GetStatus() - if got.GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state = %v, want SUSPENDED", got.GetState()) - } - if uri := durableSnapshotURI(got); uri != snapshotURI { - t.Errorf("external snapshot = %q, want it untouched at %q", uri, snapshotURI) - } - assertSnapshotPresent(t, tc, snapshotURI) - if ls := localSnapshot(got); ls != nil { - t.Errorf("local snapshot info = %v, want nil", ls) - } - if got.GetWorkerAssignment() != nil { - t.Errorf("worker assignment = %v, want nil", got.GetWorkerAssignment()) - } - if got.GetAssignedNode() != "" { - t.Errorf("assigned node = %q, want empty", got.GetAssignedNode()) - } - if !tc.fakeAtelet.TerminateCalled { - t.Errorf("expected Terminate call to clean up assigned node for paused actor") - } else if gotUID := tc.fakeAtelet.TerminateRequest.GetWorkerPodUid(); gotUID != "" { - t.Errorf("TerminateRequest.WorkerPodUid = %q, want empty for paused actor", gotUID) - } - if tc.fakeAtelet.CheckpointCalled { - t.Errorf("RevertActor checkpointed the workload, want the execution discarded") - } -} - -// TestRevertActor_FromCrashed recovers a crashed actor back to SUSPENDED at its -// last external snapshot so it can be resumed again. -func TestRevertActor_FromCrashed(t *testing.T) { - ns := namespaceForTest("ns-revert-crashed") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - const name = "id1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - suspended, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerName) - snapshotURI := durableSnapshotURI(suspended.GetActor().GetStatus()) - if snapshotURI == "" { - t.Fatalf("SuspendActor wrote no external snapshot: %v", suspended) - } - - // Resume onto worker-1, then delete the worker pod so the actor crashes. - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}); err != nil { - t.Fatalf("second ResumeActor failed: %v", err) - } - deleteWorkerPod(t, tc, ns, "worker-1") - - crashed, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - if crashed.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Fatalf("state = %v, want CRASHED", crashed.GetStatus().GetState()) - } - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.TerminateCalled = false - tc.fakeAtelet.CheckpointCalled = false - tc.fakeAtelet.Lock.Unlock() - - reverted, err := tc.client.RevertActor(ctx, &ateapi.RevertActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("RevertActor from CRASHED failed: %v", err) - } - - got := reverted.GetActor().GetStatus() - if got.GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state = %v, want SUSPENDED", got.GetState()) - } - if uri := durableSnapshotURI(got); uri != snapshotURI { - t.Errorf("external snapshot = %q, want it untouched at %q", uri, snapshotURI) - } - assertSnapshotPresent(t, tc, snapshotURI) - if got.GetWorkerAssignment() != nil { - t.Errorf("worker assignment = %v, want nil", got.GetWorkerAssignment()) - } - if got.GetAssignedNode() != "" { - t.Errorf("assigned node = %q, want empty", got.GetAssignedNode()) - } - if !tc.fakeAtelet.TerminateCalled { - t.Errorf("expected Terminate call to clean up assigned node for crashed actor") - } else if gotUID := tc.fakeAtelet.TerminateRequest.GetWorkerPodUid(); gotUID != "" { - t.Errorf("TerminateRequest.WorkerPodUid = %q, want empty for crashed actor", gotUID) - } - if tc.fakeAtelet.CheckpointCalled { - t.Errorf("RevertActor checkpointed the workload, want the execution discarded") - } - - // Verify the recovered actor can be resumed onto a new worker. - createWorkerPod(t, tc, ns, "worker-2", "node1", "pool1") - resumed, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("ResumeActor after revert from CRASHED failed: %v", err) - } - if resumed.GetActor().GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("resumed state = %v, want RUNNING", resumed.GetActor().GetStatus().GetState()) - } -} - -// TestRevertActor_TerminateFailureLeavesActorReverting verifies that an atelet -// error while terminating the discarded execution leaves the actor REVERTING on -// its worker, and that the next revert terminates it and finishes. -func TestRevertActor_TerminateFailureLeavesActorReverting(t *testing.T) { - ns := namespaceForTest("ns-revert-terminate-fail") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - const name = "id1" - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - actorRef := resources.ActorRef{Atespace: testAtespace, Name: name} - - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailTerminate = status.Error(codes.Internal, "injected terminate failure") - tc.fakeAtelet.Lock.Unlock() - _, err := tc.client.RevertActor(ctx, &ateapi.RevertActorRequest{Actor: ref}) - if got := status.Code(err); got != codes.Internal { - t.Fatalf("RevertActor status code = %v, want %v (err: %v)", got, codes.Internal, err) - } - - actor, err := tc.persistence.GetActor(ctx, actorRef) - if err != nil { - t.Fatalf("failed to get actor from store: %v", err) - } - if got := actor.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_REVERTING { - t.Errorf("state after failed terminate = %v, want REVERTING", got) - } - if crash := actor.GetStatus().GetCrash(); crash != nil { - t.Errorf("crash recorded after failed terminate: %v", crash) - } - if got := actor.GetStatus().GetWorkerAssignment().GetWorker().GetName(); got != podUID { - t.Errorf("assigned worker = %q, want %q kept for the retry", got, podUID) - } - - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailTerminate = nil - tc.fakeAtelet.TerminateCalled = false - tc.fakeAtelet.Lock.Unlock() - reverted, err := tc.client.RevertActor(ctx, &ateapi.RevertActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("second RevertActor failed: %v", err) - } - if got := reverted.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state after retry = %v, want SUSPENDED", got) - } - if got := reverted.GetActor().GetStatus().GetWorkerAssignment(); got != nil { - t.Errorf("worker assignment after retry = %v, want nil", got) - } - tc.fakeAtelet.Lock.Lock() - terminated := tc.fakeAtelet.TerminateCalled - tc.fakeAtelet.Lock.Unlock() - if !terminated { - t.Error("retried revert did not call atelet Terminate") - } -} - -// TestDeleteActor_TerminateFailureLeavesActorDeleting verifies that an atelet -// error while terminating a running actor leaves it DELETING on its worker, -// and that the next delete terminates it and removes it. -func TestDeleteActor_TerminateFailureLeavesActorDeleting(t *testing.T) { - ns := namespaceForTest("ns-delete-terminate-fail") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - const name = "id1" - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - actorRef := resources.ActorRef{Atespace: testAtespace, Name: name} - - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailTerminate = status.Error(codes.Internal, "injected terminate failure") - tc.fakeAtelet.Lock.Unlock() - if _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref}); err == nil { - t.Fatal("DeleteActor succeeded despite failing terminate") - } - - actor, err := tc.persistence.GetActor(ctx, actorRef) - if err != nil { - t.Fatalf("failed to get actor from store: %v", err) - } - if got := actor.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_DELETING { - t.Errorf("state after failed terminate = %v, want DELETING", got) - } - if crash := actor.GetStatus().GetCrash(); crash != nil { - t.Errorf("crash recorded after failed terminate: %v", crash) - } - if got := actor.GetStatus().GetWorkerAssignment().GetWorker().GetName(); got != podUID { - t.Errorf("assigned worker = %q, want %q kept for the retry", got, podUID) - } - - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.FailTerminate = nil - tc.fakeAtelet.TerminateCalled = false - tc.fakeAtelet.Lock.Unlock() - if _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref}); err != nil { - t.Fatalf("second DeleteActor failed: %v", err) - } - if _, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}); status.Code(err) != codes.NotFound { - t.Errorf("GetActor after retried delete err = %v, want NotFound", err) - } - tc.fakeAtelet.Lock.Lock() - terminated := tc.fakeAtelet.TerminateCalled - tc.fakeAtelet.Lock.Unlock() - if !terminated { - t.Error("retried delete did not call atelet Terminate") - } -} - -// assertActorCrashStatus reads the actor through the API and checks the crash it records. -func assertActorCrashStatus(t *testing.T, tc *testContext, name, wantMessage string) { - t.Helper() - actor, err := tc.client.GetActor(context.Background(), &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - crash := actor.GetStatus().GetCrash() - if crash == nil { - t.Fatalf("Crash = nil, want message %q", wantMessage) - } - if crash.GetMessage() != wantMessage { - t.Errorf("Crash.Message = %q, want %q", crash.GetMessage(), wantMessage) - } - if crash.GetCrashTime() == nil { - t.Error("Crash.CrashTime = nil, want set") - } -} - -// TestRevertActor_RejectsSuspended pins the rejection a lost race produces: a -// suspend that won left the actor SUSPENDED, and reporting success there would -// claim the opposite of what the revert asked for. -func TestRevertActor_RejectsSuspended(t *testing.T) { - ns := namespaceForTest("ns-revert-suspended") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - ctx := context.Background() - const name = "id1" - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: name} - - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - _, err := tc.client.RevertActor(ctx, &ateapi.RevertActorRequest{Actor: actorRef}) - if status.Code(err) != codes.FailedPrecondition { - t.Fatalf("RevertActor = %v, want FailedPrecondition", err) - } -} - -func TestRevertActor_NotFound(t *testing.T) { - ns := namespaceForTest("ns-revert-missing") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.RevertActor(context.Background(), &ateapi.RevertActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "nope"}, - }) - if status.Code(err) != codes.NotFound { - t.Fatalf("RevertActor = %v, want NotFound", err) - } -} - -func TestDeleteActor_Preconditions(t *testing.T) { - ns := namespaceForTest("ns-delete-preconditions") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - tmpl := createTemplate(t, tc, ns) - actorRef := resources.ActorRef{Atespace: testAtespace, Name: "id1"} - ref := actorRef.ToObjectRef() - create := func() *ateapi.Actor { - created, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: actorRef.Atespace, Name: actorRef.Name}, - ActorTemplate: resources.ActorTemplateRefFromActorTemplate(tmpl).ToObjectRef(), - }}) - if err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - return created - } - del := func(opts *ateapi.DeleteOptions) error { - _, err := tc.client.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref, Options: opts}) - return err - } - - actor := create() - uid, version := actor.GetMetadata().GetUid(), actor.GetMetadata().GetVersion() - - assertGrpcError(t, del(&ateapi.DeleteOptions{Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: uid, Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID}), codes.Aborted, "Actor "+actorRef.String()+" does not have uid "+foreignUID) - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID, Version: version}), codes.Aborted, "Actor "+actorRef.String()+" does not have uid "+foreignUID) - got, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("a refused delete removed the actor: %v", err) - } - if state := got.GetStatus().GetState(); state != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Fatalf("state after the refused deletes = %v, want SUSPENDED", state) - } - - if err := del(&ateapi.DeleteOptions{Version: version}); err != nil { - t.Fatalf("DeleteActor with the matching version: %v", err) - } - actor = create() - if err := del(&ateapi.DeleteOptions{Uid: actor.GetMetadata().GetUid()}); err != nil { - t.Fatalf("DeleteActor with the matching uid: %v", err) - } - actor = create() - if err := del(&ateapi.DeleteOptions{Uid: actor.GetMetadata().GetUid(), Version: actor.GetMetadata().GetVersion()}); err != nil { - t.Fatalf("DeleteActor with both guards: %v", err) - } - _, err = tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - assertGrpcError(t, err, codes.NotFound, "Actor "+actorRef.String()+" not found") -} - -// reportWorkerRuntime writes defaultRT and restorableRTs to workerName's status -// as its one sandbox class and waits for the worker cache to observe the update. -func reportWorkerRuntime(t *testing.T, tc *testContext, workerName string, defaultRT *ateapi.ActorSandboxRuntime, restorableRTs ...*ateapi.ActorSandboxRuntime) { - t.Helper() - ctx := context.Background() - cur, err := tc.persistence.GetWorker(ctx, workerName) - if err != nil { - t.Fatalf("GetWorker(%s): %v", workerName, err) - } - want := workerSandboxClasses(defaultRT, restorableRTs...) - if _, err := tc.persistence.UpdateWorker(ctx, workerName, store.PreconditionFrom(cur), func(toUpdate *ateapi.Worker) error { - toUpdate.Status.SandboxClasses = workerSandboxClasses(defaultRT, restorableRTs...) - return nil - }); err != nil { - t.Fatalf("UpdateWorker(%s): %v", workerName, err) - } - if err := wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 5*time.Second, true, func(context.Context) (bool, error) { - got, err := tc.workerCache.Worker(workerName) - return err == nil && - slices.EqualFunc(got.GetStatus().GetSandboxClasses(), want, func(a, b *ateapi.WorkerSandboxClass) bool { return proto.Equal(a, b) }), nil - }); err != nil { - t.Fatalf("worker %s runtime never reached worker cache: %v", workerName, err) - } -} - -// TestResumeActor_SandboxRuntimePlacementAndFallback exercises the end-to-end -// runtime stamping, placement, and fallback lifecycle across two workers -// advertising different SandboxRuntimes: -// 1. CreateActor -> ResumeActor -> SuspendActor stamps the worker's runtime -// onto WorkerAssignment and then onto the resulting Snapshot. -// 2. A subsequent ResumeActor places the actor onto the runtime-compatible -// worker and restores at full MEMORY fidelity when that worker has room. -// 3. When the compatible worker is full, ResumeActor falls back to the other -// worker, downgrades the restore to ROOTFS whether the snapshot is the -// actor's own or a borrowed golden, and re-stamps the new worker's runtime -// on the next SuspendActor. -// 4. When the other worker advertises the snapshot's runtime in -// restorable_runtimes, ResumeActor restores at full MEMORY fidelity, -// records the matched restorable runtime on WorkerAssignment, and preserves -// that stamp through async SuspendActor and sync SuspendActor on an -// already-SUSPENDED actor. -func TestResumeActor_SandboxRuntimePlacementAndFallback(t *testing.T) { - ns := namespaceForTest("ns-runtime-fallback") - tc := setupTest(t, ns) - defer tc.cleanup() - - ctx := context.Background() - tmpl := createTemplate(t, tc, ns) - - rtA := &ateapi.ActorSandboxRuntime{ - SandboxClass: "gvisor", - Version: &ateapi.VersionedSandboxCompat{ - SchemaVersion: "v1", - Attributes: []*ateapi.AttributeEntry{ - {Key: "architecture", Value: "amd64"}, - {Key: "sandbox_bundle_hash", Value: "hash-a"}, - }, - }, - } - rtB := &ateapi.ActorSandboxRuntime{ - SandboxClass: "gvisor", - Version: &ateapi.VersionedSandboxCompat{ - SchemaVersion: "v1", - Attributes: []*ateapi.AttributeEntry{ - {Key: "architecture", Value: "amd64"}, - {Key: "sandbox_bundle_hash", Value: "hash-b"}, - }, - }, - } - - // Start with worker-a advertising rtA so the initial resume lands on rtA. - workerA := createWorkerPod(t, tc, ns, "worker-a", "node1", "pool1") - reportWorkerRuntime(t, tc, workerA, rtA) - - actorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "actor-1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - resumed1, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("initial ResumeActor failed: %v", err) - } - if got := resumed1.GetActor().GetStatus().GetWorkerAssignment().GetSandboxRuntime(); !proto.Equal(got, rtA) { - t.Fatalf("initial WorkerAssignment.SandboxRuntime = %v, want %v", got, rtA) - } - - suspended1, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("first SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerA) - if got := durableSnapshot(suspended1.GetActor().GetStatus()).GetSandboxRuntime(); !proto.Equal(got, rtA) { - t.Fatalf("first Snapshot.SandboxRuntime = %v, want %v", got, rtA) - } - - // Add worker-b advertising an incompatible runtime (rtB). With both workers - // idle, resuming actor-1 must select worker-a and restore at MEMORY fidelity. - workerB := createWorkerPod(t, tc, ns, "worker-b", "node1", "pool1") - reportWorkerRuntime(t, tc, workerB, rtB) - - resumed2, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("second ResumeActor failed: %v", err) - } - if got := resumed2.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-a" { - t.Fatalf("second ResumeActor placed on %q, want worker-a", got) - } - if got := resumed2.GetActor().GetStatus().GetWorkerAssignment().GetSandboxRuntime(); !proto.Equal(got, rtA) { - t.Fatalf("second WorkerAssignment.SandboxRuntime = %v, want %v", got, rtA) - } - if got := tc.fakeAtelet.lastRestoreRequest().GetSnapshot().GetFidelity(); got != ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY { - t.Fatalf("second RestoreRequest.Fidelity = %v, want MEMORY", got) - } - - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}); err != nil { - t.Fatalf("second SuspendActor failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerA) - - // Tag actor-1's rtA snapshot and occupy worker-a with a blocker actor seeded - // from that tag so the rtA worker is at capacity. - tagRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "tag-rt-a"} - tag, err := tc.client.CreateTag(ctx, &ateapi.CreateTagRequest{ - Tag: &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "tag-rt-a"}, - SourceActor: actorRef, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - }, - }) - if err != nil { - t.Fatalf("CreateTag failed: %v", err) - } - if got := tag.GetStatus().GetSnapshot().GetSandboxRuntime(); !proto.Equal(got, rtA) { - t.Fatalf("Tag.Snapshot.SandboxRuntime = %v, want %v", got, rtA) - } - - blockerRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "blocker"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "blocker"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - SourceTag: tagRef, - }}); err != nil { - t.Fatalf("CreateActor(blocker) failed: %v", err) - } - blockerResumed, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: blockerRef}) - if err != nil { - t.Fatalf("ResumeActor(blocker) failed: %v", err) - } - if got := blockerResumed.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-a" { - t.Fatalf("blocker placed on %q, want worker-a", got) - } - - // With worker-a full, resuming actor-1 must fall back to worker-b, downgrade - // the restore to ROOTFS fidelity, and re-stamp rtB on the next suspend. - resumed3, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: actorRef}) - if err != nil { - t.Fatalf("fallback ResumeActor failed: %v", err) - } - if got := resumed3.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-b" { - t.Fatalf("fallback ResumeActor placed on %q, want worker-b", got) - } - if got := resumed3.GetActor().GetStatus().GetWorkerAssignment().GetSandboxRuntime(); !proto.Equal(got, rtB) { - t.Fatalf("fallback WorkerAssignment.SandboxRuntime = %v, want %v", got, rtB) - } - if got := tc.fakeAtelet.lastRestoreRequest().GetSnapshot().GetFidelity(); got != ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS { - t.Fatalf("fallback RestoreRequest.Fidelity = %v, want ROOTFS", got) - } - - suspended3, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: actorRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor after fallback failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerB) - if got := durableSnapshot(suspended3.GetActor().GetStatus()).GetSandboxRuntime(); !proto.Equal(got, rtB) { - t.Fatalf("Snapshot.SandboxRuntime after fallback suspend = %v, want %v", got, rtB) - } - - // Point the template's golden tag at a golden snapshot stamped with rtA and - // verify that a newly created actor borrowing the golden snapshot, when - // worker-a is full and it falls back onto worker-b, restores the golden at - // ROOTFS fidelity like any other durable snapshot rather than cold-booting. - goldenSnap := newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, tmpl.GetMetadata().GetUid(), goldenSnapshotName, goldenSnapshotURI(t)) - goldenSnap.SandboxRuntime = proto.Clone(rtA).(*ateapi.ActorSandboxRuntime) - stampedGoldenTag, err := tc.persistence.CreateTag(ctx, &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "golden-rt-a"}, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: tmpl.GetMetadata().GetUid()}, - Scope: ateapi.TagScope_TAG_SCOPE_PUBLISHED, - Status: &ateapi.TagStatus{ - Snapshot: goldenSnap, - ActorTemplateUid: tmpl.GetMetadata().GetUid(), - }, - }) - if err != nil { - t.Fatalf("CreateTag(golden-rt-a): %v", err) - } - curTmpl, err := tc.persistence.GetActorTemplate(ctx, resources.ActorTemplateRefFromActorTemplate(tmpl)) - if err != nil { - t.Fatalf("GetActorTemplate: %v", err) - } - if _, err := tc.persistence.UpdateActorTemplate(ctx, resources.ActorTemplateRefFromActorTemplate(curTmpl), store.PreconditionFrom(curTmpl), func(dbTemplate *ateapi.ActorTemplate) error { - dbTemplate.Status.GoldenSnapshotStatus.GoldenTag = resources.TagRefFromTag(stampedGoldenTag).ToObjectRef() - return nil - }); err != nil { - t.Fatalf("UpdateActorTemplate(golden): %v", err) - } - - goldenActorRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "golden-actor"} - goldenCreated, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "golden-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}) - if err != nil { - t.Fatalf("CreateActor(golden-actor) failed: %v", err) - } - if got := durableSnapshot(goldenCreated.GetStatus()).GetSandboxRuntime(); !proto.Equal(got, rtA) { - t.Fatalf("golden-actor initial Snapshot.SandboxRuntime = %v, want %v", got, rtA) - } - - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.RunCalled = false - tc.fakeAtelet.RestoreCalled = false - tc.fakeAtelet.Lock.Unlock() - - goldenResumed, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: goldenActorRef}) - if err != nil { - t.Fatalf("ResumeActor(golden-actor) failed: %v", err) - } - if got := goldenResumed.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-b" { - t.Fatalf("golden-actor placed on %q, want worker-b", got) - } - if got := goldenResumed.GetActor().GetStatus().GetWorkerAssignment().GetSandboxRuntime(); !proto.Equal(got, rtB) { - t.Fatalf("golden-actor WorkerAssignment.SandboxRuntime = %v, want %v", got, rtB) - } - tc.fakeAtelet.Lock.Lock() - runCalled := tc.fakeAtelet.RunCalled - restoreCalled := tc.fakeAtelet.RestoreCalled - tc.fakeAtelet.Lock.Unlock() - if runCalled || !restoreCalled { - t.Fatalf("golden-actor fallback: RunCalled=%v RestoreCalled=%v, want RunCalled=false RestoreCalled=true", runCalled, restoreCalled) - } - goldenRestore := tc.fakeAtelet.lastRestoreRequest() - if got := goldenRestore.GetSnapshot().GetFidelity(); got != ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS { - t.Fatalf("golden-actor RestoreRequest.Fidelity = %v, want ROOTFS", got) - } - if got, want := goldenRestore.GetSnapshot().GetObject().GetSnapshotUri(), goldenSnapshotURI(t); got != want { - t.Fatalf("golden-actor RestoreRequest.SnapshotUri = %q, want golden %q", got, want) - } - // A borrowed golden snapshot is shared by every actor created from it, - // and the request must say so: atelet caches only declared-SHARED sources. - if got := goldenRestore.GetSnapshot().GetObject().GetSharing(); got != ateletpb.SnapshotSharing_SNAPSHOT_SHARING_SHARED { - t.Fatalf("golden-actor RestoreRequest.Sharing = %v, want SHARED", got) - } - - // Free worker-b and have it advertise rtA in restorable_runtimes while - // keeping rtB as its default. Resuming an actor whose snapshot requires rtA - // onto worker-b (with worker-a still full) must restore at MEMORY fidelity, - // record the matched restorable entry (rtA, not rtB) on WorkerAssignment, - // and preserve rtA through async SuspendActor and sync SuspendActor on the - // already-SUSPENDED actor. - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: goldenActorRef}); err != nil { - t.Fatalf("SuspendActor(golden-actor) failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerB) - reportWorkerRuntime(t, tc, workerB, rtB, rtA) - - restorableRef := &ateapi.ObjectRef{Atespace: testAtespace, Name: "restorable-actor"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "restorable-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - SourceTag: tagRef, - }}); err != nil { - t.Fatalf("CreateActor(restorable-actor) failed: %v", err) - } - restorableResumed, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: restorableRef}) - if err != nil { - t.Fatalf("ResumeActor(restorable-actor) failed: %v", err) - } - if got := restorableResumed.GetActor().GetStatus().GetWorkerAssignment().GetWorkerPod(); got != "worker-b" { - t.Fatalf("restorable-actor placed on %q, want worker-b", got) - } - if got := restorableResumed.GetActor().GetStatus().GetWorkerAssignment().GetSandboxRuntime(); !proto.Equal(got, rtA) { - t.Fatalf("restorable-actor WorkerAssignment.SandboxRuntime = %v, want matched restorable %v", got, rtA) - } - if got := tc.fakeAtelet.lastRestoreRequest().GetSnapshot().GetFidelity(); got != ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY { - t.Fatalf("restorable-actor RestoreRequest.Fidelity = %v, want MEMORY", got) - } - - pausedResp, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: restorableRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor(restorable-actor) failed: %v", err) - } - waitForWorkerAvailable(t, tc, workerB) - if got := localSnapshot(pausedResp.GetActor().GetStatus()).GetSandboxRuntime(); !proto.Equal(got, rtA) { - t.Fatalf("paused local Snapshot.SandboxRuntime = %v, want %v", got, rtA) - } - - // A sync suspend of the already-SUSPENDED actor returns it as it is: the - // node-local snapshot keeps its runtime stamp. - suspendedFromPaused, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: restorableRef, Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}}) - if err != nil { - t.Fatalf("SuspendActor from PAUSED(restorable-actor) failed: %v", err) - } - if got := localSnapshot(suspendedFromPaused.GetActor().GetStatus()).GetSandboxRuntime(); !proto.Equal(got, rtA) { - t.Fatalf("local Snapshot.SandboxRuntime after SuspendActor from PAUSED = %v, want %v", got, rtA) - } -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/actor_volume_detach_test.go b/cmd/ateapi/internal/controlapi/functionaltest/actor_volume_detach_test.go deleted file mode 100644 index b2d615f26a..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/actor_volume_detach_test.go +++ /dev/null @@ -1,232 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "slices" - "testing" - - "github.com/google/go-cmp/cmp" - "github.com/google/go-cmp/cmp/cmpopts" - "go.ate.dev/substrate/api/ateapi/v1" - "go.ate.dev/substrate/internal/preview" - "go.ate.dev/substrate/internal/resources" - "go.ate.dev/substrate/internal/volume" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// calls returns copies of the nodes the plugin attached to and detached from, -// in call order. -func (a *attachFailVolumePlugin) calls() (attached, detached []string) { - a.mu.Lock() - defer a.mu.Unlock() - return slices.Clone(a.attachedNodes), slices.Clone(a.detachedNodes) -} - -// assertAssignedNode checks the actor's persisted assigned_node in the store -// against want. -func assertAssignedNode(t *testing.T, tc *testContext, name, step, want string) { - t.Helper() - actor, err := tc.persistence.GetActor(context.Background(), resources.ActorRef{Atespace: testAtespace, Name: name}) - if err != nil { - t.Fatalf("GetActor(%s) from store: %v", name, err) - } - if got := actor.GetStatus().GetAssignedNode(); got != want { - t.Errorf("persisted assigned_node %s = %q, want %q", step, got, want) - } -} - -// assertDetachedNodes checks the nodes the plugin detached from, in call -// order. An empty want means no detach. -func assertDetachedNodes(t *testing.T, plugin *attachFailVolumePlugin, step string, want ...string) { - t.Helper() - _, detached := plugin.calls() - if diff := cmp.Diff(want, detached, cmpopts.EquateEmpty()); diff != "" { - t.Errorf("detached nodes %s (-want +got):\n%s", step, diff) - } -} - -// createSingleVolumeActor creates a template mounting one external volume, -// worker-1 on node1, and a SUSPENDED actor named name from the template. It -// returns worker-1's Worker name. -func createSingleVolumeActor(t *testing.T, tc *testContext, ns, name string) string { - t.Helper() - preview.InitForTest(t, "ExternalVolumes") - volumes := []*ateapi.Volume{{ - Name: "vol1", - External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ - StorageClassName: "standard", - CapacityBytes: 10 << 30, - }}, - }} - mounts := []*ateapi.VolumeMount{{Name: "vol1", MountPath: "/mnt/vol1"}} - createTemplateWithVolumes(t, tc, ns, volumes, mounts) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - return workerName -} - -// resumeToRunningOnNode1 resumes the actor and checks that its volume was -// published to node1 and that the store records node1 as its assigned_node. -func resumeToRunningOnNode1(t *testing.T, tc *testContext, plugin *attachFailVolumePlugin, name string) { - t.Helper() - if _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - if attached, _ := plugin.calls(); !cmp.Equal(attached, []string{"node1"}) { - t.Fatalf("attached nodes after resume = %v, want [node1]", attached) - } - assertAssignedNode(t, tc, name, "after resume", "node1") -} - -// assertCrashedKeepingAssignedNode checks that the actor is CRASHED with no -// worker assignment, and that its status still records node as assigned_node. -func assertCrashedKeepingAssignedNode(t *testing.T, tc *testContext, name, node string) { - t.Helper() - actor, err := tc.persistence.GetActor(context.Background(), resources.ActorRef{Atespace: testAtespace, Name: name}) - if err != nil { - t.Fatalf("GetActor(%s) from store: %v", name, err) - } - if got := actor.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_CRASHED { - t.Fatalf("state = %v, want CRASHED", got) - } - if got := actor.GetStatus().GetWorkerAssignment(); got != nil { - t.Fatalf("worker assignment = %v, want nil after the crash", got) - } - assertAssignedNode(t, tc, name, "after the crash", node) -} - -// TestDeleteActor_CrashedWorkerGone_DetachesAssignedNode verifies that -// deleting an actor that crashed because its worker went away unpublishes its -// volume from the node recorded in assigned_node, although the crash cleared -// the worker assignment and the worker no longer exists. -func TestDeleteActor_CrashedWorkerGone_DetachesAssignedNode(t *testing.T) { - ns := namespaceForTest("ns-del-crashed-detach") - plugin := &attachFailVolumePlugin{} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - const name = "crashed-delete-actor" - createSingleVolumeActor(t, tc, ns, name) - resumeToRunningOnNode1(t, tc, plugin, name) - - // Deregistering the worker crashes the actor it hosts. - deleteWorkerPod(t, tc, ns, "worker-1") - assertCrashedKeepingAssignedNode(t, tc, name, "node1") - assertDetachedNodes(t, plugin, "after the crash") - - // CRASHED is deletable without AnyState. - if _, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }); err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - assertDetachedNodes(t, plugin, "after delete", "node1") - plugin.mu.Lock() - if len(plugin.deleted) != 1 { - t.Errorf("deleted volumes = %v, want exactly one", plugin.deleted) - } - plugin.mu.Unlock() -} - -// TestResumeActor_RestoreCrash_DeleteDetaches verifies that when Restore fails -// with an error a retry cannot clear after the volume was published, the -// crashed actor keeps assigned_node on record and a later delete unpublishes -// the volume from it. -func TestResumeActor_RestoreCrash_DeleteDetaches(t *testing.T) { - ns := namespaceForTest("ns-restore-crash-detach") - plugin := &attachFailVolumePlugin{} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - const name = "restore-crash-actor" - createSingleVolumeActor(t, tc, ns, name) - tc.fakeAtelet.FailRestore = status.Error(codes.Internal, "injected restore failure") - - _, err := tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if got := status.Code(err); got != codes.Internal { - t.Fatalf("ResumeActor code = %v, want %v (err: %v)", got, codes.Internal, err) - } - if attached, _ := plugin.calls(); !cmp.Equal(attached, []string{"node1"}) { - t.Fatalf("attached nodes = %v, want [node1]: the volume must be published before Restore fails", attached) - } - assertCrashedKeepingAssignedNode(t, tc, name, "node1") - assertDetachedNodes(t, plugin, "after the crash") - - if _, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }); err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - assertDetachedNodes(t, plugin, "after delete", "node1") -} - -// TestRevertActor_Crashed_DetachesAssignedNode verifies that reverting an -// actor that crashed because its worker went away unpublishes its volume from -// the node recorded in assigned_node, clears assigned_node, and leaves the -// actor SUSPENDED. -func TestRevertActor_Crashed_DetachesAssignedNode(t *testing.T) { - ns := namespaceForTest("ns-revert-crashed-detach") - plugin := &attachFailVolumePlugin{} - tc := setupTestWithVolumePlugins(t, ns, map[string]volume.VolumePluginControlPlane{ - "substrate.io/mock": plugin, - }) - defer tc.cleanup() - - const name = "crashed-revert-actor" - createSingleVolumeActor(t, tc, ns, name) - resumeToRunningOnNode1(t, tc, plugin, name) - - deleteWorkerPod(t, tc, ns, "worker-1") - assertCrashedKeepingAssignedNode(t, tc, name, "node1") - tc.fakeAtelet.Lock.Lock() - tc.fakeAtelet.TerminateCalled = false - tc.fakeAtelet.Lock.Unlock() - - reverted, err := tc.client.RevertActor(context.Background(), &ateapi.RevertActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }) - if err != nil { - t.Fatalf("RevertActor failed: %v", err) - } - if got := reverted.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { - t.Errorf("state = %v, want SUSPENDED", got) - } - assertDetachedNodes(t, plugin, "after revert", "node1") - assertAssignedNode(t, tc, name, "after revert", "") - tc.fakeAtelet.Lock.Lock() - if !tc.fakeAtelet.TerminateCalled { - t.Errorf("expected Terminate call to clean up assigned node") - } else if gotUID := tc.fakeAtelet.TerminateRequest.GetWorkerPodUid(); gotUID != "" { - t.Errorf("TerminateRequest.WorkerPodUid = %q, want empty", gotUID) - } - tc.fakeAtelet.Lock.Unlock() -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/atespace_test.go b/cmd/ateapi/internal/controlapi/functionaltest/atespace_test.go deleted file mode 100644 index 54f5aea003..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/atespace_test.go +++ /dev/null @@ -1,296 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "go.ate.dev/substrate/api/ateapi/v1" - "google.golang.org/grpc/codes" - "google.golang.org/protobuf/testing/protocmp" - "google.golang.org/protobuf/types/known/timestamppb" -) - -func TestCreateAtespace_Success(t *testing.T) { - ns := namespaceForTest("ns-create-atespace") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - - resp, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{ - Atespace: &ateapi.Atespace{ - Metadata: &ateapi.ResourceMetadata{ - Name: "team-a", - Uid: "caller-supplied-uid", - Version: 999, - CreateTime: timestamppb.New(time.Unix(1, 0)), - UpdateTime: timestamppb.New(time.Unix(1, 0)), - }, - }, - }) - if err != nil { - t.Fatalf("CreateAtespace failed: %v", err) - } - md := resp.GetMetadata() - if md.GetName() != "team-a" { - t.Errorf("Name = %q, want team-a", md.GetName()) - } - if md.GetAtespace() != "" { - t.Errorf("Atespace = %q, want empty (global-scoped)", md.GetAtespace()) - } - if md.GetVersion() != 1 { - t.Errorf("Version = %d, want 1 (caller-set 999 must be ignored)", md.GetVersion()) - } - if md.GetUid() == "" || md.GetUid() == "caller-supplied-uid" { - t.Errorf("uid = %q, want a server-generated value", md.GetUid()) - } - - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{ - Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: "team-a", - Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Errorf("CreateActor into freshly created atespace failed: %v", err) - } -} - -func TestCreateAtespace_AlreadyExists(t *testing.T) { - ns := namespaceForTest("ns-create-atespace-dup") - tc := setupTest(t, ns) - defer tc.cleanup() - - if _, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "team-a"}}}); err != nil { - t.Fatalf("first CreateAtespace failed: %v", err) - } - _, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "team-a"}}}) - assertGrpcError(t, err, codes.AlreadyExists, "Atespace team-a already exists") -} - -func TestGetAtespace_Found(t *testing.T) { - ns := namespaceForTest("ns-get-atespace") - tc := setupTest(t, ns) - defer tc.cleanup() - - created, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "team-a"}}}) - if err != nil { - t.Fatalf("CreateAtespace failed: %v", err) - } - resp, err := tc.client.GetAtespace(context.Background(), &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}}) - if err != nil { - t.Fatalf("GetAtespace failed: %v", err) - } - if diff := cmp.Diff(created, resp, protocmp.Transform()); diff != "" { - t.Errorf("GetAtespace mismatch (-created +got):\n%s", diff) - } -} - -func TestGetAtespace_NotFound(t *testing.T) { - ns := namespaceForTest("ns-get-atespace-missing") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.GetAtespace(context.Background(), &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "nope"}}) - assertGrpcError(t, err, codes.NotFound, "Atespace nope not found") -} - -func TestListAtespaces(t *testing.T) { - ns := namespaceForTest("ns-list-atespaces") - tc := setupTest(t, ns) - defer tc.cleanup() - - for _, n := range []string{"team-a", "team-b"} { - if _, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: n}}}); err != nil { - t.Fatalf("CreateAtespace(%s) failed: %v", n, err) - } - } - resp, err := tc.client.ListAtespaces(context.Background(), &ateapi.ListAtespacesRequest{}) - if err != nil { - t.Fatalf("ListAtespaces failed: %v", err) - } - got := map[string]bool{} - for _, a := range resp.GetAtespaces() { - got[a.GetMetadata().GetName()] = true - } - // setupTest seeds testAtespace; team-a and team-b were created above. - for _, n := range []string{testAtespace, "team-a", "team-b"} { - if !got[n] { - t.Errorf("ListAtespaces missing %q; got %v", n, got) - } - } -} - -func TestDeleteAtespace_Empty_Success(t *testing.T) { - ns := namespaceForTest("ns-delete-atespace-empty") - tc := setupTest(t, ns) - defer tc.cleanup() - - if _, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "team-a"}}}); err != nil { - t.Fatalf("CreateAtespace failed: %v", err) - } - deleted, err := tc.client.DeleteAtespace(context.Background(), &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}}) - if err != nil { - t.Fatalf("DeleteAtespace failed: %v", err) - } - // DeleteAtespace returns the deleted resource. - if got := deleted.GetMetadata().GetName(); got != "team-a" { - t.Errorf("deleted atespace name = %q, want team-a", got) - } - if deleted.GetMetadata().GetDeleteTime() == nil { - t.Errorf("the deleted atespace carries no delete_time") - } - - _, err = tc.client.GetAtespace(context.Background(), &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}}) - assertGrpcError(t, err, codes.NotFound, "Atespace team-a not found") -} - -func TestDeleteAtespace_NonEmpty_Rejected(t *testing.T) { - ns := namespaceForTest("ns-delete-atespace-nonempty") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - - if _, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "team-a"}}}); err != nil { - t.Fatalf("CreateAtespace failed: %v", err) - } - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - _, err := tc.client.DeleteAtespace(context.Background(), &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}}) - assertGrpcError(t, err, codes.FailedPrecondition, "Atespace team-a is not empty") - // The atespace must survive a rejected delete. - if _, err := tc.client.GetAtespace(context.Background(), &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}}); err != nil { - t.Errorf("atespace should survive a rejected delete, got %v", err) - } -} - -// TestDeleteAtespace_ScopedToTargetAtespace pins (at the RPC layer) that the -// emptiness check is scoped to the target atespace: deleting an empty atespace -// succeeds even when a different atespace holds actors. -func TestDeleteAtespace_ScopedToTargetAtespace(t *testing.T) { - ns := namespaceForTest("ns-delete-atespace-scoped") - tc := setupTest(t, ns) - defer tc.cleanup() - createTemplate(t, tc, ns) - createAtespace(t, tc, "team-a") - createAtespace(t, tc, "team-b") - - // Actor only in team-b. - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: "team-b", Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - // Empty team-a deletes fine despite team-b holding an actor. - if _, err := tc.client.DeleteAtespace(context.Background(), &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}}); err != nil { - t.Errorf("DeleteAtespace(team-a, empty) failed: %v", err) - } - // team-b is still non-empty → rejected. - _, err := tc.client.DeleteAtespace(context.Background(), &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-b"}}) - assertGrpcError(t, err, codes.FailedPrecondition, "Atespace team-b is not empty") -} - -func TestDeleteAtespace_NotFound(t *testing.T) { - ns := namespaceForTest("ns-delete-atespace-missing") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.DeleteAtespace(context.Background(), &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "nope"}}) - assertGrpcError(t, err, codes.NotFound, "Atespace nope not found") -} - -func TestValidation_Atespace(t *testing.T) { - ns := namespaceForTest("ns-validation-atespace") - tc := setupTest(t, ns) - defer tc.cleanup() - - t.Run("ListAtespaces", func(t *testing.T) { - _, err := tc.client.ListAtespaces(context.Background(), &ateapi.ListAtespacesRequest{Options: &ateapi.ListOptions{PageSize: -1}}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "page_size: Invalid value") - }) - - t.Run("ListAtespaces invalid token", func(t *testing.T) { - _, err := tc.client.ListAtespaces(context.Background(), &ateapi.ListAtespacesRequest{Options: &ateapi.ListOptions{PageToken: "%%%"}}) - assertGrpcError(t, err, codes.InvalidArgument, "invalid page_token") - }) - - t.Run("CreateAtespace", func(t *testing.T) { - _, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "atespace: Required value") - }) - - t.Run("GetAtespace", func(t *testing.T) { - _, err := tc.client.GetAtespace(context.Background(), &ateapi.GetAtespaceRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "atespace: Required value") - }) - - t.Run("DeleteAtespace", func(t *testing.T) { - _, err := tc.client.DeleteAtespace(context.Background(), &ateapi.DeleteAtespaceRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "atespace: Required value") - }) -} - -func TestDeleteAtespace_Preconditions(t *testing.T) { - ns := namespaceForTest("ns-delete-atespace-preconditions") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - ref := &ateapi.ObjectRef{Name: "team-a"} - create := func() *ateapi.Atespace { - created, err := tc.client.CreateAtespace(ctx, &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: ref.GetName()}}}) - if err != nil { - t.Fatalf("CreateAtespace failed: %v", err) - } - return created - } - del := func(opts *ateapi.DeleteOptions) error { - _, err := tc.client.DeleteAtespace(ctx, &ateapi.DeleteAtespaceRequest{Atespace: ref, Options: opts}) - return err - } - - atespace := create() - uid, version := atespace.GetMetadata().GetUid(), atespace.GetMetadata().GetVersion() - - assertGrpcError(t, del(&ateapi.DeleteOptions{Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: uid, Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID}), codes.Aborted, "Atespace team-a does not have uid "+foreignUID) - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID, Version: version}), codes.Aborted, "Atespace team-a does not have uid "+foreignUID) - if _, err := tc.client.GetAtespace(ctx, &ateapi.GetAtespaceRequest{Atespace: ref}); err != nil { - t.Fatalf("a refused delete removed the atespace: %v", err) - } - - if err := del(&ateapi.DeleteOptions{Version: version}); err != nil { - t.Fatalf("DeleteAtespace with the matching version: %v", err) - } - atespace = create() - if err := del(&ateapi.DeleteOptions{Uid: atespace.GetMetadata().GetUid()}); err != nil { - t.Fatalf("DeleteAtespace with the matching uid: %v", err) - } - atespace = create() - if err := del(&ateapi.DeleteOptions{Uid: atespace.GetMetadata().GetUid(), Version: atespace.GetMetadata().GetVersion()}); err != nil { - t.Fatalf("DeleteAtespace with both guards: %v", err) - } - _, err := tc.client.GetAtespace(ctx, &ateapi.GetAtespaceRequest{Atespace: ref}) - assertGrpcError(t, err, codes.NotFound, "Atespace team-a not found") -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/common_test.go b/cmd/ateapi/internal/controlapi/functionaltest/common_test.go deleted file mode 100644 index 668172fbe7..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/common_test.go +++ /dev/null @@ -1,915 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "fmt" - "net" - "regexp" - "testing" - "time" - - "go.ate.dev/substrate/api/ateapi/v1" - atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" - "go.ate.dev/substrate/cmd/ateapi/internal/controlapi" - "go.ate.dev/substrate/cmd/ateapi/internal/store" - "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" - "go.ate.dev/substrate/cmd/ateapi/internal/workercache" - "go.ate.dev/substrate/internal/ateinterceptors" - "go.ate.dev/substrate/internal/installdefaults" - "go.ate.dev/substrate/internal/localjwtauthority" - "go.ate.dev/substrate/internal/objectstore/objectstoretest" - "go.ate.dev/substrate/internal/objectstoreplugin/objectstoreplugintest" - "go.ate.dev/substrate/internal/preview" - "go.ate.dev/substrate/internal/resources" - "go.ate.dev/substrate/internal/volume" - "go.ate.dev/substrate/pkg/client/clientset/versioned" - "go.ate.dev/substrate/pkg/client/informers/externalversions" - "go.opentelemetry.io/otel/attribute" - sdkmetric "go.opentelemetry.io/otel/sdk/metric" - sdktrace "go.opentelemetry.io/otel/sdk/trace" - "go.opentelemetry.io/otel/sdk/trace/tracetest" - "google.golang.org/grpc" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/credentials" - "google.golang.org/grpc/credentials/insecure" - "google.golang.org/grpc/status" - "google.golang.org/grpc/test/bufconn" - "google.golang.org/protobuf/testing/protocmp" - corev1 "k8s.io/api/core/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/util/wait" - "k8s.io/client-go/informers" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/tools/cache" - "k8s.io/utils/ptr" -) - -const ( - testAtespace = "test-atespace" - testActorID = "id1" - // testStorageLocation is the --snapshot-location the test server runs - // with. No object store is wired up behind it. - testStorageLocation = "gs://fake-fake-fake" - testActorJWTIssuer = "https://idp.example.test" - - // byNode mirrors the unexported index name controlapi's atelet informer uses. - byNode = "by-node" -) - -var ( - ignoreUID = protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "uid") - ignoreVersion = protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "version") - ignoreTimestamps = protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "create_time", "update_time", "delete_time") - - // ignoreServerMetadata skips the ResourceMetadata fields the store assigns. - ignoreServerMetadata = protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "uid", "create_time", "update_time", "delete_time") -) - -type testContext struct { - service *controlapi.RPCService - client ateapi.ControlClient - noOptInClient ateapi.ControlClient // never sends preview.Header - k8sClient kubernetes.Interface - substrateClient versioned.Interface - persistence store.Interface - workerCache *workercache.Cache - fakeAtelet *FakeAteletServer - cleanup func() - // ateletIndexer is the index DialForAteletOnNode looks up atelets in. - // setupAteletOnNode waits on it so a test never dials a node whose atelet the - // informer has not seen yet. - ateletIndexer cache.Indexer - // metricReader collects what the service's instruments recorded. - metricReader *sdkmetric.ManualReader - // objectStore holds the external snapshots the service wrote, so a test can - // see which ones a flow created and released. - objectStore *objectstoretest.Fake -} - -// setupTest sets up a fully isolated test environment. -func setupTest(t *testing.T, ns string) *testContext { - t.Helper() - return setupTestWithOptions(t, ns, testOptions{}) -} - -type testOptions struct { - allowPreview bool // enable use of preview features over gRPC - volumePlugins map[string]volume.VolumePluginControlPlane -} - -// setupPreviewTest is setupTest with a client that opts in to preview -// features. It does not enable any gate; call preview.InitForTest for that. -func setupPreviewTest(t *testing.T, ns string) *testContext { - t.Helper() - return setupTestWithOptions(t, ns, testOptions{allowPreview: true}) -} - -// setupTestWithVolumePlugins is setupPreviewTest with the default mock volume -// plugin replaced by plugins, keyed by driver name. Tests that need a -// failure-injecting plugin pass it here rather than swapping it into the -// running RPCService, so each test owns its own plugin set. -func setupTestWithVolumePlugins(t *testing.T, ns string, plugins map[string]volume.VolumePluginControlPlane) *testContext { - t.Helper() - return setupTestWithOptions(t, ns, testOptions{volumePlugins: plugins, allowPreview: true}) -} - -func setupTestWithOptions(t *testing.T, ns string, options testOptions) *testContext { - t.Helper() - - var dialOpts []grpc.DialOption - if options.allowPreview { - dialOpts = preview.DialOptionsWithOptIn() - } - - // 1. Start an isolated PostgreSQL-backed store. - persistence, cleanupStore := storetest.SetupTestStore(t) - - // 2. Initialize Clientsets using global cfg - k8sClient, err := kubernetes.NewForConfig(cfg) - if err != nil { - cleanupStore() - t.Fatalf("failed to create k8s clientset: %v", err) - } - - substrateClient, err := versioned.NewForConfig(cfg) - if err != nil { - cleanupStore() - t.Fatalf("failed to create substrate clientset: %v", err) - } - - // 3. Initialize Informers - ateletFactory, ateletInformer := controlapi.AteletInformer(k8sClient, installdefaults.SystemNamespace) - scFactory := informers.NewSharedInformerFactory(k8sClient, 0) - scLister := scFactory.Storage().V1().StorageClasses().Lister() - - substrateInformerFactory := externalversions.NewSharedInformerFactory(substrateClient, 0) - csiDriverConfigLister := substrateInformerFactory.Ate().V1().CSIDriverConfigs().Lister() - - ctx, cancel := context.WithCancel(context.Background()) - - ateletFactory.Start(ctx.Done()) - substrateInformerFactory.Start(ctx.Done()) - scFactory.Start(ctx.Done()) - - ateletFactory.WaitForCacheSync(ctx.Done()) - substrateInformerFactory.WaitForCacheSync(ctx.Done()) - scFactory.WaitForCacheSync(ctx.Done()) - - // 4. Initialize Service - wc := workercache.New(persistence, 5*time.Minute) - if err := wc.Start(ctx); err != nil { - cancel() - cleanupStore() - t.Fatalf("failed to start worker cache: %v", err) - } - - // Dial the fake atelet over insecure transport instead of per-atelet mTLS, - // so DialForAteletOnNode's real lookup/dial/cache path is exercised under test. - dialer := controlapi.NewAteletDialer(ateletInformer.GetIndexer(), installdefaults.AteletSPIFFEID(installdefaults.SystemNamespace), "", "", - controlapi.WithDialCredentials(func(_ string) (credentials.TransportCredentials, error) { - return insecure.NewCredentials(), nil - })) - - metricReader := sdkmetric.NewManualReader() - instruments, err := controlapi.NewInstruments(sdkmetric.NewMeterProvider(sdkmetric.WithReader(metricReader)).Meter("ateapi")) - if err != nil { - cancel() - cleanupStore() - t.Fatalf("failed to create metric instruments: %v", err) - } - volPlugins := options.volumePlugins - if volPlugins == nil { - mockPlugin := volume.NewMockVolumePlugin() - mockDriverName, err := mockPlugin.DriverName(ctx) - if err != nil { - t.Fatalf("failed to get mock driver name: %v", err) - } - volPlugins = map[string]volume.VolumePluginControlPlane{ - mockDriverName: mockPlugin, - } - } - - actorJWTAuthority, err := localjwtauthority.GenerateAuthority("ES256", "1") - if err != nil { - t.Fatalf("Error generating actor JWT authority: %v", err) - } - - actorJWTAuthorityPool := &localjwtauthority.ConcretePool{ - Authorities: []*localjwtauthority.Authority{ - actorJWTAuthority, - }, - ActiveForSigning: "1", - } - - objectStore := objectstoretest.New() - - service := controlapi.NewRPCService( - persistence, - wc, - csiDriverConfigLister, - scLister, - dialer, - instruments, - "", - 30*time.Second, - volPlugins, - objectstoreplugintest.ControlClient(objectStore), - testActorJWTIssuer, - actorJWTAuthorityPool, - testStorageLocation, - ) - - // 5. Start REAL gRPC Server for ATE API - grpcServer := grpc.NewServer(grpc.ChainUnaryInterceptor( - ateinterceptors.ServerUnaryInterceptor, - ateinterceptors.RejectUnknownFieldsUnaryInterceptor, - preview.UnaryServerInterceptor, - )) - ateapi.RegisterControlServer(grpcServer, service) - - lis := bufconn.Listen(8192) - - go func() { - if err := grpcServer.Serve(lis); err != nil { - t.Logf("grpc server exited: %v", err) - } - }() - - baseDialOpts := []grpc.DialOption{ - grpc.WithTransportCredentials(insecure.NewCredentials()), - grpc.WithContextDialer(func(ctx context.Context, s string) (net.Conn, error) { - return lis.Dial() - }), - } - conn, err := grpc.NewClient("passthrough://bufnet", append(baseDialOpts, dialOpts...)...) - if err != nil { - grpcServer.Stop() - cancel() - cleanupStore() - t.Fatalf("failed to connect: %v", err) - } - noOptInConn, err := grpc.NewClient("passthrough://bufnet", baseDialOpts...) - if err != nil { - conn.Close() - grpcServer.Stop() - cancel() - cleanupStore() - t.Fatalf("failed to connect: %v", err) - } - t.Cleanup(func() { noOptInConn.Close() }) - - client := ateapi.NewControlClient(conn) - - // Call Reset on global mock - fakeAtelet.Reset() - // A checkpoint writes its external snapshot into this test's own store, so - // the copy and release steps have something to act on. - fakeAtelet.SetObjectStore(objectStore) - - // Create namespace - _, err = k8sClient.CoreV1().Namespaces().Create(context.Background(), &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{Name: ns}, - }, metav1.CreateOptions{}) - if err != nil { - conn.Close() - grpcServer.Stop() - cancel() - cleanupStore() - t.Fatalf("failed to create namespace %s: %v", ns, err) - } - - // CreateActor now requires the atespace to exist first. - if _, err := client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: testAtespace}}}); err != nil { - conn.Close() - grpcServer.Stop() - cancel() - cleanupStore() - t.Fatalf("failed to seed test atespace %q: %v", testAtespace, err) - } - - cleanup := func() { - conn.Close() - grpcServer.Stop() - cancel() - cleanupStore() - } - - return &testContext{ - service: service, - client: client, - noOptInClient: ateapi.NewControlClient(noOptInConn), - k8sClient: k8sClient, - substrateClient: substrateClient, - persistence: persistence, - workerCache: wc, - fakeAtelet: fakeAtelet, - cleanup: cleanup, - ateletIndexer: ateletInformer.GetIndexer(), - metricReader: metricReader, - objectStore: objectStore, - } -} - -// snapshotObjectNames returns the names, relative to snapshotURI, of the -// objects the external snapshot there is made of. Empty means the snapshot is -// not in object storage — either never written, or collected. -func snapshotObjectNames(t *testing.T, tc *testContext, snapshotURI string) []string { - t.Helper() - uri, err := resources.ParseSnapshotURI(snapshotURI) - if err != nil { - t.Fatalf("ParseSnapshotURI(%q) = %v", snapshotURI, err) - } - return tc.objectStore.Snapshot(t, uri) -} - -// assertSnapshotPresent fails when the external snapshot at snapshotURI is not -// in object storage. -func assertSnapshotPresent(t *testing.T, tc *testContext, snapshotURI string) { - t.Helper() - if names := snapshotObjectNames(t, tc, snapshotURI); len(names) == 0 { - t.Errorf("external snapshot %s is not in object storage, want it present", snapshotURI) - } -} - -// assertSnapshotCollected fails when anything is left of the external snapshot -// at snapshotURI. -func assertSnapshotCollected(t *testing.T, tc *testContext, snapshotURI string) { - t.Helper() - if names := snapshotObjectNames(t, tc, snapshotURI); len(names) != 0 { - t.Errorf("external snapshot %s still holds %v, want it collected", snapshotURI, names) - } -} - -const goldenSnapshotName = "9c2f7b41-6d05-4e83-a1f7-3b8c0d5e2a94" - -// goldenSnapshotURI is the snapshot owned by the test template's golden tag. -func goldenSnapshotURI(t *testing.T) string { - t.Helper() - uri, err := resources.NewTagSnapshotURI(testStorageLocation, testAtespace, goldenSnapshotName) - if err != nil { - t.Fatalf("NewTagSnapshotURI: %v", err) - } - return uri.String() -} - -// snapshotOwnedByActor reports whether snapshotURI sits under the actor's own -// prefix. That is what says the actor took the snapshot itself rather than -// borrowing it from a tag, and so what decides whether its suspends and its -// delete may collect it. -func snapshotOwnedByActor(t *testing.T, actor *ateapi.Actor, snapshotURI string) bool { - t.Helper() - uri, err := resources.ParseSnapshotURI(snapshotURI) - if err != nil { - t.Fatalf("ParseSnapshotURI(%q) = %v", snapshotURI, err) - } - return uri.OwnedBy(resources.ActorSnapshotOwner(actor.GetMetadata().GetAtespace(), actor.GetMetadata().GetUid())) -} - -// assertSnapshotOwnedByActor fails when snapshotURI is not under the actor's -// own prefix. -func assertSnapshotOwnedByActor(t *testing.T, actor *ateapi.Actor, snapshotURI string) { - t.Helper() - if !snapshotOwnedByActor(t, actor, snapshotURI) { - t.Errorf("external snapshot %s is not under actor %s's own prefix, want it owned by the actor", snapshotURI, resources.ActorRefFromActor(actor)) - } -} - -// snapshotName returns the name snapshotURI gives its snapshot in object -// storage, which the Snapshot's uuid must match. -func snapshotName(t *testing.T, snapshotURI string) string { - t.Helper() - uri, err := resources.ParseSnapshotURI(snapshotURI) - if err != nil { - t.Fatalf("ParseSnapshotURI(%q) = %v", snapshotURI, err) - } - return uri.Name() -} - -func namespaceForTest(baseName string) string { - return fmt.Sprintf("%s-%d", baseName, time.Now().UnixNano()) -} - -func createTemplate(t *testing.T, tc *testContext, ns string) *ateapi.ActorTemplate { - t.Helper() - return createTemplateWithContainers(t, tc, ns, []*ateapi.Container{ - { - Name: "main", - Image: "main@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - Command: []string{"/main"}, - }, - }) -} - -// createAtespace creates an atespace via the API. -func createAtespace(t *testing.T, tc *testContext, name string) { - t.Helper() - if _, err := tc.client.CreateAtespace(context.Background(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: name}}}); err != nil { - t.Fatalf("CreateAtespace(%s) failed: %v", name, err) - } -} - -const poolLabelKey = "pool" - -func createTemplateWithContainers(t *testing.T, tc *testContext, ns string, containers []*ateapi.Container) *ateapi.ActorTemplate { - t.Helper() - return createTemplateWithContainersAndVolumes(t, tc, ns, containers, nil) -} - -func createTemplateWithVolumes(t *testing.T, tc *testContext, ns string, volumes []*ateapi.Volume, mounts []*ateapi.VolumeMount) *ateapi.ActorTemplate { - t.Helper() - return createTemplateWithContainersAndVolumes(t, tc, ns, []*ateapi.Container{ - { - Name: "main", - Image: "main@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - Command: []string{"/main"}, - VolumeMounts: mounts, - }, - }, volumes) -} - -// createTemplateWithContainersAndVolumes creates the substrate ActorTemplate -// "tmpl1" in testAtespace, backed by a WorkerPool in ns whose labels match the -// template's worker selector, and seeds its golden snapshot. ns keys the pool -// labels, so each test's template still selects only its own pool. -func createTemplateWithContainersAndVolumes(t *testing.T, tc *testContext, ns string, containers []*ateapi.Container, volumes []*ateapi.Volume) *ateapi.ActorTemplate { - t.Helper() - - createWorkerPool(t, tc, ns, "pool1", map[string]string{poolLabelKey: ns}) - - created, err := tc.client.CreateActorTemplate(context.Background(), &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "tmpl1", - }, - Containers: containers, - Volumes: volumes, - WorkerSelector: &ateapi.Selector{ - MatchLabels: map[string]string{poolLabelKey: ns}, - }, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 512<<20)}, - }, - }) - if err != nil { - t.Fatalf("failed to create actor template: %v", err) - } - - tag, err := tc.persistence.CreateTag(context.Background(), &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: created.GetMetadata().GetUid()}, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: created.GetMetadata().GetUid()}, - Scope: ateapi.TagScope_TAG_SCOPE_PUBLISHED, - Status: &ateapi.TagStatus{ - Snapshot: newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, created.GetMetadata().GetUid(), goldenSnapshotName, goldenSnapshotURI(t)), - ActorTemplateUid: created.GetMetadata().GetUid(), - }, - }) - if err != nil { - t.Fatalf("create golden tag: %v", err) - } - - // Record the golden snapshot on the template's status directly in the - // store, as the ActorTemplateReconciler's checkpoint would: there is no - // status RPC, and the reconciler does not run in this test environment. - updated, err := tc.persistence.UpdateActorTemplate(context.Background(), - resources.ActorTemplateRefFromActorTemplate(created), store.PreconditionFrom(created), - func(dbTemplate *ateapi.ActorTemplate) error { - dbTemplate.Status = &ateapi.ActorTemplateStatus{ - GoldenSnapshotStatus: &ateapi.GoldenSnapshotStatus{ - GoldenTag: resources.TagRefFromTag(tag).ToObjectRef(), - }, - } - return nil - }) - if err != nil { - t.Fatalf("failed to record the template's golden snapshot: %v", err) - } - return updated -} - -func newDurableSnapshot(gen int32, owner ateapi.SnapshotOwner, fidelity ateapi.SnapshotFidelity, templateUID, uuid, uri string) *ateapi.Snapshot { - return &ateapi.Snapshot{ - Uuid: uuid, - Generation: gen, - Owner: owner, - Fidelity: fidelity, - ActorTemplateUid: templateUID, - DurableSnapshot: &ateapi.SnapshotStorage{ - State: ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED, - Object: &ateapi.ObjectSnapshot{SnapshotUri: uri}, - }, - } -} - -// newPausedSnapshot is the snapshot an asynchronous suspend leaves on node -// locality: its durable copy, under the actor's own prefix, is PENDING until -// atelet uploads it. -func newPausedSnapshot(t *testing.T, gen int32, fidelity ateapi.SnapshotFidelity, templateUID, actorUID, uuid, locality string) *ateapi.Snapshot { - t.Helper() - uri, err := resources.NewActorSnapshotURI(testStorageLocation, testAtespace, actorUID, uuid) - if err != nil { - t.Fatalf("NewActorSnapshotURI: %v", err) - } - return &ateapi.Snapshot{ - Uuid: uuid, - Generation: gen, - Owner: ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR, - Fidelity: fidelity, - ActorTemplateUid: templateUID, - Locality: locality, - DurableSnapshot: &ateapi.SnapshotStorage{ - State: ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING, - Object: &ateapi.ObjectSnapshot{SnapshotUri: uri.String()}, - }, - } -} - -func durableSnapshot(status *ateapi.ActorStatus) *ateapi.Snapshot { - var best *ateapi.Snapshot - for _, snap := range status.GetSnapshots() { - st := snap.GetDurableSnapshot() - if st.GetState() == ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED && - st.GetObject().GetSnapshotUri() != "" { - if best == nil || snap.GetGeneration() > best.GetGeneration() { - best = snap - } - } - } - return best -} - -func durableSnapshotStorage(status *ateapi.ActorStatus) *ateapi.SnapshotStorage { - return durableSnapshot(status).GetDurableSnapshot() -} - -func durableSnapshotURI(status *ateapi.ActorStatus) string { - return durableSnapshotStorage(status).GetObject().GetSnapshotUri() -} - -func localSnapshot(status *ateapi.ActorStatus) *ateapi.Snapshot { - var best *ateapi.Snapshot - for _, snap := range status.GetSnapshots() { - if snap.GetLocality() != "" && snap.GetUuid() != "" { - if best == nil || snap.GetGeneration() > best.GetGeneration() { - best = snap - } - } - } - return best -} - -func tagSnapshotURI(tag *ateapi.Tag) string { - return tag.GetStatus().GetSnapshot().GetDurableSnapshot().GetObject().GetSnapshotUri() -} - -func createWorkerPool(t *testing.T, tc *testContext, ns string, name string, labels map[string]string) { - t.Helper() - wp := &atev1.WorkerPool{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: ns, - Labels: labels, - }, - Spec: atev1.WorkerPoolSpec{ - Replicas: 1, - WorkerImage: "worker@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", - SandboxClasses: []atev1.WorkerPoolSandboxClass{{Name: atev1.SandboxClassGvisor}}, - }, - } - if _, err := tc.substrateClient.AteV1().WorkerPools(ns).Create(context.Background(), wp, metav1.CreateOptions{}); err != nil { - t.Fatalf("failed to create WorkerPool: %v", err) - } -} - -// createTemplateWithSelector creates a substrate ActorTemplate in -// testAtespace with the given worker selector and no golden snapshot. -func createTemplateWithSelector(t *testing.T, tc *testContext, name string, selector *ateapi.Selector) *ateapi.ActorTemplate { - t.Helper() - created, err := tc.client.CreateActorTemplate(context.Background(), &ateapi.CreateActorTemplateRequest{ - ActorTemplate: &ateapi.ActorTemplate{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: name, - }, - Containers: []*ateapi.Container{ - {Name: "main", Image: "main@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855", Command: []string{"/main"}}, - }, - WorkerSelector: selector, - Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(1000, 512<<20)}, - }, - }) - if err != nil { - t.Fatalf("failed to create actor template: %v", err) - } - return created -} - -// createWorkerPod creates a worker pod, registers the matching Worker, and -// waits for it to reach the worker cache. It returns the name of the resulting -// Worker, which is the key to look it up by. -// -// Both halves are needed: the Worker record is what the scheduler places actors -// on, and the pod is what the atelet dialer resolves to reach one. In a real -// cluster the syncer in ate-controller derives the first from the second; here -// the test writes both, building the Worker exactly as the syncer would. -func createWorkerPod(t *testing.T, tc *testContext, ns string, name string, nodeName string, poolName string) string { - t.Helper() - pod := &corev1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: ns, - Labels: map[string]string{ - "ate.dev/worker-pool": poolName, - }, - }, - Spec: corev1.PodSpec{ - NodeName: nodeName, - Containers: []corev1.Container{ - {Name: "main", Image: "nginx"}, - }, - }, - } - createdPod, err := tc.k8sClient.CoreV1().Pods(ns).Create(context.Background(), pod, metav1.CreateOptions{}) - if err != nil { - t.Fatalf("failed to create worker pod: %v", err) - } - createdPod.Status.PodIPs = []corev1.PodIP{{IP: "127.0.0.1"}} - createdPod.Status.Phase = corev1.PodRunning - createdPod.Status.Conditions = []corev1.PodCondition{{ - Type: corev1.PodReady, - Status: corev1.ConditionTrue, - }} - _, err = tc.k8sClient.CoreV1().Pods(ns).UpdateStatus(context.Background(), createdPod, metav1.UpdateOptions{}) - if err != nil { - t.Fatalf("failed to update worker pod status: %v", err) - } - - // The WorkerPool supplies the fields the syncer copies off it. - pool, err := tc.substrateClient.AteV1().WorkerPools(ns).Get(context.Background(), poolName, metav1.GetOptions{}) - if err != nil { - t.Fatalf("failed to get WorkerPool %s/%s: %v", ns, poolName, err) - } - if _, err := tc.client.CreateWorker(context.Background(), &ateapi.CreateWorkerRequest{ - Worker: &ateapi.Worker{ - // Workers are global-scoped and named after the pod UID. - Metadata: &ateapi.ResourceMetadata{Name: string(createdPod.UID)}, - WorkerNamespace: ns, - WorkerPool: poolName, - WorkerPod: name, - WorkerPodUid: string(createdPod.UID), - NodeName: nodeName, - Labels: pool.GetLabels(), - // Capacity is not settable here: a Worker gets it from its own - // worker's report, which the reportWorkerCapacity below stands in - // for. These pods declare no limits, so only the actor ceiling is - // reported; see setWorkerActorCapacity for tests needing more. - }, - }); err != nil { - t.Fatalf("failed to register worker: %v", err) - } - // As the syncer does once the pod is Ready. - if _, err := tc.client.MarkWorkerAvailable(context.Background(), &ateapi.MarkWorkerAvailableRequest{ - Worker: &ateapi.ObjectRef{Name: string(createdPod.UID)}, - }); err != nil { - t.Fatalf("failed to mark worker available: %v", err) - } - reportWorkerCapacity(t, tc, string(createdPod.UID), 1) - - // Wait for the worker to appear in worker cache. - err = wait.PollUntilContextTimeout(context.Background(), 10*time.Millisecond, 5*time.Second, true, func(ctx context.Context) (bool, error) { - workers, err := tc.workerCache.Workers() - if err != nil { - return false, nil // Cache not ready yet; retry. - } - for _, w := range workers { - if w.GetWorkerNamespace() == ns && w.GetWorkerPod() == name { - return true, nil - } - } - return false, nil - }) - if err != nil { - t.Fatalf("failed to wait for worker to appear in worker cache: %v", err) - } - return string(createdPod.UID) -} - -// waitForWorkerAvailable waits for an assignment release to reach the worker -// cache. Lifecycle RPCs commit the release to the store before the cache's -// PostgreSQL watch processes the corresponding update. -func waitForWorkerAvailable(t *testing.T, tc *testContext, workerName string) { - t.Helper() - err := wait.PollUntilContextTimeout(context.Background(), 10*time.Millisecond, 5*time.Second, true, func(context.Context) (bool, error) { - worker, err := tc.workerCache.Worker(workerName) - if err != nil { - return false, nil - } - // Hosting nothing is what "available" means, and the allocation total - // is how a cached Worker reports it: it does not carry the records. - return worker.GetStatus().GetState() == ateapi.WorkerState_WORKER_STATE_ACTIVE && - worker.GetStatus().GetAllocated().GetActors() == 0, nil - }) - if err != nil { - t.Fatalf("failed to wait for worker %s to become available: %v", workerName, err) - } -} - -// createAteletPod creates an atelet pod on nodeName and marks it Running with -// an IP, which DialForAteletOnNode requires. The pod carries the namespace and -// app=atelet label AteletInformer selects on, and is indexed by its node. -func createAteletPod(kc kubernetes.Interface, name, nodeName string) error { - pod := &corev1.Pod{ - ObjectMeta: metav1.ObjectMeta{ - Name: name, - Namespace: installdefaults.SystemNamespace, - Labels: map[string]string{"app": "atelet"}, - }, - Spec: corev1.PodSpec{ - NodeName: nodeName, - Containers: []corev1.Container{{Name: "main", Image: "nginx"}}, - }, - } - created, err := kc.CoreV1().Pods(installdefaults.SystemNamespace).Create(context.Background(), pod, metav1.CreateOptions{}) - if apierrors.IsAlreadyExists(err) { - return nil - } - if err != nil { - return fmt.Errorf("creating atelet pod %s on %s: %w", name, nodeName, err) - } - created.Status.PodIPs = []corev1.PodIP{{IP: "127.0.0.1"}} - created.Status.Phase = corev1.PodRunning - if _, err := kc.CoreV1().Pods(installdefaults.SystemNamespace).UpdateStatus(context.Background(), created, metav1.UpdateOptions{}); err != nil { - return fmt.Errorf("updating atelet pod %s status: %w", name, err) - } - return nil -} - -// setupAteletOnNode makes nodeName dialable for the duration of the test: it -// creates an atelet pod there, waits for the dialer's index to see it, and -// removes it on cleanup. The package fixture only creates one atelet, on -// node1, and the dialer resolves atelets per node, so a worker on any other -// node is unreachable without this. -func setupAteletOnNode(t *testing.T, tc *testContext, name, nodeName string) { - t.Helper() - if err := createAteletPod(tc.k8sClient, name, nodeName); err != nil { - t.Fatalf("%v", err) - } - t.Cleanup(func() { - _ = tc.k8sClient.CoreV1().Pods(installdefaults.SystemNamespace).Delete(context.Background(), name, metav1.DeleteOptions{ - GracePeriodSeconds: ptr.To[int64](0), - }) - }) - - // Wait for the dialer's index to see the newly created atlet - err := wait.PollUntilContextTimeout(context.Background(), 10*time.Millisecond, 5*time.Second, true, func(ctx context.Context) (bool, error) { - atelets, err := tc.ateletIndexer.ByIndex(byNode, nodeName) - if err != nil { - return false, nil - } - for _, obj := range atelets { - p := obj.(*corev1.Pod) - if p.Name == name && len(p.Status.PodIPs) > 0 { - return true, nil - } - } - return false, nil - }) - if err != nil { - t.Fatalf("failed to wait for atelet pod on %s to be indexed: %v", nodeName, err) - } -} - -func deleteWorkerPod(t *testing.T, tc *testContext, ns string, name string) { - t.Helper() - err := tc.k8sClient.CoreV1().Pods(ns).Delete(context.Background(), name, metav1.DeleteOptions{ - GracePeriodSeconds: ptr.To[int64](0), - }) - if err != nil { - t.Fatalf("failed to delete worker pod %s: %v", name, err) - } - - // Deregister the Worker, as the syncer would once it saw the pod go. The - // Worker is named after the pod UID, but the caller only has the pod name, - // so it is found by the pod fields it carries. - resp, err := tc.client.ListWorkers(context.Background(), &ateapi.ListWorkersRequest{}) - if err != nil { - t.Fatalf("failed to list workers: %v", err) - } - for _, w := range resp.GetWorkers() { - if w.GetWorkerNamespace() != ns || w.GetWorkerPod() != name { - continue - } - if _, err := tc.client.DeleteWorker(context.Background(), &ateapi.DeleteWorkerRequest{ - Worker: &ateapi.ObjectRef{Name: w.GetMetadata().GetName()}, - }); err != nil { - t.Fatalf("failed to deregister worker %s: %v", w.GetMetadata().GetName(), err) - } - } - - err = wait.PollUntilContextTimeout(context.Background(), 10*time.Millisecond, 5*time.Second, true, func(ctx context.Context) (bool, error) { - workers, err := tc.workerCache.Workers() - if err != nil { - return false, nil // Cache not ready yet; retry. - } - for _, w := range workers { - if w.GetWorkerNamespace() == ns && w.GetWorkerPod() == name { - return false, nil // Still there - } - } - return true, nil - }) - if err != nil { - t.Fatalf("failed to wait for worker to be removed from worker cache: %v", err) - } -} - -func assertGrpcErrorRegex(t *testing.T, err error, wantCode codes.Code, wantMsg string) { - t.Helper() - fn := func(got string) (string, bool) { - matched, matchErr := regexp.MatchString(wantMsg, got) - if matchErr != nil { - t.Fatalf("failed to compile regex %q: %v", wantMsg, matchErr) - } - return wantMsg, matched - } - assertGrpcErrorImpl(t, err, wantCode, fn) -} - -func assertGrpcError(t *testing.T, err error, wantCode codes.Code, wantMsg string) { - t.Helper() - fn := func(got string) (string, bool) { - return wantMsg, got == wantMsg - } - assertGrpcErrorImpl(t, err, wantCode, fn) -} - -func assertGrpcErrorImpl(t *testing.T, err error, wantCode codes.Code, msgMatches func(got string) (string, bool)) { - t.Helper() - if err == nil { - t.Fatalf("expected error, got nil") - } - st, ok := status.FromError(err) - if !ok { - t.Fatalf("expected gRPC status error, got: %v", err) - } - if st.Code() != wantCode { - t.Errorf("expected status %v, got %v", wantCode, st.Code()) - } - if want, ok := msgMatches(st.Message()); !ok { - t.Errorf("expected message %q, got %q", want, st.Message()) - } -} - -// recordRootSpanAttrs runs fn under a fresh recording root span from a local -// TracerProvider and returns that span's attributes, so a test can observe what -// the code under test stamps on the span carried in ctx. It never swaps the -// global provider (the code under test reads its span via trace.SpanFromContext, -// not the global provider), so span tests stay parallel-safe. -func recordRootSpanAttrs(t *testing.T, fn func(ctx context.Context)) map[attribute.Key]attribute.Value { - t.Helper() - sr := tracetest.NewSpanRecorder() - tp := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) - ctx, root := tp.Tracer("test").Start(context.Background(), "root") - fn(ctx) - root.End() - for _, s := range sr.Ended() { - if s.Name() == "root" { - m := make(map[attribute.Key]attribute.Value, len(s.Attributes())) - for _, kv := range s.Attributes() { - m[kv.Key] = kv.Value - } - return m - } - } - t.Fatal("root span not recorded") - return nil -} - -func assertSpanStr(t *testing.T, attrs map[attribute.Key]attribute.Value, key attribute.Key, want string) { - t.Helper() - v, ok := attrs[key] - if !ok { - t.Errorf("missing %s", key) - return - } - if v.AsString() != want { - t.Errorf("%s = %q, want %q", key, v.AsString(), want) - } -} - -// foreignUID matches no stored object, for guards that must miss. -const foreignUID = "0f0e0d0c-0b0a-4908-8706-050403020100" diff --git a/cmd/ateapi/internal/controlapi/functionaltest/egress_policy_test.go b/cmd/ateapi/internal/controlapi/functionaltest/egress_policy_test.go deleted file mode 100644 index 2f57faebce..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/egress_policy_test.go +++ /dev/null @@ -1,265 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "go.ate.dev/substrate/api/ateapi/v1" - "go.ate.dev/substrate/internal/resources" - "google.golang.org/grpc/codes" - "google.golang.org/protobuf/proto" - "google.golang.org/protobuf/testing/protocmp" - "google.golang.org/protobuf/types/known/timestamppb" -) - -func setupEgressPolicyActor(t *testing.T, testName string) (*testContext, *ateapi.ObjectRef) { - t.Helper() - ns := namespaceForTest(testName) - tc := setupTest(t, ns) - t.Cleanup(tc.cleanup) - createTemplate(t, tc, ns) - - actor := &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "egress-actor"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - } - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: actor}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - return tc, &ateapi.ObjectRef{Atespace: testAtespace, Name: "egress-actor"} -} - -func functionalEgressPolicy() *ateapi.EgressPolicy { - return &ateapi.EgressPolicy{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "default"}, - Rules: []*ateapi.EgressRule{{ - Http: &ateapi.HttpRule{Hostnames: []string{"api.example.com"}}, - }}, - } -} - -func createEgressPolicy(t *testing.T, tc *testContext, actor *ateapi.ObjectRef) *ateapi.EgressPolicy { - t.Helper() - created, err := tc.client.CreateActorEgressPolicy(context.Background(), &ateapi.CreateActorEgressPolicyRequest{ - Actor: actor, - EgressPolicy: functionalEgressPolicy(), - }) - if err != nil { - t.Fatalf("CreateActorEgressPolicy failed: %v", err) - } - return created -} - -func TestCreateActorEgressPolicy_Success(t *testing.T) { - tc, actor := setupEgressPolicyActor(t, "ns-create-egress-policy") - policy := functionalEgressPolicy() - policy.Metadata.Uid = "caller-supplied-uid" - policy.Metadata.Version = 999 - policy.Metadata.CreateTime = timestamppb.New(time.Unix(1, 0)) - policy.Metadata.UpdateTime = timestamppb.New(time.Unix(1, 0)) - - created, err := tc.client.CreateActorEgressPolicy(context.Background(), &ateapi.CreateActorEgressPolicyRequest{ - Actor: actor, - EgressPolicy: policy, - }) - if err != nil { - t.Fatalf("CreateActorEgressPolicy failed: %v", err) - } - md := created.GetMetadata() - if md.GetAtespace() != testAtespace || md.GetName() != "default" { - t.Errorf("identity = %s/%s, want %s/default", md.GetAtespace(), md.GetName(), testAtespace) - } - if md.GetVersion() != 1 { - t.Errorf("version = %d, want 1", md.GetVersion()) - } - if md.GetUid() == "" || md.GetUid() == "caller-supplied-uid" { - t.Errorf("uid = %q, want a server-generated value", md.GetUid()) - } - if md.GetCreateTime() == nil || md.GetUpdateTime() == nil || md.GetCreateTime().AsTime().Equal(time.Unix(1, 0)) || md.GetUpdateTime().AsTime().Equal(time.Unix(1, 0)) { - t.Errorf("timestamps = (%v, %v), want server-generated values", md.GetCreateTime(), md.GetUpdateTime()) - } - - got, err := tc.client.GetActorEgressPolicy(context.Background(), &ateapi.GetActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName}) - if err != nil { - t.Fatalf("GetActorEgressPolicy failed: %v", err) - } - if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { - t.Errorf("GetActorEgressPolicy mismatch (-created +got):\n%s", diff) - } -} - -func TestCreateActorEgressPolicy_Errors(t *testing.T) { - tc, actor := setupEgressPolicyActor(t, "ns-create-egress-policy-errors") - createEgressPolicy(t, tc, actor) - - _, err := tc.client.CreateActorEgressPolicy(context.Background(), &ateapi.CreateActorEgressPolicyRequest{ - Actor: actor, - EgressPolicy: functionalEgressPolicy(), - }) - assertGrpcError(t, err, codes.AlreadyExists, "EgressPolicy already exists") - - _, err = tc.client.CreateActorEgressPolicy(context.Background(), &ateapi.CreateActorEgressPolicyRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "missing-actor"}, - EgressPolicy: functionalEgressPolicy(), - }) - assertGrpcError(t, err, codes.FailedPrecondition, "parent Actor does not exist") -} - -func TestGetActorEgressPolicy_NotFound(t *testing.T) { - tc, actor := setupEgressPolicyActor(t, "ns-get-egress-policy-missing") - _, err := tc.client.GetActorEgressPolicy(context.Background(), &ateapi.GetActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName}) - assertGrpcError(t, err, codes.NotFound, "EgressPolicy for actor "+actor.GetAtespace()+"/"+actor.GetName()+" not found") -} - -func TestUpdateActorEgressPolicy(t *testing.T) { - tc, actor := setupEgressPolicyActor(t, "ns-update-egress-policy") - created := createEgressPolicy(t, tc, actor) - toUpdate := proto.Clone(created).(*ateapi.EgressPolicy) - toUpdate.Rules = []*ateapi.EgressRule{{TlsPassthrough: &ateapi.TlsPassthroughRule{Hostnames: []string{"*"}, Ports: &ateapi.Ports{Numbers: []int32{443}}}}} - - updated, err := tc.client.UpdateActorEgressPolicy(context.Background(), &ateapi.UpdateActorEgressPolicyRequest{ - Actor: actor, - EgressPolicy: toUpdate, - }) - if err != nil { - t.Fatalf("UpdateActorEgressPolicy failed: %v", err) - } - if updated.GetMetadata().GetUid() != created.GetMetadata().GetUid() || updated.GetMetadata().GetVersion() != 2 { - t.Errorf("updated metadata = %v, want original UID and version 2", updated.GetMetadata()) - } - if !updated.GetMetadata().GetCreateTime().AsTime().Equal(created.GetMetadata().GetCreateTime().AsTime()) { - t.Errorf("create_time changed from %v to %v", created.GetMetadata().GetCreateTime(), updated.GetMetadata().GetCreateTime()) - } - if !updated.GetMetadata().GetUpdateTime().AsTime().After(created.GetMetadata().GetUpdateTime().AsTime()) { - t.Errorf("update_time = %v, want after %v", updated.GetMetadata().GetUpdateTime(), created.GetMetadata().GetUpdateTime()) - } - if len(updated.GetRules()) != 1 || updated.GetRules()[0].GetTlsPassthrough() == nil { - t.Errorf("updated rules = %v, want one tls_passthrough rule", updated.GetRules()) - } - - got, err := tc.client.GetActorEgressPolicy(context.Background(), &ateapi.GetActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName}) - if err != nil { - t.Fatalf("GetActorEgressPolicy failed: %v", err) - } - if diff := cmp.Diff(updated, got, protocmp.Transform()); diff != "" { - t.Errorf("persisted policy mismatch (-updated +got):\n%s", diff) - } - - _, err = tc.client.UpdateActorEgressPolicy(context.Background(), &ateapi.UpdateActorEgressPolicyRequest{ - Actor: actor, - EgressPolicy: toUpdate, - }) - assertGrpcError(t, err, codes.Aborted, "EgressPolicy version conflict") -} - -func TestUpdateActorEgressPolicy_Preconditions(t *testing.T) { - tc, actor := setupEgressPolicyActor(t, "ns-update-egress-policy-preconditions") - created := createEgressPolicy(t, tc, actor) - - unguarded := proto.Clone(created).(*ateapi.EgressPolicy) - unguarded.Metadata.Uid, unguarded.Metadata.Version = "", 0 - _, err := tc.client.UpdateActorEgressPolicy(context.Background(), &ateapi.UpdateActorEgressPolicyRequest{Actor: actor, EgressPolicy: unguarded}) - assertGrpcError(t, err, codes.InvalidArgument, "EgressPolicy UID and version are required") - - wrongUID := proto.Clone(created).(*ateapi.EgressPolicy) - wrongUID.Metadata.Uid = "9a2b1c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d" - _, err = tc.client.UpdateActorEgressPolicy(context.Background(), &ateapi.UpdateActorEgressPolicyRequest{Actor: actor, EgressPolicy: wrongUID}) - assertGrpcError(t, err, codes.Aborted, "EgressPolicy UID conflict") - - missingActor := &ateapi.ObjectRef{Atespace: testAtespace, Name: "missing-actor"} - _, err = tc.client.UpdateActorEgressPolicy(context.Background(), &ateapi.UpdateActorEgressPolicyRequest{Actor: missingActor, EgressPolicy: created}) - assertGrpcError(t, err, codes.NotFound, "EgressPolicy not found") -} - -func TestDeleteActorEgressPolicy(t *testing.T) { - tc, actor := setupEgressPolicyActor(t, "ns-delete-egress-policy") - created := createEgressPolicy(t, tc, actor) - - deleted, err := tc.client.DeleteActorEgressPolicy(context.Background(), &ateapi.DeleteActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName}) - if err != nil { - t.Fatalf("DeleteActorEgressPolicy failed: %v", err) - } - if diff := cmp.Diff(created, deleted, protocmp.Transform(), protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "delete_time")); diff != "" { - t.Errorf("deleted policy mismatch (-created +deleted):\n%s", diff) - } - if deleted.GetMetadata().GetDeleteTime() == nil { - t.Errorf("the deleted policy carries no delete_time") - } - _, err = tc.client.DeleteActorEgressPolicy(context.Background(), &ateapi.DeleteActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName}) - assertGrpcError(t, err, codes.NotFound, "EgressPolicy not found") -} - -func TestDeleteActor_CascadesEgressPolicy(t *testing.T) { - tc, actor := setupEgressPolicyActor(t, "ns-delete-actor-egress-policy") - createEgressPolicy(t, tc, actor) - - if _, err := tc.client.DeleteActor(context.Background(), &ateapi.DeleteActorRequest{Actor: actor}); err != nil { - t.Fatalf("DeleteActor failed: %v", err) - } - _, err := tc.client.GetActorEgressPolicy(context.Background(), &ateapi.GetActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName}) - assertGrpcError(t, err, codes.NotFound, "EgressPolicy for actor "+actor.GetAtespace()+"/"+actor.GetName()+" not found") -} - -func TestValidation_ActorEgressPolicy(t *testing.T) { - tc, _ := setupEgressPolicyActor(t, "ns-validation-egress-policy") - ctx := context.Background() - - _, err := tc.client.CreateActorEgressPolicy(ctx, &ateapi.CreateActorEgressPolicyRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - _, err = tc.client.GetActorEgressPolicy(ctx, &ateapi.GetActorEgressPolicyRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - _, err = tc.client.UpdateActorEgressPolicy(ctx, &ateapi.UpdateActorEgressPolicyRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") - _, err = tc.client.DeleteActorEgressPolicy(ctx, &ateapi.DeleteActorEgressPolicyRequest{}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "actor: Required value") -} - -func TestDeleteActorEgressPolicy_Preconditions(t *testing.T) { - tc, actor := setupEgressPolicyActor(t, "ns-delete-egress-policy-preconditions") - ctx := context.Background() - del := func(opts *ateapi.DeleteOptions) error { - _, err := tc.client.DeleteActorEgressPolicy(ctx, &ateapi.DeleteActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName, Options: opts}) - return err - } - - policy := createEgressPolicy(t, tc, actor) - uid, version := policy.GetMetadata().GetUid(), policy.GetMetadata().GetVersion() - - assertGrpcError(t, del(&ateapi.DeleteOptions{Version: version + 1}), codes.Aborted, "EgressPolicy version conflict") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: uid, Version: version + 1}), codes.Aborted, "EgressPolicy version conflict") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID}), codes.Aborted, "EgressPolicy UID conflict") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID, Version: version}), codes.Aborted, "EgressPolicy UID conflict") - if _, err := tc.client.GetActorEgressPolicy(ctx, &ateapi.GetActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName}); err != nil { - t.Fatalf("a refused delete removed the policy: %v", err) - } - - if err := del(&ateapi.DeleteOptions{Version: version}); err != nil { - t.Fatalf("DeleteActorEgressPolicy with the matching version: %v", err) - } - policy = createEgressPolicy(t, tc, actor) - if err := del(&ateapi.DeleteOptions{Uid: policy.GetMetadata().GetUid()}); err != nil { - t.Fatalf("DeleteActorEgressPolicy with the matching uid: %v", err) - } - policy = createEgressPolicy(t, tc, actor) - if err := del(&ateapi.DeleteOptions{Uid: policy.GetMetadata().GetUid(), Version: policy.GetMetadata().GetVersion()}); err != nil { - t.Fatalf("DeleteActorEgressPolicy with both guards: %v", err) - } - _, err := tc.client.GetActorEgressPolicy(ctx, &ateapi.GetActorEgressPolicyRequest{Actor: actor, Name: resources.SingletonName}) - assertGrpcError(t, err, codes.NotFound, "EgressPolicy for actor "+actor.GetAtespace()+"/"+actor.GetName()+" not found") -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/main_test.go b/cmd/ateapi/internal/controlapi/functionaltest/main_test.go deleted file mode 100644 index 1ed69cd759..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/main_test.go +++ /dev/null @@ -1,350 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "fmt" - "log" - "net" - "os" - "strconv" - "sync" - "testing" - "time" - - "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" - "go.ate.dev/substrate/internal/atelet" - "go.ate.dev/substrate/internal/objectstore/objectstoretest" - "go.ate.dev/substrate/internal/proto/ateletpb" - "go.ate.dev/substrate/internal/serverboot" - "go.ate.dev/substrate/internal/testenv" - "google.golang.org/grpc" - "google.golang.org/protobuf/proto" - corev1 "k8s.io/api/core/v1" - storagev1 "k8s.io/api/storage/v1" - apierrors "k8s.io/apimachinery/pkg/api/errors" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/client-go/kubernetes" - "k8s.io/client-go/rest" -) - -var ( - cfg *rest.Config - fakeAtelet = &FakeAteletServer{} -) - -func TestMain(m *testing.M) { - // The in-process server logs RPC bodies through ateinterceptors, which - // relies on this handler to mask debug_redact fields. - serverboot.InitLoggerWithWriter(os.Stderr) - var stopEnv func() - cfg, stopEnv = testenv.Start() - - // Create ate-system namespace - k8sClient, err := kubernetes.NewForConfig(cfg) - if err != nil { - log.Fatalf("kubernetes.NewForConfig: %v", err) - } - _, err = k8sClient.CoreV1().Namespaces().Create(context.Background(), &corev1.Namespace{ - ObjectMeta: metav1.ObjectMeta{Name: "ate-system"}, - }, metav1.CreateOptions{}) - if err != nil && !apierrors.IsAlreadyExists(err) { - log.Fatalf("create ate-system namespace: %v", err) - } - - // Create StorageClasses for volume tests - _, err = k8sClient.StorageV1().StorageClasses().Create(context.Background(), &storagev1.StorageClass{ - ObjectMeta: metav1.ObjectMeta{Name: "standard"}, - Provisioner: "substrate.io/mock", - }, metav1.CreateOptions{}) - if err != nil && !apierrors.IsAlreadyExists(err) { - log.Fatalf("create standard storage class: %v", err) - } - _, err = k8sClient.StorageV1().StorageClasses().Create(context.Background(), &storagev1.StorageClass{ - ObjectMeta: metav1.ObjectMeta{Name: "fast"}, - Provisioner: "substrate.io/mock", - }, metav1.CreateOptions{}) - if err != nil && !apierrors.IsAlreadyExists(err) { - log.Fatalf("create fast storage class: %v", err) - } - - // Create shared Atelet Pod. Tests that place workers on another node add - // their own atelet there via setupAteletOnNode. - if err := createAteletPod(k8sClient, "atelet-shared", "node1"); err != nil { - log.Fatalf("%v", err) - } - - // Start Fake Atelet Server on the port ateapi dials. - ateletGrpcServer := grpc.NewServer() - ateletpb.RegisterAteletServer(ateletGrpcServer, fakeAtelet) - ateletAddr := net.JoinHostPort("127.0.0.1", strconv.Itoa(atelet.DefaultPort)) - ateletLis, err := net.Listen("tcp", ateletAddr) - if err != nil { - log.Fatalf("listen on %s: %v", ateletAddr, err) - } - go func() { - if err := ateletGrpcServer.Serve(ateletLis); err != nil { - fmt.Printf("atelet grpc server exited: %v\n", err) - } - }() - - code := m.Run() - - ateletGrpcServer.Stop() - - stopEnv() - - storetest.Shutdown() - - os.Exit(code) -} - -// FakeAteletServer implements ateletpb.WorkersServer -type FakeAteletServer struct { - ateletpb.UnimplementedAteletServer - - Lock sync.Mutex - - RunCalled bool - RunRequest *ateletpb.RunRequest - FailRun error - - CheckpointCalled bool - CheckpointRequest *ateletpb.CheckpointRequest - FailCheckpoint error - KeepCheckpointLocal bool - // checkpointed is each actor's last checkpointed snapshot, by UID. - checkpointed map[string]*ateletpb.Snapshot - - RestoreCalled bool - RestoreRequest *ateletpb.RestoreRequest - FailRestore error - RestoreDelay time.Duration - // RestoreWorkerEpoch, when set, is the epoch a successful Restore returns, - // so a test can stand in for the worker process that ran it. - RestoreWorkerEpoch func() int64 - - PromoteCalled bool - PromoteRequest *ateletpb.PromoteSnapshotRequest - FailPromote error - - DetachCalled bool - DetachRequest *ateletpb.DetachActorRequest - FailDetach error - - TerminateCalled bool - TerminateRequest *ateletpb.TerminateRequest - FailTerminate error - - // objectStore, when set, receives the objects a checkpoint or an upload - // writes, so the control plane's copy and release steps have real external - // snapshots to act on. setupTest points it at the test's own store. - objectStore *objectstoretest.Fake -} - -// snapshotObjects names the objects a checkpoint leaves behind. The names are -// arbitrary: nothing in the control plane reads them, it only copies and -// deletes whatever shares the snapshot's prefix. -var snapshotObjects = []string{"manifest.json", "memory.zst"} - -// SetObjectStore points the fake at the store a checkpoint should write to. -func (f *FakeAteletServer) SetObjectStore(store *objectstoretest.Fake) { - f.Lock.Lock() - defer f.Lock.Unlock() - f.objectStore = store -} - -// writeSnapshot records the external snapshot a checkpoint or an upload would -// have written at snapshotURI. Called with Lock held. -func (f *FakeAteletServer) writeSnapshot(snapshotURI string) error { - if f.objectStore == nil || snapshotURI == "" { - return nil - } - return f.objectStore.WriteSnapshot(snapshotURI, snapshotObjects...) -} - -func (f *FakeAteletServer) Reset() { - f.Lock.Lock() - defer f.Lock.Unlock() - - f.RunCalled = false - f.RunRequest = nil - f.FailRun = nil - - f.CheckpointCalled = false - f.CheckpointRequest = nil - f.FailCheckpoint = nil - f.checkpointed = nil - f.KeepCheckpointLocal = false - - f.RestoreCalled = false - f.RestoreRequest = nil - f.FailRestore = nil - f.RestoreDelay = 0 - f.RestoreWorkerEpoch = nil - - f.PromoteCalled = false - f.PromoteRequest = nil - f.FailPromote = nil - - f.DetachCalled = false - f.DetachRequest = nil - f.FailDetach = nil - - f.TerminateCalled = false - f.TerminateRequest = nil - f.FailTerminate = nil - - f.objectStore = nil -} - -func (f *FakeAteletServer) PromoteSnapshot(ctx context.Context, req *ateletpb.PromoteSnapshotRequest) (*ateletpb.PromoteSnapshotResponse, error) { - f.Lock.Lock() - defer f.Lock.Unlock() - - f.PromoteCalled = true - f.PromoteRequest = proto.Clone(req).(*ateletpb.PromoteSnapshotRequest) - if f.FailPromote != nil { - return nil, f.FailPromote - } - if err := f.writeSnapshot(req.GetSnapshot().GetObject().GetSnapshotUri()); err != nil { - return nil, err - } - // Like atelet, report the snapshot durable and still kept on the node. - report := &ateletpb.SnapshotReport{Snapshot: proto.CloneOf(req.GetSnapshot())} - return &ateletpb.PromoteSnapshotResponse{State: &ateletpb.ActorSnapshotState{ - LatestLocal: report, - LatestDurable: proto.CloneOf(report), - }}, nil -} - -// DetachActor uploads the actor's last checkpointed snapshot and reports it -// durable, with nothing left on the node. -func (f *FakeAteletServer) DetachActor(ctx context.Context, req *ateletpb.DetachActorRequest) (*ateletpb.DetachActorResponse, error) { - f.Lock.Lock() - defer f.Lock.Unlock() - - f.DetachCalled = true - f.DetachRequest = proto.CloneOf(req) - if f.FailDetach != nil { - return nil, f.FailDetach - } - snap := f.checkpointed[req.GetActorUid()] - if snap == nil { - return &ateletpb.DetachActorResponse{State: &ateletpb.ActorSnapshotState{}}, nil - } - if err := f.writeSnapshot(snap.GetObject().GetSnapshotUri()); err != nil { - return nil, err - } - return &ateletpb.DetachActorResponse{State: &ateletpb.ActorSnapshotState{ - LatestDurable: &ateletpb.SnapshotReport{Snapshot: proto.CloneOf(snap)}, - }}, nil -} - -func (f *FakeAteletServer) Run(ctx context.Context, req *ateletpb.RunRequest) (*ateletpb.RunResponse, error) { - f.Lock.Lock() - defer f.Lock.Unlock() - - f.RunCalled = true - f.RunRequest = proto.Clone(req).(*ateletpb.RunRequest) - if f.FailRun != nil { - return nil, f.FailRun - } - - // The worker process every test Worker registers, see reportWorkerCapacity. - return &ateletpb.RunResponse{WorkerEpoch: reportedEpoch}, nil -} - -func (f *FakeAteletServer) Checkpoint(ctx context.Context, req *ateletpb.CheckpointRequest) (*ateletpb.CheckpointResponse, error) { - f.Lock.Lock() - defer f.Lock.Unlock() - - f.CheckpointCalled = true - f.CheckpointRequest = proto.Clone(req).(*ateletpb.CheckpointRequest) - if f.FailCheckpoint != nil { - return nil, f.FailCheckpoint - } - if f.checkpointed == nil { - f.checkpointed = map[string]*ateletpb.Snapshot{} - } - f.checkpointed[req.GetActorUid()] = proto.CloneOf(req.GetSnapshot()) - - // Only an immediate upload is in object storage when Checkpoint returns; - // atelet does not upload deferred snapshots yet. - if req.GetUploadConfig().GetMode() == ateletpb.UploadMode_UPLOAD_MODE_IMMEDIATE { - if err := f.writeSnapshot(req.GetSnapshot().GetObject().GetSnapshotUri()); err != nil { - return nil, err - } - } - if f.KeepCheckpointLocal { - report := &ateletpb.SnapshotReport{Snapshot: proto.CloneOf(req.GetSnapshot())} - state := &ateletpb.ActorSnapshotState{LatestLocal: report} - if req.GetUploadConfig().GetMode() == ateletpb.UploadMode_UPLOAD_MODE_IMMEDIATE { - state.LatestDurable = proto.CloneOf(report) - } - return &ateletpb.CheckpointResponse{State: state}, nil - } - return &ateletpb.CheckpointResponse{}, nil -} - -func (f *FakeAteletServer) Restore(ctx context.Context, req *ateletpb.RestoreRequest) (*ateletpb.RestoreResponse, error) { - f.Lock.Lock() - defer f.Lock.Unlock() - - f.RestoreCalled = true - f.RestoreRequest = proto.Clone(req).(*ateletpb.RestoreRequest) - if f.RestoreDelay > 0 { - time.Sleep(f.RestoreDelay) - } - if f.FailRestore != nil { - return nil, f.FailRestore - } - if f.RestoreWorkerEpoch != nil { - return &ateletpb.RestoreResponse{WorkerEpoch: f.RestoreWorkerEpoch()}, nil - } - return &ateletpb.RestoreResponse{WorkerEpoch: reportedEpoch}, nil -} - -func (f *FakeAteletServer) Terminate(ctx context.Context, req *ateletpb.TerminateRequest) (*ateletpb.TerminateResponse, error) { - f.Lock.Lock() - defer f.Lock.Unlock() - - f.TerminateCalled = true - f.TerminateRequest = proto.Clone(req).(*ateletpb.TerminateRequest) - if f.FailTerminate != nil { - return nil, f.FailTerminate - } - return &ateletpb.TerminateResponse{}, nil -} - -func (f *FakeAteletServer) lastRestoreRequest() *ateletpb.RestoreRequest { - f.Lock.Lock() - defer f.Lock.Unlock() - - if f.RestoreRequest == nil { - return nil - } - return proto.Clone(f.RestoreRequest).(*ateletpb.RestoreRequest) -} - -func (f *FakeAteletServer) lastRestoreVolumePublishContext(volumeName string) map[string]string { - for _, v := range f.lastRestoreRequest().GetSpec().GetVolumes() { - if v.GetName() == volumeName { - return v.GetExternal().GetPublishContext() - } - } - return nil -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/tag_test.go b/cmd/ateapi/internal/controlapi/functionaltest/tag_test.go deleted file mode 100644 index a538e6cf3f..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/tag_test.go +++ /dev/null @@ -1,467 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "errors" - "fmt" - "testing" - - "github.com/google/go-cmp/cmp" - "go.ate.dev/substrate/api/ateapi/v1" - "go.ate.dev/substrate/cmd/ateapi/internal/store" - "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" - "go.ate.dev/substrate/internal/resources" - "google.golang.org/grpc/codes" - "google.golang.org/protobuf/testing/protocmp" -) - -// seedTag seeds a suspended actor holding an external snapshot plus -// a finished tag over a copy of it: the state CreateTag leaves -// behind. actorName must be unique within the test, since a tag records the -// actor it was taken from; opts adjust the tag before it is written. -func seedTag(t *testing.T, tc *testContext, actorName, tagName string, opts ...func(*ateapi.Tag)) *ateapi.Tag { - t.Helper() - ctx := context.Background() - actor := storetest.MustCreateActor(t, ctx, tc.persistence, &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: actorName}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, - }) - // The actor's snapshot sits under its own prefix, keyed on the UID the store - // assigns, so it can only be recorded once the row exists. - actorSnapshotURI, err := resources.NewActorSnapshotURI(testStorageLocation, testAtespace, actor.GetMetadata().GetUid(), actorName) - if err != nil { - t.Fatalf("NewActorSnapshotURI: %v", err) - } - actor, err = tc.persistence.UpdateActor(ctx, resources.ActorRefFromActor(actor), store.PreconditionFrom(actor), func(toUpdate *ateapi.Actor) error { - toUpdate.Status.LastAssignedGeneration = 1 - toUpdate.Status.Snapshots = []*ateapi.Snapshot{ - newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, "", actorSnapshotURI.Name(), actorSnapshotURI.String()), - } - return nil - }) - if err != nil { - t.Fatalf("recording the actor's external snapshot: %v", err) - } - uri, err := resources.NewTagSnapshotURI(testStorageLocation, testAtespace, resources.NewSnapshotName()) - if err != nil { - t.Fatalf("NewTagSnapshotURI: %v", err) - } - tag := &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: tagName}, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - SourceActor: resources.ActorRefFromActor(actor).ToObjectRef(), - Status: &ateapi.TagStatus{ - Snapshot: newDurableSnapshot(1, ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, durableSnapshot(actor.GetStatus()).GetFidelity(), "", uri.Name(), uri.String()), - }, - } - for _, opt := range opts { - opt(tag) - } - return storetest.MustCreateTag(t, ctx, tc.persistence, tag) -} - -// TestCreateTag_ReusedTagName tests that a tag does not move -// between external snapshots. A tag name that is already taken must be reported -// as taken, and the objects the existing tag names must be exactly what its own -// creator wrote, because the rejected create reserves the name before it copies anything. -func TestCreateTag_ReusedTagName(t *testing.T) { - ns := namespaceForTest("ns-tag-reused-name") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - workerName := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - // Actor A is suspended and tagged, the ordinary way. - const tagName = "before-upgrade" - actorFirstSnapshotURI := suspendActorForTest(t, tc, workerName, "actor-a") - first, err := tc.client.CreateTag(context.Background(), &ateapi.CreateTagRequest{ - Tag: &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: tagName}, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-a"}, - }, - }) - if err != nil { - t.Fatalf("CreateTag(actor-a) failed: %v", err) - } - tagSnapshotURI := tagSnapshotURI(first) - // Tag owns a snapshot. So it must not be empty. - wantObjects := snapshotObjectNames(t, tc, tagSnapshotURI) - if len(wantObjects) == 0 { - t.Fatalf("the tag's external snapshot %s is empty", tagSnapshotURI) - } - - // Create & Suspend actor B. Then, try to tag its snapshot with the same name - // that was already tagged by actor A. - secondSnapshotURI := suspendActorForTest(t, tc, workerName, "actor-b") - if secondSnapshotURI == actorFirstSnapshotURI { - t.Fatalf("both actors suspended to %s, want distinct external snapshots", secondSnapshotURI) - } - _, err = tc.client.CreateTag(context.Background(), &ateapi.CreateTagRequest{ - Tag: &ateapi.Tag{ - // Same tagName that was written before. - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: tagName}, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-b"}, - }, - }) - assertGrpcError(t, err, codes.AlreadyExists, fmt.Sprintf("Tag %s/%s already exists; delete it and create it again to retry", testAtespace, tagName)) - - // The row still contains actor A's tag - stored, err := tc.client.GetTag(context.Background(), &ateapi.GetTagRequest{ - Tag: &ateapi.ObjectRef{Atespace: testAtespace, Name: tagName}, - }) - if err != nil { - t.Fatalf("GetTag failed: %v", err) - } - if diff := cmp.Diff(first, stored, protocmp.Transform()); diff != "" { - t.Errorf("the rejected create modified the tag (-before +after):\n%s", diff) - } - // ...and so do the objects pointed by it. - if diff := cmp.Diff(wantObjects, snapshotObjectNames(t, tc, tagSnapshotURI)); diff != "" { - t.Errorf("the rejected create rewrote the tag's external snapshot (-before +after):\n%s", diff) - } - // Actor B kept its own snapshot: the failed tag didn't garbage collect anything - assertSnapshotPresent(t, tc, secondSnapshotURI) - - // The collision is not a dead end: a free name works. - if _, err := tc.client.CreateTag(context.Background(), &ateapi.CreateTagRequest{ - Tag: &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "after-upgrade"}, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-b"}, - }, - }); err != nil { - t.Fatalf("CreateTag under a free name failed: %v", err) - } -} - -// TestCreateTag_FromPausedActor verifies that tagging a suspended actor whose -// local snapshot is not uploaded yet has the atelet on its node upload the -// node-local snapshot first, and tags that snapshot. The actor keeps the -// snapshot on its node. -func TestCreateTag_FromPausedActor(t *testing.T) { - ns := namespaceForTest("ns-tag-paused") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - ctx := context.Background() - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-paused"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: ref.GetAtespace(), Name: ref.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - if _, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: ref, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, - }); err != nil { - t.Fatalf("pause failed: %v", err) - } - paused, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - pausedSnap := localSnapshot(paused.GetStatus()) - if pausedSnap == nil { - t.Fatal("paused actor has no local snapshot") - } - - tag, err := tc.client.CreateTag(ctx, &ateapi.CreateTagRequest{ - Tag: &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "from-paused"}, - Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, - SourceActor: ref, - }, - }) - if err != nil { - t.Fatalf("CreateTag failed: %v", err) - } - - if got := tc.fakeAtelet.PromoteRequest.GetSnapshot().GetSnapshotUuid(); got != pausedSnap.GetUuid() { - t.Errorf("PromoteSnapshot snapshot uuid = %q, want the paused snapshot %q", got, pausedSnap.GetUuid()) - } - if len(snapshotObjectNames(t, tc, tagSnapshotURI(tag))) == 0 { - t.Errorf("the tag's external snapshot %s is empty", tagSnapshotURI(tag)) - } - stored, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - // The node-local snapshot is now durable and stays on its node. - if got := durableSnapshot(stored.GetStatus()); got.GetUuid() != pausedSnap.GetUuid() { - t.Errorf("latest durable snapshot = %v, want the paused snapshot %q", got, pausedSnap.GetUuid()) - } - if got := localSnapshot(stored.GetStatus()); got.GetUuid() != pausedSnap.GetUuid() { - t.Errorf("local snapshot = %v, want the paused snapshot %q kept on its node", got, pausedSnap.GetUuid()) - } -} - -// suspendActorForTest creates, resumes and suspends an actor on workerName, -// and returns the URI of the external snapshot the suspend wrote. -func suspendActorForTest(t *testing.T, tc *testContext, workerName, name string) string { - t.Helper() - ctx := context.Background() - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor(%s) failed: %v", name, err) - } - // Successive actors share the one worker, and scheduling reads the worker - // cache: the preceding suspend released the worker in the store, but the - // cache only learns of it on its next watch poll. - waitForWorkerAvailable(t, tc, workerName) - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - }); err != nil { - t.Fatalf("ResumeActor(%s) failed: %v", name, err) - } - suspended, err := tc.client.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: name}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor(%s) failed: %v", name, err) - } - uri := durableSnapshotURI(suspended.GetActor().GetStatus()) - if uri == "" { - t.Fatalf("SuspendActor(%s) wrote no external snapshot: %v", name, suspended) - } - return uri -} - -// TestUpdateTag_Preconditions verifies the required version and uid -// guards carried in the tag's metadata. -func TestUpdateTag_Preconditions(t *testing.T) { - ns := namespaceForTest("ns-update-tag-preconditions") - tc := setupTest(t, ns) - defer tc.cleanup() - - createTemplate(t, tc, ns) - - ctx := context.Background() - const tagName = "before-upgrade" - - // Each call to update() flips the scope, so every accepted update is an - // observable write that bumps the version. - // The tag under test is seeded from actor-2; source_actor is immutable, so - // every update has to echo it back. - update := func(meta *ateapi.ResourceMetadata, scope ateapi.TagScope) (*ateapi.Tag, error) { - meta.Atespace, meta.Name = testAtespace, tagName - return tc.client.UpdateTag(context.Background(), &ateapi.UpdateTagRequest{ - Tag: &ateapi.Tag{ - Metadata: meta, - Scope: scope, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-2"}, - }, - }) - } - - // Delete and recreate the same atespace/name tag, so the first lifecycle's - // uid becomes stale. - staleUID := seedTag(t, tc, "actor-1", tagName).GetMetadata().GetUid() - if _, err := tc.client.DeleteTag(ctx, &ateapi.DeleteTagRequest{ - Tag: &ateapi.ObjectRef{Atespace: testAtespace, Name: tagName}, - }); err != nil { - t.Fatalf("DeleteTag failed: %v", err) - } - - tagged := seedTag(t, tc, "actor-2", tagName) - staleVersion := tagged.GetMetadata().GetVersion() - uid := tagged.GetMetadata().GetUid() - if uid == staleUID { - t.Fatalf("recreated tag reused uid %s, want a fresh one", uid) - } - // No preconditions - _, err := update(&ateapi.ResourceMetadata{}, ateapi.TagScope_TAG_SCOPE_PUBLISHED) - assertGrpcError(t, err, codes.InvalidArgument, fmt.Sprintf("while updating tag %s/%s: persistence: precondition required: uid", testAtespace, tagName)) - - // The uid from the deleted lifecycle must be rejected, even though the - // atespace/name it was observed under still resolves and the version it - // guards on matches the recreated tag's. - _, err = update(&ateapi.ResourceMetadata{Uid: staleUID, Version: staleVersion}, ateapi.TagScope_TAG_SCOPE_PUBLISHED) - assertGrpcError(t, err, codes.Aborted, fmt.Sprintf("Tag %s/%s not found with uid %s", testAtespace, tagName, staleUID)) - - // Both guards matching the observed state: the update goes through, and - // moves the tag past the version observed above. - first, err := update(&ateapi.ResourceMetadata{Uid: uid, Version: staleVersion}, ateapi.TagScope_TAG_SCOPE_PUBLISHED) - if err != nil { - t.Fatalf("UpdateTag(matching guards) failed: %v", err) - } - currentVersion := first.GetMetadata().GetVersion() - if currentVersion <= staleVersion { - t.Fatalf("version = %d, want greater than %d after an update", currentVersion, staleVersion) - } - if got, want := first.GetScope(), ateapi.TagScope_TAG_SCOPE_PUBLISHED; got != want { - t.Errorf("scope = %v, want %v", got, want) - } - - // The version observed before that write is now stale: rejected rather than - // silently overwriting the concurrent change. - _, err = update(&ateapi.ResourceMetadata{Uid: uid, Version: staleVersion}, ateapi.TagScope_TAG_SCOPE_ATESPACE) - assertGrpcError(t, err, codes.Aborted, "concurrent update conflict, please retry") - - // Guarding on the version the last write produced succeeds again. - updated, err := update(&ateapi.ResourceMetadata{Uid: uid, Version: currentVersion}, ateapi.TagScope_TAG_SCOPE_ATESPACE) - if err != nil { - t.Fatalf("UpdateTag(matching guards) failed: %v", err) - } - if got, want := updated.GetScope(), ateapi.TagScope_TAG_SCOPE_ATESPACE; got != want { - t.Errorf("scope = %v, want %v", got, want) - } - if updated.GetMetadata().GetVersion() <= currentVersion { - t.Errorf("version = %d, want greater than %d", updated.GetMetadata().GetVersion(), currentVersion) - } - - // The guard the client just satisfied is now stale in turn. - _, err = update(&ateapi.ResourceMetadata{Uid: uid, Version: currentVersion}, ateapi.TagScope_TAG_SCOPE_PUBLISHED) - assertGrpcError(t, err, codes.Aborted, "concurrent update conflict, please retry") -} - -func TestUpdateTag_NotFound(t *testing.T) { - ns := namespaceForTest("ns-update-tag-notfound") - tc := setupTest(t, ns) - defer tc.cleanup() - - _, err := tc.client.UpdateTag(context.Background(), &ateapi.UpdateTagRequest{ - Tag: &ateapi.Tag{ - Metadata: &ateapi.ResourceMetadata{ - Atespace: testAtespace, - Name: "does-not-exist", - // Well-formed guards to pass preconditions validation - Uid: "9a2b1c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d", - Version: 1, - }, - Scope: ateapi.TagScope_TAG_SCOPE_PUBLISHED, - SourceActor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "actor-1"}, - }, - }) - assertGrpcError(t, err, codes.NotFound, "Tag test-atespace/does-not-exist not found") -} - -// TestUpdateTag_DeletingTag verifies a tag left in place by a failed delete -// can no longer be updated. -func TestUpdateTag_DeletingTag(t *testing.T) { - ns := namespaceForTest("ns-update-tag-deleting") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - createTemplate(t, tc, ns) - - tagRef := resources.TagRefFromTag(seedTag(t, tc, "actor-1", "v1")) - tc.objectStore.OnList = func(string, string) error { return errors.New("injected list failure") } - if _, err := tc.client.DeleteTag(ctx, &ateapi.DeleteTagRequest{Tag: tagRef.ToObjectRef()}); err == nil { - t.Fatal("DeleteTag succeeded despite the failing snapshot cleanup") - } - - marked, err := tc.client.GetTag(ctx, &ateapi.GetTagRequest{Tag: tagRef.ToObjectRef()}) - if err != nil { - t.Fatalf("GetTag after the failed delete: %v", err) - } - marked.Scope = ateapi.TagScope_TAG_SCOPE_PUBLISHED - _, err = tc.client.UpdateTag(ctx, &ateapi.UpdateTagRequest{Tag: marked}) - assertGrpcError(t, err, codes.FailedPrecondition, "Tag "+tagRef.String()+" is being deleted") -} - -func TestDeleteTag(t *testing.T) { - ns := namespaceForTest("ns-delete-tag") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - createTemplate(t, tc, ns) - - created := seedTag(t, tc, "actor-1", "v1") - tagRef := resources.TagRefFromTag(created) - snapshotURI, err := resources.ParseSnapshotURI(tagSnapshotURI(created)) - if err != nil { - t.Fatalf("ParseSnapshotURI: %v", err) - } - tc.objectStore.PutSnapshot(t, snapshotURI, "manifest.json") - - deleted, err := tc.client.DeleteTag(ctx, &ateapi.DeleteTagRequest{Tag: tagRef.ToObjectRef()}) - if err != nil { - t.Fatalf("DeleteTag failed: %v", err) - } - if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreVersion, ignoreTimestamps); diff != "" { - t.Errorf("DeleteTag response mismatch (-created +deleted):\n%s", diff) - } - if deleted.GetMetadata().GetDeleteTime() == nil { - t.Errorf("the deleted tag carries no delete_time") - } - assertSnapshotCollected(t, tc, snapshotURI.String()) - _, err = tc.client.GetTag(ctx, &ateapi.GetTagRequest{Tag: tagRef.ToObjectRef()}) - assertGrpcError(t, err, codes.NotFound, "Tag "+tagRef.String()+" not found") -} - -func TestDeleteTag_NotFound(t *testing.T) { - ns := namespaceForTest("ns-delete-tag-missing") - tc := setupTest(t, ns) - defer tc.cleanup() - - tagRef := resources.TagRef{Atespace: testAtespace, Name: "missing"} - _, err := tc.client.DeleteTag(context.Background(), &ateapi.DeleteTagRequest{Tag: tagRef.ToObjectRef()}) - assertGrpcError(t, err, codes.NotFound, "Tag "+tagRef.String()+" not found") -} - -func TestDeleteTag_Preconditions(t *testing.T) { - ns := namespaceForTest("ns-delete-tag-preconditions") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - createTemplate(t, tc, ns) - tagRef := resources.TagRef{Atespace: testAtespace, Name: "v1"} - ref := tagRef.ToObjectRef() - del := func(opts *ateapi.DeleteOptions) error { - _, err := tc.client.DeleteTag(ctx, &ateapi.DeleteTagRequest{Tag: ref, Options: opts}) - return err - } - - tag := seedTag(t, tc, "actor-1", tagRef.Name) - uid, version := tag.GetMetadata().GetUid(), tag.GetMetadata().GetVersion() - - assertGrpcError(t, del(&ateapi.DeleteOptions{Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: uid, Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID}), codes.Aborted, "Tag "+tagRef.String()+" does not have uid "+foreignUID) - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID, Version: version}), codes.Aborted, "Tag "+tagRef.String()+" does not have uid "+foreignUID) - if _, err := tc.client.GetTag(ctx, &ateapi.GetTagRequest{Tag: ref}); err != nil { - t.Fatalf("a refused delete removed the tag: %v", err) - } - - if err := del(&ateapi.DeleteOptions{Version: version}); err != nil { - t.Fatalf("DeleteTag with the matching version: %v", err) - } - tag = seedTag(t, tc, "actor-2", tagRef.Name) - if err := del(&ateapi.DeleteOptions{Uid: tag.GetMetadata().GetUid()}); err != nil { - t.Fatalf("DeleteTag with the matching uid: %v", err) - } - tag = seedTag(t, tc, "actor-3", tagRef.Name) - if err := del(&ateapi.DeleteOptions{Uid: tag.GetMetadata().GetUid(), Version: tag.GetMetadata().GetVersion()}); err != nil { - t.Fatalf("DeleteTag with both guards: %v", err) - } - _, err := tc.client.GetTag(ctx, &ateapi.GetTagRequest{Tag: ref}) - assertGrpcError(t, err, codes.NotFound, "Tag "+tagRef.String()+" not found") -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/worker_contention_test.go b/cmd/ateapi/internal/controlapi/functionaltest/worker_contention_test.go deleted file mode 100644 index 8fc1573d1c..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/worker_contention_test.go +++ /dev/null @@ -1,228 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "fmt" - "sync" - "testing" - "time" - - "k8s.io/apimachinery/pkg/util/wait" - - "go.ate.dev/substrate/api/ateapi/v1" - "go.ate.dev/substrate/cmd/ateapi/internal/store" - "go.ate.dev/substrate/internal/hardware" - "google.golang.org/protobuf/proto" -) - -// TestResumeActor_ConcurrentOntoOneWorker is the regression test for a refusal -// that only concurrency produces, and that a worker hosting one actor could -// never have shown. -// -// Claiming a worker rewrites that worker's whole record, so actors activating -// onto the SAME worker are N writers compare-and-swapping one row. All but one -// lose each round. That is fine and expected -- the loser re-reads and tries -// again -- but only if the retry budget is sized for how many writers there -// are. It was five steps from 10ms, and on a real cluster that rejected 21% of -// activations at 12 in flight and 67% at 24, every one of them failing at -// ~235ms with "timed out waiting for the condition". -// -// Nothing sequential catches it: the same activations one at a time all -// succeed, which is exactly what the pre-existing resume tests do. -func TestResumeActor_ConcurrentOntoOneWorker(t *testing.T) { - const actors = 128 - - ns := namespaceForTest("ns-resume-contention") - tc := setupTest(t, ns) - defer tc.cleanup() - - // createTemplate makes pool1 for us; widen it so one worker has room for all - // of them. The point is that they contend, not that they are turned away for - // lack of capacity. - createTemplate(t, tc, ns) - createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - setWorkerActorCapacity(t, tc, "pool1", actors) - - for i := range actors { - if _, err := tc.client.CreateActor(context.Background(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: fmt.Sprintf("id%d", i)}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor %d: %v", i, err) - } - } - - // Resume them all at once. Starting the goroutines is not enough to make - // them race -- release them together so they arrive at the claim inside the - // same window. - var start sync.WaitGroup - start.Add(1) - var wg sync.WaitGroup - errs := make([]error, actors) - for i := range actors { - wg.Go(func() { - start.Wait() - _, errs[i] = tc.client.ResumeActor(context.Background(), &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: fmt.Sprintf("id%d", i)}, - }) - }) - } - start.Done() - wg.Wait() - - var failed int - for i, err := range errs { - if err != nil { - failed++ - if failed <= 3 { - t.Errorf("ResumeActor id%d: %v", i, err) - } - } - } - if failed > 0 { - t.Fatalf("%d of %d concurrent activations onto one worker were refused; "+ - "they contend on the worker record and the retry budget has to absorb that", failed, actors) - } - - // And every one of them is really on the worker: a claim that was lost but - // reported as won would show up here rather than as an error above. Found by - // pod rather than by taking the only worker in the list -- the list is - // process-wide, so a -count>1 run sees the workers earlier iterations made. - listed, err := tc.client.ListWorkers(context.Background(), &ateapi.ListWorkersRequest{}) - if err != nil { - t.Fatalf("ListWorkers: %v", err) - } - var worker *ateapi.Worker - for _, candidate := range listed.GetWorkers() { - if candidate.GetWorkerNamespace() == ns && candidate.GetWorkerPod() == "worker-1" { - worker = candidate - break - } - } - if worker == nil { - t.Fatalf("worker %s/worker-1 not in the list of %d", ns, len(listed.GetWorkers())) - } - // A listing reports occupancy through the allocation total; the assignments - // themselves are their own records. - if got := int(worker.GetStatus().GetAllocated().GetActors()); got != actors { - t.Errorf("worker allocation counts %d actors, want %d", got, actors) - } - page, err := tc.persistence.ListWorkerAssignments(context.Background(), worker.GetMetadata().GetName(), store.ListOptions{}) - if err != nil { - t.Fatalf("ListWorkerAssignments: %v", err) - } - if len(page.Items) != actors { - t.Errorf("worker holds %d assignments, want %d", len(page.Items), actors) - } -} - -// setWorkerActorCapacity raises the actors ceiling on every Worker in the pool. -// -// The ceiling is the Worker's, reported by its worker, so a test that wants more -// than the unset default of one writes it where the reporter would. Waits for -// the scheduler's cache to see it, since placement reads that and not the store. -func setWorkerActorCapacity(t *testing.T, tc *testContext, pool string, actors int32) { - t.Helper() - page, err := tc.persistence.ListWorkers(context.Background(), store.ListOptions{PageSize: 1000}) - if err != nil { - t.Fatalf("listing workers: %v", err) - } - var reported int - for _, w := range page.Items { - if w.GetWorkerPool() != pool { - continue - } - reportWorkerCapacity(t, tc, w.GetMetadata().GetName(), actors) - reported++ - } - if reported == 0 { - t.Fatalf("no workers in pool %q to give capacity", pool) - } -} - -// reportedEpoch is the epoch reportWorkerCapacity registers, and the one the -// fake atelet reports its workloads ran under. -const reportedEpoch = 1 - -// defaultWorkerRuntime returns the default ActorSandboxRuntime that -// reportWorkerCapacity records on a test worker of the given sandbox class. -func defaultWorkerRuntime(class string) *ateapi.ActorSandboxRuntime { - if class == "" { - class = "gvisor" - } - return &ateapi.ActorSandboxRuntime{ - SandboxClass: class, - Version: &ateapi.VersionedSandboxCompat{ - SchemaVersion: hardware.SchemaVersionV1, - Attributes: []*ateapi.AttributeEntry{ - {Key: hardware.AttrArchitecture, Value: "amd64"}, - {Key: hardware.AttrSandboxBundleHash, Value: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, - }, - }, - } -} - -// workerSandboxClasses is the sandbox_classes a worker reports to run def as -// its default runtime and restore restorable beyond it, all of def's class. -// The arguments are the ActorSandboxRuntimes a test also expects on snapshots and -// assignments, so both sides of a match derive from one value; the compats -// are copied so the stored row never aliases them. -func workerSandboxClasses(def *ateapi.ActorSandboxRuntime, restorable ...*ateapi.ActorSandboxRuntime) []*ateapi.WorkerSandboxClass { - class := &ateapi.WorkerSandboxClass{SandboxClass: def.GetSandboxClass(), DefaultRuntime: &ateapi.WorkerSandboxRuntime{Version: proto.CloneOf(def.GetVersion())}} - for _, r := range restorable { - class.RestorableRuntimes = append(class.RestorableRuntimes, &ateapi.WorkerSandboxRuntime{Version: proto.CloneOf(r.GetVersion())}) - } - return []*ateapi.WorkerSandboxClass{class} -} - -// reportWorkerCapacity stands in for the worker process's registration and -// runtimes report, which atelet forwards to WorkerService in a real cluster, -// with compute for actors of the size test templates declare. A Worker not yet -// registered gets reportedEpoch, an IP and a default runtime; one already -// registered keeps them. It waits for the worker cache, which placement reads, -// to catch up. -func reportWorkerCapacity(t *testing.T, tc *testContext, name string, actors int32) { - t.Helper() - ctx := context.Background() - worker, err := tc.persistence.GetWorker(ctx, name) - if err != nil { - t.Fatalf("getting worker %s: %v", name, err) - } - if _, err := tc.persistence.UpdateWorker(ctx, name, store.PreconditionFrom(worker), func(toUpdate *ateapi.Worker) error { - if toUpdate.Status.RegisteredEpoch == 0 { - toUpdate.Status.RegisteredEpoch = reportedEpoch - toUpdate.Status.Ips = []string{"127.0.0.1"} - } - toUpdate.Status.Capacity = &ateapi.WorkerResources{ - Actors: actors, - CpuMillicores: int64(actors) * 1000, MemoryBytes: int64(actors) * 512 << 20, - } - if len(toUpdate.Status.SandboxClasses) == 0 { - toUpdate.Status.SandboxClasses = workerSandboxClasses(defaultWorkerRuntime("gvisor")) - } - return nil - }); err != nil { - t.Fatalf("setting capacity on worker %s: %v", name, err) - } - if err := wait.PollUntilContextTimeout(ctx, 10*time.Millisecond, 5*time.Second, true, - func(context.Context) (bool, error) { - got, err := tc.workerCache.Worker(name) - return err == nil && got.GetStatus().GetCapacity().GetActors() == actors, nil - }); err != nil { - t.Fatalf("worker %s did not reach capacity.actors=%d in the cache: %v", name, actors, err) - } -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/worker_restart_test.go b/cmd/ateapi/internal/controlapi/functionaltest/worker_restart_test.go deleted file mode 100644 index 70d8abab2f..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/worker_restart_test.go +++ /dev/null @@ -1,156 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "slices" - "testing" - - "go.ate.dev/substrate/api/ateapi/v1" - "go.ate.dev/substrate/cmd/ateapi/internal/controlapi" - "go.ate.dev/substrate/cmd/ateapi/internal/store" - "google.golang.org/grpc/codes" - "google.golang.org/grpc/status" -) - -// TestResumeActor_RetriedAfterWorkerRestartDuringRestore drives a resume whose -// restore finished on a worker process that was replaced before the resume -// committed RUNNING. The resume reports Unavailable and keeps its assignment; -// the reconciler for the new epoch leaves the RESUMING actor to it; a retry -// while the new process has yet to report its runtimes waits; and the next -// retry restores the actor on the new process, stamped with its epoch and IPs. -func TestResumeActor_RetriedAfterWorkerRestartDuringRestore(t *testing.T) { - ns := namespaceForTest("ns-restart-restore") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - - createTemplate(t, tc, ns) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - ref := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: ref.GetAtespace(), Name: ref.GetName()}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - - const newEpoch = reportedEpoch + 1 - newIPs := []string{"127.0.0.2"} - updateWorker := func(mutate func(*ateapi.WorkerStatus)) { - t.Helper() - worker, err := tc.persistence.GetWorker(ctx, podUID) - if err != nil { - t.Fatalf("GetWorker: %v", err) - } - if _, err := tc.persistence.UpdateWorker(ctx, podUID, store.PreconditionFrom(worker), func(w *ateapi.Worker) error { - mutate(w.Status) - return nil - }); err != nil { - t.Fatalf("UpdateWorker: %v", err) - } - } - getActor := func() *ateapi.Actor { - t.Helper() - actor, err := tc.client.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("GetActor failed: %v", err) - } - return actor - } - - // The restore finishes on the original process, which then exits; a new - // process registers before the resume commits. Registering activates its - // epoch, replaces the IPs, and clears the runtimes until it reports them. - var restores int - tc.fakeAtelet.RestoreWorkerEpoch = func() int64 { - restores++ - if restores == 1 { - updateWorker(func(s *ateapi.WorkerStatus) { - s.RegisteredEpoch = newEpoch - s.Ips = newIPs - s.SandboxClasses = nil - }) - return reportedEpoch - } - return newEpoch - } - - _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}) - if got := status.Code(err); got != codes.Unavailable { - t.Fatalf("first ResumeActor = %v (err %v), want Unavailable", got, err) - } - if got := getActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RESUMING { - t.Fatalf("actor state after the first resume = %v, want RESUMING", got) - } - - // The reconciler for the new epoch leaves the RESUMING actor, and its - // claim, to the resume. - if err := controlapi.NewWorkerWorkflow(tc.persistence, nil).ReconcileAssignments(ctx, podUID); err != nil { - t.Fatalf("ReconcileAssignments: %v", err) - } - if got := getActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RESUMING { - t.Fatalf("actor state after reconcile = %v, want RESUMING", got) - } - - // Until the new process reports its runtimes the retry waits, without - // restoring or crashing anything. - _, err = tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}) - if got := status.Code(err); got != codes.Unavailable { - t.Fatalf("ResumeActor before runtimes are reported = %v (err %v), want Unavailable", got, err) - } - if restores != 1 { - t.Fatalf("restores = %d before runtimes are reported, want 1", restores) - } - - updateWorker(func(s *ateapi.WorkerStatus) { - s.SandboxClasses = workerSandboxClasses(defaultWorkerRuntime("gvisor")) - }) - resp, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}) - if err != nil { - t.Fatalf("ResumeActor after the restart: %v", err) - } - if restores != 2 { - t.Errorf("restores = %d, want the retry to restore again", restores) - } - actor := resp.GetActor() - if got := actor.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Fatalf("actor state = %v, want RUNNING", got) - } - assignment := actor.GetStatus().GetWorkerAssignment() - if got := assignment.GetWorkerEpoch(); got != newEpoch { - t.Errorf("worker_epoch = %d, want %d", got, newEpoch) - } - if got := assignment.GetWorkerPodIps(); !slices.Equal(got, newIPs) { - t.Errorf("worker_pod_ips = %v, want %v", got, newIPs) - } - - // The claim taken by the first attempt is the one the actor runs under: - // the worker still books one actor, and a later reconcile keeps it. - if err := controlapi.NewWorkerWorkflow(tc.persistence, nil).ReconcileAssignments(ctx, podUID); err != nil { - t.Fatalf("ReconcileAssignments: %v", err) - } - if got := getActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RUNNING { - t.Errorf("actor state after a later reconcile = %v, want RUNNING", got) - } - worker, err := tc.persistence.GetWorker(ctx, podUID) - if err != nil { - t.Fatalf("GetWorker: %v", err) - } - if got := worker.GetStatus().GetAllocated().GetActors(); got != 1 { - t.Errorf("worker allocated actors = %d, want 1", got) - } -} diff --git a/cmd/ateapi/internal/controlapi/functionaltest/worker_test.go b/cmd/ateapi/internal/controlapi/functionaltest/worker_test.go deleted file mode 100644 index 0aa56a2c7e..0000000000 --- a/cmd/ateapi/internal/controlapi/functionaltest/worker_test.go +++ /dev/null @@ -1,407 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 functionaltest - -import ( - "context" - "fmt" - "testing" - "time" - - "github.com/google/go-cmp/cmp" - "go.ate.dev/substrate/api/ateapi/v1" - "google.golang.org/grpc/codes" - "google.golang.org/protobuf/testing/protocmp" - "k8s.io/apimachinery/pkg/util/wait" -) - -// Workers are named after the pod UID they were derived from. -const testWorkerName = "5f2c1a90-7b34-4e6d-8a11-0c3e9d5b7f42" - -// newTestWorker returns a Worker in the shape CreateWorker accepts: named after -// its pod UID, with the pod coordinates filled in and no status. Status is -// output-only, and that includes capacity — a Worker gets that from its own -// worker's report to WorkerService, not from whoever registered it. These tests -// never place an actor, so the unreported default is enough. -// -// The Worker stands on its own, with no pod behind it. That is enough for the -// CRUD API — only the atelet dialer resolves a Worker to a pod, and nothing in -// ate-api reconciles the two now that the syncer runs in ate-controller. Tests -// that need both use createWorkerPod. -func newTestWorker(ns string) *ateapi.Worker { - return &ateapi.Worker{ - Metadata: &ateapi.ResourceMetadata{Name: testWorkerName}, - WorkerNamespace: ns, - WorkerPool: "pool1", - WorkerPod: "worker-api-1", - WorkerPodUid: testWorkerName, - NodeName: "node1", - } -} - -// registerWorker registers newTestWorker over the API and returns it as stored. -func registerWorker(t *testing.T, tc *testContext, ns string) *ateapi.Worker { - t.Helper() - created, err := tc.client.CreateWorker(context.Background(), &ateapi.CreateWorkerRequest{Worker: newTestWorker(ns)}) - if err != nil { - t.Fatalf("CreateWorker failed: %v", err) - } - return created -} - -func workerRef(name string) *ateapi.ObjectRef { - return &ateapi.ObjectRef{Name: name} -} - -// waitForWorkerState waits for a state committed by an RPC to reach the worker -// cache, which follows the store through a PostgreSQL watch and so lands -// shortly after the call returns rather than with it. -func waitForWorkerState(t *testing.T, tc *testContext, name string, want ateapi.WorkerState) { - t.Helper() - err := wait.PollUntilContextTimeout(context.Background(), 10*time.Millisecond, 5*time.Second, true, func(context.Context) (bool, error) { - worker, err := tc.workerCache.Worker(name) - if err != nil { - return false, nil - } - return worker.GetStatus().GetState() == want, nil - }) - if err != nil { - t.Fatalf("worker %s did not reach state %v in the worker cache: %v", name, want, err) - } -} - -func containsWorker(workers []*ateapi.Worker, name string) bool { - for _, w := range workers { - if w.GetMetadata().GetName() == name { - return true - } - } - return false -} - -// TestCreateAndGetWorker registers a Worker and reads it back, checking that -// the server assigns the metadata and the UNAVAILABLE status a new Worker -// starts in. -func TestCreateAndGetWorker(t *testing.T) { - ns := namespaceForTest("ns-worker-create-get") - tc := setupTest(t, ns) - defer tc.cleanup() - - created := registerWorker(t, tc, ns) - - want := newTestWorker(ns) - want.Metadata.Version = 1 - want.Status = &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_UNAVAILABLE} - if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreServerMetadata); diff != "" { - t.Errorf("CreateWorker response mismatch (-want +got):\n%s", diff) - } - if created.GetMetadata().GetUid() == "" { - t.Errorf("CreateWorker returned no uid, which every later guard needs") - } - - got, err := tc.client.GetWorker(context.Background(), &ateapi.GetWorkerRequest{Worker: workerRef(testWorkerName)}) - if err != nil { - t.Fatalf("GetWorker failed: %v", err) - } - if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { - t.Errorf("GetWorker returned something other than what CreateWorker stored (-created +got):\n%s", diff) - } -} - -// TestListWorkers tests that registered workers are listed. -// Workflow: -// 1. Creates a mock WorkerPool in Kubernetes. -// 2. Creates a mock worker Pod in Kubernetes belonging to that pool, registers -// the Worker the syncer would derive from it, and reports the capacity its -// worker would. -// 3. Calls ListWorkers RPC. -// 4. Verifies that the worker appears in the response. -func TestListWorkers(t *testing.T) { - ns := namespaceForTest("ns-list-workers") - tc := setupTest(t, ns) - defer tc.cleanup() - - createWorkerPool(t, tc, ns, "pool1", map[string]string{"foo": "bar"}) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - listResp, err := tc.client.ListWorkers(context.Background(), &ateapi.ListWorkersRequest{}) - if err != nil { - t.Fatalf("ListWorkers failed: %v", err) - } - - var filteredWorkers []*ateapi.Worker - for _, w := range listResp.GetWorkers() { - if w.GetWorkerNamespace() == ns { - filteredWorkers = append(filteredWorkers, w) - } - } - - want := []*ateapi.Worker{ - { - Metadata: &ateapi.ResourceMetadata{ - Name: podUID, - // Three writes: the registration, marking it available, then - // the capacity report. - Version: 3, - }, - WorkerNamespace: ns, - WorkerPool: "pool1", - WorkerPod: "worker-1", - WorkerPodUid: podUID, - NodeName: "node1", - Labels: map[string]string{"foo": "bar"}, - Status: &ateapi.WorkerStatus{ - State: ateapi.WorkerState_WORKER_STATE_ACTIVE, - RegisteredEpoch: reportedEpoch, - Ips: []string{"127.0.0.1"}, - Capacity: &ateapi.WorkerResources{Actors: 1, CpuMillicores: 1000, MemoryBytes: 512 << 20}, - SandboxClasses: workerSandboxClasses(defaultWorkerRuntime("gvisor")), - }, - }, - } - - if diff := cmp.Diff(want, filteredWorkers, protocmp.Transform(), ignoreServerMetadata); diff != "" { - t.Errorf("ListWorkers response mismatch (-want +got):\n%s", diff) - } -} - -// TestListWorkerActorAssignments reads the Actors a Worker hosts. They are a -// subresource rather than a field on Worker, so this is the only way to see -// them: a Worker hosting nothing lists an empty page, and one an Actor was -// placed on lists that Actor. -func TestListWorkerActorAssignments(t *testing.T) { - ns := namespaceForTest("ns-worker-assignments") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - - // createTemplate makes pool1 and tmpl1; the worker is what tmpl1's actors - // get placed on. - createTemplate(t, tc, ns) - podUID := createWorkerPod(t, tc, ns, "worker-1", "node1", "pool1") - - empty, err := tc.client.ListWorkerActorAssignments(ctx, &ateapi.ListWorkerActorAssignmentsRequest{Worker: workerRef(podUID)}) - if err != nil { - t.Fatalf("ListWorkerActorAssignments on an empty worker failed: %v", err) - } - if got := len(empty.GetActorAssignments()); got != 0 { - t.Errorf("worker hosting nothing lists %d assignments, want 0", got) - } - - if _, err := tc.client.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: testAtespace, Name: "id1"}, - ActorTemplate: &ateapi.ObjectRef{Atespace: testAtespace, Name: "tmpl1"}, - }}); err != nil { - t.Fatalf("CreateActor failed: %v", err) - } - if _, err := tc.client.ResumeActor(ctx, &ateapi.ResumeActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"}, - }); err != nil { - t.Fatalf("ResumeActor failed: %v", err) - } - - listed, err := tc.client.ListWorkerActorAssignments(ctx, &ateapi.ListWorkerActorAssignmentsRequest{Worker: workerRef(podUID)}) - if err != nil { - t.Fatalf("ListWorkerActorAssignments failed: %v", err) - } - if len(listed.GetActorAssignments()) != 1 { - t.Fatalf("worker hosting one actor lists %d assignments, want 1", len(listed.GetActorAssignments())) - } - want := &ateapi.ObjectRef{Atespace: testAtespace, Name: "id1"} - if diff := cmp.Diff(want, listed.GetActorAssignments()[0].GetActor(), protocmp.Transform()); diff != "" { - t.Errorf("assignment names the wrong actor (-want +got):\n%s", diff) - } -} - -// TestUpdateWorker changes labels, the only mutable field. An update replaces -// the whole Worker, so the request is the observed one with that field changed: -// its metadata carries the uid and version guards, and everything else has to -// be sent back as-is to avoid being cleared. -func TestUpdateWorker(t *testing.T) { - ns := namespaceForTest("ns-worker-update") - tc := setupTest(t, ns) - defer tc.cleanup() - - worker := registerWorker(t, tc, ns) - worker.Labels = map[string]string{"tier": "batch"} - - updated, err := tc.client.UpdateWorker(context.Background(), &ateapi.UpdateWorkerRequest{Worker: worker}) - if err != nil { - t.Fatalf("UpdateWorker failed: %v", err) - } - - want := newTestWorker(ns) - want.Metadata.Version = 2 - want.Labels = map[string]string{"tier": "batch"} - want.Status = &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_UNAVAILABLE} - if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreServerMetadata); diff != "" { - t.Errorf("UpdateWorker response mismatch (-want +got):\n%s", diff) - } -} - -// TestDrainWorker marks a Worker as terminating, and checks the state reaches -// the worker cache the scheduler places actors from. Without that, a drained -// Worker would keep taking work. -func TestDrainWorker(t *testing.T) { - ns := namespaceForTest("ns-worker-drain") - tc := setupTest(t, ns) - defer tc.cleanup() - - registerWorker(t, tc, ns) - waitForWorkerState(t, tc, testWorkerName, ateapi.WorkerState_WORKER_STATE_UNAVAILABLE) - - drained, err := tc.client.DrainWorker(context.Background(), &ateapi.DrainWorkerRequest{Worker: workerRef(testWorkerName)}) - if err != nil { - t.Fatalf("DrainWorker failed: %v", err) - } - - wantWorker := newTestWorker(ns) - wantWorker.Metadata.Version = 2 - wantWorker.Status = &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_DRAINING} - want := &ateapi.DrainWorkerResponse{Worker: wantWorker} - if diff := cmp.Diff(want, drained, protocmp.Transform(), ignoreServerMetadata); diff != "" { - t.Errorf("DrainWorker response mismatch (-want +got):\n%s", diff) - } - - waitForWorkerState(t, tc, testWorkerName, ateapi.WorkerState_WORKER_STATE_DRAINING) -} - -// TestMarkWorkerAvailability moves a Worker between ACTIVE and UNAVAILABLE, and -// checks each state reaches the worker cache the scheduler places actors from. -func TestMarkWorkerAvailability(t *testing.T) { - ns := namespaceForTest("ns-worker-availability") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - - registerWorker(t, tc, ns) - waitForWorkerState(t, tc, testWorkerName, ateapi.WorkerState_WORKER_STATE_UNAVAILABLE) - - available, err := tc.client.MarkWorkerAvailable(ctx, &ateapi.MarkWorkerAvailableRequest{Worker: workerRef(testWorkerName)}) - if err != nil { - t.Fatalf("MarkWorkerAvailable failed: %v", err) - } - want := newTestWorker(ns) - want.Metadata.Version = 2 - want.Status = &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_ACTIVE} - if diff := cmp.Diff(want, available.GetWorker(), protocmp.Transform(), ignoreServerMetadata); diff != "" { - t.Errorf("MarkWorkerAvailable response mismatch (-want +got):\n%s", diff) - } - waitForWorkerState(t, tc, testWorkerName, ateapi.WorkerState_WORKER_STATE_ACTIVE) - - unavailable, err := tc.client.MarkWorkerUnavailable(ctx, &ateapi.MarkWorkerUnavailableRequest{Worker: workerRef(testWorkerName)}) - if err != nil { - t.Fatalf("MarkWorkerUnavailable failed: %v", err) - } - want.Metadata.Version = 3 - want.Status = &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_UNAVAILABLE} - if diff := cmp.Diff(want, unavailable.GetWorker(), protocmp.Transform(), ignoreServerMetadata); diff != "" { - t.Errorf("MarkWorkerUnavailable response mismatch (-want +got):\n%s", diff) - } - waitForWorkerState(t, tc, testWorkerName, ateapi.WorkerState_WORKER_STATE_UNAVAILABLE) -} - -// TestDeleteWorker deregisters a Worker and checks it is gone. The delete -// marks and drains the Worker in one write on its way out, so the record it -// returns is one write past the one Create stored. Deregistering is not -// silently idempotent, so a second attempt reports NOT_FOUND. -func TestDeleteWorker(t *testing.T) { - ns := namespaceForTest("ns-worker-delete") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - - registerWorker(t, tc, ns) - - deleted, err := tc.client.DeleteWorker(ctx, &ateapi.DeleteWorkerRequest{Worker: workerRef(testWorkerName)}) - if err != nil { - t.Fatalf("DeleteWorker failed: %v", err) - } - want := newTestWorker(ns) - want.Metadata.Version = 2 - want.Status = &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_DRAINING} - if diff := cmp.Diff(want, deleted, protocmp.Transform(), ignoreServerMetadata); diff != "" { - t.Errorf("DeleteWorker response mismatch (-want +got):\n%s", diff) - } - if deleted.GetMetadata().GetDeleteTime() == nil { - t.Error("DeleteWorker returned a worker without delete_time") - } - - listed, err := tc.client.ListWorkers(ctx, &ateapi.ListWorkersRequest{}) - if err != nil { - t.Fatalf("ListWorkers failed: %v", err) - } - if containsWorker(listed.GetWorkers(), testWorkerName) { - t.Errorf("ListWorkers still returns worker %s after DeleteWorker", testWorkerName) - } - - _, err = tc.client.DeleteWorker(ctx, &ateapi.DeleteWorkerRequest{Worker: workerRef(testWorkerName)}) - assertGrpcError(t, err, codes.NotFound, fmt.Sprintf("Worker %s not found", testWorkerName)) -} - -func TestValidation_Worker(t *testing.T) { - ns := namespaceForTest("ns-validation-worker") - tc := setupTest(t, ns) - defer tc.cleanup() - - t.Run("ListWorkers", func(t *testing.T) { - _, err := tc.client.ListWorkers(context.Background(), &ateapi.ListWorkersRequest{Options: &ateapi.ListOptions{PageSize: -1}}) - assertGrpcErrorRegex(t, err, codes.InvalidArgument, "page_size: Invalid value") - }) - - t.Run("ListWorkers invalid token", func(t *testing.T) { - _, err := tc.client.ListWorkers(context.Background(), &ateapi.ListWorkersRequest{Options: &ateapi.ListOptions{PageToken: "%%%"}}) - assertGrpcError(t, err, codes.InvalidArgument, "invalid page_token") - }) -} - -func TestDeleteWorker_Preconditions(t *testing.T) { - ns := namespaceForTest("ns-worker-delete-preconditions") - tc := setupTest(t, ns) - defer tc.cleanup() - ctx := context.Background() - ref := workerRef(testWorkerName) - del := func(opts *ateapi.DeleteOptions) error { - _, err := tc.client.DeleteWorker(ctx, &ateapi.DeleteWorkerRequest{Worker: ref, Options: opts}) - return err - } - - worker := registerWorker(t, tc, ns) - uid, version := worker.GetMetadata().GetUid(), worker.GetMetadata().GetVersion() - - assertGrpcError(t, del(&ateapi.DeleteOptions{Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: uid, Version: version + 1}), codes.Aborted, "concurrent update conflict, please retry") - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID}), codes.Aborted, "Worker "+testWorkerName+" does not have uid "+foreignUID) - assertGrpcError(t, del(&ateapi.DeleteOptions{Uid: foreignUID, Version: version}), codes.Aborted, "Worker "+testWorkerName+" does not have uid "+foreignUID) - if _, err := tc.client.GetWorker(ctx, &ateapi.GetWorkerRequest{Worker: ref}); err != nil { - t.Fatalf("a refused delete removed the worker: %v", err) - } - - // The delete drains the worker first, which moves the version; the guard - // is checked against the record the caller read. - if err := del(&ateapi.DeleteOptions{Version: version}); err != nil { - t.Fatalf("DeleteWorker with the matching version: %v", err) - } - worker = registerWorker(t, tc, ns) - if err := del(&ateapi.DeleteOptions{Uid: worker.GetMetadata().GetUid()}); err != nil { - t.Fatalf("DeleteWorker with the matching uid: %v", err) - } - worker = registerWorker(t, tc, ns) - if err := del(&ateapi.DeleteOptions{Uid: worker.GetMetadata().GetUid(), Version: worker.GetMetadata().GetVersion()}); err != nil { - t.Fatalf("DeleteWorker with both guards: %v", err) - } - _, err := tc.client.GetWorker(ctx, &ateapi.GetWorkerRequest{Worker: ref}) - assertGrpcError(t, err, codes.NotFound, "Worker "+testWorkerName+" not found") -} diff --git a/cmd/ateapi/internal/controlapi/hosting_test.go b/cmd/ateapi/internal/controlapi/hosting_test.go index e9b2a829f7..4dbf586894 100644 --- a/cmd/ateapi/internal/controlapi/hosting_test.go +++ b/cmd/ateapi/internal/controlapi/hosting_test.go @@ -186,11 +186,11 @@ func TestHostingNodeAfterResumeOntoNewWorker(t *testing.T) { if err := wc.Start(cacheCtx); err != nil { t.Fatalf("workercache.Start: %v", err) } - w := &ActorWorkflow{store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} + w := &ActorWorkflow{gates: testGates, store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} tmpl := &ateapi.ActorTemplate{ WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"pool": "b"}}, } - resuming, _, err := w.assignWorkerAttempt(ctx, actorRef, actor, tmpl) + resuming, _, err := w.assignWorkerAttempt(ctx, actorRef, actor, tmpl, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt: %v", err) } diff --git a/cmd/ateapi/internal/controlapi/main_test.go b/cmd/ateapi/internal/controlapi/main_test.go index 8aefc024f8..e67cf733b8 100644 --- a/cmd/ateapi/internal/controlapi/main_test.go +++ b/cmd/ateapi/internal/controlapi/main_test.go @@ -23,11 +23,16 @@ import ( "go.ate.dev/substrate/internal/preview" ) +// testGates are the preview gates most tests run with. Most tests store +// snapshots under their template's storageLocation, which is honored only with +// the PerTemplateSnapshotLocation gate. Tests that need other gates build their +// own with preview.NewForTest. +var testGates *preview.Gates + func TestMain(m *testing.M) { - // Most tests store snapshots under their template's storageLocation, which - // is honored only with this gate. Tests that need it off call - // preview.InitForTest. - if err := preview.Init(string(preview.GatePerTemplateSnapshotLocation)); err != nil { + var err error + testGates, err = preview.New(string(preview.GatePerTemplateSnapshotLocation)) + if err != nil { fmt.Fprintln(os.Stderr, err) os.Exit(1) } diff --git a/cmd/ateapi/internal/controlapi/metrics.go b/cmd/ateapi/internal/controlapi/metrics.go index 7316a94d51..85f1bccf84 100644 --- a/cmd/ateapi/internal/controlapi/metrics.go +++ b/cmd/ateapi/internal/controlapi/metrics.go @@ -20,20 +20,25 @@ import ( "time" "go.ate.dev/substrate/api/ateapi/v1" - atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/scheduling" "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/hardware" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/metric" - "k8s.io/apimachinery/pkg/labels" ) const ( - workerpoolWorkersMetric = "ate.workerpool.workers" - lifecycleOpDurationMetric = "ate.actor.lifecycle.operation.duration" - schedulerAssignmentMetric = "ate.scheduler.assignment.duration" - actorCrashesMetric = "ate.actor.crashes" + workerpoolWorkersMetric = "ate.workerpool.workers" + workerCPUCapacityMetric = "ate.worker.cpu.capacity" + workerCPUAllocatedMetric = "ate.worker.cpu.allocated" + workerMemoryCapacityMetric = "ate.worker.memory.capacity" + workerMemoryAllocatedMetric = "ate.worker.memory.allocated" + workerActorCapacityMetric = "ate.worker.actor.capacity" + workerActorAllocatedMetric = "ate.worker.actor.allocated" + lifecycleOpDurationMetric = "ate.actor.lifecycle.operation.duration" + schedulerAssignmentMetric = "ate.scheduler.assignment.duration" + actorCrashesMetric = "ate.actor.crashes" ) var actorCrashesCounter metric.Int64Counter @@ -61,11 +66,10 @@ func recordActorCrash(ctx context.Context, attrs []attribute.KeyValue) { } // RegisterWorkerCount wires the ate.workerpool.workers observable against workers -// (workercache.Cache.Workers in prod) and listPools (a WorkerPool lister's List, -// used to seed zero-valued series). Worker counts are spatially summable (over +// (workercache.Cache.Workers in prod). Worker counts are spatially summable (over // states = pool size, over pools = fleet), which is the UpDownCounter contract; a // gauge would be wrong for a value meant to be summed. -func RegisterWorkerCount(meter metric.Meter, workers func() ([]*ateapi.Worker, error), listPools func(labels.Selector) ([]*atev1.WorkerPool, error)) error { +func RegisterWorkerCount(meter metric.Meter, workers func() ([]*ateapi.Worker, error)) error { counter, err := meter.Int64ObservableUpDownCounter( workerpoolWorkersMetric, metric.WithUnit("{worker}"), @@ -83,20 +87,6 @@ func RegisterWorkerCount(meter metric.Meter, workers func() ([]*ateapi.Worker, e } type key struct{ namespace, pool, state, class string } tally := make(map[key]int64) - // Seed every state at 0 for every known pool so a saturated or empty pool - // reports 0, not an absent series that breaks idle==0 alerts. A failed - // list just means no seeding this cycle, not a broken observation. - if pools, err := listPools(labels.Everything()); err == nil { - for _, p := range pools { - class := string(p.Spec.DefaultSandboxClass()) - if class == "" { - class = string(atev1.SandboxClassGvisor) - } - for _, state := range workerStates { - tally[key{p.Namespace, p.Name, state, class}] = 0 - } - } - } for _, w := range ws { state := workerState(w) // A Worker has no sandbox class until its worker registers with @@ -104,6 +94,18 @@ func RegisterWorkerCount(meter metric.Meter, workers func() ([]*ateapi.Worker, e // scheduler puts no actor on a worker that offers no class, thus // the pool's series must not count it as free capacity. class := ateattr.NormalizeSandboxClass(hardware.SandboxClass(w.GetStatus())) + if class != ateattr.SandboxClassUnknown { + // Seed every state at 0 for the worker's pool so an idle==0 + // alert sees 0 when the pool is full. Unknown seeds nothing, + // so a pool has no series for its class until a worker reports + // one; the idle query in docs/guides/observability.md allows for that. + for _, s := range workerStates { + k := key{w.GetWorkerNamespace(), w.GetWorkerPool(), s, class} + if _, exists := tally[k]; !exists { + tally[k] = 0 + } + } + } tally[key{w.GetWorkerNamespace(), w.GetWorkerPool(), state, class}]++ } for k, n := range tally { @@ -146,6 +148,113 @@ func workerState(w *ateapi.Worker) string { } } +// RegisterWorkerResources wires the per-worker capacity and allocated +// instruments, the substrate form of k8s.node.{cpu,memory,pod}.allocatable. +// They are per worker and not per pool because free room does not add up +// across workers: ten workers with 0.5 CPU free each cannot take a 1 CPU actor. +// +// A worker has a capacity series for a resource only while the scheduler can +// place on it and it reports that resource, so a draining or unregistered +// worker never reads as free room. Allocated is what the actors booked (their +// limits plus runtime overhead), not what they use. Every worker reports it, +// 0 when empty: a series that vanished on emptying would leave its last +// non-zero value in the backend for the lookback window. +// +// Every ateapi replica reports every worker, and each instrument has one series +// per worker. Past 2000 workers that hits the SDK's default cardinality limit +// and the rest fold into one overflow series, so a larger fleet must raise +// OTEL_GO_X_CARDINALITY_LIMIT on ateapi. +func RegisterWorkerResources(meter metric.Meter, workers func() ([]*ateapi.Worker, error)) error { + cpuCapacity, err := meter.Float64ObservableUpDownCounter( + workerCPUCapacityMetric, + metric.WithUnit("{cpu}"), + metric.WithDescription("CPU cores of a worker that actors can book."), + ) + if err != nil { + return fmt.Errorf("create %s updowncounter: %w", workerCPUCapacityMetric, err) + } + cpuAllocated, err := meter.Float64ObservableUpDownCounter( + workerCPUAllocatedMetric, + metric.WithUnit("{cpu}"), + metric.WithDescription("CPU cores of a worker that its actors booked."), + ) + if err != nil { + return fmt.Errorf("create %s updowncounter: %w", workerCPUAllocatedMetric, err) + } + memoryCapacity, err := meter.Int64ObservableUpDownCounter( + workerMemoryCapacityMetric, + metric.WithUnit("By"), + metric.WithDescription("Memory of a worker that actors can book."), + ) + if err != nil { + return fmt.Errorf("create %s updowncounter: %w", workerMemoryCapacityMetric, err) + } + memoryAllocated, err := meter.Int64ObservableUpDownCounter( + workerMemoryAllocatedMetric, + metric.WithUnit("By"), + metric.WithDescription("Memory of a worker that its actors booked."), + ) + if err != nil { + return fmt.Errorf("create %s updowncounter: %w", workerMemoryAllocatedMetric, err) + } + actorCapacity, err := meter.Int64ObservableUpDownCounter( + workerActorCapacityMetric, + metric.WithUnit("{actor}"), + metric.WithDescription("Number of actors a worker can hold."), + ) + if err != nil { + return fmt.Errorf("create %s updowncounter: %w", workerActorCapacityMetric, err) + } + actorAllocated, err := meter.Int64ObservableUpDownCounter( + workerActorAllocatedMetric, + metric.WithUnit("{actor}"), + metric.WithDescription("Number of actors assigned to a worker."), + ) + if err != nil { + return fmt.Errorf("create %s updowncounter: %w", workerActorAllocatedMetric, err) + } + + _, err = meter.RegisterCallback(func(_ context.Context, o metric.Observer) error { + ws, err := workers() + if err != nil { + // Worker cache unavailable (warmup/reconnect): skip the whole observation. + return nil + } + for _, w := range ws { + capacity, allocated := w.GetStatus().GetCapacity(), w.GetStatus().GetAllocated() + // checkRoom places nothing on a worker with no actor slots, whatever + // CPU and memory it has. + placeable := w.GetStatus().GetState() == ateapi.WorkerState_WORKER_STATE_ACTIVE && + scheduling.Registered(w) && capacity.GetActors() > 0 + attrs := metric.WithAttributes(ateattr.WorkerMetricAttributes(w)...) + + // A capacity of 0 is a resource the worker did not report, not a + // full worker, so it gets no series. + if placeable && capacity.GetCpuMillicores() > 0 { + o.ObserveFloat64(cpuCapacity, cores(capacity.GetCpuMillicores()), attrs) + } + if placeable && capacity.GetMemoryBytes() > 0 { + o.ObserveInt64(memoryCapacity, capacity.GetMemoryBytes(), attrs) + } + if placeable { + o.ObserveInt64(actorCapacity, int64(capacity.GetActors()), attrs) + } + o.ObserveFloat64(cpuAllocated, cores(allocated.GetCpuMillicores()), attrs) + o.ObserveInt64(memoryAllocated, allocated.GetMemoryBytes(), attrs) + o.ObserveInt64(actorAllocated, int64(allocated.GetActors()), attrs) + } + return nil + }, cpuCapacity, cpuAllocated, memoryCapacity, memoryAllocated, actorCapacity, actorAllocated) + if err != nil { + return fmt.Errorf("register worker resource callback: %w", err) + } + return nil +} + +func cores(millicores int64) float64 { + return float64(millicores) / 1000 +} + // Instruments holds ateapi's actor-lifecycle and scheduler duration histograms. // A nil *Instruments is a valid no-op, so call sites need no guard. Worker-count // is registered separately (RegisterWorkerCount): a callback-driven observable, diff --git a/cmd/ateapi/internal/controlapi/metrics_test.go b/cmd/ateapi/internal/controlapi/metrics_test.go index d9c7e87db1..c44d62c7f3 100644 --- a/cmd/ateapi/internal/controlapi/metrics_test.go +++ b/cmd/ateapi/internal/controlapi/metrics_test.go @@ -18,11 +18,12 @@ import ( "context" "errors" "fmt" + "maps" + "slices" "testing" "time" "go.ate.dev/substrate/api/ateapi/v1" - atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/ateattr" "go.opentelemetry.io/otel/attribute" @@ -30,25 +31,21 @@ import ( "go.opentelemetry.io/otel/sdk/metric/metricdata" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - "k8s.io/apimachinery/pkg/labels" ) // newWorkerCountReader registers ate.workerpool.workers against a local // ManualReader-backed provider so tests stay parallel-safe and never touch the // global meter provider. -func newWorkerCountReader(t *testing.T, workers func() ([]*ateapi.Worker, error), listPools func(labels.Selector) ([]*atev1.WorkerPool, error)) *sdkmetric.ManualReader { +func newWorkerCountReader(t *testing.T, workers func() ([]*ateapi.Worker, error)) *sdkmetric.ManualReader { t.Helper() reader := sdkmetric.NewManualReader() mp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)) - if err := RegisterWorkerCount(mp.Meter("ateapi"), workers, listPools); err != nil { + if err := RegisterWorkerCount(mp.Meter("ateapi"), workers); err != nil { t.Fatalf("RegisterWorkerCount: %v", err) } return reader } -func noPools(labels.Selector) ([]*atev1.WorkerPool, error) { return nil, nil } - func collectMetric(t *testing.T, reader *sdkmetric.ManualReader, name string) (metricdata.Metrics, bool) { t.Helper() var rm metricdata.ResourceMetrics @@ -93,7 +90,8 @@ func worker(namespace, pool, class string, allocated, capacity int32) *ateapi.Wo type series struct{ namespace, pool, state, class string } -// seeded adds the zero series ateapi reports for every state of a known pool. +// seeded adds the zero series ateapi reports for every state of a pool and +// class once a worker of that class reports in. func seeded(m map[series]int64, namespace, pool, class string) map[series]int64 { if m == nil { m = make(map[series]int64) @@ -139,7 +137,7 @@ func TestWorkerCountTally(t *testing.T) { worker("ns-2", "pool-a", "gvisor", 0, 1), }, nil } - reader := newWorkerCountReader(t, workers, noPools) + reader := newWorkerCountReader(t, workers) m := mustMetric(t, reader, workerpoolWorkersMetric) if m.Unit != "{worker}" { @@ -154,19 +152,20 @@ func TestWorkerCountTally(t *testing.T) { } got := seriesCounts(sum) - want := map[series]int64{ - {"ns-1", "pool-a", ateattr.WorkerStateIdle, "gvisor"}: 2, - {"ns-1", "pool-a", ateattr.WorkerStateAtCapacity, "gvisor"}: 1, - {"ns-1", "pool-a", ateattr.WorkerStatePartial, "gvisor"}: 1, - {"ns-1", "pool-b", ateattr.WorkerStateIdle, "microvm"}: 1, - {"ns-2", "pool-a", ateattr.WorkerStateIdle, "gvisor"}: 1, - } + want := seeded(nil, "ns-1", "pool-a", "gvisor") + want = seeded(want, "ns-1", "pool-b", "microvm") + want = seeded(want, "ns-2", "pool-a", "gvisor") + want[series{"ns-1", "pool-a", ateattr.WorkerStateIdle, "gvisor"}] = 2 + want[series{"ns-1", "pool-a", ateattr.WorkerStateAtCapacity, "gvisor"}] = 1 + want[series{"ns-1", "pool-a", ateattr.WorkerStatePartial, "gvisor"}] = 1 + want[series{"ns-1", "pool-b", ateattr.WorkerStateIdle, "microvm"}] = 1 + want[series{"ns-2", "pool-a", ateattr.WorkerStateIdle, "gvisor"}] = 1 if len(got) != len(want) { t.Fatalf("got %d series, want %d: %v", len(got), len(want), got) } for k, v := range want { - if got[k] != v { - t.Errorf("series %v = %d, want %d", k, got[k], v) + if gv, ok := got[k]; !ok || gv != v { + t.Errorf("series %v = %d (present=%v), want %d", k, gv, ok, v) } } } @@ -177,7 +176,7 @@ func TestWorkerCountSkipsWhenCacheNotReady(t *testing.T) { notReady := func() ([]*ateapi.Worker, error) { return nil, context.DeadlineExceeded } - reader := newWorkerCountReader(t, notReady, noPools) + reader := newWorkerCountReader(t, notReady) if _, ok := collectMetric(t, reader, workerpoolWorkersMetric); ok { t.Errorf("%s was collected, want no datapoints while cache not ready", workerpoolWorkersMetric) @@ -411,32 +410,18 @@ func TestSchedulerAssignmentShapeAndOutcomes(t *testing.T) { } } -func workerPool(namespace, name string, class atev1.SandboxClass) *atev1.WorkerPool { - return &atev1.WorkerPool{ - ObjectMeta: metav1.ObjectMeta{Namespace: namespace, Name: name}, - Spec: atev1.WorkerPoolSpec{SandboxClasses: []atev1.WorkerPoolSandboxClass{{Name: class}}}, - } -} - -// TestWorkerCountSeedsZeroForKnownPools covers the saturation cases: a pool whose -// only state has no workers, and a pool with no workers at all, both report 0 -// rather than an absent series. Empty pool class defaults to gvisor. -func TestWorkerCountSeedsZeroForKnownPools(t *testing.T) { - pools := func(labels.Selector) ([]*atev1.WorkerPool, error) { - return []*atev1.WorkerPool{ - workerPool("ns-1", "pool-a", ""), - workerPool("ns-2", "pool-a", atev1.SandboxClassMicroVM), - }, nil - } +// TestWorkerCountSeedsZeroForPoolsWithWorkers covers the saturation case: a pool whose +// only worker is at_capacity still reports 0 for idle, partial, and +// unschedulable, so an idle==0 alert fires. +func TestWorkerCountSeedsZeroForPoolsWithWorkers(t *testing.T) { workers := func() ([]*ateapi.Worker, error) { return []*ateapi.Worker{worker("ns-1", "pool-a", "gvisor", 1, 1)}, nil } - reader := newWorkerCountReader(t, workers, pools) + reader := newWorkerCountReader(t, workers) sum := mustMetric(t, reader, workerpoolWorkersMetric).Data.(metricdata.Sum[int64]) got := seriesCounts(sum) want := seeded(nil, "ns-1", "pool-a", "gvisor") - want = seeded(want, "ns-2", "pool-a", "microvm") want[series{"ns-1", "pool-a", ateattr.WorkerStateAtCapacity, "gvisor"}] = 1 if len(got) != len(want) { t.Fatalf("got %d series, want %d: %v", len(got), len(want), got) @@ -448,57 +433,50 @@ func TestWorkerCountSeedsZeroForKnownPools(t *testing.T) { } } -// TestWorkerCountEmptyClassWorker covers the workers that have not yet -// reported default_runtime via RegisterWorker. They report as unknown, not as -// an empty-string class, and not as capacity of the pool they name: the -// scheduler puts no actor on them, thus the pool's own series stays at 0 and -// an idle==0 alert on it still fires. +// TestWorkerCountEmptyClassWorker covers the workers whose process has not yet +// reported a class with SetWorkerSandboxRuntimes. They count under unknown and +// seed no zero series: the scheduler puts no actor on them, so the pool has no +// series for its class until a worker reports one. func TestWorkerCountEmptyClassWorker(t *testing.T) { - const ( - gvisor = string(atev1.SandboxClassGvisor) - microvm = string(atev1.SandboxClassMicroVM) - ) tests := []struct { name string - pools []*atev1.WorkerPool workers []*ateapi.Worker want map[series]int64 }{ { - name: "gvisor pool", - pools: []*atev1.WorkerPool{workerPool("ns-1", "pool-empty", "")}, + // Three workers, one series. No gvisor series exists, so a plain + // idle==0 alert on gvisor does not fire for this pool. + name: "only workers without a class", workers: []*ateapi.Worker{ worker("ns-1", "pool-empty", "", 0, 1), worker("ns-1", "pool-empty", "", 0, 1), worker("ns-1", "pool-empty", "", 0, 1), }, - want: withCount(seeded(nil, "ns-1", "pool-empty", gvisor), - series{"ns-1", "pool-empty", ateattr.WorkerStateIdle, ateattr.SandboxClassUnknown}, 3), - }, - { - // No gvisor series shows for a pool that runs no gvisor. - name: "microvm pool", - pools: []*atev1.WorkerPool{workerPool("ns-1", "pool-micro", atev1.SandboxClassMicroVM)}, - workers: []*ateapi.Worker{worker("ns-1", "pool-micro", "", 0, 1)}, - want: withCount(seeded(nil, "ns-1", "pool-micro", microvm), - series{"ns-1", "pool-micro", ateattr.WorkerStateIdle, ateattr.SandboxClassUnknown}, 1), + want: map[series]int64{ + {"ns-1", "pool-empty", ateattr.WorkerStateIdle, ateattr.SandboxClassUnknown}: 3, + }, }, { - // A worker that matches no pool has no class to fall back to. - name: "orphan worker", - pools: nil, - workers: []*ateapi.Worker{worker("ns-1", "pool-orphan", "", 0, 1)}, - want: map[series]int64{ - {"ns-1", "pool-orphan", ateattr.WorkerStateIdle, ateattr.SandboxClassUnknown}: 1, + // The worker with a class seeds the gvisor series; the ones + // without stay under unknown and do not count as gvisor capacity. + name: "workers with and without a class", + workers: []*ateapi.Worker{ + worker("ns-1", "pool-mixed", "gvisor", 1, 1), + worker("ns-1", "pool-mixed", "", 0, 1), + worker("ns-1", "pool-mixed", "", 0, 1), + worker("ns-1", "pool-mixed", "", 0, 1), }, + want: withCount( + withCount(seeded(nil, "ns-1", "pool-mixed", "gvisor"), + series{"ns-1", "pool-mixed", ateattr.WorkerStateAtCapacity, "gvisor"}, 1), + series{"ns-1", "pool-mixed", ateattr.WorkerStateIdle, ateattr.SandboxClassUnknown}, 3), }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - pools := func(labels.Selector) ([]*atev1.WorkerPool, error) { return tt.pools, nil } workers := func() ([]*ateapi.Worker, error) { return tt.workers, nil } - reader := newWorkerCountReader(t, workers, pools) + reader := newWorkerCountReader(t, workers) sum := mustMetric(t, reader, workerpoolWorkersMetric).Data.(metricdata.Sum[int64]) got := seriesCounts(sum) @@ -559,10 +537,7 @@ func TestWorkerCountSumsToPool(t *testing.T) { draining, unreported, } - pools := func(labels.Selector) ([]*atev1.WorkerPool, error) { - return []*atev1.WorkerPool{workerPool("ns-1", "pool-a", "")}, nil - } - reader := newWorkerCountReader(t, func() ([]*ateapi.Worker, error) { return ws, nil }, pools) + reader := newWorkerCountReader(t, func() ([]*ateapi.Worker, error) { return ws, nil }) got := seriesCounts(mustMetric(t, reader, workerpoolWorkersMetric).Data.(metricdata.Sum[int64])) want := seeded(nil, "ns-1", "pool-a", "gvisor") @@ -584,3 +559,286 @@ func TestWorkerCountSumsToPool(t *testing.T) { t.Errorf("sum over states = %d, want pool size %d", total, len(ws)) } } + +const ( + testWorkerName = "0b6c1f6e-6d0a-4c43-9a43-8f4a2b0e7d11" + testWorkerPod = "pool-a-7c9d8" + testWorkerNode = "node-1" +) + +// resourceWorker builds a worker of ns-1/pool-a that has registered as gvisor, +// so only state, capacity and allocated decide which series it has. +func resourceWorker(state ateapi.WorkerState, capacity, allocated *ateapi.WorkerResources) *ateapi.Worker { + return &ateapi.Worker{ + Metadata: &ateapi.ResourceMetadata{Name: testWorkerName}, + WorkerNamespace: "ns-1", + WorkerPool: "pool-a", + WorkerPod: testWorkerPod, + NodeName: testWorkerNode, + Status: &ateapi.WorkerStatus{ + State: state, + Capacity: capacity, + Allocated: allocated, + RegisteredEpoch: 1, + SandboxClasses: []*ateapi.WorkerSandboxClass{{SandboxClass: "gvisor"}}, + }, + } +} + +func newWorkerResourcesReader(t *testing.T, workers func() ([]*ateapi.Worker, error)) *sdkmetric.ManualReader { + t.Helper() + reader := sdkmetric.NewManualReader() + mp := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)) + if err := RegisterWorkerResources(mp.Meter("ateapi"), workers); err != nil { + t.Fatalf("RegisterWorkerResources: %v", err) + } + return reader +} + +var workerResourceMetrics = []string{ + workerCPUCapacityMetric, + workerCPUAllocatedMetric, + workerMemoryCapacityMetric, + workerMemoryAllocatedMetric, + workerActorCapacityMetric, + workerActorAllocatedMetric, +} + +// workerResourceValues returns metric name -> worker name -> value for every +// per-worker resource series. +func workerResourceValues(t *testing.T, reader *sdkmetric.ManualReader) map[string]map[string]float64 { + t.Helper() + var rm metricdata.ResourceMetrics + if err := reader.Collect(context.Background(), &rm); err != nil { + t.Fatalf("collect: %v", err) + } + got := make(map[string]map[string]float64) + add := func(metricName string, attrs attribute.Set, v float64) { + worker, _ := attrs.Value(ateattr.WorkerNameKey) + if got[metricName] == nil { + got[metricName] = make(map[string]float64) + } + got[metricName][worker.AsString()] = v + } + for _, sm := range rm.ScopeMetrics { + for _, m := range sm.Metrics { + switch data := m.Data.(type) { + case metricdata.Sum[float64]: + for _, dp := range data.DataPoints { + add(m.Name, dp.Attributes, dp.Value) + } + case metricdata.Sum[int64]: + for _, dp := range data.DataPoints { + add(m.Name, dp.Attributes, float64(dp.Value)) + } + default: + t.Fatalf("%s data type = %T, want a Sum", m.Name, m.Data) + } + } + } + return got +} + +func TestWorkerResourceSeries(t *testing.T) { + const gib = int64(1) << 30 + full := &ateapi.WorkerResources{CpuMillicores: 2500, MemoryBytes: 4 * gib, Actors: 10} + booked := &ateapi.WorkerResources{CpuMillicores: 500, MemoryBytes: gib, Actors: 2} + // Every worker reports allocated, so a worker with nothing booked has + // these series at 0 rather than none. + emptyAllocated := map[string]float64{ + workerCPUAllocatedMetric: 0, + workerMemoryAllocatedMetric: 0, + workerActorAllocatedMetric: 0, + } + with := func(base map[string]float64, extra map[string]float64) map[string]float64 { + out := maps.Clone(base) + maps.Copy(out, extra) + return out + } + tests := []struct { + name string + worker *ateapi.Worker + want map[string]float64 + }{ + { + name: "placeable worker reports both sides, cpu in cores", + worker: resourceWorker(ateapi.WorkerState_WORKER_STATE_ACTIVE, full, booked), + want: map[string]float64{ + workerCPUCapacityMetric: 2.5, + workerCPUAllocatedMetric: 0.5, + workerMemoryCapacityMetric: float64(4 * gib), + workerMemoryAllocatedMetric: float64(gib), + workerActorCapacityMetric: 10, + workerActorAllocatedMetric: 2, + }, + }, + { + // The ratio of allocated to capacity must read 0, not be missing. + name: "empty placeable worker reports allocated as 0", + worker: resourceWorker(ateapi.WorkerState_WORKER_STATE_ACTIVE, full, nil), + want: with(emptyAllocated, map[string]float64{ + workerCPUCapacityMetric: 2.5, + workerMemoryCapacityMetric: float64(4 * gib), + workerActorCapacityMetric: 10, + }), + }, + { + // A capacity of 0 is a resource the worker did not report. A 0 + // series would read as a full worker. + name: "unreported resource has no capacity series", + worker: resourceWorker(ateapi.WorkerState_WORKER_STATE_ACTIVE, &ateapi.WorkerResources{Actors: 10}, nil), + want: with(emptyAllocated, map[string]float64{workerActorCapacityMetric: 10}), + }, + { + // checkRoom places nothing on a worker with no actor slots, so its + // CPU and memory are not room either. + name: "worker without actor slots has no capacity", + worker: resourceWorker(ateapi.WorkerState_WORKER_STATE_ACTIVE, + &ateapi.WorkerResources{CpuMillicores: 2500, MemoryBytes: 4 * gib}, nil), + want: emptyAllocated, + }, + { + // Allocated can exceed capacity after the capacity shrinks. + name: "allocated above capacity is reported as is", + worker: resourceWorker(ateapi.WorkerState_WORKER_STATE_ACTIVE, + &ateapi.WorkerResources{Actors: 2}, &ateapi.WorkerResources{Actors: 5}), + want: with(emptyAllocated, map[string]float64{ + workerActorCapacityMetric: 2, + workerActorAllocatedMetric: 5, + }), + }, + { + name: "draining worker keeps its bookings and loses its capacity", + worker: resourceWorker(ateapi.WorkerState_WORKER_STATE_DRAINING, full, booked), + want: map[string]float64{ + workerCPUAllocatedMetric: 0.5, + workerMemoryAllocatedMetric: float64(gib), + workerActorAllocatedMetric: 2, + }, + }, + { + // The series must drop to 0, not vanish, or the backend keeps the + // last bookings for its lookback window. + name: "emptied draining worker reports allocated as 0", + worker: resourceWorker(ateapi.WorkerState_WORKER_STATE_DRAINING, full, nil), + want: emptyAllocated, + }, + { + name: "unavailable worker has no capacity", + worker: resourceWorker(ateapi.WorkerState_WORKER_STATE_UNAVAILABLE, full, nil), + want: emptyAllocated, + }, + { + // An ACTIVE worker whose new process has not reported its runtimes + // takes no actor, so it must not read as free room. + name: "unregistered active worker has no capacity", + worker: func() *ateapi.Worker { + w := resourceWorker(ateapi.WorkerState_WORKER_STATE_ACTIVE, full, &ateapi.WorkerResources{Actors: 1}) + w.Status.RegisteredEpoch = 0 + return w + }(), + want: with(emptyAllocated, map[string]float64{workerActorAllocatedMetric: 1}), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + reader := newWorkerResourcesReader(t, func() ([]*ateapi.Worker, error) { + return []*ateapi.Worker{tt.worker}, nil + }) + got := workerResourceValues(t, reader) + for _, name := range workerResourceMetrics { + gv, ok := got[name][testWorkerName] + wv, want := tt.want[name] + switch { + case ok != want: + t.Errorf("%s present = %v, want %v", name, ok, want) + case ok && gv != wv: + t.Errorf("%s = %v, want %v", name, gv, wv) + } + } + }) + } +} + +// TestWorkerResourceShape pins the units, the instrument kind and the labels, +// and checks that two workers of one pool stay two series. +func TestWorkerResourceShape(t *testing.T) { + first := resourceWorker(ateapi.WorkerState_WORKER_STATE_ACTIVE, + &ateapi.WorkerResources{CpuMillicores: 1000, MemoryBytes: 1 << 30, Actors: 4}, nil) + second := resourceWorker(ateapi.WorkerState_WORKER_STATE_ACTIVE, + &ateapi.WorkerResources{CpuMillicores: 1000, MemoryBytes: 1 << 30, Actors: 4}, nil) + second.Metadata.Name = "second" + reader := newWorkerResourcesReader(t, func() ([]*ateapi.Worker, error) { + return []*ateapi.Worker{first, second}, nil + }) + + units := map[string]string{ + workerCPUCapacityMetric: "{cpu}", + workerCPUAllocatedMetric: "{cpu}", + workerMemoryCapacityMetric: "By", + workerMemoryAllocatedMetric: "By", + workerActorCapacityMetric: "{actor}", + workerActorAllocatedMetric: "{actor}", + } + wantAttrs := attribute.NewSet( + ateattr.WorkerNameKey.String(testWorkerName), + ateattr.K8sPodNameKey.String(testWorkerPod), + ateattr.K8sNodeNameKey.String(testWorkerNode), + ateattr.WorkerPoolNamespaceKey.String("ns-1"), + ateattr.WorkerPoolNameKey.String("pool-a"), + ateattr.SandboxClassKey.String("gvisor"), + ) + + var rm metricdata.ResourceMetrics + if err := reader.Collect(context.Background(), &rm); err != nil { + t.Fatalf("collect: %v", err) + } + seen := make(map[string]bool) + for _, sm := range rm.ScopeMetrics { + for _, m := range sm.Metrics { + seen[m.Name] = true + if want := units[m.Name]; m.Unit != want { + t.Errorf("%s unit = %q, want %q", m.Name, m.Unit, want) + } + var monotonic bool + var attrs []attribute.Set + switch data := m.Data.(type) { + case metricdata.Sum[float64]: + monotonic = data.IsMonotonic + for _, dp := range data.DataPoints { + attrs = append(attrs, dp.Attributes) + } + case metricdata.Sum[int64]: + monotonic = data.IsMonotonic + for _, dp := range data.DataPoints { + attrs = append(attrs, dp.Attributes) + } + default: + t.Fatalf("%s data type = %T, want a Sum", m.Name, m.Data) + } + if monotonic { + t.Errorf("%s IsMonotonic = true, want an updowncounter", m.Name) + } + if len(attrs) != 2 { + t.Fatalf("%s has %d series, want one per worker", m.Name, len(attrs)) + } + if !slices.ContainsFunc(attrs, func(s attribute.Set) bool { return s.Equals(&wantAttrs) }) { + t.Errorf("%s has no series with %v, got %v", m.Name, wantAttrs.Encoded(attribute.DefaultEncoder()), attrs) + } + } + } + for _, name := range workerResourceMetrics { + if !seen[name] { + t.Errorf("%s not collected", name) + } + } +} + +func TestWorkerResourcesSkipWhenCacheNotReady(t *testing.T) { + reader := newWorkerResourcesReader(t, func() ([]*ateapi.Worker, error) { + return nil, context.DeadlineExceeded + }) + if got := workerResourceValues(t, reader); len(got) != 0 { + t.Errorf("collected %v, want no series while the cache is not ready", got) + } +} diff --git a/cmd/ateapi/internal/controlapi/mint_after_release_test.go b/cmd/ateapi/internal/controlapi/mint_after_release_test.go index 71a7beae6f..ea84f43bad 100644 --- a/cmd/ateapi/internal/controlapi/mint_after_release_test.go +++ b/cmd/ateapi/internal/controlapi/mint_after_release_test.go @@ -33,6 +33,7 @@ import ( "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/installdefaults" "go.ate.dev/substrate/internal/localca" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "google.golang.org/grpc/codes" ) @@ -180,7 +181,7 @@ func newTestMinter(t *testing.T, st store.Interface) *workerservice.Server { } caPool := &localca.ConcretePool{CAs: []*localca.CA{ca}, ActiveForSigning: "1"} ateletID := installdefaults.SPIFFEID(installdefaults.SystemNamespace, installdefaults.AteletServiceAccount) - return workerservice.New(st, nil, ateletID, caPool, "", nil) + return workerservice.New(st, nil, ateletID, caPool, "", nil, preview.NewForTest(t)) } // newTestCSR returns a certificate signing request for a fresh actor key. diff --git a/cmd/ateapi/internal/controlapi/pagination.go b/cmd/ateapi/internal/controlapi/pagination.go index 9dea3a5a79..848e679051 100644 --- a/cmd/ateapi/internal/controlapi/pagination.go +++ b/cmd/ateapi/internal/controlapi/pagination.go @@ -39,10 +39,10 @@ func toStoreListOptions(opts *ateapi.ListOptions) store.ListOptions { func mapListError(err error) error { if errors.Is(err, store.ErrInvalidPageToken) { - return apierror.InvalidArgument("invalid page_token") + return apierror.InvalidArgument("invalid page_token").WithCause(err) } if errors.Is(err, store.ErrInvalidPageSize) { - return apierror.InvalidArgument("invalid page_size") + return apierror.InvalidArgument("invalid page_size").WithCause(err) } return err } diff --git a/cmd/ateapi/internal/controlapi/preconditions.go b/cmd/ateapi/internal/controlapi/preconditions.go new file mode 100644 index 0000000000..f27c83643b --- /dev/null +++ b/cmd/ateapi/internal/controlapi/preconditions.go @@ -0,0 +1,52 @@ +// Copyright 2026 The Agent Substrate 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 controlapi + +import ( + "errors" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/store" + "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/resources" +) + +type preconditionOptions interface { + GetUid() string + GetVersion() int64 +} + +func toPreconditions(opts preconditionOptions) store.Precondition { + if opts == nil { + return store.Precondition{} + } + return store.Precondition{UID: opts.GetUid(), Version: opts.GetVersion()} +} + +func actorUIDConflictError(actorRef resources.ActorRef, expectedUID string, err error) error { + return apierror.Aborted("Actor %s does not have uid %s", actorRef, expectedUID).WithCause(err) +} + +// checkActorPreconditions returns ABORTED if actor does not match precondition. +func checkActorPreconditions(actorRef resources.ActorRef, precondition store.Precondition, actor *ateapi.Actor) error { + err := precondition.Check(actor.GetMetadata()) + switch { + case errors.Is(err, store.ErrUIDConflict): + return actorUIDConflictError(actorRef, precondition.UID, err) + case errors.Is(err, store.ErrVersionConflict): + return apierror.Aborted("Actor %s is not at version %d, please retry", actorRef, precondition.Version).WithCause(err) + } + return err +} diff --git a/cmd/ateapi/internal/controlapi/preview_gates.go b/cmd/ateapi/internal/controlapi/preview_gates.go new file mode 100644 index 0000000000..de1d3c115d --- /dev/null +++ b/cmd/ateapi/internal/controlapi/preview_gates.go @@ -0,0 +1,71 @@ +// Copyright 2026 The Agent Substrate 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 controlapi + +import ( + "fmt" + + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protoreflect" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" +) + +// PreviewMethodGates maps each method of services whose (method) annotation +// names a preview gate to that gate. The keys are gRPC full method names, +// such as "/substrate.ateapi.v1.Control/GetActor". +func PreviewMethodGates(services protoreflect.ServiceDescriptors) (map[string]preview.Gate, error) { + gates := map[string]preview.Gate{} + for i := range services.Len() { + sd := services.Get(i) + methods := sd.Methods() + for j := range methods.Len() { + md := methods.Get(j) + gate, err := methodPreviewGate(md) + if err != nil { + return nil, err + } + if gate != "" { + gates[grpcFullMethodName(sd, md)] = gate + } + } + } + return gates, nil +} + +// grpcFullMethodName returns the gRPC full method name for md, such as +// "/substrate.ateapi.v1.Control/GetActor". +func grpcFullMethodName(sd protoreflect.ServiceDescriptor, md protoreflect.MethodDescriptor) string { + return fmt.Sprintf("/%s/%s", sd.FullName(), md.Name()) +} + +func methodPreviewGate(md protoreflect.MethodDescriptor) (preview.Gate, error) { + g := proto.GetExtension(md.Options(), ateapi.E_Method).(*ateapi.MethodAnnotation).GetPreviewGate() + if g == nil { + return "", nil + } + gate := g.GetName() + if md.IsStreamingClient() || md.IsStreamingServer() { + return "", fmt.Errorf("%s: streaming methods cannot use preview_gate", md.FullName()) + } + if gate == preview.All { + return "", fmt.Errorf("%s: preview gate %q names every gate", md.FullName(), gate) + } + if err := preview.Verify(gate); err != nil { + return "", fmt.Errorf("%s: %w", md.FullName(), err) + } + return preview.Gate(gate), nil +} diff --git a/cmd/ateapi/internal/controlapi/preview_gates_test.go b/cmd/ateapi/internal/controlapi/preview_gates_test.go new file mode 100644 index 0000000000..4881d72aa0 --- /dev/null +++ b/cmd/ateapi/internal/controlapi/preview_gates_test.go @@ -0,0 +1,137 @@ +// Copyright 2026 The Agent Substrate 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 controlapi + +import ( + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/reflect/protodesc" + "google.golang.org/protobuf/reflect/protoreflect" + "google.golang.org/protobuf/reflect/protoregistry" + "google.golang.org/protobuf/types/descriptorpb" + _ "google.golang.org/protobuf/types/known/emptypb" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/preview" +) + +type testMethod struct { + name string + resource string + gate *ateapi.MethodPreviewGate + clientStreaming bool + serverStreaming bool +} + +func buildTestServices(t *testing.T, methods ...testMethod) protoreflect.ServiceDescriptors { + t.Helper() + var protos []*descriptorpb.MethodDescriptorProto + for _, m := range methods { + var opts *descriptorpb.MethodOptions + if m.resource != "" || m.gate != nil { + opts = &descriptorpb.MethodOptions{} + proto.SetExtension(opts, ateapi.E_Method, &ateapi.MethodAnnotation{Resource: m.resource, PreviewGate: m.gate}) + } + protos = append(protos, &descriptorpb.MethodDescriptorProto{ + Name: proto.String(m.name), + InputType: proto.String(".google.protobuf.Empty"), + OutputType: proto.String(".google.protobuf.Empty"), + ClientStreaming: proto.Bool(m.clientStreaming), + ServerStreaming: proto.Bool(m.serverStreaming), + Options: opts, + }) + } + fd, err := protodesc.NewFile(&descriptorpb.FileDescriptorProto{ + Name: proto.String("test.proto"), + Package: proto.String("test"), + Dependency: []string{"google/protobuf/empty.proto"}, + Service: []*descriptorpb.ServiceDescriptorProto{{Name: proto.String("Svc"), Method: protos}}, + }, protoregistry.GlobalFiles) + if err != nil { + t.Fatal(err) + } + return fd.Services() +} + +func TestPreviewMethodGates(t *testing.T) { + gates := preview.NewForTest(t, preview.All).Enabled() + if len(gates) == 0 { + t.Fatal("need a real gate to test PreviewMethodGates") + } + known := gates[0] + + tests := []struct { + name string + methods []testMethod + want map[string]preview.Gate + wantErr string + }{ + { + name: "gated and ungated methods", + methods: []testMethod{ + {name: "NoOptions"}, + {name: "Ungated", resource: "Widget"}, + {name: "Gated", resource: "Widget", gate: &ateapi.MethodPreviewGate{Name: known}}, + }, + want: map[string]preview.Gate{"/test.Svc/Gated": preview.Gate(known)}, + }, + { + name: "unknown gate", + methods: []testMethod{{name: "Gated", gate: &ateapi.MethodPreviewGate{Name: "NoSuchGate"}}}, + wantErr: "unknown preview gate", + }, + { + name: "gate without a name", + methods: []testMethod{{name: "Gated", gate: &ateapi.MethodPreviewGate{}}}, + wantErr: "unknown preview gate", + }, + { + name: "ALL pseudo-gate", + methods: []testMethod{{name: "Gated", gate: &ateapi.MethodPreviewGate{Name: preview.All}}}, + wantErr: "names every gate", + }, + { + name: "client streaming", + methods: []testMethod{{name: "Stream", gate: &ateapi.MethodPreviewGate{Name: known}, clientStreaming: true}}, + wantErr: "streaming methods", + }, + { + name: "server streaming", + methods: []testMethod{{name: "Stream", gate: &ateapi.MethodPreviewGate{Name: known}, serverStreaming: true}}, + wantErr: "streaming methods", + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + got, err := PreviewMethodGates(buildTestServices(t, tc.methods...)) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("PreviewMethodGates() error = %v, want one containing %q", err, tc.wantErr) + } + return + } + if err != nil { + t.Fatalf("PreviewMethodGates() error = %v", err) + } + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("PreviewMethodGates() mismatch (-want +got):\n%s", diff) + } + }) + } +} diff --git a/cmd/ateapi/internal/controlapi/service.go b/cmd/ateapi/internal/controlapi/service.go index 952f8ec442..e5450765b2 100644 --- a/cmd/ateapi/internal/controlapi/service.go +++ b/cmd/ateapi/internal/controlapi/service.go @@ -24,6 +24,7 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/cmd/ateapi/internal/workercache" "go.ate.dev/substrate/internal/localjwtauthority" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "go.ate.dev/substrate/internal/volume" "go.ate.dev/substrate/internal/volume/csi" @@ -39,7 +40,6 @@ import ( type RPCService struct { ateapi.UnimplementedControlServer impl serviceStore - persistence serviceStore workerCache *workercache.Cache dialer *AteletDialer csiDriverConfigLister atelisters.CSIDriverConfigLister @@ -49,6 +49,7 @@ type RPCService struct { mu sync.RWMutex volumePlugins map[string]volume.VolumePluginControlPlane objectStorePlugin objectstore.ControlProviderClient + gates *preview.Gates actorJWTIssuer string actorIDJWTPool localjwtauthority.Pool @@ -62,7 +63,8 @@ type VolumePluginRegistry interface { } // NewRPCService creates an instance of the ControlServer service. This is what -// implements the outward-facing RPC interface. +// implements the outward-facing RPC interface. It also returns the ServiceImpl +// the service uses, for in-process writers such as the ActorTemplateReconciler. // // instruments may be nil; the record helpers no-op. // @@ -75,6 +77,8 @@ type VolumePluginRegistry interface { // // snapshotLocation is ate-api-server's cluster-wide --snapshot-location; see // resolveSnapshotLocation. +// +// gates are ate-api-server's preview gates. func NewRPCService( persistence store.Interface, workerCache *workercache.Cache, @@ -89,12 +93,12 @@ func NewRPCService( actorJWTIssuer string, actorIDJWTPool localjwtauthority.Pool, snapshotLocation string, -) *RPCService { - impl := newServiceImpl(persistence, storageClassLister) + gates *preview.Gates, +) (*RPCService, *ServiceImpl) { + impl := newServiceImpl(persistence, storageClassLister, gates) impl.clusterSnapshotLocation = snapshotLocation s := &RPCService{ impl: impl, - persistence: persistence, workerCache: workerCache, csiDriverConfigLister: csiDriverConfigLister, dialer: dialer, @@ -103,11 +107,12 @@ func NewRPCService( objectStorePlugin: objectStorePlugin, actorJWTIssuer: actorJWTIssuer, actorIDJWTPool: actorIDJWTPool, + gates: gates, } - s.actorWorkflow = NewActorWorkflow(impl, workerCache, dialer, storageClassLister, instruments, egressGatewayAddress, s, actorWorkflowDeadline, objectStorePlugin) + s.actorWorkflow = NewActorWorkflow(impl, workerCache, dialer, storageClassLister, instruments, egressGatewayAddress, s, actorWorkflowDeadline, objectStorePlugin, gates) s.actorWorkflow.clusterSnapshotLocation = snapshotLocation - s.workerWorkflow = NewWorkerWorkflow(impl, dialer) - return s + s.workerWorkflow = NewWorkerWorkflow(impl, dialer, gates) + return s, impl } // serviceStore enumerates the exact storage methods needed by @@ -120,26 +125,35 @@ type serviceStore interface { CreateEgressPolicy(ctx context.Context, actorRef resources.ActorRef, policy *ateapi.EgressPolicy) (*ateapi.EgressPolicy, error) GetEgressPolicy(ctx context.Context, actorRef resources.ActorRef) (*ateapi.EgressPolicy, error) UpdateEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapi.EgressPolicy) error) (*ateapi.EgressPolicy, error) - DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions) (*ateapi.EgressPolicy, error) + DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (*ateapi.EgressPolicy, error) GetTag(ctx context.Context, tagRef resources.TagRef) (*ateapi.Tag, error) ListTags(ctx context.Context, atespace string, opts store.ListOptions) (store.ListResponse[*ateapi.Tag], error) UpdateTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(toUpdate *ateapi.Tag) error) (*ateapi.Tag, error) - DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions) (*ateapi.Tag, error) + DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition) (*ateapi.Tag, error) + CreateExternalVolume(ctx context.Context, volume *ateapi.ExternalVolume) (*ateapi.ExternalVolume, error) + GetExternalVolume(ctx context.Context, volumeRef resources.ExternalVolumeRef) (*ateapi.ExternalVolume, error) + ListExternalVolumes(ctx context.Context, atespace string, opts store.ListOptions) (store.ListResponse[*ateapi.ExternalVolume], error) + DeleteExternalVolume(ctx context.Context, volumeRef resources.ExternalVolumeRef, precondition store.Precondition) (*ateapi.ExternalVolume, error) CreateAtespace(ctx context.Context, atespace *ateapi.Atespace) (*ateapi.Atespace, error) GetAtespace(ctx context.Context, name string) (*ateapi.Atespace, error) ListAtespaces(ctx context.Context, opts store.ListOptions) (store.ListResponse[*ateapi.Atespace], error) - DeleteAtespace(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.Atespace, error) + DeleteAtespace(ctx context.Context, name string, precondition store.Precondition) (*ateapi.Atespace, error) + CreateCSIDriver(ctx context.Context, driver *ateapi.CsiDriver) (*ateapi.CsiDriver, error) + GetCSIDriver(ctx context.Context, name string) (*ateapi.CsiDriver, error) + ListCSIDrivers(ctx context.Context, opts store.ListOptions) (store.ListResponse[*ateapi.CsiDriver], error) + UpdateCSIDriver(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapi.CsiDriver) error) (*ateapi.CsiDriver, error) + DeleteCSIDriver(ctx context.Context, name string, precondition store.Precondition) (*ateapi.CsiDriver, error) CreateGlobalAccessPolicy(ctx context.Context, policy *ateapi.AccessPolicy) (*ateapi.AccessPolicy, error) GetGlobalAccessPolicy(ctx context.Context) (*ateapi.AccessPolicy, error) UpdateGlobalAccessPolicy(ctx context.Context, precondition store.Precondition, mutate func(*ateapi.AccessPolicy) error) (*ateapi.AccessPolicy, error) CreateAtespaceAccessPolicy(ctx context.Context, name string, policy *ateapi.AccessPolicy) (*ateapi.AccessPolicy, error) GetAtespaceAccessPolicy(ctx context.Context, name string) (*ateapi.AccessPolicy, error) UpdateAtespaceAccessPolicy(ctx context.Context, name string, precondition store.Precondition, mutate func(*ateapi.AccessPolicy) error) (*ateapi.AccessPolicy, error) - DeleteAtespaceAccessPolicy(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.AccessPolicy, error) + DeleteAtespaceAccessPolicy(ctx context.Context, name string, precondition store.Precondition) (*ateapi.AccessPolicy, error) CreateActorTemplate(ctx context.Context, template *ateapi.ActorTemplate) (*ateapi.ActorTemplate, error) GetActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef) (*ateapi.ActorTemplate, error) ListActorTemplates(ctx context.Context, atespace string, opts store.ListOptions) (store.ListResponse[*ateapi.ActorTemplate], error) - DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions) (*ateapi.ActorTemplate, error) + DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition) (*ateapi.ActorTemplate, error) ListWorkers(ctx context.Context, opts store.ListOptions) (store.ListResponse[*ateapi.Worker], error) GetWorker(ctx context.Context, name string) (*ateapi.Worker, error) ListWorkerAssignments(ctx context.Context, workerName string, opts store.ListOptions) (store.ListResponse[*ateapi.ActorAssignment], error) @@ -183,6 +197,8 @@ type ServiceImpl struct { // clusterSnapshotLocation is ate-api-server's --snapshot-location; see // resolveSnapshotLocation. clusterSnapshotLocation string + + gates *preview.Gates } var _ store.Interface = (*ServiceImpl)(nil) @@ -192,10 +208,12 @@ var _ store.Interface = (*ServiceImpl)(nil) func newServiceImpl( persistence store.Interface, storageClassLister storagev1listers.StorageClassLister, + gates *preview.Gates, ) *ServiceImpl { s := &ServiceImpl{ store: persistence, storageClassLister: storageClassLister, + gates: gates, } return s } diff --git a/cmd/ateapi/internal/controlapi/snapshot_helpers.go b/cmd/ateapi/internal/controlapi/snapshot_helpers.go index 1ee1729d04..5c9499fe09 100644 --- a/cmd/ateapi/internal/controlapi/snapshot_helpers.go +++ b/cmd/ateapi/internal/controlapi/snapshot_helpers.go @@ -152,10 +152,10 @@ func tagDurableSnapshotURI(tag *ateapi.Tag, storageState ateapi.SnapshotStorageS // otherwise snapshotLocation, ate-api-server's cluster-wide // --snapshot-location. It fails with FailedPrecondition when neither is set. // -// It reads the process-wide gate rather than preview.IsEnabledFor, so a -// request's preview opt-out cannot move where an actor's snapshots live. -func resolveSnapshotLocation(snapshotLocation string, actorTemplate *ateapi.ActorTemplate) (string, error) { - if preview.IsEnabled(preview.GatePerTemplateSnapshotLocation) { +// It reads gates.IsEnabled rather than gates.IsEnabledFor, so a request's +// preview opt-out cannot move where an actor's snapshots live. +func resolveSnapshotLocation(gates *preview.Gates, snapshotLocation string, actorTemplate *ateapi.ActorTemplate) (string, error) { + if gates.IsEnabled(preview.GatePerTemplateSnapshotLocation) { if location := actorTemplate.GetSnapshotConfig().GetStorageLocation(); location != "" { return location, nil } diff --git a/cmd/ateapi/internal/controlapi/snapshot_helpers_test.go b/cmd/ateapi/internal/controlapi/snapshot_helpers_test.go index 73fa44c71a..5a90b8facb 100644 --- a/cmd/ateapi/internal/controlapi/snapshot_helpers_test.go +++ b/cmd/ateapi/internal/controlapi/snapshot_helpers_test.go @@ -325,12 +325,12 @@ func TestResolveSnapshotLocation(t *testing.T) { if tt.gateEnabled { gates = []string{string(preview.GatePerTemplateSnapshotLocation)} } - preview.InitForTest(t, gates...) + g := preview.NewForTest(t, gates...) tmpl := &ateapi.ActorTemplate{ Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "tmpl"}, SnapshotConfig: &ateapi.SnapshotConfig{StorageLocation: tt.templateLocation}, } - got, err := resolveSnapshotLocation(tt.bucketPrefix, tmpl) + got, err := resolveSnapshotLocation(g, tt.bucketPrefix, tmpl) if tt.wantErr { if apierror.Code(err) != codes.FailedPrecondition { t.Fatalf("resolveSnapshotLocation() err = %v, want FailedPrecondition", err) diff --git a/cmd/ateapi/internal/controlapi/snapshot_report.go b/cmd/ateapi/internal/controlapi/snapshot_report.go index 1966bbc68a..3245c66890 100644 --- a/cmd/ateapi/internal/controlapi/snapshot_report.go +++ b/cmd/ateapi/internal/controlapi/snapshot_report.go @@ -80,7 +80,7 @@ func (w *ActorWorkflow) ApplyReportedSnapshotState(ctx context.Context, actorRef return nil }); err != nil { if errors.Is(err, store.ErrVersionConflict) { - return apierror.Aborted("concurrent update conflict, please retry") + return apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } return err } @@ -94,7 +94,7 @@ func (w *ActorWorkflow) loadReportedActor(ctx context.Context, actorRef resource actor, err := w.store.GetActor(ctx, actorRef) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Actor %s not found", actorRef) + return nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } return nil, err } diff --git a/cmd/ateapi/internal/controlapi/span_identity_test.go b/cmd/ateapi/internal/controlapi/span_identity_test.go index c71271f952..7a0b1e7f53 100644 --- a/cmd/ateapi/internal/controlapi/span_identity_test.go +++ b/cmd/ateapi/internal/controlapi/span_identity_test.go @@ -21,8 +21,10 @@ import ( "go.opentelemetry.io/otel/attribute" sdktrace "go.opentelemetry.io/otel/sdk/trace" "go.opentelemetry.io/otel/sdk/trace/tracetest" + "google.golang.org/grpc/codes" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/resources" ) @@ -108,3 +110,123 @@ func TestSetSpanActorAttributes_NoRecordingSpanIsNoop(t *testing.T) { setSpanActorAttributes(context.Background(), &ateapi.Actor{Metadata: &ateapi.ResourceMetadata{Name: "a1"}}) setSpanActorRefAttributes(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "a1"}) } + +// TestActorRPCs_StampSpanIdentity checks what each actor RPC stamps on its span: +// the actor's full identity once it holds the stored actor, and only the ref +// when it has not read one. +func TestActorRPCs_StampSpanIdentity(t *testing.T) { + ref := &ateapi.ObjectRef{Atespace: "team-a", Name: "actor-1"} + newService := func(t *testing.T) *RPCService { + t.Helper() + persistence := newTestPersistence(t) + return &RPCService{gates: testGates, impl: newServiceImpl(persistence, nil, testGates), actorWorkflow: newTestActorWorkflow(t, persistence, "ns", "tmpl1")} + } + createRequest := &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: ref.GetAtespace(), Name: ref.GetName()}, + ActorTemplate: &ateapi.ObjectRef{Atespace: "ns", Name: "tmpl1"}, + }} + assertFullIdentity := func(t *testing.T, attrs map[attribute.Key]attribute.Value, actor *ateapi.Actor) { + t.Helper() + assertSpanStr(t, attrs, ateattr.AtespaceKey, ref.GetAtespace()) + assertSpanStr(t, attrs, ateattr.ActorNameKey, ref.GetName()) + assertSpanStr(t, attrs, ateattr.ActorUIDKey, actor.GetMetadata().GetUid()) + assertSpanStr(t, attrs, ateattr.TemplateNameKey, "tmpl1") + assertSpanStr(t, attrs, ateattr.TemplateAtespaceKey, "ns") + if v, ok := attrs[ateattr.ActorVersionKey]; !ok || v.AsInt64() != actor.GetMetadata().GetVersion() { + t.Errorf("%s = %v, want %d", ateattr.ActorVersionKey, v.String(), actor.GetMetadata().GetVersion()) + } + } + assertRefOnly := func(t *testing.T, attrs map[attribute.Key]attribute.Value) { + t.Helper() + assertSpanStr(t, attrs, ateattr.AtespaceKey, ref.GetAtespace()) + assertSpanStr(t, attrs, ateattr.ActorNameKey, ref.GetName()) + for _, k := range []attribute.Key{ateattr.ActorUIDKey, ateattr.TemplateNameKey, ateattr.TemplateAtespaceKey, ateattr.ActorVersionKey} { + if _, ok := attrs[k]; ok { + t.Errorf("unexpected %s on a ref-only span", k) + } + } + } + + t.Run("CreateActor stamps the full identity", func(t *testing.T) { + svc := newService(t) + var created *ateapi.Actor + attrs := recordRootSpanAttrs(t, func(ctx context.Context) { + var err error + if created, err = svc.CreateActor(ctx, createRequest); err != nil { + t.Fatalf("CreateActor: %v", err) + } + }) + assertFullIdentity(t, attrs, created) + }) + + t.Run("UpdateActor stamps the full identity", func(t *testing.T) { + svc := newService(t) + toUpdate, err := svc.CreateActor(context.Background(), createRequest) + if err != nil { + t.Fatalf("CreateActor: %v", err) + } + toUpdate.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "1"}} + var updated *ateapi.Actor + attrs := recordRootSpanAttrs(t, func(ctx context.Context) { + var err error + if updated, err = svc.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: toUpdate}); err != nil { + t.Fatalf("UpdateActor: %v", err) + } + }) + assertFullIdentity(t, attrs, updated) + }) + + t.Run("UpdateActor of a missing actor stamps the ref only", func(t *testing.T) { + svc := newService(t) + attrs := recordRootSpanAttrs(t, func(ctx context.Context) { + _, err := svc.UpdateActor(ctx, &ateapi.UpdateActorRequest{Actor: &ateapi.Actor{Metadata: &ateapi.ResourceMetadata{ + Atespace: ref.GetAtespace(), + Name: ref.GetName(), + Uid: "9a2b1c3d-4e5f-6a7b-8c9d-0e1f2a3b4c5d", + Version: 1, + }}}) + if got := apierror.Code(err); got != codes.NotFound { + t.Fatalf("UpdateActor = %v, want NotFound", err) + } + }) + assertRefOnly(t, attrs) + }) + + t.Run("DeleteActor stamps the ref", func(t *testing.T) { + svc := newService(t) + if _, err := svc.CreateActor(context.Background(), createRequest); err != nil { + t.Fatalf("CreateActor: %v", err) + } + attrs := recordRootSpanAttrs(t, func(ctx context.Context) { + if _, err := svc.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + }) + assertSpanStr(t, attrs, ateattr.AtespaceKey, ref.GetAtespace()) + assertSpanStr(t, attrs, ateattr.ActorNameKey, ref.GetName()) + }) + + t.Run("ResumeActor of a missing actor stamps the ref only", func(t *testing.T) { + svc := newService(t) + attrs := recordRootSpanAttrs(t, func(ctx context.Context) { + if _, err := svc.ResumeActor(ctx, &ateapi.ResumeActorRequest{Actor: ref}); err == nil { + t.Fatal("ResumeActor of a missing actor succeeded") + } + }) + assertRefOnly(t, attrs) + }) + + t.Run("SuspendActor of a missing actor stamps the ref only", func(t *testing.T) { + svc := newService(t) + attrs := recordRootSpanAttrs(t, func(ctx context.Context) { + _, err := svc.SuspendActor(ctx, &ateapi.SuspendActorRequest{ + Actor: ref, + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, + }) + if got := apierror.Code(err); got != codes.NotFound { + t.Fatalf("SuspendActor = %v, want NotFound", err) + } + }) + assertRefOnly(t, attrs) + }) +} diff --git a/cmd/ateapi/internal/controlapi/tag.go b/cmd/ateapi/internal/controlapi/tag.go index 435fa21275..dbaab4d7ab 100644 --- a/cmd/ateapi/internal/controlapi/tag.go +++ b/cmd/ateapi/internal/controlapi/tag.go @@ -24,6 +24,7 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/defaults" "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "google.golang.org/protobuf/proto" "k8s.io/apimachinery/pkg/util/validation/field" @@ -43,7 +44,7 @@ func (s *RPCService) CreateTag(ctx context.Context, req *ateapi.CreateTagRequest defaults.Apply(inTag) } - if errs := apivalidation.ValidateCreateTagRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateCreateTagRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } actorRef := resources.ActorRefFromObjectRef(req.GetTag().GetSourceActor()) @@ -52,7 +53,7 @@ func (s *RPCService) CreateTag(ctx context.Context, req *ateapi.CreateTagRequest tag, err := s.actorWorkflow.TagActorSnapshot(ctx, req.GetTag()) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.FailedPrecondition("Actor %s not found", actorRef) + return nil, apierror.FailedPrecondition("Actor %s not found", actorRef).WithCause(err) } return nil, err } @@ -65,13 +66,13 @@ func (s *ServiceImpl) CreateTag(ctx context.Context, tag *ateapi.Tag) (*ateapi.T } func (s *RPCService) GetTag(ctx context.Context, req *ateapi.GetTagRequest) (*ateapi.Tag, error) { - if errs := apivalidation.ValidateGetTagRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateGetTagRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } tagRef := resources.TagRefFromObjectRef(req.GetTag()) tag, err := s.impl.GetTag(ctx, tagRef) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Tag %s not found", tagRef) + return nil, apierror.NotFound("Tag %s not found", tagRef).WithCause(err) } if err != nil { return nil, fmt.Errorf("while getting tag: %w", err) @@ -85,7 +86,7 @@ func (s *ServiceImpl) GetTag(ctx context.Context, tagRef resources.TagRef) (*ate } func (s *RPCService) ListTags(ctx context.Context, req *ateapi.ListTagsRequest) (*ateapi.ListTagsResponse, error) { - if errs := apivalidation.ValidateListTagsRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateListTagsRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } page, err := s.impl.ListTags(ctx, req.GetAtespace(), toStoreListOptions(req.GetOptions())) @@ -117,7 +118,7 @@ func (s *RPCService) UpdateTag(ctx context.Context, req *ateapi.UpdateTagRequest inTag.Status = nil } - if errs := apivalidation.ValidateUpdateTagRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateUpdateTagRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } in := req.GetTag() @@ -151,22 +152,19 @@ func (s *RPCService) UpdateTag(ctx context.Context, req *ateapi.UpdateTagRequest }) if err != nil { if errors.Is(err, errTagPending) { - return nil, apierror.FailedPrecondition("Tag %s/%s is still being created", tagRef.Atespace, tagRef.Name) + return nil, apierror.FailedPrecondition("Tag %s/%s is still being created", tagRef.Atespace, tagRef.Name).WithCause(err) } if errors.Is(err, errTagDeleting) { - return nil, apierror.FailedPrecondition("Tag %s/%s is being deleted", tagRef.Atespace, tagRef.Name) - } - if errors.Is(err, store.ErrImmutableField) { - return nil, apierror.InvalidArgument("while updating tag %s/%s: %v", tagRef.Atespace, tagRef.Name, err) + return nil, apierror.FailedPrecondition("Tag %s/%s is being deleted", tagRef.Atespace, tagRef.Name).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("Tag %s/%s not found with uid %s", tagRef.Atespace, tagRef.Name, in.GetMetadata().GetUid()) + return nil, apierror.Aborted("Tag %s/%s not found with uid %s", tagRef.Atespace, tagRef.Name, in.GetMetadata().GetUid()).WithCause(err) } if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Tag %s/%s not found", tagRef.Atespace, tagRef.Name) + return nil, apierror.NotFound("Tag %s/%s not found", tagRef.Atespace, tagRef.Name).WithCause(err) } if errors.Is(err, store.ErrPreconditionRequired) { return nil, apierror.InvalidArgument("while updating tag %s/%s: %v", tagRef.Atespace, tagRef.Name, err) @@ -177,34 +175,131 @@ func (s *RPCService) UpdateTag(ctx context.Context, req *ateapi.UpdateTagRequest } func (s *ServiceImpl) UpdateTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(toUpdate *ateapi.Tag) error) (*ateapi.Tag, error) { - return s.store.UpdateTag(ctx, tagRef, precondition, func(toUpdate *ateapi.Tag) error { - // Apply the mutation function to the stored value. + return s.store.UpdateTag(ctx, tagRef, precondition, validatedTagMutation(ctx, s.gates, mutate)) +} + +// validatedTagMutation wraps mutate so the Tag it writes is validated as an +// update of the stored Tag. RPCService.UpdateTag merges the client's tag into +// the stored one, and its request validation cannot compare the two, so a +// failure here is an API error. +func validatedTagMutation(ctx context.Context, gates *preview.Gates, mutate func(*ateapi.Tag) error) func(*ateapi.Tag) error { + return func(toUpdate *ateapi.Tag) error { oldVal := proto.CloneOf(toUpdate) - if err := mutate(toUpdate); err != nil { - return err + if mutate != nil { + if err := mutate(toUpdate); err != nil { + return err + } } - - // Validate the merged tag against the one it replaces. This is where - // the rules the request could not be checked against land: scope, and - // the immutability of metadata and source_actor. - errs := apivalidation.ValidateTagUpdate(ctx, field.NewPath("tag"), toUpdate, oldVal) - return resources.ToAPIError(errs) - }) + if errs := apivalidation.ValidateTagUpdate(ctx, gates, field.NewPath("tag"), toUpdate, oldVal); len(errs) > 0 { + return resources.ToAPIError(errs) + } + return nil + } } // DeleteTag removes the tag and collects the external snapshot it owns. func (s *RPCService) DeleteTag(ctx context.Context, req *ateapi.DeleteTagRequest) (*ateapi.Tag, error) { - if errs := apivalidation.ValidateDeleteTagRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateDeleteTagRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } - return s.actorWorkflow.DeleteTag(ctx, resources.TagRefFromObjectRef(req.GetTag()), toDeletePreconditions(req.GetOptions())) + tagRef := resources.TagRefFromObjectRef(req.GetTag()) + tag, err := s.impl.GetTag(ctx, tagRef) + if errors.Is(err, store.ErrNotFound) { + return nil, apierror.NotFound("Tag %s not found", tagRef).WithCause(err) + } + if err != nil { + return nil, fmt.Errorf("while getting tag: %w", err) + } + if err := s.checkNotLiveGoldenTag(ctx, tag); err != nil { + return nil, err + } + precondition := toPreconditions(req.GetOptions()) + // The check read the tag before ActorWorkflow.DeleteTag takes the tag + // lease. Pin the tag it read where the caller set no guard, so a tag that + // changes in between, such as a golden tag finishing or replacing it, + // fails the delete with Aborted. + if precondition.UID == "" { + precondition.UID = tag.GetMetadata().GetUid() + } + if precondition.Version == 0 { + precondition.Version = tag.GetMetadata().GetVersion() + } + return s.actorWorkflow.DeleteTag(ctx, tagRef, precondition) +} + +// checkNotLiveGoldenTag refuses to delete a live ActorTemplate's golden tag: +// the tag the template records, which CreateActor without a sourceTag starts +// from, or a finished golden tag the template controller is about to record. +// The controller records that tag without checking that it still exists, and +// does not build a new golden once it has recorded one, so deleting either +// would break CreateActor for the template until it is recreated. +// +// Every other tag may be deleted: one the template doesn't use, an unfinished +// golden tag (the controller deletes one itself before it retries the copy), +// the golden tag of a template whose golden failed, and one already marked for +// deletion, which CreateActor rejects, so that a delete that failed partway +// can finish. DeleteActorTemplate removes the golden tag through +// ActorWorkflow.DeleteTag, not this RPC. +func (s *RPCService) checkNotLiveGoldenTag(ctx context.Context, tag *ateapi.Tag) error { + // A golden tag is named after the template it was captured under, so no + // other tag needs the template lookup. + templateUID := tag.GetStatus().GetActorTemplateUid() + if templateUID == "" || tag.GetMetadata().GetName() != templateUID || tag.GetMetadata().GetDeleteTime() != nil { + return nil + } + tagRef := resources.TagRefFromTag(tag) + tmpl, err := s.findActorTemplateByUID(ctx, tagRef.Atespace, templateUID) + if err != nil { + return err + } + if tmpl == nil || tmpl.GetMetadata().GetDeleteTime() != nil { + return nil + } + golden := tmpl.GetStatus().GetGoldenSnapshotStatus() + if recorded := golden.GetGoldenTag(); recorded != nil { + if resources.TagRefFromObjectRef(recorded) != tagRef { + return nil + } + } else if golden.GetErrorMessage() != "" || !isFinishedGoldenTag(tag, tmpl) { + return nil + } + return apierror.FailedPrecondition("Tag %s is the golden snapshot of ActorTemplate %s; delete the ActorTemplate to remove it", tagRef, resources.ActorTemplateRefFromActorTemplate(tmpl)) +} + +// isFinishedGoldenTag reports whether tag is a finished copy of tmpl's golden +// actor, which the template controller records as tmpl's golden tag. +func isFinishedGoldenTag(tag *ateapi.Tag, tmpl *ateapi.ActorTemplate) bool { + goldenActor := resources.ActorRef{Atespace: tmpl.GetMetadata().GetAtespace(), Name: tmpl.GetMetadata().GetUid()} + return resources.ActorRefFromObjectRef(tag.GetSourceActor()) == goldenActor && + tagDurableSnapshotURI(tag, ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED) != "" +} + +// findActorTemplateByUID returns the ActorTemplate in atespace with the given +// UID, or nil if there is none. +func (s *RPCService) findActorTemplateByUID(ctx context.Context, atespace, uid string) (*ateapi.ActorTemplate, error) { + opts := store.ListOptions{} + for { + page, err := s.impl.ListActorTemplates(ctx, atespace, opts) + if err != nil { + return nil, fmt.Errorf("while listing actor templates: %w", err) + } + for _, tmpl := range page.Items { + if tmpl.GetMetadata().GetUid() == uid { + return tmpl, nil + } + } + if page.NextPageToken == "" { + return nil, nil + } + opts.PageToken = page.NextPageToken + } } -func (s *ServiceImpl) MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions, mutate func(*ateapi.Tag) error) (*ateapi.Tag, error) { - return s.store.MarkTagForDeletion(ctx, tagRef, precondition, mutate) +func (s *ServiceImpl) MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(*ateapi.Tag) error) (*ateapi.Tag, error) { + return s.store.MarkTagForDeletion(ctx, tagRef, precondition, validatedTagMutation(ctx, s.gates, mutate)) } -func (s *ServiceImpl) DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions) (*ateapi.Tag, error) { +func (s *ServiceImpl) DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition) (*ateapi.Tag, error) { // TODO: implement this return s.store.DeleteTag(ctx, tagRef, precondition) } diff --git a/cmd/ateapi/internal/controlapi/tag_test.go b/cmd/ateapi/internal/controlapi/tag_test.go index 4bc06d75d5..8434472a5c 100644 --- a/cmd/ateapi/internal/controlapi/tag_test.go +++ b/cmd/ateapi/internal/controlapi/tag_test.go @@ -16,10 +16,13 @@ package controlapi import ( "context" + "errors" + "sync" "testing" "github.com/google/go-cmp/cmp" "google.golang.org/grpc/codes" + "google.golang.org/protobuf/proto" "google.golang.org/protobuf/testing/protocmp" "go.ate.dev/substrate/api/ateapi/v1" @@ -35,7 +38,7 @@ func TestListTags(t *testing.T) { ctx := context.Background() persistence, cleanup := storetest.SetupTestStore(t) t.Cleanup(cleanup) - svc := &RPCService{impl: newServiceImpl(persistence, nil)} + svc := &RPCService{gates: testGates, impl: newServiceImpl(persistence, nil, testGates)} const otherAtespace = "other-atespace" seedTag := func(atespace, name string) { @@ -301,7 +304,7 @@ func rpcServiceWithTag(t *testing.T, tag *ateapi.Tag) (*RPCService, *ateapi.Tag) seeded := newTestTag(t, name, actor) seeded.Scope = tag.GetScope() created := storetest.MustCreateTag(t, ctx, persistence, seeded) - return &RPCService{impl: newServiceImpl(persistence, nil)}, created + return &RPCService{gates: testGates, impl: newServiceImpl(persistence, nil, testGates)}, created } // TestUpdateTag_DeleteRecreateRace checks that an update is not @@ -325,16 +328,16 @@ func TestUpdateTag_DeleteRecreateRace(t *testing.T) { Interface: persistence, inject: func() { tagRef := resources.TagRef{Atespace: testAtespace, Name: tagName} - if _, err := persistence.MarkTagForDeletion(ctx, tagRef, store.DeletePreconditions{}, nil); err != nil { + if _, err := persistence.MarkTagForDeletion(ctx, tagRef, store.Precondition{}, nil); err != nil { t.Fatalf("Racing writer: MarkTagForDeletion: %v", err) } - if _, err := persistence.DeleteTag(ctx, tagRef, store.DeletePreconditions{}); err != nil { + if _, err := persistence.DeleteTag(ctx, tagRef, store.Precondition{}); err != nil { t.Fatalf("Racing writer: DeleteTag: %v", err) } recreatedTag = storetest.MustCreateTag(t, ctx, persistence, newTestTag(t, tagName, actorTwo)) }, } - svc := &RPCService{impl: newServiceImpl(racing, nil)} + svc := &RPCService{gates: testGates, impl: newServiceImpl(racing, nil, testGates)} // The client asserts "only update the tag with uid A". Its version guard is // satisfied by B as well, because re-tagging resets the version to 1: the @@ -386,7 +389,7 @@ func TestUpdateTag_ConcurrentUpdate(t *testing.T) { } }, } - svc := &RPCService{impl: newServiceImpl(racing, nil)} + svc := &RPCService{gates: testGates, impl: newServiceImpl(racing, nil, testGates)} originalTag.Scope = ateapi.TagScope_TAG_SCOPE_PUBLISHED _, err := svc.UpdateTag(ctx, &ateapi.UpdateTagRequest{ @@ -417,7 +420,7 @@ func TestUpdateTag_PendingTag(t *testing.T) { ctx := context.Background() persistence, cleanup := storetest.SetupTestStore(t) t.Cleanup(cleanup) - svc := &RPCService{impl: newServiceImpl(persistence, nil)} + svc := &RPCService{gates: testGates, impl: newServiceImpl(persistence, nil, testGates)} actor := newTestSuspendedActor(t, ctx, persistence, testAtespace, "actor-1") tag := storetest.MustCreateTag(t, ctx, persistence, newPendingTestTag(t, "v1", actor)) @@ -436,3 +439,185 @@ func TestUpdateTag_PendingTag(t *testing.T) { t.Errorf("stored scope = %v, want %v: the rejected update published a pending tag", got, want) } } + +// TestUpdateTagStatus checks that ServiceImpl lets a write complete a pending +// tag's snapshot, and rejects writes that repoint it. +func TestUpdateTagStatus(t *testing.T) { + ctx := context.Background() + persistence, cleanup := storetest.SetupTestStore(t) + t.Cleanup(cleanup) + impl := newServiceImpl(persistence, nil, testGates) + + actor := newTestSuspendedActor(t, ctx, persistence, testAtespace, "actor-1") + tag := storetest.MustCreateTag(t, ctx, persistence, newPendingTestTag(t, "v1", actor)) + ref := resources.TagRefFromTag(tag) + repoint := func(toUpdate *ateapi.Tag) error { + toUpdate.Status.Snapshot.DurableSnapshot.Object.SnapshotUri += "-elsewhere" + return nil + } + + if _, err := impl.UpdateTag(ctx, ref, store.PreconditionFrom(tag), repoint); apierror.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateTag repointing the snapshot: error = %v, want code InvalidArgument", err) + } + if _, err := impl.MarkTagForDeletion(ctx, ref, store.Precondition{UID: tag.GetMetadata().GetUid(), Version: tag.GetMetadata().GetVersion()}, repoint); apierror.Code(err) != codes.InvalidArgument { + t.Errorf("MarkTagForDeletion repointing the snapshot: error = %v, want code InvalidArgument", err) + } + if _, err := impl.UpdateTag(ctx, ref, store.PreconditionFrom(tag), func(toUpdate *ateapi.Tag) error { + toUpdate.Status.Snapshot.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED + return nil + }); err != nil { + t.Errorf("UpdateTag completing the snapshot failed: %v", err) + } +} + +// TestDeleteTag_GoldenTag checks that DeleteTag refuses the golden tag a live +// ActorTemplate records, or the finished one it is about to record, and +// deletes every other tag. +func TestDeleteTag_GoldenTag(t *testing.T) { + const missingTemplateUID = "00000000-0000-4000-8000-000000000000" + tests := []struct { + name string + // tagName and tagTemplateUID default to the template's UID. + tagName string + tagTemplateUID string + // fromUserActor takes the tag from an ordinary actor of the template, + // not its golden actor. + fromUserActor bool + pending bool + recorded bool + templateFailed bool + deleteTemplate bool + markedForDeletion bool + // duringDelete changes the tag after DeleteTag checks it and before + // the workflow marks it for deletion. + duringDelete func(t *testing.T, ctx context.Context, persistence store.Interface, tag *ateapi.Tag) + wantCode codes.Code + }{ + {name: "golden tag the template records", recorded: true, wantCode: codes.FailedPrecondition}, + {name: "finished golden tag the template has not recorded yet", wantCode: codes.FailedPrecondition}, + {name: "unfinished golden tag", pending: true, wantCode: codes.OK}, + {name: "golden tag finished during the delete", pending: true, duringDelete: finishTag, wantCode: codes.Aborted}, + {name: "golden tag of a template whose golden failed", templateFailed: true, wantCode: codes.OK}, + {name: "golden tag whose delete failed partway", recorded: true, markedForDeletion: true, wantCode: codes.OK}, + {name: "golden tag of a template being deleted", recorded: true, deleteTemplate: true, wantCode: codes.OK}, + {name: "golden tag of a missing template", tagName: missingTemplateUID, tagTemplateUID: missingTemplateUID, wantCode: codes.OK}, + {name: "user tag named after the template", fromUserActor: true, wantCode: codes.OK}, + {name: "user tag named after the template after its golden failed", fromUserActor: true, templateFailed: true, wantCode: codes.OK}, + {name: "user tag replaced by the golden tag during the delete", fromUserActor: true, duringDelete: replaceWithGoldenTag, wantCode: codes.Aborted}, + {name: "ordinary tag taken under the template", tagName: "v1", fromUserActor: true, wantCode: codes.OK}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + ctx := context.Background() + persistence := newTestPersistence(t) + template := seedSubstrateTemplate(t, ctx, persistence, "tmpl") + templateUID := template.GetMetadata().GetUid() + tagName, tagTemplateUID := tt.tagName, tt.tagTemplateUID + if tagName == "" { + tagName = templateUID + } + if tagTemplateUID == "" { + tagTemplateUID = templateUID + } + actor := newTestSuspendedActor(t, ctx, persistence, "team-a", "actor-1") + seeded := newTestTag(t, tagName, actor) + if tt.pending { + seeded = newPendingTestTag(t, tagName, actor) + } + if !tt.fromUserActor { + seeded.SourceActor = &ateapi.ObjectRef{Atespace: "team-a", Name: tagTemplateUID} + } + seeded.Status.ActorTemplateUid = tagTemplateUID + tag := storetest.MustCreateTag(t, ctx, persistence, seeded) + tagRef := resources.TagRefFromTag(tag) + + if tt.recorded || tt.templateFailed { + templateRef := resources.ActorTemplateRefFromActorTemplate(template) + if _, err := persistence.UpdateActorTemplate(ctx, templateRef, store.PreconditionFrom(template), func(dbTemplate *ateapi.ActorTemplate) error { + dbTemplate.Status = &ateapi.ActorTemplateStatus{GoldenSnapshotStatus: &ateapi.GoldenSnapshotStatus{}} + if tt.recorded { + dbTemplate.Status.GoldenSnapshotStatus.GoldenTag = tagRef.ToObjectRef() + } + if tt.templateFailed { + dbTemplate.Status.GoldenSnapshotStatus.ErrorMessage = "golden tag belongs to another actor or template" + } + return nil + }); err != nil { + t.Fatalf("UpdateActorTemplate: %v", err) + } + } + if tt.deleteTemplate { + if _, err := persistence.MarkActorTemplateForDeletion(ctx, resources.ActorTemplateRefFromActorTemplate(template), store.Precondition{}, nil); err != nil { + t.Fatalf("MarkActorTemplateForDeletion: %v", err) + } + } + if tt.markedForDeletion { + if _, err := persistence.MarkTagForDeletion(ctx, tagRef, store.Precondition{}, nil); err != nil { + t.Fatalf("MarkTagForDeletion: %v", err) + } + } + + w, _ := newFinalizeWorkflow(persistence) + if tt.duringDelete != nil { + w.store = &beforeMarkTagStore{Interface: persistence, before: func() { + tt.duringDelete(t, ctx, persistence, tag) + }} + } + s := &RPCService{gates: testGates, impl: newServiceImpl(persistence, nil, testGates), actorWorkflow: w} + _, err := s.DeleteTag(ctx, &ateapi.DeleteTagRequest{Tag: tagRef.ToObjectRef()}) + if code := apierror.Code(err); code != tt.wantCode { + t.Fatalf("DeleteTag = %v (code %v), want code %v", err, code, tt.wantCode) + } + _, err = persistence.GetTag(ctx, tagRef) + if tt.wantCode == codes.OK { + if !errors.Is(err, store.ErrNotFound) { + t.Errorf("GetTag after DeleteTag = %v, want ErrNotFound", err) + } + } else if err != nil { + t.Errorf("GetTag after a refused DeleteTag = %v, want the tag kept", err) + } + }) + } +} + +// finishTag completes the copy of a pending tag. +func finishTag(t *testing.T, ctx context.Context, persistence store.Interface, tag *ateapi.Tag) { + t.Helper() + if _, err := persistence.UpdateTag(ctx, resources.TagRefFromTag(tag), store.PreconditionFrom(tag), func(toUpdate *ateapi.Tag) error { + toUpdate.Status.Snapshot.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED + return nil + }); err != nil { + t.Errorf("finishing the tag: %v", err) + } +} + +// replaceWithGoldenTag deletes tag and creates, under its name, a finished copy +// of the golden actor of the template the tag was taken under. +func replaceWithGoldenTag(t *testing.T, ctx context.Context, persistence store.Interface, tag *ateapi.Tag) { + t.Helper() + tagRef := resources.TagRefFromTag(tag) + if _, err := persistence.MarkTagForDeletion(ctx, tagRef, store.Precondition{}, nil); err != nil { + t.Errorf("MarkTagForDeletion: %v", err) + return + } + if _, err := persistence.DeleteTag(ctx, tagRef, store.Precondition{}); err != nil { + t.Errorf("DeleteTag: %v", err) + return + } + golden := proto.CloneOf(tag) + golden.Metadata = &ateapi.ResourceMetadata{Atespace: tagRef.Atespace, Name: tagRef.Name} + golden.SourceActor = &ateapi.ObjectRef{Atespace: tagRef.Atespace, Name: tag.GetStatus().GetActorTemplateUid()} + storetest.MustCreateTag(t, ctx, persistence, golden) +} + +// beforeMarkTagStore calls before ahead of the first MarkTagForDeletion. +type beforeMarkTagStore struct { + store.Interface + once sync.Once + before func() +} + +func (b *beforeMarkTagStore) MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(*ateapi.Tag) error) (*ateapi.Tag, error) { + b.once.Do(b.before) + return b.Interface.MarkTagForDeletion(ctx, tagRef, precondition, mutate) +} diff --git a/cmd/ateapi/internal/controlapi/template_reconciler.go b/cmd/ateapi/internal/controlapi/template_reconciler.go index f5617eeac6..e8ed0b4b0f 100644 --- a/cmd/ateapi/internal/controlapi/template_reconciler.go +++ b/cmd/ateapi/internal/controlapi/template_reconciler.go @@ -36,9 +36,9 @@ import ( const ( templateListPageSize = 100 - // templateWorkerCount is the number of goroutines draining the work - // queue. - templateWorkerCount = 5 + // DefaultTemplateReconcilerWorkers is the default number of goroutines + // draining the template work queue. + DefaultTemplateReconcilerWorkers = 5 // goldenSnapshotWarmup is the default wall-clock delay between resuming // the golden actor and taking its snapshot, for templates without a @@ -91,24 +91,35 @@ type ActorTemplateReconciler struct { control goldenActorControl queue workqueue.TypedRateLimitingInterface[resources.ActorTemplateRef] resyncInterval time.Duration + workers int } -func NewActorTemplateReconciler(persistence templateReconcilerStore, control goldenActorControl, resyncInterval time.Duration) *ActorTemplateReconciler { +// NewActorTemplateReconciler constructs a reconciler for stored ActorTemplates. +// Both resyncInterval and workers must be positive. +func NewActorTemplateReconciler(persistence templateReconcilerStore, control goldenActorControl, resyncInterval time.Duration, workers int) (*ActorTemplateReconciler, error) { + if resyncInterval <= 0 { + return nil, fmt.Errorf("resyncInterval must be positive, got %s", resyncInterval) + } + if workers < 1 { + return nil, fmt.Errorf("workers must be at least 1, got %d", workers) + } return &ActorTemplateReconciler{ persistence: persistence, control: control, resyncInterval: resyncInterval, + workers: workers, // Create rate-limiting queue with exponential backoff queue: workqueue.NewTypedRateLimitingQueue(workqueue.DefaultTypedControllerRateLimiter[resources.ActorTemplateRef]()), - } + }, nil } // Start launches the queue workers and the resync producer; there is no event // source for stored templates, so the periodic list is the event source. func (r *ActorTemplateReconciler) Start(ctx context.Context) { + slog.InfoContext(ctx, "Starting ActorTemplateReconciler", slog.Int("workers", r.workers), slog.Duration("resyncInterval", r.resyncInterval)) go func() { defer r.queue.ShutDown() - for range templateWorkerCount { + for range r.workers { go wait.UntilWithContext(ctx, r.runWorker, time.Second) } wait.UntilWithContext(ctx, r.resync, r.resyncInterval) diff --git a/cmd/ateapi/internal/controlapi/template_reconciler_test.go b/cmd/ateapi/internal/controlapi/template_reconciler_test.go index aea76020c7..053a90c753 100644 --- a/cmd/ateapi/internal/controlapi/template_reconciler_test.go +++ b/cmd/ateapi/internal/controlapi/template_reconciler_test.go @@ -21,7 +21,9 @@ import ( "strconv" "strings" "sync" + "sync/atomic" "testing" + "testing/synctest" "time" "unicode/utf8" @@ -101,7 +103,7 @@ func (s *fakeTemplateStore) ListActorTemplates(_ context.Context, _ string, opts func (s *fakeTemplateStore) UpdateActorTemplate(_ context.Context, ref resources.ActorTemplateRef, precondition store.Precondition, mutate func(*ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) { s.mu.Lock() defer s.mu.Unlock() - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } tmpl, ok := s.templates[ref] @@ -391,8 +393,13 @@ func withFailed(reason string) func(*ateapi.ActorTemplate) { } } -func newTestTemplateReconciler(persistence templateReconcilerStore, control goldenActorControl) *ActorTemplateReconciler { - return NewActorTemplateReconciler(persistence, control, 7*time.Second) +func newTestTemplateReconciler(t testing.TB, persistence templateReconcilerStore, control goldenActorControl) *ActorTemplateReconciler { + t.Helper() + r, err := NewActorTemplateReconciler(persistence, control, 7*time.Second, DefaultTemplateReconcilerWorkers) + if err != nil { + t.Fatal(err) + } + return r } func TestGoldenSnapshotWarmupFor(t *testing.T) { @@ -613,7 +620,7 @@ func TestReconcileOne(t *testing.T) { st = newFakeTemplateStore(tt.template) } st.leaseErr = tt.leaseErr - r := newTestTemplateReconciler(st, tt.control) + r := newTestTemplateReconciler(t, st, tt.control) requeueAfter, err := r.reconcileOne(context.Background(), testTemplateRef) if (err != nil) != tt.wantErr { @@ -688,7 +695,7 @@ func (c *goldenEgressControl) GetActorEgressPolicy(ctx context.Context, req *ate } func TestReconcileOne_GoldenEgressPolicyBeforeResume(t *testing.T) { - preview.InitForTest(t, "GoldenEgressPolicy") + gates := preview.NewForTest(t, "GoldenEgressPolicy") for _, tt := range []struct { name string policy *ateapi.EgressPolicyTemplate @@ -699,9 +706,9 @@ func TestReconcileOne_GoldenEgressPolicyBeforeResume(t *testing.T) { t.Run(tt.name, func(t *testing.T) { ctx := t.Context() persistence := newTestPersistence(t) - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, gates) impl.clusterSnapshotLocation = "gs://cluster-bucket/" - svc := &RPCService{impl: impl} + svc := &RPCService{gates: gates, impl: impl} storetest.MustCreateAtespace(t, ctx, persistence, "templates") tmpl, err := svc.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { tmpl.Metadata = &ateapi.ResourceMetadata{Atespace: "templates", Name: "tmpl"} @@ -735,10 +742,11 @@ func TestReconcileOne_GoldenEgressPolicyBeforeResume(t *testing.T) { } return nil, stop }} - r := newTestTemplateReconciler(persistence, control) + r := newTestTemplateReconciler(t, persistence, control) defer r.queue.ShutDown() // Turning the gate off must not drop an existing template's policy. - preview.InitForTest(t) + impl.gates = preview.NewForTest(t) + svc.gates = impl.gates for range 2 { if _, err := r.reconcileOne(ctx, resources.ActorTemplateRefFromActorTemplate(tmpl)); !errors.Is(err, stop) { t.Fatalf("reconcile = %v, want to reach resume with the policy present", err) @@ -749,14 +757,14 @@ func TestReconcileOne_GoldenEgressPolicyBeforeResume(t *testing.T) { } func TestReconcileOne_GoldenEgressPolicyRecovery(t *testing.T) { - preview.InitForTest(t, "GoldenEgressPolicy") + gates := preview.NewForTest(t, "GoldenEgressPolicy") for _, scenario := range []string{"create fails", "create response lost", "lookup fails", "conflicting policy"} { t.Run(scenario, func(t *testing.T) { ctx := t.Context() persistence := newTestPersistence(t) - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, gates) impl.clusterSnapshotLocation = "gs://cluster-bucket/" - svc := &RPCService{impl: impl} + svc := &RPCService{gates: gates, impl: impl} storetest.MustCreateAtespace(t, ctx, persistence, "templates") tmpl, err := svc.CreateActorTemplate(ctx, &ateapi.CreateActorTemplateRequest{ActorTemplate: validActorTemplate(func(tmpl *ateapi.ActorTemplate) { tmpl.Metadata = &ateapi.ResourceMetadata{Atespace: "templates", Name: "tmpl"} @@ -799,7 +807,7 @@ func TestReconcileOne_GoldenEgressPolicyRecovery(t *testing.T) { var previousPolicy *ateapi.EgressPolicy for pass := range 2 { // A fresh reconciler must recover from persisted state alone. - r := newTestTemplateReconciler(persistence, control) + r := newTestTemplateReconciler(t, persistence, control) after, err := r.reconcileOne(ctx, resources.ActorTemplateRefFromActorTemplate(tmpl)) r.queue.ShutDown() switch { @@ -894,7 +902,7 @@ func TestReconcileOne_GoldenActorRequests(t *testing.T) { goldenSnapshot := "gs://bucket/root/atespaces/ns/actors/" + someActorUID + "/snapshots/snap-1" control := &fakeGoldenControl{snapshot: goldenSnapshot} - r := newTestTemplateReconciler(st, control) + r := newTestTemplateReconciler(t, st, control) if _, err := r.reconcileOne(ctx, testTemplateRef); err != nil { t.Fatalf("reconcileOne failed: %v", err) @@ -939,7 +947,7 @@ func TestCheckpoint_TerminalStateErrors(t *testing.T) { } { t.Run(seed.name, func(t *testing.T) { st := newFakeTemplateStore(testTemplate(seed.opt)) - r := newTestTemplateReconciler(st, &fakeGoldenControl{}) + r := newTestTemplateReconciler(t, st, &fakeGoldenControl{}) // Checkpoint against a template a concurrent writer already // drove to a terminal state. @@ -1016,7 +1024,7 @@ func TestTruncateUTF8(t *testing.T) { func TestFail_TruncatesErrorMessage(t *testing.T) { ctx := context.Background() st := newFakeTemplateStore(testTemplate()) - r := newTestTemplateReconciler(st, &fakeGoldenControl{}) + r := newTestTemplateReconciler(t, st, &fakeGoldenControl{}) if err := r.fail(ctx, testTemplate(), reasonGoldenActorInvalid, strings.Repeat("é", maxGoldenErrorMessageLen)); err != nil { t.Fatalf("fail() error = %v", err) @@ -1033,7 +1041,7 @@ func TestFail_TruncatesErrorMessage(t *testing.T) { if !utf8.ValidString(msg) { t.Error("error_message is not valid UTF-8") } - op := apivalidation.MakeUpdateOp(ctx) + op := apivalidation.MakeUpdateOp(ctx, testGates) if errs := apivalidation.Validate_GoldenSnapshotStatus(ctx, op, nil, golden, &ateapi.GoldenSnapshotStatus{}); len(errs) != 0 { t.Errorf("stored status fails validation: %v", errs) } @@ -1045,7 +1053,7 @@ func TestFail_TruncatesErrorMessage(t *testing.T) { func TestCheckpoint_StaleObservationConflicts(t *testing.T) { ctx := context.Background() st := newFakeTemplateStore(testTemplate()) - r := newTestTemplateReconciler(st, &fakeGoldenControl{}) + r := newTestTemplateReconciler(t, st, &fakeGoldenControl{}) // A concurrent writer advances the stored version past the observation. if _, err := st.UpdateActorTemplate(ctx, testTemplateRef, store.PreconditionFrom(testTemplate()), func(*ateapi.ActorTemplate) error { return nil }); err != nil { @@ -1101,7 +1109,7 @@ func TestResync_QueuesOnlyActionableTemplates(t *testing.T) { tmpl.Metadata.Name = templateName(tt.name) templates = append(templates, tmpl) } - r := newTestTemplateReconciler(newFakeTemplateStore(templates...), &fakeGoldenControl{}) + r := newTestTemplateReconciler(t, newFakeTemplateStore(templates...), &fakeGoldenControl{}) r.resync(context.Background()) @@ -1126,7 +1134,7 @@ func TestResync_FollowsPagination(t *testing.T) { testTemplate(func(tmpl *ateapi.ActorTemplate) { tmpl.Metadata.Name = "tmpl-c" }), ) st.forcePageSize = 1 - r := newTestTemplateReconciler(st, &fakeGoldenControl{}) + r := newTestTemplateReconciler(t, st, &fakeGoldenControl{}) r.resync(context.Background()) @@ -1176,7 +1184,7 @@ func TestReconcileOne_GoldenTagRecovery(t *testing.T) { tagErr: tt.createTagErr, deleteErr: tt.deleteActorErr, deleteTagErr: tt.deleteTagErr, } st := newFakeTemplateStore(testTemplate()) - r := newTestTemplateReconciler(st, control) + r := newTestTemplateReconciler(t, st, control) defer r.queue.ShutDown() _, err := r.reconcileOne(t.Context(), testTemplateRef) wantErr := tt.createTagErr != nil || tt.deleteActorErr != nil || tt.deleteTagErr != nil @@ -1237,7 +1245,7 @@ func TestReconcileOne_GoldenTagConflict(t *testing.T) { } control := &fakeGoldenControl{tag: proto.CloneOf(tag), exists: true} st := newFakeTemplateStore(testTemplate()) - r := newTestTemplateReconciler(st, control) + r := newTestTemplateReconciler(t, st, control) defer r.queue.ShutDown() for range 2 { after, err := r.reconcileOne(t.Context(), testTemplateRef) @@ -1259,3 +1267,77 @@ func TestReconcileOne_GoldenTagConflict(t *testing.T) { }) } } + +// blockingTagControl parks every GetTag call until its context ends, counting +// the calls so a test can see how many reconciles are in flight at once. +type blockingTagControl struct { + fakeGoldenControl + inFlight atomic.Int32 +} + +func (c *blockingTagControl) GetTag(ctx context.Context, _ *ateapi.GetTagRequest) (*ateapi.Tag, error) { + c.inFlight.Add(1) + <-ctx.Done() + return nil, ctx.Err() +} + +func TestNewActorTemplateReconciler_InvalidArgs(t *testing.T) { + t.Parallel() + cases := []struct { + name string + resyncInterval time.Duration + workers int + }{ + {name: "zero workers", resyncInterval: time.Second, workers: 0}, + {name: "negative workers", resyncInterval: time.Second, workers: -1}, + {name: "zero resyncInterval", resyncInterval: 0, workers: 1}, + {name: "negative resyncInterval", resyncInterval: -time.Second, workers: 1}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + r, err := NewActorTemplateReconciler(newFakeTemplateStore(), &fakeGoldenControl{}, tc.resyncInterval, tc.workers) + if err == nil { + t.Fatalf("NewActorTemplateReconciler(%s, %d) succeeded, want error", tc.resyncInterval, tc.workers) + } + if r != nil { + t.Fatalf("NewActorTemplateReconciler(%s, %d) returned non-nil reconciler on error", tc.resyncInterval, tc.workers) + } + }) + } +} + +func TestStart_RunsConfiguredWorkers(t *testing.T) { + t.Parallel() + const templateCount = 8 + templates := make([]*ateapi.ActorTemplate, templateCount) + for i := range templates { + templates[i] = testTemplate(func(tmpl *ateapi.ActorTemplate) { + tmpl.Metadata.Name = "tmpl-" + strconv.Itoa(i) + tmpl.Metadata.Uid = "uid-" + strconv.Itoa(i) + }) + } + + for _, workers := range []int{1, DefaultTemplateReconcilerWorkers + 1} { + t.Run(strconv.Itoa(workers), func(t *testing.T) { + t.Parallel() + synctest.Test(t, func(t *testing.T) { + ctrl := &blockingTagControl{} + ctx, cancel := context.WithCancel(t.Context()) + r, err := NewActorTemplateReconciler(newFakeTemplateStore(templates...), ctrl, time.Hour, workers) + if err != nil { + t.Fatal(err) + } + r.Start(ctx) + + // Every worker is parked in GetTag and the rest of the + // templates are still queued. + synctest.Wait() + if got := int(ctrl.inFlight.Load()); got != workers { + t.Errorf("reconciles in flight = %d, want %d", got, workers) + } + cancel() + }) + }) + } +} diff --git a/cmd/ateapi/internal/controlapi/volumes.go b/cmd/ateapi/internal/controlapi/volumes.go index d9de1a3ff7..cad4847c06 100644 --- a/cmd/ateapi/internal/controlapi/volumes.go +++ b/cmd/ateapi/internal/controlapi/volumes.go @@ -31,7 +31,7 @@ import ( // externalVolumesStatus wraps vols for ActorStatus, leaving the field unset // when the actor has no external volumes. -func externalVolumesStatus(vols []*ateapi.ExternalVolumeStatus) *ateapi.ExternalVolumes { +func externalVolumesStatus(vols []*ateapi.ActorExternalVolumeStatus) *ateapi.ExternalVolumes { if len(vols) == 0 { return nil } @@ -40,23 +40,23 @@ func externalVolumesStatus(vols []*ateapi.ExternalVolumeStatus) *ateapi.External // initialExternalVolumes constructs the actor's volume objects before volume // creation. A volume has no storage volume ID until it is provisioned. -func initialExternalVolumes(ctx context.Context, scLister storagev1listers.StorageClassLister, template *ateapi.ActorTemplate) ([]*ateapi.ExternalVolumeStatus, error) { +func initialExternalVolumes(ctx context.Context, scLister storagev1listers.StorageClassLister, template *ateapi.ActorTemplate) ([]*ateapi.ActorExternalVolumeStatus, error) { if template == nil { return nil, apierror.InvalidArgument("template is required") } - var volumes []*ateapi.ExternalVolumeStatus + var volumes []*ateapi.ActorExternalVolumeStatus for _, vol := range template.GetVolumes() { if vol.GetExternal().GetTemplate() != nil { scName := vol.GetExternal().GetTemplate().GetStorageClassName() sc, err := scLister.Get(scName) if err != nil { if k8serrors.IsNotFound(err) { - return nil, apierror.FailedPrecondition("StorageClass %q not found", scName) + return nil, apierror.FailedPrecondition("StorageClass %q not found", scName).WithCause(err) } return nil, apierror.Internal("failed to get StorageClass %q: %v", scName, err) } - volumes = append(volumes, &ateapi.ExternalVolumeStatus{ + volumes = append(volumes, &ateapi.ActorExternalVolumeStatus{ Name: vol.GetName(), VolumeType: sc.Provisioner, }) @@ -68,8 +68,8 @@ func initialExternalVolumes(ctx context.Context, scLister storagev1listers.Stora // createActorVolumes provisions the external volumes in volumesToCreate that have no storage volume ID, using the provided volume plugin. // It returns the list of external volumes (with storage IDs), or an error if any creation fails. // Any volumes processed before or during a failure are returned alongside the error so they can be persisted on the actor. -func createActorVolumes(ctx context.Context, registry VolumePluginRegistry, scLister storagev1listers.StorageClassLister, actorUID string, template *ateapi.ActorTemplate, volumesToCreate []*ateapi.ExternalVolumeStatus) (resultVolumes []*ateapi.ExternalVolumeStatus, err error) { - resultVolumes = make([]*ateapi.ExternalVolumeStatus, 0, len(volumesToCreate)) +func createActorVolumes(ctx context.Context, registry VolumePluginRegistry, scLister storagev1listers.StorageClassLister, actorUID string, template *ateapi.ActorTemplate, volumesToCreate []*ateapi.ActorExternalVolumeStatus) (resultVolumes []*ateapi.ActorExternalVolumeStatus, err error) { + resultVolumes = make([]*ateapi.ActorExternalVolumeStatus, 0, len(volumesToCreate)) var currentIdx int defer func() { @@ -106,7 +106,7 @@ func createActorVolumes(ctx context.Context, registry VolumePluginRegistry, scLi sc, err := scLister.Get(scName) if err != nil { if k8serrors.IsNotFound(err) { - return resultVolumes, apierror.FailedPrecondition("StorageClass %q not found", scName) + return resultVolumes, apierror.FailedPrecondition("StorageClass %q not found", scName).WithCause(err) } return resultVolumes, apierror.Internal("failed to get StorageClass %q: %v", scName, err) } @@ -134,7 +134,7 @@ func createActorVolumes(ctx context.Context, registry VolumePluginRegistry, scLi return resultVolumes, apierror.Internal("volume plugin returned no ID for volume %q", specVol.GetName()) } - resultVolumes = append(resultVolumes, &ateapi.ExternalVolumeStatus{ + resultVolumes = append(resultVolumes, &ateapi.ActorExternalVolumeStatus{ Name: volName, StorageVolumeId: resp.VolumeID, VolumeType: sc.Provisioner, @@ -145,7 +145,7 @@ func createActorVolumes(ctx context.Context, registry VolumePluginRegistry, scLi } // deleteActorVolumes deletes all external volumes in the list. -func deleteActorVolumes(ctx context.Context, registry VolumePluginRegistry, actorUID string, volumes []*ateapi.ExternalVolumeStatus) error { +func deleteActorVolumes(ctx context.Context, registry VolumePluginRegistry, actorUID string, volumes []*ateapi.ActorExternalVolumeStatus) error { if actorUID == "" { return errors.New("actorUID is required") } @@ -177,8 +177,8 @@ func deleteActorVolumes(ctx context.Context, registry VolumePluginRegistry, acto } // getMountedActorVolumes filters the actor's volumes and returns only those that are declared and mounted in the ActorTemplate. -func getMountedActorVolumes(ctx context.Context, ref *ateapi.ObjectRef, volumes []*ateapi.ExternalVolumeStatus, template *ateapi.ActorTemplate) []*ateapi.ExternalVolumeStatus { - var mounted []*ateapi.ExternalVolumeStatus +func getMountedActorVolumes(ctx context.Context, ref *ateapi.ObjectRef, volumes []*ateapi.ActorExternalVolumeStatus, template *ateapi.ActorTemplate) []*ateapi.ActorExternalVolumeStatus { + var mounted []*ateapi.ActorExternalVolumeStatus for _, vol := range volumes { // Find the corresponding volume in the ActorTemplate to check if it's mounted var matchedTemplateVol *ateapi.Volume diff --git a/cmd/ateapi/internal/controlapi/volumes_test.go b/cmd/ateapi/internal/controlapi/volumes_test.go index a7366a0c9f..7d52f0fdbb 100644 --- a/cmd/ateapi/internal/controlapi/volumes_test.go +++ b/cmd/ateapi/internal/controlapi/volumes_test.go @@ -68,7 +68,7 @@ func TestActorVolumesStorageClassErrors(t *testing.T) { }}, }}, } - volumes := []*ateapi.ExternalVolumeStatus{{ + volumes := []*ateapi.ActorExternalVolumeStatus{{ Name: "data-vol", VolumeType: "mock-standard", }} @@ -140,7 +140,7 @@ func TestInitialActorVolumes(t *testing.T) { }, } - want := []*ateapi.ExternalVolumeStatus{ + want := []*ateapi.ActorExternalVolumeStatus{ { Name: "data-vol-1", VolumeType: "mock-standard", @@ -212,22 +212,22 @@ func TestCreateActorVolumes(t *testing.T) { tests := []struct { name string tmpl *ateapi.ActorTemplate - inputVolumes []*ateapi.ExternalVolumeStatus + inputVolumes []*ateapi.ActorExternalVolumeStatus storageClasses map[string]*storagev1.StorageClass wantErr bool - wantRes []*ateapi.ExternalVolumeStatus + wantRes []*ateapi.ActorExternalVolumeStatus }{ { name: "partial failure returns error and preserves succeeded, failed, and remaining volumes", tmpl: multiVolTmpl, - inputVolumes: []*ateapi.ExternalVolumeStatus{ + inputVolumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", VolumeType: "mock-standard"}, // Its type differs from its StorageClass's provisioner, so creating it fails. {Name: "vol2", VolumeType: "mock-fast"}, {Name: "vol3", VolumeType: "mock-standard"}, }, wantErr: true, - wantRes: []*ateapi.ExternalVolumeStatus{ + wantRes: []*ateapi.ActorExternalVolumeStatus{ { Name: "vol1", StorageVolumeId: "mock-vol-substrate-actor-uid-123-vol1", @@ -240,14 +240,14 @@ func TestCreateActorVolumes(t *testing.T) { { name: "volume with a storage volume id is not created again", tmpl: standardTmpl, - inputVolumes: []*ateapi.ExternalVolumeStatus{ + inputVolumes: []*ateapi.ActorExternalVolumeStatus{ { Name: "data-vol", StorageVolumeId: "existing-vol-id", }, }, wantErr: false, - wantRes: []*ateapi.ExternalVolumeStatus{ + wantRes: []*ateapi.ActorExternalVolumeStatus{ { Name: "data-vol", StorageVolumeId: "existing-vol-id", @@ -257,18 +257,18 @@ func TestCreateActorVolumes(t *testing.T) { { name: "volume not found in template returns error", tmpl: &ateapi.ActorTemplate{}, - inputVolumes: []*ateapi.ExternalVolumeStatus{ + inputVolumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "missing-vol"}, }, wantErr: true, - wantRes: []*ateapi.ExternalVolumeStatus{ + wantRes: []*ateapi.ActorExternalVolumeStatus{ {Name: "missing-vol"}, }, }, { name: "storage class parameters are propagated to volume context", tmpl: standardTmpl, - inputVolumes: []*ateapi.ExternalVolumeStatus{ + inputVolumes: []*ateapi.ActorExternalVolumeStatus{ { Name: "data-vol", VolumeType: "mock-standard", @@ -285,7 +285,7 @@ func TestCreateActorVolumes(t *testing.T) { }, }, wantErr: false, - wantRes: []*ateapi.ExternalVolumeStatus{ + wantRes: []*ateapi.ActorExternalVolumeStatus{ { Name: "data-vol", StorageVolumeId: "mock-vol-substrate-actor-uid-123-data-vol", @@ -355,7 +355,7 @@ func TestCreateActorVolumesRejectsEmptyPluginID(t *testing.T) { scLister := &fakeStorageClassLister{storageClasses: map[string]*storagev1.StorageClass{ "standard": {ObjectMeta: metav1.ObjectMeta{Name: "standard"}, Provisioner: "mock-standard"}, }} - input := []*ateapi.ExternalVolumeStatus{{Name: "data-vol", VolumeType: "mock-standard"}} + input := []*ateapi.ActorExternalVolumeStatus{{Name: "data-vol", VolumeType: "mock-standard"}} res, err := createActorVolumes(context.Background(), registry, scLister, "actor-uid-123", tmpl, input) if got := apierror.Code(err); got != codes.Internal { @@ -383,14 +383,14 @@ func TestDeleteActorVolumes(t *testing.T) { tests := []struct { name string actorUID string - volumes []*ateapi.ExternalVolumeStatus + volumes []*ateapi.ActorExternalVolumeStatus wantDeleted []string wantErr bool }{ { name: "uses storage volume ID when present", actorUID: "uid-abc", - volumes: []*ateapi.ExternalVolumeStatus{ + volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "storage-vol-123", VolumeType: "mock"}, }, wantDeleted: []string{"storage-vol-123"}, @@ -399,7 +399,7 @@ func TestDeleteActorVolumes(t *testing.T) { { name: "falls back to actorVolumeID when storage volume ID is empty", actorUID: "uid-abc", - volumes: []*ateapi.ExternalVolumeStatus{ + volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "", VolumeType: "mock"}, }, wantDeleted: []string{"substrate-uid-abc-vol1"}, @@ -479,7 +479,7 @@ func TestDetachActorVolumes(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Name: "actor-1", Atespace: "default"}, Status: &ateapi.ActorStatus{ AssignedNode: "node-1", - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "mock"}, {Name: "vol2", StorageVolumeId: "storage-vol-2", VolumeType: "mock"}, }}, @@ -510,7 +510,7 @@ func TestDetachActorVolumes(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Name: "actor-1", Atespace: "default"}, Status: &ateapi.ActorStatus{ AssignedNode: "node-1", - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "mounted-vol", StorageVolumeId: "storage-vol-mounted", VolumeType: "mock"}, {Name: "unmounted-vol", StorageVolumeId: "storage-vol-unmounted", VolumeType: "mock"}, }}, @@ -539,7 +539,7 @@ func TestDetachActorVolumes(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Name: "actor-1", Atespace: "default"}, Status: &ateapi.ActorStatus{ AssignedNode: "node-1", - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "", VolumeType: "mock"}, {Name: "vol2", StorageVolumeId: "storage-vol-2", VolumeType: "mock"}, }}, @@ -569,7 +569,7 @@ func TestDetachActorVolumes(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Name: "actor-1", Atespace: "default"}, Status: &ateapi.ActorStatus{ AssignedNode: "node-1", - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "mock"}, {Name: "vol2", StorageVolumeId: "storage-vol-2", VolumeType: "mock"}, }}, @@ -587,7 +587,7 @@ func TestDetachActorVolumes(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Name: "actor-1", Atespace: "default"}, Status: &ateapi.ActorStatus{ AssignedNode: "node-1", - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "mock"}, }}, }, @@ -608,7 +608,7 @@ func TestDetachActorVolumes(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Name: "actor-1", Atespace: "default"}, Status: &ateapi.ActorStatus{ AssignedNode: "node-1", - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "mock"}, {Name: "vol2", StorageVolumeId: "storage-vol-2", VolumeType: "mock"}, }}, @@ -632,7 +632,7 @@ func TestDetachActorVolumes(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Name: "actor-1", Atespace: "default"}, Status: &ateapi.ActorStatus{ AssignedNode: "node-1", - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "unknown-plugin"}, }}, }, @@ -646,7 +646,7 @@ func TestDetachActorVolumes(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Name: "actor-1", Atespace: "default"}, Status: &ateapi.ActorStatus{ AssignedNode: "", - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "mock"}, }}, }, diff --git a/cmd/ateapi/internal/controlapi/worker.go b/cmd/ateapi/internal/controlapi/worker.go index a16766a3b6..32007723d4 100644 --- a/cmd/ateapi/internal/controlapi/worker.go +++ b/cmd/ateapi/internal/controlapi/worker.go @@ -24,6 +24,7 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/defaults" "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "google.golang.org/protobuf/proto" "k8s.io/apimachinery/pkg/util/validation/field" @@ -33,7 +34,7 @@ import ( // subresource rather than a field on Worker, so this is the only way to read // them and neither GetWorker nor ListWorkers grows with occupancy. func (s *RPCService) ListWorkerActorAssignments(ctx context.Context, req *ateapi.ListWorkerActorAssignmentsRequest) (*ateapi.ListWorkerActorAssignmentsResponse, error) { - if errs := apivalidation.ValidateListWorkerActorAssignmentsRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateListWorkerActorAssignmentsRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } name := req.GetWorker().GetName() @@ -43,7 +44,7 @@ func (s *RPCService) ListWorkerActorAssignments(ctx context.Context, req *ateapi // Worker hosting nothing. if _, err := s.impl.GetWorker(ctx, name); err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Worker %s not found", name) + return nil, apierror.NotFound("Worker %s not found", name).WithCause(err) } return nil, fmt.Errorf("while fetching worker %s: %w", name, err) } @@ -59,7 +60,7 @@ func (s *RPCService) ListWorkerActorAssignments(ctx context.Context, req *ateapi } func (s *RPCService) ListWorkers(ctx context.Context, req *ateapi.ListWorkersRequest) (*ateapi.ListWorkersResponse, error) { - if errs := apivalidation.ValidateListWorkersRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateListWorkersRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -78,14 +79,14 @@ func (s *ServiceImpl) ListWorkers(ctx context.Context, opts store.ListOptions) ( } func (s *RPCService) GetWorker(ctx context.Context, req *ateapi.GetWorkerRequest) (*ateapi.Worker, error) { - if errs := apivalidation.ValidateGetWorkerRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateGetWorkerRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } name := req.GetWorker().GetName() worker, err := s.impl.GetWorker(ctx, name) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Worker %s not found", name) + return nil, apierror.NotFound("Worker %s not found", name).WithCause(err) } if err != nil { return nil, fmt.Errorf("while getting worker: %w", err) @@ -113,7 +114,7 @@ func (s *RPCService) CreateWorker(ctx context.Context, req *ateapi.CreateWorkerR } // Validate the request, including the object within it. - if errs := apivalidation.ValidateCreateWorkerRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateCreateWorkerRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -129,7 +130,7 @@ func (s *ServiceImpl) CreateWorker(ctx context.Context, inWorker *ateapi.Worker) } // Verify that the result is properly valid before storing it. - if errs := apivalidation.ValidateWorkerUpdate(ctx, field.NewPath("worker"), outWorker, inWorker, true); len(errs) > 0 { + if errs := apivalidation.ValidateWorkerUpdate(ctx, s.gates, field.NewPath("worker"), outWorker, inWorker, true); len(errs) > 0 { return nil, resources.ToInternalError(errs) } @@ -137,7 +138,7 @@ func (s *ServiceImpl) CreateWorker(ctx context.Context, inWorker *ateapi.Worker) created, err := s.store.CreateWorker(ctx, outWorker) if err != nil { if errors.Is(err, store.ErrAlreadyExists) { - return nil, apierror.AlreadyExists("Worker %s already exists", inWorker.GetMetadata().GetName()) + return nil, apierror.AlreadyExists("Worker %s already exists", inWorker.GetMetadata().GetName()).WithCause(err) } return nil, fmt.Errorf("while creating worker: %w", err) } @@ -159,7 +160,7 @@ func (s *RPCService) UpdateWorker(ctx context.Context, req *ateapi.UpdateWorkerR } // Validate the request. - if errs := apivalidation.ValidateUpdateWorkerRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateUpdateWorkerRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -180,30 +181,38 @@ func (s *RPCService) UpdateWorker(ctx context.Context, req *ateapi.UpdateWorkerR } func (s *ServiceImpl) UpdateWorker(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapi.Worker) error) (*ateapi.Worker, error) { - return s.store.UpdateWorker(ctx, name, precondition, func(toUpdate *ateapi.Worker) error { + return s.store.UpdateWorker(ctx, name, precondition, validatedWorkerMutation(ctx, s.gates, mutate)) +} + +// validatedWorkerMutation wraps mutate so the Worker it writes is validated as +// an update of the stored Worker. +func validatedWorkerMutation(ctx context.Context, gates *preview.Gates, mutate func(*ateapi.Worker) error) func(*ateapi.Worker) error { + return func(toUpdate *ateapi.Worker) error { // Apply the mutation function to the stored value. oldVal := proto.CloneOf(toUpdate) - if err := mutate(toUpdate); err != nil { - return err + if mutate != nil { + if err := mutate(toUpdate); err != nil { + return err + } } newVal := toUpdate // Validate the mutated value before doing any further work. This is // what enforces the immutable fields, since only the stored worker // gives declarative validation an old value to compare against. - if errs := apivalidation.ValidateWorkerUpdate(ctx, field.NewPath("worker"), newVal, oldVal, false); len(errs) > 0 { + if errs := apivalidation.ValidateWorkerUpdate(ctx, gates, field.NewPath("worker"), newVal, oldVal, false); len(errs) > 0 { return resources.ToAPIError(errs) } // Do any further work on the resource. // Validate the final value before storing it. - if errs := apivalidation.ValidateWorkerUpdate(ctx, field.NewPath("worker"), newVal, oldVal, true); len(errs) > 0 { + if errs := apivalidation.ValidateWorkerUpdate(ctx, gates, field.NewPath("worker"), newVal, oldVal, true); len(errs) > 0 { return resources.ToInternalError(errs) } return nil - }) + } } // BindActorToWorker and UpdateActorAndRelease validate the Actor they write as @@ -226,24 +235,24 @@ func (s *ServiceImpl) ListWorkerAssignments(ctx context.Context, workerName stri } func (s *RPCService) DeleteWorker(ctx context.Context, req *ateapi.DeleteWorkerRequest) (*ateapi.Worker, error) { - if errs := apivalidation.ValidateDeleteWorkerRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateDeleteWorkerRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } // The delete releases the Actor bound to this Worker before removing the // record, so it is a workflow rather than a single store call. - return s.workerWorkflow.DeleteWorker(ctx, req.GetWorker().GetName(), toDeletePreconditions(req.GetOptions())) + return s.workerWorkflow.DeleteWorker(ctx, req.GetWorker().GetName(), toPreconditions(req.GetOptions())) } -func (s *ServiceImpl) MarkWorkerForDeletion(ctx context.Context, name string, precondition store.DeletePreconditions, mutate func(*ateapi.Worker) error) (*ateapi.Worker, error) { - return s.store.MarkWorkerForDeletion(ctx, name, precondition, mutate) +func (s *ServiceImpl) MarkWorkerForDeletion(ctx context.Context, name string, precondition store.Precondition, mutate func(*ateapi.Worker) error) (*ateapi.Worker, error) { + return s.store.MarkWorkerForDeletion(ctx, name, precondition, validatedWorkerMutation(ctx, s.gates, mutate)) } -func (s *ServiceImpl) DeleteWorker(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.Worker, error) { +func (s *ServiceImpl) DeleteWorker(ctx context.Context, name string, precondition store.Precondition) (*ateapi.Worker, error) { return s.store.DeleteWorker(ctx, name, precondition) } func (s *RPCService) DrainWorker(ctx context.Context, req *ateapi.DrainWorkerRequest) (*ateapi.DrainWorkerResponse, error) { - if errs := apivalidation.ValidateDrainWorkerRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateDrainWorkerRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } drained, err := s.mutateNamedWorker(ctx, req.GetWorker().GetName(), func(toUpdate *ateapi.Worker) error { @@ -263,7 +272,7 @@ func (s *RPCService) DrainWorker(ctx context.Context, req *ateapi.DrainWorkerReq } func (s *RPCService) MarkWorkerAvailable(ctx context.Context, req *ateapi.MarkWorkerAvailableRequest) (*ateapi.MarkWorkerAvailableResponse, error) { - if errs := apivalidation.ValidateMarkWorkerAvailableRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateMarkWorkerAvailableRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } marked, err := s.mutateNamedWorker(ctx, req.GetWorker().GetName(), func(toUpdate *ateapi.Worker) error { @@ -283,7 +292,7 @@ func (s *RPCService) MarkWorkerAvailable(ctx context.Context, req *ateapi.MarkWo } func (s *RPCService) MarkWorkerUnavailable(ctx context.Context, req *ateapi.MarkWorkerUnavailableRequest) (*ateapi.MarkWorkerUnavailableResponse, error) { - if errs := apivalidation.ValidateMarkWorkerUnavailableRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateMarkWorkerUnavailableRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } marked, err := s.mutateNamedWorker(ctx, req.GetWorker().GetName(), func(toUpdate *ateapi.Worker) error { @@ -314,7 +323,7 @@ var errWorkerDraining = errors.New("worker is draining") func (s *RPCService) mutateNamedWorker(ctx context.Context, name string, mutate func(toUpdate *ateapi.Worker) error) (*ateapi.Worker, error) { observed, err := s.impl.GetWorker(ctx, name) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Worker %s not found", name) + return nil, apierror.NotFound("Worker %s not found", name).WithCause(err) } if err != nil { return nil, fmt.Errorf("while getting worker %s: %w", name, err) @@ -337,13 +346,13 @@ func (s *RPCService) mutateWorker(ctx context.Context, name string, precondition } switch { case errors.Is(err, errWorkerDraining): - return nil, apierror.FailedPrecondition("Worker %s is draining", name) + return nil, apierror.FailedPrecondition("Worker %s is draining", name).WithCause(err) case errors.Is(err, store.ErrNotFound): - return nil, apierror.NotFound("Worker %s not found", name) + return nil, apierror.NotFound("Worker %s not found", name).WithCause(err) case errors.Is(err, store.ErrUIDConflict): - return nil, apierror.Aborted("Worker %s is not the one the request describes", name) + return nil, apierror.Aborted("Worker %s is not the one the request describes", name).WithCause(err) case errors.Is(err, store.ErrVersionConflict): - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) case errors.Is(err, store.ErrPreconditionRequired): return nil, apierror.InvalidArgument("while updating worker %s: %v", name, err) } diff --git a/cmd/ateapi/internal/controlapi/worker_assignment_reconciler.go b/cmd/ateapi/internal/controlapi/worker_assignment_reconciler.go index 517e29aaf0..d49de1ed73 100644 --- a/cmd/ateapi/internal/controlapi/worker_assignment_reconciler.go +++ b/cmd/ateapi/internal/controlapi/worker_assignment_reconciler.go @@ -23,6 +23,7 @@ import ( "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/store" + "go.ate.dev/substrate/internal/preview" "k8s.io/apimachinery/pkg/util/wait" "k8s.io/client-go/util/workqueue" ) @@ -54,10 +55,10 @@ type WorkerAssignmentReconciler struct { queue workqueue.TypedRateLimitingInterface[string] } -func NewWorkerAssignmentReconciler(persistence workerWorkflowStore, workers workerWatcher) *WorkerAssignmentReconciler { +func NewWorkerAssignmentReconciler(persistence workerWorkflowStore, workers workerWatcher, gates *preview.Gates) *WorkerAssignmentReconciler { return &WorkerAssignmentReconciler{ persistence: persistence, - workflow: NewWorkerWorkflow(persistence, nil), + workflow: NewWorkerWorkflow(persistence, nil, gates), workers: workers, queue: workqueue.NewTypedRateLimitingQueue(workqueue.DefaultTypedControllerRateLimiter[string]()), } diff --git a/cmd/ateapi/internal/controlapi/worker_assignment_reconciler_test.go b/cmd/ateapi/internal/controlapi/worker_assignment_reconciler_test.go index b88f3f7f87..77224f2804 100644 --- a/cmd/ateapi/internal/controlapi/worker_assignment_reconciler_test.go +++ b/cmd/ateapi/internal/controlapi/worker_assignment_reconciler_test.go @@ -38,7 +38,7 @@ func epochWorker(name string, registered, observed int64) *ateapi.Worker { } func TestWorkerAssignmentReconciler_QueuesUnobservedWorkers(t *testing.T) { - r := NewWorkerAssignmentReconciler(nil, noWorkers{}) + r := NewWorkerAssignmentReconciler(nil, noWorkers{}, testGates) defer r.queue.ShutDown() for _, w := range []*ateapi.Worker{ @@ -77,7 +77,7 @@ func TestWorkerAssignmentReconciler_SkipsWorkerLeasedElsewhere(t *testing.T) { } defer lease.Close() - r := NewWorkerAssignmentReconciler(persistence, noWorkers{}) + r := NewWorkerAssignmentReconciler(persistence, noWorkers{}, testGates) defer r.queue.ShutDown() if err := r.reconcileOne(ctx, apiWorkerName); !errors.Is(err, errWorkerLeased) { t.Fatalf("reconcileOne() = %v, want errWorkerLeased", err) @@ -107,7 +107,7 @@ func startAssignmentReconciler(t *testing.T, ctx context.Context, persistence st if err := wc.Start(ctx); err != nil { t.Fatalf("workercache.Start: %v", err) } - NewWorkerAssignmentReconciler(persistence, wc).Start(ctx) + NewWorkerAssignmentReconciler(persistence, wc, testGates).Start(ctx) } // End to end: the syncer's raise is all it takes for the reconciler to hear of diff --git a/cmd/ateapi/internal/controlapi/worker_test.go b/cmd/ateapi/internal/controlapi/worker_test.go index a109869634..24bf3aafac 100644 --- a/cmd/ateapi/internal/controlapi/worker_test.go +++ b/cmd/ateapi/internal/controlapi/worker_test.go @@ -72,8 +72,8 @@ func newWorkerAPIService(t *testing.T) (*RPCService, store.Interface) { t.Helper() persistence, cleanup := storetest.SetupTestStore(t) t.Cleanup(cleanup) - impl := newServiceImpl(persistence, nil) - return &RPCService{impl: impl, workerWorkflow: NewWorkerWorkflow(persistence, newNodeAteletDialer(t, &capturingTerminator{}))}, persistence + impl := newServiceImpl(persistence, nil, testGates) + return &RPCService{gates: testGates, impl: impl, workerWorkflow: NewWorkerWorkflow(persistence, newNodeAteletDialer(t, &capturingTerminator{}), testGates)}, persistence } // seedAPIWorker registers a worker directly through the store and returns it as @@ -783,7 +783,7 @@ func TestServiceImplUpdateWorker_ImmutableFields(t *testing.T) { ctx := context.Background() persistence, cleanup := storetest.SetupTestStore(t) defer cleanup() - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, testGates) // Every case below is rejected, so nothing writes and this stays the // current incarnation for all of them. @@ -864,7 +864,7 @@ func TestServiceImplAssignmentWrites_ValidateActor(t *testing.T) { ctx := context.Background() persistence, cleanup := storetest.SetupTestStore(t) defer cleanup() - impl := newServiceImpl(persistence, nil) + impl := newServiceImpl(persistence, nil, testGates) seedAPIWorker(t, ctx, persistence, validWorker(apiWorkerName)) actor := storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "actor-1"}, @@ -945,3 +945,35 @@ func TestCreateWorker_HoldsNoCapacityUntilReported(t *testing.T) { t.Errorf("a request carrying a ceiling set capacity to %v, want none", capacity) } } + +// TestMarkWorkerForDeletion checks that ServiceImpl validates the Worker a +// mark-for-deletion writes, as it does for an update. +func TestMarkWorkerForDeletion(t *testing.T) { + ctx := context.Background() + _, persistence := newWorkerAPIService(t) + impl := newServiceImpl(persistence, nil, testGates) + worker := seedAPIWorker(t, ctx, persistence, validWorker(apiWorkerName)) + precondition := store.PreconditionFrom(worker) + + if _, err := impl.MarkWorkerForDeletion(ctx, apiWorkerName, precondition, func(toUpdate *ateapi.Worker) error { + toUpdate.WorkerPod = "worker-pod-2" + return nil + }); apierror.Code(err) != codes.InvalidArgument { + t.Errorf("MarkWorkerForDeletion changing worker_pod: error = %v, want code InvalidArgument", err) + } + + marked, err := impl.MarkWorkerForDeletion(ctx, apiWorkerName, precondition, func(toUpdate *ateapi.Worker) error { + toUpdate.Status.State = ateapi.WorkerState_WORKER_STATE_DRAINING + return nil + }) + if err != nil { + t.Fatalf("MarkWorkerForDeletion failed: %v", err) + } + if marked.GetMetadata().GetDeleteTime() == nil || marked.GetStatus().GetState() != ateapi.WorkerState_WORKER_STATE_DRAINING { + t.Errorf("marked worker = %v, want delete_time set and state DRAINING", marked) + } + + if _, err := impl.MarkWorkerForDeletion(ctx, apiWorkerName, store.PreconditionFrom(marked), nil); err != nil { + t.Errorf("MarkWorkerForDeletion with a nil mutate failed: %v", err) + } +} diff --git a/cmd/ateapi/internal/controlapi/workflow.go b/cmd/ateapi/internal/controlapi/workflow.go index deac7d526d..b75b6d67e2 100644 --- a/cmd/ateapi/internal/controlapi/workflow.go +++ b/cmd/ateapi/internal/controlapi/workflow.go @@ -31,6 +31,7 @@ import ( "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/pluginsocket" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" @@ -117,6 +118,7 @@ type ActorWorkflow struct { workflowDeadline time.Duration objectStorePlugin objectstore.ControlProviderClient clusterSnapshotLocation string + gates *preview.Gates } // NewActorWorkflow creates a new ActorWorkflow. workflowDeadline bounds @@ -135,6 +137,7 @@ func NewActorWorkflow( pluginRegistry VolumePluginRegistry, workflowDeadline time.Duration, objectStorePlugin objectstore.ControlProviderClient, + gates *preview.Gates, ) *ActorWorkflow { return &ActorWorkflow{ store: store, @@ -147,13 +150,14 @@ func NewActorWorkflow( pluginRegistry: pluginRegistry, workflowDeadline: workflowDeadline, objectStorePlugin: objectStorePlugin, + gates: gates, } } // snapshotLocation returns the base object-storage URI actorTemplate's // snapshots are stored under; see resolveSnapshotLocation. func (w *ActorWorkflow) snapshotLocation(actorTemplate *ateapi.ActorTemplate) (string, error) { - return resolveSnapshotLocation(w.clusterSnapshotLocation, actorTemplate) + return resolveSnapshotLocation(w.gates, w.clusterSnapshotLocation, actorTemplate) } // cleanupSnapshot deletes every object under prefix through the control @@ -175,8 +179,8 @@ func (w *ActorWorkflow) copySnapshot(ctx context.Context, src, dst resources.Sto type actorWorkflowStore interface { GetActor(ctx context.Context, actorRef resources.ActorRef) (*ateapi.Actor, error) UpdateActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(toUpdate *ateapi.Actor) error) (*ateapi.Actor, error) - MarkActorForDeletion(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions, mutate func(toUpdate *ateapi.Actor) error) (*ateapi.Actor, error) - DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions) (*ateapi.Actor, error) + MarkActorForDeletion(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(toUpdate *ateapi.Actor) error) (*ateapi.Actor, error) + DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (*ateapi.Actor, error) GetWorker(ctx context.Context, name string) (*ateapi.Worker, error) UpdateWorker(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapi.Worker) error) (*ateapi.Worker, error) BindActorToWorker(ctx context.Context, workerName string, assignment *ateapi.ActorAssignment, admit func(*ateapi.Worker) error, actorRef resources.ActorRef, precondition store.Precondition, mutate func(toUpdate *ateapi.Actor) error) (*ateapi.Actor, error) @@ -188,11 +192,11 @@ type actorWorkflowStore interface { CreateTag(ctx context.Context, tag *ateapi.Tag) (*ateapi.Tag, error) GetTag(ctx context.Context, tagRef resources.TagRef) (*ateapi.Tag, error) UpdateTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(toUpdate *ateapi.Tag) error) (*ateapi.Tag, error) - MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions, mutate func(toUpdate *ateapi.Tag) error) (*ateapi.Tag, error) - DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions) (*ateapi.Tag, error) + MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(toUpdate *ateapi.Tag) error) (*ateapi.Tag, error) + DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition) (*ateapi.Tag, error) GetActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef) (*ateapi.ActorTemplate, error) - MarkActorTemplateForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions, mutate func(toUpdate *ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) - DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions) (*ateapi.ActorTemplate, error) + MarkActorTemplateForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition, mutate func(toUpdate *ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) + DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition) (*ateapi.ActorTemplate, error) AcquireLease(ctx context.Context, key string) (*store.Lease, error) } @@ -205,6 +209,7 @@ type actorWorkflowStore interface { type WorkerWorkflow struct { store workerWorkflowStore dialer *AteletDialer + gates *preview.Gates reclaimTimeout time.Duration now func() time.Time @@ -214,10 +219,11 @@ type WorkerWorkflow struct { // NewWorkerWorkflow creates a new WorkerWorkflow. dialer may be nil when the // caller only runs ReconcileAssignments. -func NewWorkerWorkflow(store workerWorkflowStore, dialer *AteletDialer) *WorkerWorkflow { +func NewWorkerWorkflow(store workerWorkflowStore, dialer *AteletDialer, gates *preview.Gates) *WorkerWorkflow { return &WorkerWorkflow{ store: store, dialer: dialer, + gates: gates, reclaimTimeout: defaultWorkerReclaimTimeout, now: time.Now, gaveUp: make(map[string]time.Time), @@ -229,8 +235,8 @@ func NewWorkerWorkflow(store workerWorkflowStore, dialer *AteletDialer) *WorkerW type workerWorkflowStore interface { GetWorker(ctx context.Context, name string) (*ateapi.Worker, error) UpdateWorker(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapi.Worker) error) (*ateapi.Worker, error) - MarkWorkerForDeletion(ctx context.Context, name string, precondition store.DeletePreconditions, mutate func(toUpdate *ateapi.Worker) error) (*ateapi.Worker, error) - DeleteWorker(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.Worker, error) + MarkWorkerForDeletion(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapi.Worker) error) (*ateapi.Worker, error) + DeleteWorker(ctx context.Context, name string, precondition store.Precondition) (*ateapi.Worker, error) ListWorkerAssignments(ctx context.Context, workerName string, opts store.ListOptions) (store.ListResponse[*ateapi.ActorAssignment], error) UpdateActorAndRelease(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(toUpdate *ateapi.Actor) error) (*ateapi.Actor, *ateapi.Worker, error) GetActor(ctx context.Context, actorRef resources.ActorRef) (*ateapi.Actor, error) @@ -251,7 +257,7 @@ func acquireLease(ctx context.Context, holder leaseHolder, key, subject string) lease, err := holder.AcquireLease(ctx, key) if err != nil { if errors.Is(err, store.ErrLeaseConflict) { - return nil, nil, apierror.Aborted("another operation is in progress for this %s", subject) + return nil, nil, apierror.Aborted("another operation is in progress for this %s", subject).WithCause(err) } return nil, nil, fmt.Errorf("while acquiring lease: %w", err) } diff --git a/cmd/ateapi/internal/controlapi/workflow_delete.go b/cmd/ateapi/internal/controlapi/workflow_delete.go index bdd949a4cc..89d797856b 100644 --- a/cmd/ateapi/internal/controlapi/workflow_delete.go +++ b/cmd/ateapi/internal/controlapi/workflow_delete.go @@ -32,7 +32,7 @@ import ( ) // DeleteActor executes the workflow to delete an actor. Idempotent. -func (w *ActorWorkflow) DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions) (*ateapi.Actor, error) { +func (w *ActorWorkflow) DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (*ateapi.Actor, error) { ctx = preview.ContextWithOptIn(ctx) ctx, lease, err := w.acquireActorLease(ctx, actorRef) if err != nil { @@ -145,7 +145,7 @@ func (w *ActorWorkflow) ensureAteletTerminated(ctx context.Context, actorRef res slog.String("actor", actorRef.Name), slog.String("templateAtespace", actor.GetActorTemplate().GetAtespace()), slog.String("templateName", actor.GetActorTemplate().GetName())) - workloadSpec = fallbackWorkloadSpec(actor) + workloadSpec = fallbackWorkloadSpec(w.gates, actor) } req := &ateletpb.TerminateRequest{ @@ -175,14 +175,14 @@ func (w *ActorWorkflow) ensureAteletTerminated(ctx context.Context, actorRef res // unmounts them from the node. A volume with no StorageVolumeId was never // provisioned (e.g. the actor failed while PENDING), so there is nothing // mounted to name. -func fallbackWorkloadSpec(actor *ateapi.Actor) *ateletpb.WorkloadSpec { +func fallbackWorkloadSpec(gates *preview.Gates, actor *ateapi.Actor) *ateletpb.WorkloadSpec { // Given that external volumes has been in the codebase for a while and // its preview-ness is solely around the API, and that the impact of // disabling the gate while in use would be an orphaned volume // attachment, we are NOT checking the ExternalVolumes gate in the // delete/suspend path. spec := &ateletpb.WorkloadSpec{} - if preview.IsEnabled(preview.GateExternalVolumes) { + if gates.IsEnabled(preview.GateExternalVolumes) { for _, vol := range actor.GetStatus().GetExternalVolumes().GetVolumes() { if vol.GetStorageVolumeId() == "" { continue @@ -239,7 +239,7 @@ func (w *ActorWorkflow) ensureWorkerReleased(ctx context.Context, actorRef resou return nil }) if err != nil { - return nil, actorWriteError(actorRef, err) + return nil, actorWriteError(actorRef, precondition.UID, err) } return updatedActor, nil } @@ -249,7 +249,7 @@ var errAlreadyMarked = errors.New("already marked for deletion") // ensureMarkedDeleting sets the actor's delete_time, checking precondition, // and moves it to DELETING, returning the stored copy. Skips when a previous // attempt already marked the actor. -func (w *ActorWorkflow) ensureMarkedDeleting(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions) (updated *ateapi.Actor, err error) { +func (w *ActorWorkflow) ensureMarkedDeleting(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (updated *ateapi.Actor, err error) { ctx, done := stepSpan(ctx, "MarkDeleting") defer func() { err = done(err) }() @@ -268,13 +268,13 @@ func (w *ActorWorkflow) ensureMarkedDeleting(ctx context.Context, actorRef resou } if err != nil { if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("Actor %s does not have uid %s", actorRef, precondition.UID) + return nil, apierror.Aborted("Actor %s does not have uid %s", actorRef, precondition.UID).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Actor %s not found", actorRef) + return nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } return nil, fmt.Errorf("while marking actor for deletion: %w", err) } @@ -379,22 +379,22 @@ func (w *ActorWorkflow) finalizeDeleted(ctx context.Context, actor *ateapi.Actor // Only the uid guards the delete. The mark already committed this // incarnation to deletion, and a later write such as an UpdateActor RPC, // which takes no actor lease, must not block removing the row. - precondition := store.DeletePreconditions{UID: actor.GetMetadata().GetUid()} + precondition := store.Precondition{UID: actor.GetMetadata().GetUid()} deleted, err := w.store.DeleteActor(ctx, actorRef, precondition) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Actor %s not found", actorRef) + return nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("Actor %s does not have uid %s", actorRef, precondition.UID) + return nil, apierror.Aborted("Actor %s does not have uid %s", actorRef, precondition.UID).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } if errors.Is(err, store.ErrFailedPrecondition) { // The release step cleared the Actor's worker assignment, and // only a resume, which refuses a DELETING Actor, sets it again. - return nil, apierror.Internal("Actor %s names a worker after its release", actorRef) + return nil, apierror.Internal("Actor %s names a worker after its release", actorRef).WithCause(err) } return nil, fmt.Errorf("while deleting actor from DB: %w", err) } diff --git a/cmd/ateapi/internal/controlapi/workflow_delete_test.go b/cmd/ateapi/internal/controlapi/workflow_delete_test.go index e6c685b283..26fef58572 100644 --- a/cmd/ateapi/internal/controlapi/workflow_delete_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_delete_test.go @@ -86,12 +86,12 @@ func TestDeleteActorWorkflow_ExecutionPaths(t *testing.T) { } seedWorkflowActor(t, ctx, st, actorRef, "ns", tmplName, tc.seedState) if tc.markActorForDeletion { - if _, err := st.MarkActorForDeletion(ctx, actorRef, store.DeletePreconditions{}, nil); err != nil { + if _, err := st.MarkActorForDeletion(ctx, actorRef, store.Precondition{}, nil); err != nil { t.Fatalf("MarkActorForDeletion: %v", err) } } - deleted, err := w.DeleteActor(ctx, actorRef, store.DeletePreconditions{}) + deleted, err := w.DeleteActor(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("DeleteActor failed: %v", err) } @@ -216,17 +216,17 @@ func TestRevertAndDelete_AssignedNodeGone(t *testing.T) { s.Snapshots = append(s.Snapshots, local) } if tc.volume { - s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + s.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "vol1", StorageVolumeId: "storage-vol-1", VolumeType: "mock"}}} } }) wantState := ateapi.ActorState_ACTOR_STATE_REVERTING if verb == "revert" { - _, err = w.RevertActor(ctx, actorRef) + _, err = w.RevertActor(ctx, actorRef, store.Precondition{}) } else { wantState = ateapi.ActorState_ACTOR_STATE_DELETING - _, err = w.DeleteActor(ctx, actorRef, store.DeletePreconditions{}) + _, err = w.DeleteActor(ctx, actorRef, store.Precondition{}) } switch { case tc.wantDetachErr: @@ -292,7 +292,7 @@ func TestEnsureMarkedDeleting_AllStates(t *testing.T) { t.Fatalf("get seeded actor: %v", err) } - updated, err := w.ensureMarkedDeleting(ctx, actorRef, store.DeletePreconditions{Version: actor.GetMetadata().GetVersion()}) + updated, err := w.ensureMarkedDeleting(ctx, actorRef, store.Precondition{Version: actor.GetMetadata().GetVersion()}) if err != nil { t.Fatalf("ensureMarkedDeleting failed: %v", err) } @@ -303,7 +303,7 @@ func TestEnsureMarkedDeleting_AllStates(t *testing.T) { t.Error("ensureMarkedDeleting left delete_time unset") } - again, err := w.ensureMarkedDeleting(ctx, actorRef, store.DeletePreconditions{}) + again, err := w.ensureMarkedDeleting(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("second ensureMarkedDeleting failed: %v", err) } @@ -456,7 +456,7 @@ func TestDeleteActor_CollectsInFlightSnapshotWithoutTemplate(t *testing.T) { ctx := context.Background() persistence := newTestPersistence(t) objects := objectstoretest.New() - w := NewActorWorkflow(persistence, nil, nil, nil, nil, "", nil, time.Minute, objectstoreplugintest.ControlClient(objects)) + w := NewActorWorkflow(persistence, nil, nil, nil, nil, "", nil, time.Minute, objectstoreplugintest.ControlClient(objects), testGates) actorRef := resources.ActorRef{Atespace: "team-a", Name: "actor-1"} actor := storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ @@ -478,7 +478,7 @@ func TestDeleteActor_CollectsInFlightSnapshotWithoutTemplate(t *testing.T) { } }) - if _, err := w.DeleteActor(ctx, actorRef, store.DeletePreconditions{}); err != nil { + if _, err := w.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatalf("DeleteActor: %v", err) } if left := objects.Prefix(t, inFlight.OwnerPrefix()); len(left) != 0 { @@ -606,12 +606,12 @@ func TestDeleteActor_CollectsSnapshotsAfterWorkerDelete(t *testing.T) { objects.PutSnapshot(t, fresh, "manifest.json") return apierror.Unavailable("worker pod is gone") } - if _, err := actorWorkflow.SuspendActor(ctx, actorRef, suspendSync); apierror.Code(err) != codes.Unavailable { + if _, err := actorWorkflow.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync); apierror.Code(err) != codes.Unavailable { t.Fatalf("SuspendActor err = %v, want Unavailable from the failed checkpoint", err) } // SuspendActor failed mid-checkpoint and released the actor's lease, // leaving the actor in SUSPENDING; DeleteWorker then crashes it. - if _, err := NewWorkerWorkflow(persistence, actorWorkflow.dialer).DeleteWorker(ctx, workerName, store.DeletePreconditions{}); err != nil { + if _, err := NewWorkerWorkflow(persistence, actorWorkflow.dialer, testGates).DeleteWorker(ctx, workerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker: %v", err) } @@ -624,7 +624,7 @@ func TestDeleteActor_CollectsSnapshotsAfterWorkerDelete(t *testing.T) { if got := stored.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_CRASHED { t.Fatalf("state = %v, want CRASHED", got) } - if _, err := actorWorkflow.DeleteActor(ctx, actorRef, store.DeletePreconditions{}); err != nil { + if _, err := actorWorkflow.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatalf("DeleteActor: %v", err) } if left := objects.Prefix(t, fresh.OwnerPrefix()); len(left) != 0 { @@ -642,7 +642,7 @@ func TestDeleteActorWorkflow_RetryKeepsAdmission(t *testing.T) { ctx := context.Background() persistence := newTestPersistence(t) objects := objectstoretest.New() - w := NewActorWorkflow(persistence, nil, nil, nil, nil, "", nil, time.Minute, objectstoreplugintest.ControlClient(objects)) + w := NewActorWorkflow(persistence, nil, nil, nil, nil, "", nil, time.Minute, objectstoreplugintest.ControlClient(objects), testGates) actorRef := resources.ActorRef{Atespace: "team-a", Name: "actor-1"} actor := storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ @@ -661,7 +661,7 @@ func TestDeleteActorWorkflow_RetryKeepsAdmission(t *testing.T) { } }) // The guards a client sends after reading the actor. - guards := store.DeletePreconditions{UID: observed.GetMetadata().GetUid(), Version: observed.GetMetadata().GetVersion()} + guards := store.Precondition{UID: observed.GetMetadata().GetUid(), Version: observed.GetMetadata().GetVersion()} objects.OnDelete = func(string, string) error { return errObjectStore } if _, err := w.DeleteActor(ctx, actorRef, guards); !isObjectStoreErr(err) { @@ -678,7 +678,7 @@ func TestDeleteActorWorkflow_RetryKeepsAdmission(t *testing.T) { t.Fatalf("state after the failure = %v, want DELETING", got) } - if _, err := w.DeleteActor(ctx, actorRef, store.DeletePreconditions{UID: guards.UID}); !isObjectStoreErr(err) { + if _, err := w.DeleteActor(ctx, actorRef, store.Precondition{UID: guards.UID}); !isObjectStoreErr(err) { t.Fatalf("retried DeleteActor = %v, want it to report %v", err, errObjectStore) } retried, err := persistence.GetActor(ctx, actorRef) @@ -694,14 +694,14 @@ func TestDeleteActorWorkflow_RetryKeepsAdmission(t *testing.T) { if _, err := w.DeleteActor(ctx, actorRef, guards); apierror.Code(err) != codes.Aborted { t.Fatalf("retry with the original version = %v, want ABORTED", err) } - deleted, err := w.DeleteActor(ctx, actorRef, store.DeletePreconditions{UID: guards.UID}) + deleted, err := w.DeleteActor(ctx, actorRef, store.Precondition{UID: guards.UID}) if err != nil { t.Fatalf("retry with the uid alone: %v", err) } if !deleted.GetMetadata().GetDeleteTime().AsTime().Equal(admitted.GetMetadata().GetDeleteTime().AsTime()) { t.Errorf("the retry re-stamped delete_time: %v, want %v", deleted.GetMetadata().GetDeleteTime().AsTime(), admitted.GetMetadata().GetDeleteTime().AsTime()) } - if _, err := w.DeleteActor(ctx, actorRef, store.DeletePreconditions{}); apierror.Code(err) != codes.NotFound { + if _, err := w.DeleteActor(ctx, actorRef, store.Precondition{}); apierror.Code(err) != codes.NotFound { t.Errorf("DeleteActor after the row is gone = %v, want NOT_FOUND", err) } } @@ -712,7 +712,7 @@ func TestDeleteActorWorkflow_RetryKeepsAdmission(t *testing.T) { func TestEnsureWorkerReleased_RecreatedActorKeepsAssignment(t *testing.T) { ctx := context.Background() persistence := newTestPersistence(t) - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} bound := func(uid string) *ateapi.Actor { return &ateapi.Actor{ Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "actor-1", Uid: uid}, @@ -728,13 +728,13 @@ func TestEnsureWorkerReleased_RecreatedActorKeepsAssignment(t *testing.T) { deleted := storetest.MustCreateActor(t, ctx, persistence, bound("")) actorRef := resources.ActorRefFromActor(deleted) // The delete that finished released the Actor's worker before removing it. - if _, err := persistence.MarkActorForDeletion(ctx, actorRef, store.DeletePreconditions{}, func(a *ateapi.Actor) error { + if _, err := persistence.MarkActorForDeletion(ctx, actorRef, store.Precondition{}, func(a *ateapi.Actor) error { a.Status.WorkerAssignment = nil return nil }); err != nil { t.Fatalf("MarkActorForDeletion: %v", err) } - if _, err := persistence.DeleteActor(ctx, actorRef, store.DeletePreconditions{}); err != nil { + if _, err := persistence.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatalf("DeleteActor: %v", err) } recreated := storetest.MustCreateActor(t, ctx, persistence, bound("")) diff --git a/cmd/ateapi/internal/controlapi/workflow_objectstore_plugin_test.go b/cmd/ateapi/internal/controlapi/workflow_objectstore_plugin_test.go index c62b53ccf9..085f3ff9a1 100644 --- a/cmd/ateapi/internal/controlapi/workflow_objectstore_plugin_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_objectstore_plugin_test.go @@ -55,7 +55,7 @@ func TestObjectStorePluginErrorCodeToClient(t *testing.T) { {codes.FailedPrecondition, codes.Internal}, } { t.Run(tc.pluginCode.String(), func(t *testing.T) { - w := &ActorWorkflow{objectStorePlugin: failingControlPlugin{err: status.Error(tc.pluginCode, "plugin failed")}} + w := &ActorWorkflow{gates: testGates, objectStorePlugin: failingControlPlugin{err: status.Error(tc.pluginCode, "plugin failed")}} for name, call := range map[string]func(context.Context) error{ "cleanup": func(ctx context.Context) error { return w.cleanupSnapshot(ctx, prefix) }, "copy": func(ctx context.Context) error { return w.copySnapshot(ctx, prefix, prefix) }, diff --git a/cmd/ateapi/internal/controlapi/workflow_reconcile_assignments_test.go b/cmd/ateapi/internal/controlapi/workflow_reconcile_assignments_test.go index 6a00b9ffba..72819b8cc7 100644 --- a/cmd/ateapi/internal/controlapi/workflow_reconcile_assignments_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_reconcile_assignments_test.go @@ -56,7 +56,7 @@ func mustRaiseEpoch(t *testing.T, ctx context.Context, persistence store.Interfa func mustReconcileAssignments(t *testing.T, ctx context.Context, persistence store.Interface) { t.Helper() - if err := NewWorkerWorkflow(persistence, nil).ReconcileAssignments(ctx, apiWorkerName); err != nil { + if err := NewWorkerWorkflow(persistence, nil, testGates).ReconcileAssignments(ctx, apiWorkerName); err != nil { t.Fatalf("ReconcileAssignments() failed: %v", err) } } @@ -233,7 +233,7 @@ func TestReconcileAssignments_WaitsForBusyActor(t *testing.T) { if err != nil { t.Fatalf("AcquireLease() failed: %v", err) } - err = NewWorkerWorkflow(persistence, nil).ReconcileAssignments(ctx, apiWorkerName) + err = NewWorkerWorkflow(persistence, nil, testGates).ReconcileAssignments(ctx, apiWorkerName) if !errors.Is(err, errActorBusy) { t.Fatalf("ReconcileAssignments() = %v, want errActorBusy", err) } @@ -314,7 +314,7 @@ func TestReconcileAssignments_KeepsActorReboundSinceList(t *testing.T) { t.Fatalf("BindActorToWorker() failed: %v", err) } }} - if err := NewWorkerWorkflow(rebinding, nil).ReconcileAssignments(ctx, apiWorkerName); err != nil { + if err := NewWorkerWorkflow(rebinding, nil, testGates).ReconcileAssignments(ctx, apiWorkerName); err != nil { t.Fatalf("ReconcileAssignments() failed: %v", err) } @@ -343,7 +343,7 @@ func TestReconcileAssignments_RetriesRecordAfterConcurrentBind(t *testing.T) { binding := &hookedStore{Interface: persistence, beforeUpdateWorker: func() { assignAPIWorker(t, ctx, persistence, apiWorkerName, boundUID) }} - if err := NewWorkerWorkflow(binding, nil).ReconcileAssignments(ctx, apiWorkerName); err != nil { + if err := NewWorkerWorkflow(binding, nil, testGates).ReconcileAssignments(ctx, apiWorkerName); err != nil { t.Fatalf("ReconcileAssignments() failed: %v", err) } @@ -368,12 +368,12 @@ func TestReconcileAssignments_LeavesReplacedWorker(t *testing.T) { mustRaiseEpoch(t, ctx, persistence, 5) replacing := &hookedStore{Interface: persistence, beforeUpdateWorker: func() { - if _, err := persistence.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := persistence.DeleteWorker(ctx, apiWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker() failed: %v", err) } seedEpochWorker(t, ctx, persistence, 1, 1) }} - if err := NewWorkerWorkflow(replacing, nil).ReconcileAssignments(ctx, apiWorkerName); err != nil { + if err := NewWorkerWorkflow(replacing, nil, testGates).ReconcileAssignments(ctx, apiWorkerName); err != nil { t.Fatalf("ReconcileAssignments() failed: %v", err) } @@ -391,7 +391,7 @@ func TestReconcileAssignments_FailureKeepsObservedEpoch(t *testing.T) { seedRunningActor(t, ctx, persistence) mustRaiseEpoch(t, ctx, persistence, 2) - failing := NewWorkerWorkflow(failingUpdateActorStore{Interface: persistence, err: errors.New("crash failed")}, nil) + failing := NewWorkerWorkflow(failingUpdateActorStore{Interface: persistence, err: errors.New("crash failed")}, nil, testGates) if err := failing.ReconcileAssignments(ctx, apiWorkerName); err == nil { t.Fatal("ReconcileAssignments() = nil error, want the crash failure reported") } @@ -451,9 +451,9 @@ func TestAssignWorkerAttempt_LeavesWorkerEpochUnset(t *testing.T) { t.Fatalf("workercache.Start: %v", err) } - w := &ActorWorkflow{store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} + w := &ActorWorkflow{gates: testGates, store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} tmpl := &ateapi.ActorTemplate{} - stored, _, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl) + stored, _, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt: %v", err) } diff --git a/cmd/ateapi/internal/controlapi/workflow_resume.go b/cmd/ateapi/internal/controlapi/workflow_resume.go index 324a16eda6..09f8f3eb8c 100644 --- a/cmd/ateapi/internal/controlapi/workflow_resume.go +++ b/cmd/ateapi/internal/controlapi/workflow_resume.go @@ -22,6 +22,8 @@ import ( "slices" "time" + "github.com/google/uuid" + "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/scheduling" "go.ate.dev/substrate/cmd/ateapi/internal/store" @@ -51,7 +53,8 @@ type restoreTelemetry struct { // ResumeActor executes the workflow to resume a suspended actor. Idempotent: // a re-entered workflow fast-forwards past the steps a previous attempt // completed, deriving progress from the persisted actor alone. -func (w *ActorWorkflow) ResumeActor(ctx context.Context, actorRef resources.ActorRef) (_ *ateapi.Actor, resumed bool, err error) { +// Fails with ABORTED if the actor does not match precondition. +func (w *ActorWorkflow) ResumeActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (_ *ateapi.Actor, resumed bool, err error) { ctx = preview.ContextWithOptIn(ctx) start := time.Now() var actor *ateapi.Actor @@ -75,10 +78,16 @@ func (w *ActorWorkflow) ResumeActor(ctx context.Context, actorRef resources.Acto // Read before taking the distributed lease so that hot-path checks do not // upsert and delete a PostgreSQL lease row. Any state that needs work is read // again under the lease below. - actor, err = w.store.GetActor(ctx, actorRef) + // actor stays nil until the guards match, so a refused call does not label + // its metric with another actor's template and pool. + observed, err := w.store.GetActor(ctx, actorRef) if err != nil { return nil, false, err } + if err = checkActorPreconditions(actorRef, precondition, observed); err != nil { + return nil, false, err + } + actor = observed if wasRunning = actor.GetStatus().GetState() == ateapi.ActorState_ACTOR_STATE_RUNNING; wasRunning { return actor, false, nil } @@ -89,7 +98,7 @@ func (w *ActorWorkflow) ResumeActor(ctx context.Context, actorRef resources.Acto } defer lease.Close() - actor, actorTemplate, err = w.loadActorForResume(leaseCtx, actorRef) + actor, actorTemplate, err = w.loadActorForResume(leaseCtx, actorRef, precondition) if err != nil { return nil, false, err } @@ -103,14 +112,14 @@ func (w *ActorWorkflow) ResumeActor(ctx context.Context, actorRef resources.Acto actor = created var worker *ateapi.Worker var assigned *ateapi.Actor - assigned, worker, err = w.ensureWorkerAssigned(leaseCtx, actorRef, actor, actorTemplate) + assigned, worker, err = w.ensureWorkerAssigned(leaseCtx, actorRef, actor, actorTemplate, precondition) if err != nil && shouldDetachFromNode(actor, err) { var detached *ateapi.Actor - if detached, err = w.detachFromFullNode(leaseCtx, actorRef, actor, actorTemplate, err); err != nil { + if detached, err = w.detachFromFullNode(leaseCtx, actorRef, actor, actorTemplate, err, precondition); err != nil { return nil, false, err } actor = detached - assigned, worker, err = w.ensureWorkerAssigned(leaseCtx, actorRef, actor, actorTemplate) + assigned, worker, err = w.ensureWorkerAssigned(leaseCtx, actorRef, actor, actorTemplate, precondition) } if err != nil { return nil, false, err @@ -121,29 +130,34 @@ func (w *ActorWorkflow) ResumeActor(ctx context.Context, actorRef resources.Acto return nil, false, err } var workerEpoch int64 - if tele, workerEpoch, err = w.ensureAteletRestored(leaseCtx, actorRef, actor, actorTemplate, volumePublishContexts); err != nil { + var activationUID string + if tele, workerEpoch, activationUID, err = w.ensureAteletRestored(leaseCtx, actorRef, actor, actorTemplate, volumePublishContexts); err != nil { return nil, false, err } var running *ateapi.Actor - if running, err = w.finalizeRunning(leaseCtx, actorRef, workerEpoch); err != nil { + if running, err = w.finalizeRunning(leaseCtx, actorRef, workerEpoch, activationUID); err != nil { return nil, false, err } actor = running return actor, true, nil } -// loadActorForResume fetches the current actor record and its template. -func (w *ActorWorkflow) loadActorForResume(ctx context.Context, actorRef resources.ActorRef) (_ *ateapi.Actor, _ *ateapi.ActorTemplate, err error) { +// loadActorForResume fetches the current actor record, checks it against +// precondition, and fetches its template. +func (w *ActorWorkflow) loadActorForResume(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (_ *ateapi.Actor, _ *ateapi.ActorTemplate, err error) { ctx, done := stepSpan(ctx, "LoadActorForResume") defer func() { err = done(err) }() actor, err := w.store.GetActor(ctx, actorRef) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, nil, apierror.NotFound("Actor %s not found", actorRef) + return nil, nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } return nil, nil, fmt.Errorf("while getting actor from DB: %w", err) } + if err := checkActorPreconditions(actorRef, precondition, actor); err != nil { + return nil, nil, err + } // If the actor is already running, there is no pending restore to prepare // for. Short-circuit immediately to avoid an unnecessary template read on @@ -195,7 +209,7 @@ func (w *ActorWorkflow) ensureVolumesCreated(ctx context.Context, actorRef resou ctx, done := stepSpan(ctx, "CreateVolumes") defer func() { err = done(err) }() - pending := slices.ContainsFunc(actor.GetStatus().GetExternalVolumes().GetVolumes(), func(vol *ateapi.ExternalVolumeStatus) bool { + pending := slices.ContainsFunc(actor.GetStatus().GetExternalVolumes().GetVolumes(), func(vol *ateapi.ActorExternalVolumeStatus) bool { return vol.GetStorageVolumeId() == "" }) if !pending { @@ -223,18 +237,16 @@ func (w *ActorWorkflow) ensureVolumesCreated(ctx context.Context, actorRef resou } storedActor, updateErr := w.store.UpdateActor(ctx, actorRef, updatePrecondition, persistVolumes) if updateErr != nil { - if errors.Is(updateErr, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") - } - return nil, fmt.Errorf("while updating actor after volume creation: %w", updateErr) + return nil, fmt.Errorf("while updating actor after volume creation: %w", actorWriteError(actorRef, updatePrecondition.UID, updateErr)) } return storedActor, nil } // ensureWorkerAssigned assigns a worker and leaves the actor RESUMING. // Re-entry validates the recorded assignment before reuse. -// Version conflicts re-read the actor before retrying. -func (w *ActorWorkflow) ensureWorkerAssigned(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, actorTemplate *ateapi.ActorTemplate) (_ *ateapi.Actor, _ *ateapi.Worker, err error) { +// Version conflicts re-read the actor before retrying, unless the caller +// passed a version guard. +func (w *ActorWorkflow) ensureWorkerAssigned(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, actorTemplate *ateapi.ActorTemplate, precondition store.Precondition) (_ *ateapi.Actor, _ *ateapi.Worker, err error) { ctx, done := stepSpan(ctx, "AssignWorker") defer func() { err = done(err) }() @@ -268,7 +280,7 @@ func (w *ActorWorkflow) ensureWorkerAssigned(ctx context.Context, actorRef resou return false, err } attemptStart := time.Now() - attemptActor, attemptWorker, attemptErr := w.assignWorkerAttempt(ctx, actorRef, actor, actorTemplate) + attemptActor, attemptWorker, attemptErr := w.assignWorkerAttempt(ctx, actorRef, actor, actorTemplate, precondition) lastAttempt = time.Since(attemptStart) attempted = true if attemptErr == nil { @@ -308,7 +320,8 @@ func (w *ActorWorkflow) ensureWorkerAssigned(ctx context.Context, actorRef resou w.recordExhaustedAssignment(ctx, lastAttempt, actor, err) return nil, nil, err default: - // assignWorkerAttempt recorded this one itself. + // assignWorkerAttempt recorded this outcome, or skipped it on a + // precondition failure. return nil, nil, err } } @@ -341,7 +354,7 @@ func (w *ActorWorkflow) validateAssignedWorker(ctx context.Context, actorRef res workerName := actor.GetStatus().GetWorkerAssignment().GetWorker().GetName() worker, err := w.store.GetWorker(ctx, workerName) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.Aborted("worker %s of actor %s is gone", workerName, actorRef) + return nil, apierror.Aborted("worker %s of actor %s is gone", workerName, actorRef).WithCause(err) } if err != nil { return nil, fmt.Errorf("failed to get already assigned worker for actor %w", err) @@ -377,7 +390,7 @@ func (w *ActorWorkflow) validateAssignedWorker(ctx context.Context, actorRef res return nil, apierror.Aborted("actor %s has moved off worker %s since it was read", actorRef, worker.GetMetadata().GetName()) } constraints := schedulingConstraints(actor, actorTemplate) - if !w.appliesWithFallback(worker, constraints, canRelaxRuntime(actor, constraints)) { + if !w.scheduler.Applies(worker, constraints) { slog.ErrorContext(ctx, "crashing actor because previously assigned worker is not eligible anymore") // The crash releases the worker, e.g. one whose pool the actor's // worker_selector no longer matches after the failed attempt. @@ -401,8 +414,9 @@ func schedulerRecordable(err error) bool { // and persisting RESUMING with the assignment. On a version conflict it // re-reads the actor: if the fresh copy can still be resumed the refreshed // actor is returned along with the conflict so the caller retries with clean -// inputs; any other status aborts the resume. -func (w *ActorWorkflow) assignWorkerAttempt(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, actorTemplate *ateapi.ActorTemplate) (_ *ateapi.Actor, _ *ateapi.Worker, err error) { +// inputs; any other status aborts the resume. Under the caller's version guard +// the conflict aborts the resume instead. +func (w *ActorWorkflow) assignWorkerAttempt(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, actorTemplate *ateapi.ActorTemplate, precondition store.Precondition) (_ *ateapi.Actor, _ *ateapi.Worker, err error) { // Checked before a worker is claimed. if err := checkSnapshotUpload(actorRef, actor); err != nil { return nil, nil, err @@ -412,8 +426,12 @@ func (w *ActorWorkflow) assignWorkerAttempt(ctx context.Context, actorRef resour poolNamespace := "" pool := "" class := "" + record := true defer func() { - if schedulerRecordable(err) { + // Do not record scheduling errors for actors that can be detached from + // a node. Scheduling of those will be retried, so we don't want to + // double count. + if record && schedulerRecordable(err) && !shouldDetachFromNode(actor, err) { w.instruments.recordSchedulerAssignment(ctx, time.Since(start), outcome, poolNamespace, pool, class, err) } }() @@ -421,20 +439,23 @@ func (w *ActorWorkflow) assignWorkerAttempt(ctx context.Context, actorRef resour constraints := schedulingConstraints(actor, actorTemplate) snapRuntime := constraints.SnapshotRuntime class = constraints.SandboxClass - relaxable := canRelaxRuntime(actor, constraints) - assignedWorker, err := w.scheduler.Schedule(ctx, constraints) - if errors.Is(err, scheduling.ErrNoCapacity) && relaxable { - constraints.RequiredRuntime = hardware.Requirement{} - assignedWorker, err = w.scheduler.Schedule(ctx, constraints) - } + placement, err := w.scheduler.Schedule(ctx, constraints) if err != nil { + // Return FailedPrecondition only when we fail to schedule an actor + // that could resume on any node, but doesn't fit any of them. + // Scheduling failures for pinned actors will be retried, so we + // return ResourceExhausted in that case. + if errors.Is(err, scheduling.ErrDoesNotFit) && len(constraints.RequiredNodes) == 0 { + return nil, nil, apierror.FailedPrecondition("%w", errActorDoesNotFit).WithCause(err) + } if errors.Is(err, scheduling.ErrNoCapacity) { outcome = ateattr.SchedulerOutcomeNoCapacity - return nil, nil, apierror.ResourceExhausted("%w", errNoWorkerRoom) + return nil, nil, apierror.ResourceExhausted("%w", errNoWorkerRoom).WithCause(err) } return nil, nil, err } + assignedWorker := placement.Worker slog.InfoContext(ctx, "Picked worker", slog.Any("worker", assignedWorker.String())) if assignedWorker.GetNodeName() == "" { @@ -451,25 +472,27 @@ func (w *ActorWorkflow) assignWorkerAttempt(ctx context.Context, actorRef resour // Record what this claim books so release returns the same amount. It // includes the overhead the cached Worker reports, which admit checks // again under the row lock. - booking, ok := scheduling.Booking(assignedWorker, constraints) - if !ok { - return nil, nil, errWorkerFilledUp - } - assignment.Resources = booking + assignment.Resources = placement.Booking // The candidate came from a watch-fed cache, so it may already be full or no // longer eligible. The store re-asks under the Worker's row lock, where the // answer holds until the bind commits, so nothing here needs a fresh read // and two claims for the last place cannot both be admitted. + // + // admit holds the bind to the tier Schedule picked the worker at. A worker + // that lost the snapshot's runtime since the cache saw it fails admit, and + // the retry schedules again. + atPicked := constraints + atPicked.MinFidelity = placement.Fidelity // The bind evaluates the fresh row; record the assignment from the same view. bound := assignedWorker admit := func(fresh *ateapi.Worker) error { - if !w.scheduler.Applies(fresh, constraints) || !w.scheduler.HasRoom(fresh, constraints) { + if !w.scheduler.Applies(fresh, atPicked) || !w.scheduler.HasRoom(fresh, constraints) { return errWorkerFilledUp } // The Worker re-registered with a different overhead since the cache // saw it. Rare, and the retry reads the new one. - if got, _ := scheduling.Booking(fresh, constraints); !proto.Equal(got, booking) { + if got, _ := scheduling.Booking(fresh, constraints); !proto.Equal(got, placement.Booking) { return errWorkerFilledUp } bound = fresh @@ -491,14 +514,23 @@ func (w *ActorWorkflow) assignWorkerAttempt(ctx context.Context, actorRef resour return nil, nil, fmt.Errorf("selected worker disappeared before claim: %w", store.ErrVersionConflict) } if errors.Is(err, store.ErrNotFound) { - return nil, nil, apierror.NotFound("Actor %s not found", actorRef) + return nil, nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } // errWorkerFilledUp leaves the cache alone: it reports no room for // this actor's size, or an overhead the cache hasn't seen yet, so // forgetting the worker would hide it from every smaller actor until // the next watch event or relist. if !errors.Is(err, store.ErrVersionConflict) { - return nil, nil, actorWriteError(actorRef, err) + if errors.Is(err, store.ErrUIDConflict) { + record = false + } + return nil, nil, actorWriteError(actorRef, actor.GetMetadata().GetUid(), err) + } + // The caller's version guard was checked against actor, so never retry + // against a version written since. + if precondition.Version != 0 { + record = false + return nil, nil, apierror.Aborted("Actor %s changed during the resume, please retry", actorRef).WithCause(err) } // refresh the version of actor to avoid always failure in rest retries. fresh, gerr := w.store.GetActor(ctx, actorRef) @@ -506,6 +538,12 @@ func (w *ActorWorkflow) assignWorkerAttempt(ctx context.Context, actorRef resour slog.WarnContext(ctx, "Failed to refresh actor after assignment conflict", slog.Any("err", gerr)) return nil, nil, err } + // The template and the caller's uid guard were checked against the + // actor read under the lease, so never retry against a recreated one. + if fresh.GetMetadata().GetUid() != actor.GetMetadata().GetUid() { + record = false + return nil, nil, actorUIDConflictError(actorRef, actor.GetMetadata().GetUid(), store.ErrUIDConflict) + } switch fresh.GetStatus().GetState() { case ateapi.ActorState_ACTOR_STATE_SUSPENDED: slog.InfoContext(ctx, "Retrying assignment due to actor version conflict", slog.Any("actor", actorRef)) @@ -526,6 +564,11 @@ func (w *ActorWorkflow) assignWorkerAttempt(ctx context.Context, actorRef resour // constraints. var errNoWorkerRoom = errors.New("no worker has room for the actor") +// errActorDoesNotFit reports that the Actor would not fit any eligible worker +// even if that worker were empty. Retrying succeeds only once a larger worker +// is active. +var errActorDoesNotFit = errors.New("the actor is larger than every eligible worker") + // errWorkerFilledUp reports that the Worker the scheduler picked would not take // the Actor once the store asked under its row lock. Retryable: the next // attempt re-runs scheduling. @@ -570,15 +613,18 @@ func schedulingConstraints(actor *ateapi.Actor, tmpl *ateapi.ActorTemplate) sche if node := actor.GetStatus().GetAssignedNode(); node != "" { requiredNodes = []string{node} } - required := hardware.NewRequirement(requiredSnapshotRuntime(snap, tmpl)) + required := requiredSnapshotRuntime(snap, tmpl) c := scheduling.Constraints{ SandboxClass: snap.GetSandboxRuntime().GetSandboxClass(), - RequiredRuntime: required, - SnapshotRuntime: required, + SnapshotRuntime: hardware.NewRequirement(required), + MinFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, ActorSelector: labels.SelectorFromSet(labels.Set(actor.GetWorkerSelector().GetMatchLabels())), RequiredNodes: requiredNodes, Limits: tmpl.GetResources().GetLimits(), } + if canRelaxRuntime(actor, snap, required) { + c.MinFidelity = ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS + } if sel := tmpl.GetWorkerSelector(); sel != nil { c.TemplateSelector = labels.SelectorFromSet(labels.Set(sel.GetMatchLabels())) } @@ -612,9 +658,10 @@ func requiredSnapshotRuntime(snap *ateapi.Snapshot, tmpl *ateapi.ActorTemplate) return snap.GetSandboxRuntime() } -// canRelaxRuntime reports whether scheduling may drop its runtime requirement. -func canRelaxRuntime(actor *ateapi.Actor, constraints scheduling.Constraints) bool { - if constraints.RequiredRuntime.Runtime() == nil { +// canRelaxRuntime reports whether scheduling may accept a worker that +// restores snap without its memory state. +func canRelaxRuntime(actor *ateapi.Actor, snap *ateapi.Snapshot, required *ateapi.ActorSandboxRuntime) bool { + if required == nil { return false } status := actor.GetStatus() @@ -623,7 +670,6 @@ func canRelaxRuntime(actor *ateapi.Actor, constraints scheduling.Constraints) bo if status.GetState() == ateapi.ActorState_ACTOR_STATE_SUSPENDED && status.GetAssignedNode() != "" { return false } - snap := snapshotToResume(status) if snap.GetLocality() == "" { return true } @@ -635,17 +681,6 @@ func canRelaxRuntime(actor *ateapi.Actor, constraints scheduling.Constraints) bo return snap.GetDurableSnapshot().GetState() == ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED } -// appliesWithFallback reports whether worker satisfies constraints, or — when -// relaxable — satisfies constraints with RequiredRuntime relaxed. -func (w *ActorWorkflow) appliesWithFallback(worker *ateapi.Worker, constraints scheduling.Constraints, relaxable bool) bool { - relaxed := constraints - relaxed.RequiredRuntime = hardware.Requirement{} - if !w.scheduler.Applies(worker, relaxed) { - return false - } - return relaxable || constraints.RequiredRuntime.WorkerMatches(worker.GetStatus()) -} - // ensureVolumesAttached attaches the actor's mounted external volumes to the // assigned worker's node and returns each driver's attachment metadata by // volume name, for the Restore call that follows. Every volume must be @@ -656,7 +691,7 @@ func (w *ActorWorkflow) ensureVolumesAttached(ctx context.Context, actor *ateapi ctx, done := stepSpan(ctx, "AttachVolumes") defer func() { err = done(err) }() - if len(actor.GetStatus().GetExternalVolumes().GetVolumes()) > 0 && !preview.IsEnabled(preview.GateExternalVolumes) { + if len(actor.GetStatus().GetExternalVolumes().GetVolumes()) > 0 && !w.gates.IsEnabled(preview.GateExternalVolumes) { return nil, fmt.Errorf("external volumes are not supported unless the ExternalVolumes preview gate is enabled") } @@ -692,7 +727,7 @@ func (w *ActorWorkflow) ensureVolumesAttached(ctx context.Context, actor *ateapi // checkVolumesAttachable returns FailedPrecondition unless every volume has a // storage volume ID. -func checkVolumesAttachable(volumes []*ateapi.ExternalVolumeStatus) error { +func checkVolumesAttachable(volumes []*ateapi.ActorExternalVolumeStatus) error { for _, vol := range volumes { if vol.GetStorageVolumeId() == "" { return apierror.FailedPrecondition("volume %q has no storage volume ID to attach", vol.GetName()) @@ -703,30 +738,27 @@ func checkVolumesAttachable(volumes []*ateapi.ExternalVolumeStatus) error { // ensureAteletRestored brings the workload up on the assigned worker: // restoring snapshotToResume, or cold-booting from the template spec when the -// actor has no snapshot. This is the atelet reentrancy seam (#372): the -// request is keyed by the actor UID and -// the worker pod UID, so a re-entered workflow re-sends the same semantic -// request; once atelet's Restore/Run are idempotent on those keys this step -// becomes fully reentrant with no changes here. -func (w *ActorWorkflow) ensureAteletRestored(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, actorTemplate *ateapi.ActorTemplate, volumePublishContexts map[string]map[string]string) (tele restoreTelemetry, workerEpoch int64, err error) { +// actor has no snapshot. Each call starts a new activation, including when a +// workflow re-enters after losing the previous call's response. +func (w *ActorWorkflow) ensureAteletRestored(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, actorTemplate *ateapi.ActorTemplate, volumePublishContexts map[string]map[string]string) (tele restoreTelemetry, workerEpoch int64, activationUID string, err error) { ctx, done := stepSpan(ctx, "CallAteletRestore") defer func() { err = done(err) }() // A re-entered resume skips assignWorkerAttempt, which checks this too. if err := checkSnapshotUpload(actorRef, actor); err != nil { - return tele, 0, err + return tele, 0, "", err } assignment := actor.GetStatus().GetWorkerAssignment() ateletConn, err := w.dialer.DialForAteletOnNode(assignment.GetNodeName()) if err != nil { - return tele, 0, err + return tele, 0, "", err } client := ateletpb.NewAteletClient(ateletConn) workloadSpec, err := workloadSpecFromActorTemplate(actorTemplate, actor, volumePublishContexts) if err != nil { - return tele, 0, err + return tele, 0, "", err } egressGateway := w.egressGateway() @@ -739,6 +771,7 @@ func (w *ActorWorkflow) ensureAteletRestored(ctx context.Context, actorRef resou // The assignment is what the next checkpoint is stamped from, so it is also // what decides how this restore runs. sandboxRuntime := toAteletSandboxRuntime(assignment.GetSandboxRuntime()) + activationUID = uuid.NewString() // New actor without any existing snapshots to restore from. if snap == nil { @@ -746,6 +779,7 @@ func (w *ActorWorkflow) ensureAteletRestored(ctx context.Context, actorRef resou tele.SnapshotKind = ateattr.SnapshotKindBoot req := &ateletpb.RunRequest{ + ActivationUid: activationUID, WorkerPodUid: assignment.GetWorkerPodUid(), Atespace: actor.GetMetadata().GetAtespace(), ActorName: actor.GetMetadata().GetName(), @@ -759,9 +793,9 @@ func (w *ActorWorkflow) ensureAteletRestored(ctx context.Context, actorRef resou } resp, err := client.Run(ctx, req) if err != nil { - return tele, 0, handleAteletError(ctx, w.store, actorRef, ateattr.OperationResume, "Run", false, err) + return tele, 0, "", handleAteletError(ctx, w.store, actorRef, ateattr.OperationResume, "Run", false, err) } - return tele, resp.GetWorkerEpoch(), nil + return tele, resp.GetWorkerEpoch(), activationUID, nil } slog.InfoContext(ctx, "Actor has snapshot; Restoring from snapshot", slog.String("snapshot_uuid", snap.GetUuid())) @@ -786,6 +820,7 @@ func (w *ActorWorkflow) ensureAteletRestored(ctx context.Context, actorRef resou } tele.WireFidelity = ateattr.SnapshotFidelityValue(fidelity) req := &ateletpb.RestoreRequest{ + ActivationUid: activationUID, WorkerPodUid: assignment.GetWorkerPodUid(), Atespace: actor.GetMetadata().GetAtespace(), ActorName: actor.GetMetadata().GetName(), @@ -818,11 +853,11 @@ func (w *ActorWorkflow) ensureAteletRestored(ctx context.Context, actorRef resou slog.LogAttrs(ctx, slog.LevelError, "Setting Actor to crashed due to Atelet error", append(ateattr.ActorRefLogAttrs(actorRef), slog.Any("err", err))...) message := fmt.Sprintf("%s: %s", crashMessageLocalSnapshotNodeGone, ateletCrashMessage("Restore", err)) - return tele, 0, crashActorAndFail(ctx, w.store, actorRef, ateattr.OperationResume, message) + return tele, 0, "", crashActorAndFail(ctx, w.store, actorRef, ateattr.OperationResume, message) } - return tele, 0, handleAteletError(ctx, w.store, actorRef, ateattr.OperationResume, "Restore", false, err) + return tele, 0, "", handleAteletError(ctx, w.store, actorRef, ateattr.OperationResume, "Restore", false, err) } - return tele, resp.GetWorkerEpoch(), nil + return tele, resp.GetWorkerEpoch(), activationUID, nil } // logRuntimeFallback records a resume that restores without memory state @@ -844,7 +879,7 @@ func (w *ActorWorkflow) egressGateway() *ateletpb.EgressGateway { } // finalizeRunning re-reads the actor for a fresh version and commits RUNNING, -// stamped with workerEpoch, the epoch of the worker process that ran it. +// stamped with the worker process's epoch and the actor's activation UUID. // // The worker process registered that epoch, with its pod IPs, before it took // the workload. If it is still the Worker's registered epoch, the Actor is @@ -852,7 +887,7 @@ func (w *ActorWorkflow) egressGateway() *ateletpb.EgressGateway { // started did not carry. If a later epoch is registered, that process has exited and taken // the sandbox with it, so RUNNING is not committed: the error is Unavailable, // and the retried resume restores the Actor on the current process. -func (w *ActorWorkflow) finalizeRunning(ctx context.Context, actorRef resources.ActorRef, workerEpoch int64) (_ *ateapi.Actor, err error) { +func (w *ActorWorkflow) finalizeRunning(ctx context.Context, actorRef resources.ActorRef, workerEpoch int64, activationUID string) (_ *ateapi.Actor, err error) { ctx, done := stepSpan(ctx, "FinalizeRunning") defer func() { err = done(err) }() @@ -864,7 +899,7 @@ func (w *ActorWorkflow) finalizeRunning(ctx context.Context, actorRef resources. workerName := latestActor.GetStatus().GetWorkerAssignment().GetWorker().GetName() worker, err := w.store.GetWorker(ctx, workerName) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.Aborted("worker %s of actor %s is gone", workerName, actorRef) + return nil, apierror.Aborted("worker %s of actor %s is gone", workerName, actorRef).WithCause(err) } if err != nil { return nil, fmt.Errorf("while getting worker %s: %w", workerName, err) @@ -883,6 +918,7 @@ func (w *ActorWorkflow) finalizeRunning(ctx context.Context, actorRef resources. storedActor, err := w.store.UpdateActor(ctx, actorRef, store.PreconditionFrom(latestActor), func(toUpdate *ateapi.Actor) error { toUpdate.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING toUpdate.Status.WorkerAssignment.WorkerEpoch = workerEpoch + toUpdate.Status.WorkerAssignment.ActorActivationUid = activationUID toUpdate.Status.WorkerAssignment.WorkerPodIps = slices.Clone(worker.GetStatus().GetIps()) // The workload already runs, so a record that can't take the upload // doesn't hold the actor in RESUMING. The next suspend prunes the entry. @@ -893,10 +929,7 @@ func (w *ActorWorkflow) finalizeRunning(ctx context.Context, actorRef resources. return nil }) if err != nil { - if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") - } - return nil, err + return nil, actorWriteError(actorRef, latestActor.GetMetadata().GetUid(), err) } logActorStateChanged(ctx, storedActor, ateattr.OperationResume) return storedActor, nil diff --git a/cmd/ateapi/internal/controlapi/workflow_resume_detach.go b/cmd/ateapi/internal/controlapi/workflow_resume_detach.go index 680a4d5a03..e750b7b38f 100644 --- a/cmd/ateapi/internal/controlapi/workflow_resume_detach.go +++ b/cmd/ateapi/internal/controlapi/workflow_resume_detach.go @@ -19,12 +19,13 @@ import ( "errors" "fmt" "log/slog" + "time" "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/scheduling" "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/internal/apierror" - "go.ate.dev/substrate/internal/hardware" + "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/proto/ateletpb" "go.ate.dev/substrate/internal/resources" "google.golang.org/grpc/codes" @@ -44,22 +45,37 @@ func shouldDetachFromNode(actor *ateapi.Actor, assignErr error) bool { // Unreachable nodes can be forgotten when the latest local snapshot is durable. // A deleted node is released even when that snapshot is not durable, so resume // tries its upload. -func (w *ActorWorkflow) detachFromFullNode(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, actorTemplate *ateapi.ActorTemplate, assignErr error) (_ *ateapi.Actor, err error) { +func (w *ActorWorkflow) detachFromFullNode(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, actorTemplate *ateapi.ActorTemplate, assignErr error, precondition store.Precondition) (_ *ateapi.Actor, err error) { ctx, done := stepSpan(ctx, "DetachFromFullNode") defer func() { err = done(err) }() node := actor.GetStatus().GetAssignedNode() - // Assignment may have retried on a newer version than actor. - if actor, err = w.loadPinnedActor(ctx, actorRef, actor.GetMetadata().GetUid(), node); err != nil { + // Assignment may have retried on a newer version than actor. It does not + // under the caller's version guard, so pin actor's version then. + var version int64 + if precondition.Version != 0 { + version = actor.GetMetadata().GetVersion() + } + if actor, err = w.loadPinnedActor(ctx, actorRef, actor.GetMetadata().GetUid(), version, node); err != nil { return nil, err } constraints := schedulingConstraints(actor, actorTemplate) constraints.RequiredNodes = nil - constraints.RequiredRuntime = hardware.Requirement{} - if _, err := w.scheduler.Schedule(ctx, constraints); err != nil { - if errors.Is(err, scheduling.ErrNoCapacity) { - return nil, assignErr + constraints.MinFidelity = ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS + start := time.Now() + _, err = w.scheduler.Schedule(ctx, constraints) + switch { + case errors.Is(err, scheduling.ErrDoesNotFit): + err = apierror.FailedPrecondition("%w", errActorDoesNotFit).WithCause(err) + case errors.Is(err, scheduling.ErrNoCapacity): + err = assignErr + } + if err != nil { + outcome := ateattr.SchedulerOutcomeError + if errors.Is(err, errNoWorkerRoom) { + outcome = ateattr.SchedulerOutcomeNoCapacity } + w.instruments.recordSchedulerAssignment(ctx, time.Since(start), outcome, "", "", snapshotSandboxClass(actor), err) return nil, err } @@ -80,7 +96,7 @@ func (w *ActorWorkflow) detachFromFullNode(ctx context.Context, actorRef resourc return nil, apierror.Unavailable("while getting atelet conn for node %q: %w (and while checking the node: %w)", node, err, nodeErr) } if gone { - return w.recordGoneNode(ctx, actorRef, actor, node) + return w.recordGoneNode(ctx, actorRef, actor, version, node) } } return nil, apierror.Unavailable("while getting atelet conn for node %q: %w", node, err) @@ -114,13 +130,17 @@ func (w *ActorWorkflow) detachFromFullNode(ctx context.Context, actorRef resourc } // loadPinnedActor reads the actor, and fails with Aborted unless it is still -// the SUSPENDED incarnation uid, pinned to node. -func (w *ActorWorkflow) loadPinnedActor(ctx context.Context, actorRef resources.ActorRef, uid, node string) (*ateapi.Actor, error) { +// the SUSPENDED incarnation uid, pinned to node. A nonzero version must match +// too. +func (w *ActorWorkflow) loadPinnedActor(ctx context.Context, actorRef resources.ActorRef, uid string, version int64, node string) (*ateapi.Actor, error) { actor, err := w.store.GetActor(ctx, actorRef) if err != nil { return nil, fmt.Errorf("while reading Actor %s: %w", actorRef, err) } - if actor.GetMetadata().GetUid() != uid || + if actor.GetMetadata().GetUid() != uid { + return nil, actorUIDConflictError(actorRef, uid, store.ErrUIDConflict) + } + if (version != 0 && actor.GetMetadata().GetVersion() != version) || actor.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED || actor.GetStatus().GetAssignedNode() != node { return nil, apierror.Aborted("Actor %s changed during the resume, please retry", actorRef) @@ -149,10 +169,7 @@ func (w *ActorWorkflow) recordDetach(ctx context.Context, actorRef resources.Act return nil }) if err != nil { - if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") - } - return nil, fmt.Errorf("while recording the detach of Actor %s from node %q: %w", actorRef, node, err) + return nil, fmt.Errorf("while recording the detach of Actor %s from node %q: %w", actorRef, node, actorWriteError(actorRef, actor.GetMetadata().GetUid(), err)) } return stored, nil } @@ -161,9 +178,10 @@ func (w *ActorWorkflow) recordDetach(ctx context.Context, actorRef resources.Act // snapshot is not recorded durable. atelet may have uploaded it without // reporting, so the snapshot keeps its locality and resume restores it from // the upload on another node. It reads the actor again first, so an upload -// recorded during the node lookup detaches it instead. -func (w *ActorWorkflow) recordGoneNode(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, node string) (*ateapi.Actor, error) { - actor, err := w.loadPinnedActor(ctx, actorRef, actor.GetMetadata().GetUid(), node) +// recorded during the node lookup detaches it instead. A nonzero version pins +// the read as loadPinnedActor does. +func (w *ActorWorkflow) recordGoneNode(ctx context.Context, actorRef resources.ActorRef, actor *ateapi.Actor, version int64, node string) (*ateapi.Actor, error) { + actor, err := w.loadPinnedActor(ctx, actorRef, actor.GetMetadata().GetUid(), version, node) if err != nil { return nil, err } @@ -176,9 +194,9 @@ func (w *ActorWorkflow) recordGoneNode(ctx context.Context, actorRef resources.A }) if err != nil { if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("Actor %s changed during the resume, please retry", actorRef) + return nil, apierror.Aborted("Actor %s changed during the resume, please retry", actorRef).WithCause(err) } - return nil, fmt.Errorf("while releasing Actor %s from deleted node %q: %w", actorRef, node, err) + return nil, fmt.Errorf("while releasing Actor %s from deleted node %q: %w", actorRef, node, actorWriteError(actorRef, actor.GetMetadata().GetUid(), err)) } slog.InfoContext(ctx, "Released actor from its deleted node to restore its snapshot's upload on another node", slog.Any("actor", actorRef), diff --git a/cmd/ateapi/internal/controlapi/workflow_resume_detach_test.go b/cmd/ateapi/internal/controlapi/workflow_resume_detach_test.go index bcbdd06432..5606e996a2 100644 --- a/cmd/ateapi/internal/controlapi/workflow_resume_detach_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_resume_detach_test.go @@ -17,6 +17,7 @@ package controlapi import ( "context" "errors" + "slices" "strings" "testing" "time" @@ -27,6 +28,7 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" "go.ate.dev/substrate/cmd/ateapi/internal/workercache" "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/installdefaults" "go.ate.dev/substrate/internal/proto/ateletpb" "go.ate.dev/substrate/internal/resources" @@ -118,6 +120,9 @@ func TestDetachFromFullNode(t *testing.T) { otherRuntime *ateapi.ActorSandboxRuntime // snapRuntime stamps the MEMORY snapshot. snapRuntime *ateapi.ActorSandboxRuntime + // limits are the template's limits. The workers report no CPU or + // memory, so any limit makes the actor larger than every worker. + limits *ateapi.Resources // completed records the snapshot's upload COMPLETED. completed bool cancel bool @@ -201,6 +206,12 @@ func TestDetachFromFullNode(t *testing.T) { name: "no node has room: the assignment's error, without detaching", node: "node-1", wantCode: codes.ResourceExhausted, + }, { + name: "no worker on any node fits the actor: FailedPrecondition, without detaching", + node: "node-1", + otherNode: true, + limits: resources.CPUMemory(1000, 0), + wantCode: codes.FailedPrecondition, }, { name: "room only on another runtime: detaches", node: "node-1", @@ -432,7 +443,8 @@ func TestDetachFromFullNode(t *testing.T) { t.Fatalf("GetActor: %v", err) } - stored, err := w.detachFromFullNode(ctx, actorRef, actor, &ateapi.ActorTemplate{}, noRoom) + tmpl := &ateapi.ActorTemplate{Resources: &ateapi.ResourceRequirements{Limits: tt.limits}} + stored, err := w.detachFromFullNode(ctx, actorRef, actor, tmpl, noRoom, store.Precondition{}) if got := apierror.Code(err); got != tt.wantCode { t.Fatalf("detachFromFullNode() = %v, want code %v", err, tt.wantCode) } @@ -489,15 +501,51 @@ func TestDetachFromFullNode(t *testing.T) { } // TestResumeActor_DetachesFromFullNode resumes an actor pinned to node-1 with -// room on node-2: it moves to node-2 only when node-1 is full. +// room on node-2: it moves to node-2 only when node-1 is full. Each resume +// writes one scheduler record, unless the detach fails after its scheduler +// check. func TestResumeActor_DetachesFromFullNode(t *testing.T) { tests := []struct { - name string - node1 bool - wantNode string + name string + node1 bool + node2Full bool + // limits are the template's limits. The workers report no CPU or + // memory, so any limit makes the actor larger than every worker. + limits *ateapi.Resources + // detachErr is the error atelet returns from DetachActor. + detachErr error + wantCode codes.Code + wantNode string + wantOutcomes []string }{ - {name: "node-1 full: detaches and resumes on node-2", wantNode: "node-2"}, - {name: "node-1 has room: resumes there from the local copy", node1: true, wantNode: "node-1"}, + { + name: "node-1 full: detaches and resumes on node-2", + wantNode: "node-2", + wantOutcomes: []string{ateattr.SchedulerOutcomeAssigned}, + }, + { + name: "node-1 has room: resumes there from the local copy", + node1: true, + wantNode: "node-1", + wantOutcomes: []string{ateattr.SchedulerOutcomeAssigned}, + }, + { + name: "both nodes full: ResourceExhausted without detaching", + node2Full: true, + wantCode: codes.ResourceExhausted, + wantOutcomes: []string{ateattr.SchedulerOutcomeNoCapacity}, + }, + { + name: "no worker fits the actor: FailedPrecondition without detaching", + limits: resources.CPUMemory(1000, 0), + wantCode: codes.FailedPrecondition, + wantOutcomes: []string{ateattr.SchedulerOutcomeError + "/" + codes.FailedPrecondition.String()}, + }, + { + name: "atelet unreachable: Unavailable after the scheduler check, no record", + detachErr: apierror.Unavailable("connection refused"), + wantCode: codes.Unavailable, + }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -509,6 +557,7 @@ func TestResumeActor_DetachesFromFullNode(t *testing.T) { if _, err := st.CreateActorTemplate(ctx, &ateapi.ActorTemplate{ Metadata: &ateapi.ResourceMetadata{Atespace: "ns", Name: "tmpl1"}, SnapshotConfig: &ateapi.SnapshotConfig{StorageLocation: testStorageLocation}, + Resources: &ateapi.ResourceRequirements{Limits: tt.limits}, }); err != nil { t.Fatalf("create template: %v", err) } @@ -519,6 +568,12 @@ func TestResumeActor_DetachesFromFullNode(t *testing.T) { if !tt.node1 { fillWorker(t, st, workers["node-1"]) } + if tt.node2Full { + seedAssignment(t, st, workers["node-2"].GetMetadata().GetName(), &ateapi.ActorAssignment{ + Actor: &ateapi.ObjectRef{Atespace: "team-a", Name: "other-2"}, + ActorUid: "other-2-uid", + }) + } snap := newPausedSnapshot(t, 1, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, "", "pause-snap-1", "node-1") seedWorkflowActor(t, ctx, st, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_SUSPENDED, func(a *ateapi.Actor) { a.Status.AssignedNode = "node-1" @@ -526,12 +581,27 @@ func TestResumeActor_DetachesFromFullNode(t *testing.T) { a.Status.Snapshots = []*ateapi.Snapshot{proto.CloneOf(snap)} }) w, atelet := newDetachTestWorkflow(t, ctx, st) + instruments, reader := newAssignmentReader(t) + w.instruments = instruments addAteletOnNode(t, w, "node-2") atelet.detachState = detachedState(snap) + atelet.detachErr = tt.detachErr - got, resumed, err := w.ResumeActor(ctx, actorRef) - if err != nil { - t.Fatalf("ResumeActor: %v", err) + got, resumed, err := w.ResumeActor(ctx, actorRef, store.Precondition{}) + if code := apierror.Code(err); code != tt.wantCode { + t.Fatalf("ResumeActor() = %v, want code %v", err, tt.wantCode) + } + // The attempt on the full node-1 writes no record. + _, outcomes := assignmentObservations(t, reader) + if !slices.Equal(outcomes, tt.wantOutcomes) { + t.Errorf("recorded outcomes = %v, want %v", outcomes, tt.wantOutcomes) + } + if tt.wantCode != codes.OK { + detached := atelet.detachRequest() != nil + if wantDetach := tt.detachErr != nil; detached != wantDetach { + t.Errorf("DetachActor called = %v, want %v", detached, wantDetach) + } + return } if !resumed || got.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING { t.Fatalf("ResumeActor = (state %v, resumed %v), want RUNNING and resumed", got.GetStatus().GetState(), resumed) @@ -628,7 +698,7 @@ func TestResumeActor_NodeGoneWithPendingUpload(t *testing.T) { atelet.restoreErr = apierror.NotFound("snapshot has no usable local copy and no uploaded copy") } - got, resumed, err := w.ResumeActor(ctx, actorRef) + got, resumed, err := w.ResumeActor(ctx, actorRef, store.Precondition{}) restore, _ := atelet.requests() if restore.GetWorkerPodUid() != worker.GetWorkerPodUid() || restore.GetSnapshot().GetSnapshotUuid() != pending.GetUuid() { t.Fatalf("Restore = (worker %q, snapshot %q), want (%q, %q)", restore.GetWorkerPodUid(), restore.GetSnapshot().GetSnapshotUuid(), worker.GetWorkerPodUid(), pending.GetUuid()) @@ -672,7 +742,7 @@ func TestResumeActor_NodeGoneWithPendingUpload(t *testing.T) { // The crash leaves the actor on node-2, so revert terminates it // there. - reverted, err := w.RevertActor(ctx, actorRef) + reverted, err := w.RevertActor(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("RevertActor: %v", err) } @@ -682,7 +752,7 @@ func TestResumeActor_NodeGoneWithPendingUpload(t *testing.T) { atelet.mu.Lock() atelet.restoreErr = nil atelet.mu.Unlock() - if _, _, err := w.ResumeActor(ctx, actorRef); err != nil { + if _, _, err := w.ResumeActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatalf("second ResumeActor: %v", err) } if restore, _ := atelet.requests(); restore.GetSnapshot().GetSnapshotUuid() != durable.GetUuid() { @@ -710,6 +780,32 @@ func addAteletOnNode(t *testing.T, w *ActorWorkflow, node string) { w.dialer.ateletConns.Add(string(uid), &ateletConn{ip: "10.0.0.2", conn: cached.(*ateletConn).conn}) } +// Under the caller's version guard, an actor written since the resume read it +// aborts the detach before atelet is asked. +func TestDetachFromFullNode_VersionGuardAbortsOnNewerActor(t *testing.T) { + ctx := context.Background() + st := newTestPersistence(t) + actorRef := resources.ActorRef{Atespace: "team-a", Name: "id1"} + fillWorker(t, st, seedRuntimeWorker(t, ctx, st, "pod-node-1", "node-1", testSandboxRuntime())) + seedRuntimeWorker(t, ctx, st, "pod-2", "node-2", testSandboxRuntime()) + snap := newPausedSnapshot(t, 1, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, "", "pause-snap-1", "node-1") + actor := seedActorWithSnapshot(t, ctx, st, ateapi.ActorState_ACTOR_STATE_SUSPENDED, "node-1", snap) + w, atelet := newDetachTestWorkflow(t, ctx, st) + atelet.detachState = detachedState(snap) + noRoom := apierror.ResourceExhausted("%w", errNoWorkerRoom) + + if _, err := st.UpdateActor(ctx, actorRef, store.PreconditionFrom(actor), func(*ateapi.Actor) error { return nil }); err != nil { + t.Fatalf("UpdateActor: %v", err) + } + guard := store.Precondition{Version: actor.GetMetadata().GetVersion()} + if _, err := w.detachFromFullNode(ctx, actorRef, actor, &ateapi.ActorTemplate{}, noRoom, guard); apierror.Code(err) != codes.Aborted { + t.Fatalf("detachFromFullNode() = %v, want Aborted", err) + } + if atelet.detach != nil { + t.Errorf("DetachActor called with %v, want no call", atelet.detach) + } +} + // TestDetachFromFullNode_ReentryRecordsAfterConflict loses the record write // to a concurrent update, then runs the step again, as the next resume does: // the second attempt detaches again and records the detach. @@ -736,12 +832,12 @@ func TestDetachFromFullNode_ReentryRecordsAfterConflict(t *testing.T) { t.Errorf("UpdateActor: %v", err) } } - if _, err := w.detachFromFullNode(ctx, actorRef, actor, &ateapi.ActorTemplate{}, noRoom); apierror.Code(err) != codes.Aborted { + if _, err := w.detachFromFullNode(ctx, actorRef, actor, &ateapi.ActorTemplate{}, noRoom, store.Precondition{}); apierror.Code(err) != codes.Aborted { t.Fatalf("first detachFromFullNode() = %v, want Aborted", err) } atelet.onDetach = nil - stored, err := w.detachFromFullNode(ctx, actorRef, actor, &ateapi.ActorTemplate{}, noRoom) + stored, err := w.detachFromFullNode(ctx, actorRef, actor, &ateapi.ActorTemplate{}, noRoom, store.Precondition{}) if err != nil { t.Fatalf("second detachFromFullNode() = %v, want success", err) } diff --git a/cmd/ateapi/internal/controlapi/workflow_resume_test.go b/cmd/ateapi/internal/controlapi/workflow_resume_test.go index 47f3a18c40..a9dd486751 100644 --- a/cmd/ateapi/internal/controlapi/workflow_resume_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_resume_test.go @@ -98,9 +98,9 @@ func TestResumeActor_RunningFastPathDoesNotAcquireLease(t *testing.T) { Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_RUNNING}, }) st := &leaseCountingStore{Interface: persistence} - w := &ActorWorkflow{store: st} + w := &ActorWorkflow{gates: testGates, store: st} - got, resumed, err := w.ResumeActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}) + got, resumed, err := w.ResumeActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, store.Precondition{}) if err != nil { t.Fatalf("ResumeActor: %v", err) } @@ -163,9 +163,9 @@ func TestFinalizeRunning_CommitsRunning(t *testing.T) { ctx := context.Background() persistence := newTestPersistence(t) seedFinalizeActor(t, ctx, persistence, 1, []string{"10.0.0.1"}) - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} - got, err := w.finalizeRunning(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, 1) + got, err := w.finalizeRunning(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, 1, "") if err != nil { t.Fatalf("finalizeRunning: %v", err) } @@ -181,16 +181,20 @@ func TestFinalizeRunning_CommitsRunning(t *testing.T) { // worker process, is stamped with that process's epoch and the IPs it // registered, so the reconciler keeps it and traffic reaches it. func TestFinalizeRunning_StampsReportedEpochAndIPs(t *testing.T) { + const activationUID = "89a2bbd3-87a5-4f5a-a5f5-825c60ec41c9" ctx := context.Background() persistence := newTestPersistence(t) seedFinalizeActor(t, ctx, persistence, 2, []string{"10.0.0.2"}) - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} - got, err := w.finalizeRunning(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, 2) + got, err := w.finalizeRunning(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, 2, activationUID) if err != nil { t.Fatalf("finalizeRunning: %v", err) } assignment := got.GetStatus().GetWorkerAssignment() + if assignment.GetActorActivationUid() != activationUID { + t.Errorf("actor_activation_uid = %q, want %q", assignment.GetActorActivationUid(), activationUID) + } if assignment.GetWorkerEpoch() != 2 { t.Errorf("worker_epoch = %d, want 2", assignment.GetWorkerEpoch()) } @@ -220,13 +224,13 @@ func TestFinalizeRunning_ReplacedWorkerProcess(t *testing.T) { persistence := newTestPersistence(t) seedFinalizeActor(t, ctx, persistence, 2, []string{"10.0.0.2"}) if tc.deleteWorker { - if _, err := persistence.DeleteWorker(ctx, testWorkerUID("pod-1"), store.DeletePreconditions{}); err != nil { + if _, err := persistence.DeleteWorker(ctx, testWorkerUID("pod-1"), store.Precondition{}); err != nil { t.Fatalf("DeleteWorker: %v", err) } } - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} - _, err := w.finalizeRunning(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, tc.reported) + _, err := w.finalizeRunning(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, tc.reported, "") if got := apierror.Code(err); got != tc.want { t.Fatalf("finalizeRunning() = %v (err %v), want %v", got, err, tc.want) } @@ -256,9 +260,9 @@ func TestFinalizeRunning_UnrecordableUploadStillRuns(t *testing.T) { s.Snapshots[0].Locality = "node-3" s.Snapshots[0].Fidelity = ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_UNSPECIFIED }) - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} - got, err := w.finalizeRunning(ctx, ref, 1) + got, err := w.finalizeRunning(ctx, ref, 1, "") if err != nil { t.Fatalf("finalizeRunning: %v", err) } @@ -346,9 +350,9 @@ func TestAssignWorkerAttempt_BindNotFound(t *testing.T) { persistence := newTestPersistence(t) actor, wc := seedAssignFixture(t, ctx, persistence) st := &bindErrorStore{Interface: persistence, err: tc.bindErr} - w := &ActorWorkflow{store: st, workerCache: wc, scheduler: scheduling.New(wc)} + w := &ActorWorkflow{gates: testGates, store: st, workerCache: wc, scheduler: scheduling.New(wc)} - _, _, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}) + _, _, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if tc.wantErr != nil { if !errors.Is(err, tc.wantErr) { t.Fatalf("assignWorkerAttempt error = %v, want %v", err, tc.wantErr) @@ -372,10 +376,10 @@ func TestEnsureWorkerAssigned_ConflictExhaustionIsRetryable(t *testing.T) { persistence := newTestPersistence(t) actor, wc := seedAssignFixture(t, ctx, persistence) st := &bindErrorStore{Interface: persistence, err: store.ErrVersionConflict} - w := &ActorWorkflow{store: st, workerCache: wc, scheduler: scheduling.New(wc)} + w := &ActorWorkflow{gates: testGates, store: st, workerCache: wc, scheduler: scheduling.New(wc)} tmpl := &ateapi.ActorTemplate{} - _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl) + _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl, store.Precondition{}) if !errors.Is(err, store.ErrVersionConflict) { t.Fatalf("ensureWorkerAssigned error = %v, want ErrVersionConflict", err) } @@ -414,12 +418,12 @@ func TestAssignWorkerAttempt_SkipsWorkerAssignedInOtherAtespace(t *testing.T) { t.Fatalf("workercache.Start: %v", err) } - w := &ActorWorkflow{store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} + w := &ActorWorkflow{gates: testGates, store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} actor := &ateapi.Actor{ Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "shared", Uid: "actor-uid"}, } tmpl := &ateapi.ActorTemplate{} - _, _, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "shared"}, actor, tmpl) + _, _, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "shared"}, actor, tmpl, store.Precondition{}) if apierror.Code(err) != codes.ResourceExhausted { t.Fatalf("assignWorkerAttempt() error = %v, want ResourceExhausted (no worker has room)", err) } @@ -475,8 +479,8 @@ func TestEnsureWorkerAssigned_MissingUploadClaimsNoWorker(t *testing.T) { t.Fatalf("GetActor: %v", err) } - w := &ActorWorkflow{store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} - if _, _, err := w.ensureWorkerAssigned(ctx, actorRef, actor, &ateapi.ActorTemplate{}); apierror.Code(err) != codes.DataLoss { + w := &ActorWorkflow{gates: testGates, store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} + if _, _, err := w.ensureWorkerAssigned(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}); apierror.Code(err) != codes.DataLoss { t.Fatalf("ensureWorkerAssigned() error = %v, want DataLoss", err) } @@ -556,9 +560,9 @@ func TestAssignWorkerAttempt_RetryAfterConflictPicksFreshWorker(t *testing.T) { t.Fatalf("workercache.Start: %v", err) } - w := &ActorWorkflow{store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} + w := &ActorWorkflow{gates: testGates, store: persistence, workerCache: wc, scheduler: scheduling.New(wc)} tmpl := &ateapi.ActorTemplate{} - _, worker, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl) + _, worker, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt() on retry = %v, want nil (must re-pick a free worker)", err) } @@ -646,19 +650,45 @@ func seedAssignFixture(t *testing.T, ctx context.Context, persistence store.Inte return actor, wc } +// recreatingGetStore deletes and recreates the actor on the first GetActor. +type recreatingGetStore struct { + store.Interface + once sync.Once + recreate func() +} + +func (s *recreatingGetStore) GetActor(ctx context.Context, actorRef resources.ActorRef) (*ateapi.Actor, error) { + s.once.Do(s.recreate) + return s.Interface.GetActor(ctx, actorRef) +} + // TestAssignWorkerAttempt_ConflictRefreshesActor verifies the actor write's // conflict handling within a single attempt: a concurrent spec write leaves // ErrVersionConflict with the refreshed actor returned for the retry, while -// a concurrent transition out of a resumable state aborts the resume. +// a concurrent transition out of a resumable state, or a recreated actor, +// aborts the resume. func TestAssignWorkerAttempt_ConflictRefreshesActor(t *testing.T) { t.Parallel() tests := []struct { name string // mutate is the racing concurrent write applied to the fresh actor. mutate func(fresh *ateapi.Actor) + // recreateBeforeBind deletes and recreates the actor before the bind. + recreateBeforeBind bool + // recreateOnRefresh deletes and recreates the actor between the + // failed bind and the refresh. + recreateOnRefresh bool + // versionGuard passes the caller's version guard, checked against the + // actor before the racing write. + versionGuard bool // wantRetry means the attempt surfaces ErrVersionConflict with the // refreshed actor returned; otherwise Aborted. wantRetry bool + // wantUIDConflict means the error must report a UID mismatch for actor. + wantUIDConflict bool + // wantSchedulerObs is the expected count of scheduler assignment + // observations recorded for the attempt. + wantSchedulerObs int // wantStoredState is the persisted state after Execute. wantStoredState ateapi.ActorState }{ @@ -667,16 +697,47 @@ func TestAssignWorkerAttempt_ConflictRefreshesActor(t *testing.T) { mutate: func(fresh *ateapi.Actor) { fresh.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"team": "blue"}} }, - wantRetry: true, - wantStoredState: ateapi.ActorState_ACTOR_STATE_SUSPENDED, + wantRetry: true, + wantSchedulerObs: 0, + wantStoredState: ateapi.ActorState_ACTOR_STATE_SUSPENDED, }, { name: "another writer crash the Actor", mutate: func(fresh *ateapi.Actor) { fresh.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED }, - wantRetry: false, - wantStoredState: ateapi.ActorState_ACTOR_STATE_CRASHED, + wantRetry: false, + wantSchedulerObs: 1, + wantStoredState: ateapi.ActorState_ACTOR_STATE_CRASHED, + }, + { + name: "the actor is recreated before the bind", + recreateBeforeBind: true, + wantRetry: false, + wantUIDConflict: true, + wantSchedulerObs: 0, + wantStoredState: ateapi.ActorState_ACTOR_STATE_SUSPENDED, + }, + { + name: "the actor is recreated before the refresh", + mutate: func(fresh *ateapi.Actor) { + fresh.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"team": "blue"}} + }, + recreateOnRefresh: true, + wantRetry: false, + wantUIDConflict: true, + wantSchedulerObs: 0, + wantStoredState: ateapi.ActorState_ACTOR_STATE_SUSPENDED, + }, + { + name: "another writer refreshes the Actor under a version guard", + mutate: func(fresh *ateapi.Actor) { + fresh.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"team": "blue"}} + }, + versionGuard: true, + wantRetry: false, + wantSchedulerObs: 0, + wantStoredState: ateapi.ActorState_ACTOR_STATE_SUSPENDED, }, } for _, tc := range tests { @@ -685,9 +746,27 @@ func TestAssignWorkerAttempt_ConflictRefreshesActor(t *testing.T) { ctx := context.Background() persistence := newTestPersistence(t) actor, wc := seedAssignFixture(t, ctx, persistence) + recreateActor := func() { + if _, err := persistence.DeleteActor(ctx, resources.ActorRefFromActor(actor), store.Precondition{}); err != nil { + t.Errorf("recreate DeleteActor: %v", err) + return + } + storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "id1"}, + Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, + }) + } + base := persistence + if tc.recreateOnRefresh { + base = &recreatingGetStore{Interface: persistence, recreate: recreateActor} + } var injected *ateapi.Actor - st := &conflictInjectingStore{Interface: persistence, inject: func() { + st := &conflictInjectingStore{Interface: base, inject: func() { + if tc.recreateBeforeBind { + recreateActor() + return + } fresh, err := persistence.GetActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}) if err != nil { t.Errorf("inject GetActor: %v", err) @@ -704,9 +783,15 @@ func TestAssignWorkerAttempt_ConflictRefreshesActor(t *testing.T) { } }} - w := &ActorWorkflow{store: st, workerCache: wc, scheduler: scheduling.New(wc)} + instruments, reader := newAssignmentReader(t) + w := &ActorWorkflow{gates: testGates, store: st, workerCache: wc, scheduler: scheduling.New(wc), instruments: instruments} tmpl := &ateapi.ActorTemplate{} - refreshed, _, err := w.assignWorkerAttempt(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl) + var precondition store.Precondition + if tc.versionGuard { + precondition.Version = actor.GetMetadata().GetVersion() + } + actorRef := resources.ActorRef{Atespace: "team-a", Name: "id1"} + refreshed, _, err := w.assignWorkerAttempt(ctx, actorRef, actor, tmpl, precondition) if tc.wantRetry { if !errors.Is(err, store.ErrVersionConflict) { @@ -722,15 +807,32 @@ func TestAssignWorkerAttempt_ConflictRefreshesActor(t *testing.T) { if got := apierror.Code(err); got != codes.Aborted { t.Fatalf("apierror.Code(err) = %v, want %v (err: %v)", got, codes.Aborted, err) } + if errors.Is(err, store.ErrVersionConflict) { + t.Errorf("assignWorkerAttempt error = %v, must not match ErrVersionConflict", err) + } + if tc.wantUIDConflict { + want := fmt.Sprintf("Actor %s does not have uid %s", actorRef, actor.GetMetadata().GetUid()) + if !strings.Contains(err.Error(), want) { + t.Errorf("assignWorkerAttempt error = %q, want substring %q", err, want) + } + } + } + + if got, outcomes := assignmentObservations(t, reader); got != tc.wantSchedulerObs { + t.Errorf("observations on ate.scheduler.assignment.duration = %d %v, want %d", got, outcomes, tc.wantSchedulerObs) } - stored, err := persistence.GetActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}) + stored, err := persistence.GetActor(ctx, actorRef) if err != nil { t.Fatalf("GetActor: %v", err) } if stored.GetStatus().GetState() != tc.wantStoredState { t.Errorf("stored state = %v, want %v", stored.GetStatus().GetState(), tc.wantStoredState) } + wantRecreated := tc.recreateBeforeBind || tc.recreateOnRefresh + if got := stored.GetMetadata().GetUid() != actor.GetMetadata().GetUid(); got != wantRecreated { + t.Errorf("stored actor recreated = %v, want %v", got, wantRecreated) + } // The losing bind rolls back with the actor update. if worker := storetest.WorkerHostingActor(t, ctx, persistence, stored.GetMetadata().GetUid()); worker != "" { t.Errorf("worker %q holds the actor, want none: the losing bind leaves no claim", worker) @@ -786,7 +888,7 @@ func TestResumeActorWorkflow_RejectedAndIdempotentPaths(t *testing.T) { } }) - actor, resumed, err := w.ResumeActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}) + actor, resumed, err := w.ResumeActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, store.Precondition{}) if tc.wantErr { if got := apierror.Code(err); got != codes.FailedPrecondition { t.Fatalf("apierror.Code(err) = %v, want %v (err: %v)", got, codes.FailedPrecondition, err) @@ -828,14 +930,14 @@ func TestResumeActorWorkflow_RejectedAndIdempotentPaths(t *testing.T) { // step because the orchestrator early-returns.) func TestEnsureWorkerAssigned_RejectsNonResumableStates(t *testing.T) { ctx := context.Background() - w := &ActorWorkflow{} + w := &ActorWorkflow{gates: testGates} for _, st := range allActorStates { switch st { case ateapi.ActorState_ACTOR_STATE_SUSPENDED, ateapi.ActorState_ACTOR_STATE_RESUMING: continue } actor := &ateapi.Actor{Status: &ateapi.ActorStatus{State: st}, Metadata: &ateapi.ResourceMetadata{Name: "id1", Uid: "actor-uid-1"}} - _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Name: "id1"}, actor, &ateapi.ActorTemplate{}) + _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) assertPrerequisiteResult(t, st, err, false) } } @@ -871,7 +973,7 @@ func TestResumeActor_MetricSkipsAlreadyRunningNoop(t *testing.T) { } }) - _, _, err := w.ResumeActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}) + _, _, err := w.ResumeActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, store.Precondition{}) if tt.wantRecord && err == nil { t.Fatal("expected resume to fail, got nil error") } @@ -1018,7 +1120,7 @@ func TestValidateAssignedWorker(t *testing.T) { } } - w := &ActorWorkflow{store: persistence, scheduler: scheduling.New(nil)} + w := &ActorWorkflow{gates: testGates, store: persistence, scheduler: scheduling.New(nil)} resumingActor := &ateapi.Actor{ Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "shared", Uid: uid}, Status: &ateapi.ActorStatus{ @@ -1079,9 +1181,9 @@ func TestLoadActorForResume_RunningActorShortCircuits(t *testing.T) { // to fetch either. seedWorkflowActor(t, ctx, persistence, actorRef, "ns", "missing-tmpl", ateapi.ActorState_ACTOR_STATE_RUNNING) - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} - actor, tmpl, err := w.loadActorForResume(ctx, actorRef) + actor, tmpl, err := w.loadActorForResume(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("loadActorForResume() unexpected error = %v", err) } @@ -1272,7 +1374,7 @@ func newWireCaptureWorkflow(t *testing.T, persistence store.Interface) (*ActorWo t.Helper() fake := &capturingAtelet{} - return &ActorWorkflow{store: persistence, dialer: newNodeAteletDialer(t, fake), workflowDeadline: time.Minute}, fake + return &ActorWorkflow{gates: testGates, store: persistence, dialer: newNodeAteletDialer(t, fake), workflowDeadline: time.Minute}, fake } // newNodeAteletDialer resolves node-1's atelet to an in-process fake. The @@ -1923,10 +2025,10 @@ func TestResumeActor_AteletWireRequest(t *testing.T) { a.Status.LastAssignedGeneration = gen }) - actor, loadedTmpl, err := w.loadActorForResume(ctx, actorRef) + actor, loadedTmpl, err := w.loadActorForResume(ctx, actorRef, store.Precondition{}) var tele restoreTelemetry if err == nil { - tele, _, err = w.ensureAteletRestored(ctx, actorRef, actor, loadedTmpl, nil) + tele, _, _, err = w.ensureAteletRestored(ctx, actorRef, actor, loadedTmpl, nil) } if got := apierror.Code(err); got != tt.want.code { t.Fatalf("apierror.Code(err) = %v, want %v (err: %v)", got, tt.want.code, err) @@ -2002,7 +2104,6 @@ func (p *publishContextVolumePlugin) AttachVolume(ctx context.Context, req volum // The attach step hands the publish context to the Restore call in memory and // leaves the stored actor untouched. func TestEnsureVolumesAttached_ReturnsPublishContext(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") ctx := context.Background() persistence := newTestPersistence(t) actorRef := resources.ActorRef{Atespace: "team-a", Name: "id1"} @@ -2010,7 +2111,7 @@ func TestEnsureVolumesAttached_ReturnsPublishContext(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "id1"}, Status: &ateapi.ActorStatus{ State: ateapi.ActorState_ACTOR_STATE_RESUMING, - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ {Name: "mounted", StorageVolumeId: "storage-mounted", VolumeType: "mock"}, {Name: "unmounted", StorageVolumeId: "storage-unmounted", VolumeType: "mock"}, }}, @@ -2023,6 +2124,7 @@ func TestEnsureVolumesAttached_ReturnsPublishContext(t *testing.T) { plugin := &publishContextVolumePlugin{publishContext: map[string]string{"devicePath": "/dev/xvdba"}} w := &ActorWorkflow{ + gates: preview.NewForTest(t, "ExternalVolumes"), store: persistence, pluginRegistry: &mockPluginRegistry{plugins: map[string]volume.VolumePluginControlPlane{ "mock": plugin, @@ -2098,7 +2200,7 @@ func TestEnsureVolumesCreated(t *testing.T) { Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "id1"}, Status: &ateapi.ActorStatus{ State: tt.state, - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{{Name: "data", VolumeType: "mock"}}}, + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{Name: "data", VolumeType: "mock"}}}, }, }) actor, err := persistence.GetActor(ctx, actorRef) @@ -2108,6 +2210,7 @@ func TestEnsureVolumesCreated(t *testing.T) { plugin := &createCountingVolumePlugin{} w := &ActorWorkflow{ + gates: testGates, store: persistence, pluginRegistry: &mockPluginRegistry{plugins: map[string]volume.VolumePluginControlPlane{"mock": plugin}}, storageClassLister: &fakeStorageClassLister{storageClasses: map[string]*storagev1.StorageClass{ @@ -2150,16 +2253,16 @@ type filledUpScheduler struct { // Schedule repeats the last worker, so a test that offers no free one keeps // returning a full worker until the backoff ends. -func (s *filledUpScheduler) Schedule(context.Context, scheduling.Constraints) (*ateapi.Worker, error) { +func (s *filledUpScheduler) Schedule(_ context.Context, c scheduling.Constraints) (scheduling.Placement, error) { i := min(s.calls, len(s.workers)-1) s.calls++ if s.onSchedule != nil { s.onSchedule(s.calls) } if s.err != nil { - return nil, s.err + return scheduling.Placement{}, s.err } - return s.workers[i], nil + return placementOf(s.workers[i], c), nil } func (s *filledUpScheduler) Applies(*ateapi.Worker, scheduling.Constraints) bool { return true } @@ -2168,17 +2271,26 @@ func (s *filledUpScheduler) HasRoom(worker *ateapi.Worker, _ scheduling.Constrai return !s.full[worker.GetWorkerPod()] } +// placementOf is the Placement the real Schedule returns when it picks worker +// under c. +func placementOf(worker *ateapi.Worker, c scheduling.Constraints) scheduling.Placement { + _, fidelity := c.SnapshotRuntime.BestRuntime(worker.GetStatus()) + booking, _ := scheduling.Booking(worker, c) + return scheduling.Placement{Worker: worker, Fidelity: fidelity, Booking: booking} +} + // contentionStore is the smallest store that an assignment attempt needs. The // bug under test is in the metric path, so nothing here reaches a database. type contentionStore struct { actorWorkflowStore - workers map[string]*ateapi.Worker - actor *ateapi.Actor + workers map[string]*ateapi.Worker + actor *ateapi.Actor + boundAssignment *ateapi.ActorAssignment } // BindActorToWorker runs admit as the real store does under the Worker's row // lock, and returns its refusal unchanged. -func (s *contentionStore) BindActorToWorker(_ context.Context, workerName string, _ *ateapi.ActorAssignment, admit func(*ateapi.Worker) error, _ resources.ActorRef, _ store.Precondition, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { +func (s *contentionStore) BindActorToWorker(_ context.Context, workerName string, assignment *ateapi.ActorAssignment, admit func(*ateapi.Worker) error, _ resources.ActorRef, _ store.Precondition, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { worker, ok := s.workers[workerName] if !ok { return nil, store.ErrNotFound @@ -2193,6 +2305,7 @@ func (s *contentionStore) BindActorToWorker(_ context.Context, workerName string return nil, err } s.actor = updated + s.boundAssignment = proto.CloneOf(assignment) return updated, nil } @@ -2309,6 +2422,7 @@ func newContendedWorkflow(t *testing.T, sched *filledUpScheduler) (*ActorWorkflo t.Fatalf("workercache.Start: %v", err) } w := &ActorWorkflow{ + gates: testGates, store: &contentionStore{workers: byName, actor: actor}, workerCache: wc, scheduler: sched, @@ -2329,7 +2443,7 @@ func TestEnsureWorkerAssigned_ContentionRecordsOneObservation(t *testing.T) { } w, actor, reader := newContendedWorkflow(t, sched) - _, worker, err := w.ensureWorkerAssigned(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}) + _, worker, err := w.ensureWorkerAssigned(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if err != nil { t.Fatalf("ensureWorkerAssigned: %v", err) } @@ -2363,7 +2477,7 @@ func TestEnsureWorkerAssigned_ExhaustedBackoffRecordsOneError(t *testing.T) { } w, actor, reader := newContendedWorkflow(t, sched) - _, _, err := w.ensureWorkerAssigned(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}) + _, _, err := w.ensureWorkerAssigned(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if err == nil { t.Fatal("ensureWorkerAssigned succeeded, want a failure after the backoff ended") } @@ -2432,7 +2546,7 @@ func TestEnsureWorkerAssigned_CancelledDuringBackoffRecordsOne(t *testing.T) { } defer cancel() - _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}) + _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if !errors.Is(err, context.Canceled) { t.Fatalf("ensureWorkerAssigned error = %v, want context.Canceled", err) } @@ -2462,7 +2576,7 @@ func TestEnsureWorkerAssigned_CancelledBeforeFirstAttemptRecordsNothing(t *testi ctx, cancel := context.WithCancel(context.Background()) cancel() - _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}) + _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if !errors.Is(err, context.Canceled) { t.Fatalf("ensureWorkerAssigned error = %v, want context.Canceled", err) } @@ -2494,7 +2608,7 @@ func TestEnsureWorkerAssigned_CancelledInLastSleepRecordsOne(t *testing.T) { } defer cancel() - _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}) + _, _, err := w.ensureWorkerAssigned(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if !errors.Is(err, context.Canceled) { t.Fatalf("ensureWorkerAssigned error = %v, want context.Canceled", err) } @@ -2523,7 +2637,7 @@ func TestEnsureWorkerAssigned_ContextEndsInsideAttemptRecordsOne(t *testing.T) { } w, actor, reader := newContendedWorkflow(t, sched) - _, _, err := w.ensureWorkerAssigned(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}) + _, _, err := w.ensureWorkerAssigned(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if !errors.Is(err, context.DeadlineExceeded) { t.Fatalf("ensureWorkerAssigned error = %v, want context.DeadlineExceeded", err) } @@ -2541,6 +2655,65 @@ func TestEnsureWorkerAssigned_ContextEndsInsideAttemptRecordsOne(t *testing.T) { } } +// TestEnsureWorkerAssigned_CapacityOutcome checks the record of an attempt +// that finds no room. An actor larger than every worker records error. A pinned +// actor records nothing, because detachFromFullNode records it. +func TestEnsureWorkerAssigned_CapacityOutcome(t *testing.T) { + tests := []struct { + name string + assignedNode string + schedErr error + wantCode codes.Code + wantOutcomes []string + }{ + { + name: "full workers", + schedErr: scheduling.ErrNoCapacity, + wantCode: codes.ResourceExhausted, + wantOutcomes: []string{ateattr.SchedulerOutcomeNoCapacity}, + }, + { + name: "larger than every worker", + schedErr: scheduling.ErrDoesNotFit, + wantCode: codes.FailedPrecondition, + wantOutcomes: []string{ateattr.SchedulerOutcomeError + "/" + codes.FailedPrecondition.String()}, + }, + { + name: "pinned, full workers on the node", + assignedNode: "node-1", + schedErr: scheduling.ErrNoCapacity, + wantCode: codes.ResourceExhausted, + // No outcomes for pinned actors + }, + { + name: "pinned, larger than every worker on the node", + assignedNode: "node-1", + schedErr: scheduling.ErrDoesNotFit, + wantCode: codes.ResourceExhausted, + // No outcomes for pinned actors + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + sched := &filledUpScheduler{ + workers: []*ateapi.Worker{contendedWorker("free-pod")}, + err: tt.schedErr, + } + w, actor, reader := newContendedWorkflow(t, sched) + actor.Status.AssignedNode = tt.assignedNode + + _, _, err := w.ensureWorkerAssigned(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, &ateapi.ActorTemplate{}, store.Precondition{}) + if got := apierror.Code(err); got != tt.wantCode { + t.Errorf("ensureWorkerAssigned() = %v, want code %v", err, tt.wantCode) + } + _, outcomes := assignmentObservations(t, reader) + if diff := cmp.Diff(tt.wantOutcomes, outcomes); diff != "" { + t.Errorf("recorded outcomes (-want +got):\n%s", diff) + } + }) + } +} + // testRuntime is a gvisor ActorSandboxRuntime for arch under compatibility schema // v1. A non-empty bundleHash adds a sandbox_bundle_hash attribute, so two // runtimes can share an architecture and still differ, as two versions of @@ -2661,7 +2834,7 @@ func newSchedulingWorkflow(t *testing.T, ctx context.Context, st store.Interface if err := wc.Start(cacheCtx); err != nil { t.Fatalf("workercache.Start: %v", err) } - return &ActorWorkflow{store: st, workerCache: wc, scheduler: scheduling.New(wc)} + return &ActorWorkflow{gates: testGates, store: st, workerCache: wc, scheduler: scheduling.New(wc)} } // assertAssignedRuntime checks the runtime recorded on actor's assignment, @@ -2673,20 +2846,20 @@ func assertAssignedRuntime(t *testing.T, actor *ateapi.Actor, want *ateapi.Actor } } -// relaxingTestScheduler stands in for a fleet where no runtime-compatible -// worker has room: a strict Schedule reports no capacity and a relaxed one -// returns relaxedWorker, as the scheduler's cache would. Applies and HasRoom -// are the real ones. +// relaxingTestScheduler returns a fixed cached worker for a relaxable +// Schedule call (MinFidelity == ROOTFS), while using the real Applies and +// HasRoom under the store's row lock. type relaxingTestScheduler struct { + t *testing.T scheduling.Scheduler relaxedWorker *ateapi.Worker } -func (s *relaxingTestScheduler) Schedule(_ context.Context, c scheduling.Constraints) (*ateapi.Worker, error) { - if c.RequiredRuntime.Runtime() != nil { - return nil, scheduling.ErrNoCapacity +func (s *relaxingTestScheduler) Schedule(_ context.Context, c scheduling.Constraints) (scheduling.Placement, error) { + if c.MinFidelity != ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS { + s.t.Fatalf("Schedule called with MinFidelity %v, want ROOTFS", c.MinFidelity) } - return s.relaxedWorker, nil + return placementOf(s.relaxedWorker, c), nil } func TestAssignWorkerAttempt_PrefersRuntimeMatchingWorkerAndFallsBack(t *testing.T) { @@ -2707,7 +2880,7 @@ func TestAssignWorkerAttempt_PrefersRuntimeMatchingWorkerAndFallsBack(t *testing seedRuntimeWorker(t, ctx, st, "amd-pod", "node-amd", amd64RT) actor := seedActorWithSnapshot(t, ctx, st, suspended, "", durableMemorySnapshot(t, amd64RT)) - stored, worker, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}) + stored, worker, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt: %v", err) } @@ -2723,7 +2896,7 @@ func TestAssignWorkerAttempt_PrefersRuntimeMatchingWorkerAndFallsBack(t *testing seedRuntimeWorker(t, ctx, st, "amd-pod", "node-amd", newDefaultRT, oldRestorableRT) actor := seedActorWithSnapshot(t, ctx, st, suspended, "", durableMemorySnapshot(t, oldRestorableRT)) - stored, _, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}) + stored, _, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt: %v", err) } @@ -2738,7 +2911,7 @@ func TestAssignWorkerAttempt_PrefersRuntimeMatchingWorkerAndFallsBack(t *testing seedRuntimeWorker(t, ctx, st, "arm-pod", "node-arm", arm64RT) actor := seedActorWithSnapshot(t, ctx, st, suspended, "", durableMemorySnapshot(t, amd64RT)) - stored, worker, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}) + stored, worker, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt: %v", err) } @@ -2766,7 +2939,7 @@ func TestAssignWorkerAttempt_PrefersRuntimeMatchingWorkerAndFallsBack(t *testing snap.Fidelity = fidelity actor := seedActorWithSnapshot(t, ctx, st, suspended, "", snap) - _, _, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}) + _, _, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if apierror.Code(err) != codes.ResourceExhausted { t.Fatalf("assignWorkerAttempt with only a microvm worker = %v, want ResourceExhausted", err) } @@ -2783,7 +2956,7 @@ func TestAssignWorkerAttempt_PrefersRuntimeMatchingWorkerAndFallsBack(t *testing local.SandboxRuntime = amd64RT actor := seedActorWithSnapshot(t, ctx, st, suspended, "node-1", local) - _, _, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}) + _, _, err := newSchedulingWorkflow(t, ctx, st).assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if got := apierror.Code(err); got != codes.ResourceExhausted { t.Fatalf("apierror.Code(err) = %v, want %v (err: %v)", got, codes.ResourceExhausted, err) } @@ -2807,37 +2980,67 @@ func TestAssignWorkerAttempt_PrefersRuntimeMatchingWorkerAndFallsBack(t *testing t.Run("relaxed schedule landing on restorable worker records matched restorable runtime", func(t *testing.T) { ctx := context.Background() st := newTestPersistence(t) - // A compatible worker freed up between the strict and the relaxed - // Schedule: the relaxed pick can restore the snapshot after all. + // A Schedule with MinFidelity ROOTFS that lands on a worker which can + // restore at MEMORY still stamps the matching restorable runtime. worker := seedRuntimeWorker(t, ctx, st, "amd-pod", "node-amd", newDefaultRT, oldRestorableRT) actor := seedActorWithSnapshot(t, ctx, st, suspended, "", durableMemorySnapshot(t, oldRestorableRT)) - w := &ActorWorkflow{store: st, scheduler: &relaxingTestScheduler{Scheduler: scheduling.New(nil), relaxedWorker: worker}} - stored, _, err := w.assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}) + w := &ActorWorkflow{gates: testGates, store: st, scheduler: &relaxingTestScheduler{t: t, Scheduler: scheduling.New(nil), relaxedWorker: worker}} + stored, _, err := w.assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt: %v", err) } - // Relaxing the constraint must not relabel the assignment: it is - // derived from the snapshot's stamp, not from the relaxed constraints. + // Lowering MinFidelity must not relabel the assignment: it is derived + // from the snapshot's stamp, not from MinFidelity. assertAssignedRuntime(t, stored, oldRestorableRT) }) - t.Run("records runtime from row-locked worker when cached worker runtime is stale", func(t *testing.T) { + t.Run("refuses row-locked worker that lost the runtime it was picked for", func(t *testing.T) { ctx := context.Background() st := newTestPersistence(t) // The stored row no longer lists the old version; the cached copy the - // scheduler hands back still does. + // scheduler hands back still does, so Schedule picked it for MEMORY. fresh := seedRuntimeWorker(t, ctx, st, "amd-pod", "node-amd", newDefaultRT) stale := proto.CloneOf(fresh) stale.Status.SandboxClasses = workerSandboxClasses(newDefaultRT, oldRestorableRT) actor := seedActorWithSnapshot(t, ctx, st, suspended, "", durableMemorySnapshot(t, oldRestorableRT)) - w := &ActorWorkflow{store: st, scheduler: &relaxingTestScheduler{Scheduler: scheduling.New(nil), relaxedWorker: stale}} - stored, bound, err := w.assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}) + w := &ActorWorkflow{gates: testGates, store: st, scheduler: &relaxingTestScheduler{t: t, Scheduler: scheduling.New(nil), relaxedWorker: stale}} + if _, _, err := w.assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}); !errors.Is(err, errWorkerFilledUp) { + t.Fatalf("assignWorkerAttempt error = %v, want errWorkerFilledUp", err) + } + after, err := st.GetActor(ctx, actorRef) + if err != nil { + t.Fatalf("GetActor: %v", err) + } + if got := after.GetStatus().GetState(); got != suspended { + t.Errorf("state = %v, want SUSPENDED", got) + } + if got := after.GetStatus().GetWorkerAssignment(); got != nil { + t.Errorf("WorkerAssignment = %v, want none", got) + } + if worker := storetest.WorkerHostingActor(t, ctx, st, actor.GetMetadata().GetUid()); worker != "" { + t.Errorf("worker %q holds the actor, want none", worker) + } + }) + + t.Run("records runtime from row-locked worker when cached worker runtime is stale", func(t *testing.T) { + ctx := context.Background() + st := newTestPersistence(t) + // The stored row gained the old version since the cache saw it: Schedule + // picked it at ROOTFS, and admit accepts the fresh row and records the + // restorable runtime it now carries. + fresh := seedRuntimeWorker(t, ctx, st, "amd-pod", "node-amd", newDefaultRT, oldRestorableRT) + stale := proto.CloneOf(fresh) + stale.Status.SandboxClasses = workerSandboxClasses(newDefaultRT) + actor := seedActorWithSnapshot(t, ctx, st, suspended, "", durableMemorySnapshot(t, oldRestorableRT)) + + w := &ActorWorkflow{gates: testGates, store: st, scheduler: &relaxingTestScheduler{t: t, Scheduler: scheduling.New(nil), relaxedWorker: stale}} + stored, bound, err := w.assignWorkerAttempt(ctx, actorRef, actor, &ateapi.ActorTemplate{}, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt: %v", err) } - assertAssignedRuntime(t, stored, newDefaultRT) + assertAssignedRuntime(t, stored, oldRestorableRT) if diff := cmp.Diff(fresh.GetStatus().GetSandboxClasses(), bound.GetStatus().GetSandboxClasses(), protocmp.Transform()); diff != "" { t.Errorf("returned worker SandboxClasses mismatch, want the fresh row's (-fresh +got):\n%s", diff) } @@ -2876,7 +3079,7 @@ func TestValidateAssignedWorker_RuntimeFallback(t *testing.T) { }, } - w := &ActorWorkflow{store: st, scheduler: scheduling.New(nil)} + w := &ActorWorkflow{gates: testGates, store: st, scheduler: scheduling.New(nil)} worker, err := w.validateAssignedWorker(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, resumingActor, &ateapi.ActorTemplate{}) if err != nil { t.Fatalf("validateAssignedWorker: %v", err) @@ -2919,7 +3122,7 @@ func TestValidateAssignedWorker_RuntimeFallback(t *testing.T) { }, } - w := &ActorWorkflow{store: st, scheduler: scheduling.New(nil)} + w := &ActorWorkflow{gates: testGates, store: st, scheduler: scheduling.New(nil)} worker, err := w.validateAssignedWorker(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, resumingActor, &ateapi.ActorTemplate{}) if err != nil { t.Fatalf("validateAssignedWorker: %v", err) @@ -3073,8 +3276,8 @@ func TestRequiredSnapshotRuntime(t *testing.T) { } // mockVolume returns a volume served by the "mock" plugin. -func mockVolume(name, storageID string) *ateapi.ExternalVolumeStatus { - return &ateapi.ExternalVolumeStatus{Name: name, StorageVolumeId: storageID, VolumeType: "mock"} +func mockVolume(name, storageID string) *ateapi.ActorExternalVolumeStatus { + return &ateapi.ActorExternalVolumeStatus{Name: name, StorageVolumeId: storageID, VolumeType: "mock"} } // volumeTemplate returns a template that declares the volumes named in @@ -3095,7 +3298,7 @@ func volumeTemplate(declared []string, mounted ...string) *ateapi.ActorTemplate // seedVolumeAssignFixture stores one free gvisor worker on node and a // SUSPENDED actor holding volumes, and returns the stored actor plus a // started worker cache. -func seedVolumeAssignFixture(t *testing.T, ctx context.Context, persistence store.Interface, node string, volumes ...*ateapi.ExternalVolumeStatus) (*ateapi.Actor, *workercache.Cache) { +func seedVolumeAssignFixture(t *testing.T, ctx context.Context, persistence store.Interface, node string, volumes ...*ateapi.ActorExternalVolumeStatus) (*ateapi.Actor, *workercache.Cache) { t.Helper() if _, err := persistence.CreateWorker(ctx, &ateapi.Worker{ Metadata: &ateapi.ResourceMetadata{Name: testWorkerUID("pod-1")}, @@ -3133,6 +3336,7 @@ func seedVolumeAssignFixture(t *testing.T, ctx context.Context, persistence stor // serves "mock" volumes with plugin. func newVolumeAssignWorkflow(st store.Interface, wc *workercache.Cache, plugin volume.VolumePluginControlPlane) *ActorWorkflow { return &ActorWorkflow{ + gates: testGates, store: st, workerCache: wc, scheduler: scheduling.New(wc), @@ -3147,11 +3351,11 @@ func newVolumeAssignWorkflow(st store.Interface, wc *workercache.Cache, plugin v // FailedPrecondition before any publish call, even when a valid volume // precedes it. func TestResume_ChecksMountedVolumesBeforeAttach(t *testing.T) { - preview.InitForTest(t, "ExternalVolumes") + gates := preview.NewForTest(t, "ExternalVolumes") tests := []struct { name string // last is the second mounted volume, placed after every other volume. - last *ateapi.ExternalVolumeStatus + last *ateapi.ActorExternalVolumeStatus // wantErr is a substring of the expected FailedPrecondition; empty // means the attach succeeds. wantErr string @@ -3176,10 +3380,11 @@ func TestResume_ChecksMountedVolumesBeforeAttach(t *testing.T) { ) plugin := &publishContextVolumePlugin{} w := newVolumeAssignWorkflow(persistence, wc, plugin) + w.gates = gates // u is declared but not mounted; o is not declared at all. tmpl := volumeTemplate([]string{"a", "u", "b"}, "a", "b") - assigned, worker, err := w.assignWorkerAttempt(ctx, actorRef, actor, tmpl) + assigned, worker, err := w.assignWorkerAttempt(ctx, actorRef, actor, tmpl, store.Precondition{}) if err != nil { t.Fatalf("assignWorkerAttempt: %v", err) } @@ -3363,7 +3568,7 @@ func TestCanRelaxRuntime(t *testing.T) { AssignedNode: tc.node, Snapshots: tc.snapshots, }} - if got := canRelaxRuntime(actor, scheduling.Constraints{RequiredRuntime: hardware.NewRequirement(tc.required)}); got != tc.want { + if got := canRelaxRuntime(actor, snapshotToResume(actor.GetStatus()), tc.required); got != tc.want { t.Errorf("canRelaxRuntime = %v, want %v", got, tc.want) } }) @@ -3448,7 +3653,7 @@ func TestAssignWorkerAttempt_WorkerWithoutNodeRejectsVolumes(t *testing.T) { w := newVolumeAssignWorkflow(persistence, wc, plugin) tmpl := volumeTemplate([]string{"vol"}, tt.mounted...) - _, _, err := w.assignWorkerAttempt(ctx, actorRef, actor, tmpl) + _, _, err := w.assignWorkerAttempt(ctx, actorRef, actor, tmpl, store.Precondition{}) stored, gerr := persistence.GetActor(ctx, actorRef) if gerr != nil { t.Fatalf("GetActor: %v", gerr) @@ -3486,13 +3691,17 @@ func TestAssignWorkerAttempt_RefusesChangedOverhead(t *testing.T) { w.store.(*contentionStore).workers[locked.GetMetadata().GetName()] = locked tmpl := &ateapi.ActorTemplate{Resources: &ateapi.ResourceRequirements{Limits: &ateapi.Resources{MemoryBytes: 256 << 20}}} - _, _, err := w.assignWorkerAttempt(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl) + _, _, err := w.assignWorkerAttempt(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl, store.Precondition{}) if !errors.Is(err, errWorkerFilledUp) { t.Fatalf("assignWorkerAttempt() = %v, want %v", err, errWorkerFilledUp) } w.store.(*contentionStore).workers[locked.GetMetadata().GetName()] = cached - if _, _, err := w.assignWorkerAttempt(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl); err != nil { + if _, _, err := w.assignWorkerAttempt(context.Background(), resources.ActorRef{Atespace: "team-a", Name: "id1"}, actor, tmpl, store.Precondition{}); err != nil { t.Fatalf("assignWorkerAttempt() with an unchanged overhead = %v", err) } + wantBooking := &ateapi.Resources{MemoryBytes: 256<<20 + 4<<20} + if got := w.store.(*contentionStore).boundAssignment.GetResources(); !proto.Equal(got, wantBooking) { + t.Errorf("assignment.Resources = %v, want %v", got, wantBooking) + } } diff --git a/cmd/ateapi/internal/controlapi/workflow_revert.go b/cmd/ateapi/internal/controlapi/workflow_revert.go index 4c228b3136..082f09d437 100644 --- a/cmd/ateapi/internal/controlapi/workflow_revert.go +++ b/cmd/ateapi/internal/controlapi/workflow_revert.go @@ -57,7 +57,8 @@ func isRevertable(actor *ateapi.Actor) bool { // Idempotent: each step keys on a persisted field rather than on the state the // actor was reverted from, so a re-entered workflow fast-forwards to wherever // the previous attempt stopped. -func (w *ActorWorkflow) RevertActor(ctx context.Context, actorRef resources.ActorRef) (_ *ateapi.Actor, err error) { +// Fails with ABORTED if the actor does not match precondition. +func (w *ActorWorkflow) RevertActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (_ *ateapi.Actor, err error) { ctx = preview.ContextWithOptIn(ctx) start := time.Now() var actor *ateapi.Actor @@ -80,7 +81,7 @@ func (w *ActorWorkflow) RevertActor(ctx context.Context, actorRef resources.Acto } defer lease.Close() - actor, actorTemplate, err = w.loadActorForRevert(leaseCtx, actorRef) + actor, actorTemplate, err = w.loadActorForRevert(leaseCtx, actorRef, precondition) if err != nil { return nil, err } @@ -112,18 +113,22 @@ func (w *ActorWorkflow) RevertActor(ctx context.Context, actorRef resources.Acto return finalized, nil } -// loadActorForRevert fetches the current actor record and its template. -func (w *ActorWorkflow) loadActorForRevert(ctx context.Context, actorRef resources.ActorRef) (_ *ateapi.Actor, _ *ateapi.ActorTemplate, err error) { +// loadActorForRevert fetches the current actor record, checks it against +// precondition, and fetches its template. +func (w *ActorWorkflow) loadActorForRevert(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (_ *ateapi.Actor, _ *ateapi.ActorTemplate, err error) { ctx, done := stepSpan(ctx, "LoadActorForRevert") defer func() { err = done(err) }() actor, err := w.store.GetActor(ctx, actorRef) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, nil, apierror.NotFound("Actor %s not found", actorRef) + return nil, nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } return nil, nil, fmt.Errorf("while fetching actor: %w", err) } + if err := checkActorPreconditions(actorRef, precondition, actor); err != nil { + return nil, nil, err + } actorTemplate, err := resolveActorTemplate(ctx, w.store, actor) if errors.Is(err, errActorTemplateNotFound) { @@ -160,10 +165,7 @@ func (w *ActorWorkflow) ensureMarkedReverting(ctx context.Context, actorRef reso return nil }) if err != nil { - if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") - } - return nil, fmt.Errorf("while setting actor state to REVERTING: %w", err) + return nil, fmt.Errorf("while setting actor state to REVERTING: %w", actorWriteError(actorRef, actor.GetMetadata().GetUid(), err)) } logActorStateChanged(ctx, storedActor, ateattr.OperationRevert) return storedActor, nil @@ -276,7 +278,7 @@ func (w *ActorWorkflow) ensureRevertedFinalized(ctx context.Context, actorRef re return nil }) if err != nil { - return nil, actorWriteError(actorRef, err) + return nil, actorWriteError(actorRef, latestActor.GetMetadata().GetUid(), err) } logActorStateChanged(ctx, storedActor, ateattr.OperationRevert) w.releaseDroppedSnapshots(ctx, latestActor, storedActor) diff --git a/cmd/ateapi/internal/controlapi/workflow_revert_test.go b/cmd/ateapi/internal/controlapi/workflow_revert_test.go index 177af4610d..5dfabe08fd 100644 --- a/cmd/ateapi/internal/controlapi/workflow_revert_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_revert_test.go @@ -96,6 +96,31 @@ func TestEnsureMarkedReverting_AcceptsPaused(t *testing.T) { } } +// An actor recreated after the workflow read it fails the write with ABORTED, +// the code the RPC returns, so the lifecycle metric records the same code. +func TestEnsureMarkedReverting_RecreatedActorAborts(t *testing.T) { + ctx := context.Background() + st, cleanup := storetest.SetupTestStore(t) + defer cleanup() + w := newTestActorWorkflow(t, st, "ns", "tmpl1") + + actorRef := resources.ActorRef{Atespace: "team-a", Name: "id1"} + seedWorkflowActor(t, ctx, st, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_CRASHED) + stale, err := st.GetActor(ctx, actorRef) + if err != nil { + t.Fatalf("get seeded actor: %v", err) + } + if _, err := st.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + seedWorkflowActor(t, ctx, st, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_CRASHED) + + _, err = w.ensureMarkedReverting(ctx, actorRef, stale) + if got := apierror.Code(err); got != codes.Aborted { + t.Errorf("ensureMarkedReverting code = %v, want %v; error = %v", got, codes.Aborted, err) + } +} + // TestRevertActor_ReturnsActorToItsSnapshot covers the whole workflow from each // accepted origin: the actor lands SUSPENDED holding the same external snapshot // it started with, and every pointer to the discarded execution is gone. @@ -155,7 +180,7 @@ func TestRevertActor_ReturnsActorToItsSnapshot(t *testing.T) { } }) - reverted, err := w.RevertActor(ctx, actorRef) + reverted, err := w.RevertActor(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("RevertActor: %v", err) } @@ -205,7 +230,7 @@ func TestRevertActor_ReturnsActorToItsSnapshot(t *testing.T) { }) seedWireWorker(t, ctx, st, assignmentOf(running)) wire, atelet := newWireCaptureWorkflow(t, st) - suspended, err := wire.SuspendActor(ctx, actorRef, suspendSync) + suspended, err := wire.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync) if err != nil { t.Fatalf("SuspendActor after revert: %v", err) } @@ -294,7 +319,7 @@ func TestRevertActor_UnreachableNode(t *testing.T) { } } } - reverted, err := w.RevertActor(ctx, ref) + reverted, err := w.RevertActor(ctx, ref, store.Precondition{}) if got := apierror.Code(err); got != tt.wantCode { t.Fatalf("RevertActor = %v, want %v", err, tt.wantCode) } @@ -316,7 +341,7 @@ func TestRevertActor_UnreachableNode(t *testing.T) { atelet.mu.Lock() atelet.onTerminate = nil atelet.mu.Unlock() - reverted, err = w.RevertActor(ctx, ref) + reverted, err = w.RevertActor(ctx, ref, store.Precondition{}) if err != nil { t.Fatalf("retry after conflict: %v", err) } @@ -373,7 +398,7 @@ func TestRevertActor_PausedSnapshotAlreadyUploaded(t *testing.T) { } }) - reverted, err := w.RevertActor(ctx, actorRef) + reverted, err := w.RevertActor(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("RevertActor: %v", err) } @@ -403,7 +428,7 @@ func TestRevertActor_RejectsSuspended(t *testing.T) { actorRef := resources.ActorRef{Atespace: "team-a", Name: "id1"} seedWorkflowActor(t, ctx, st, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_SUSPENDED) - if _, err := w.RevertActor(ctx, actorRef); apierror.Code(err) != codes.FailedPrecondition { + if _, err := w.RevertActor(ctx, actorRef, store.Precondition{}); apierror.Code(err) != codes.FailedPrecondition { t.Fatalf("RevertActor = %v, want FailedPrecondition", err) } }) @@ -417,10 +442,10 @@ func TestRevertActor_RejectsSuspended(t *testing.T) { actorRef := resources.ActorRef{Atespace: "team-a", Name: "id1"} seedWorkflowActor(t, ctx, st, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_CRASHED) - if _, err := w.RevertActor(ctx, actorRef); err != nil { + if _, err := w.RevertActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatalf("first RevertActor: %v", err) } - if _, err := w.RevertActor(ctx, actorRef); apierror.Code(err) != codes.FailedPrecondition { + if _, err := w.RevertActor(ctx, actorRef, store.Precondition{}); apierror.Code(err) != codes.FailedPrecondition { t.Fatalf("second RevertActor = %v, want FailedPrecondition", err) } }) @@ -438,7 +463,7 @@ func TestRevertActor_MissingTemplate(t *testing.T) { actorRef := resources.ActorRef{Atespace: "team-a", Name: "id1"} seedWorkflowActor(t, ctx, st, actorRef, "ns", "missing-tmpl", ateapi.ActorState_ACTOR_STATE_CRASHED) - reverted, err := w.RevertActor(ctx, actorRef) + reverted, err := w.RevertActor(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("RevertActor: %v", err) } @@ -462,7 +487,7 @@ func TestRevertActor_NoSnapshotToRevertTo(t *testing.T) { a.Status.Crash = newActorCrash("resume", crashMessageWorkerDraining) }) - reverted, err := w.RevertActor(ctx, actorRef) + reverted, err := w.RevertActor(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("RevertActor: %v", err) } @@ -637,7 +662,7 @@ func TestEnsureInProgressSnapshotDiscarded(t *testing.T) { func TestEnsureRevertedFinalized_NoObjectStore(t *testing.T) { ctx := context.Background() persistence := newTestPersistence(t) - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} actor := storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "actor-1"}, @@ -678,7 +703,7 @@ func TestEnsureRevertedFinalized_NoObjectStore(t *testing.T) { func TestRevertActor_LostLeaseKeepsNewAssignment(t *testing.T) { ctx := context.Background() persistence := newTestPersistence(t) - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} stale := storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "actor-1"}, diff --git a/cmd/ateapi/internal/controlapi/workflow_suspend.go b/cmd/ateapi/internal/controlapi/workflow_suspend.go index 051454d324..72990fce12 100644 --- a/cmd/ateapi/internal/controlapi/workflow_suspend.go +++ b/cmd/ateapi/internal/controlapi/workflow_suspend.go @@ -16,7 +16,6 @@ package controlapi import ( "context" - "errors" "fmt" "log/slog" "time" @@ -74,7 +73,8 @@ func (m suspendMode) uploadMode() ateletpb.UploadMode { // is returned as it is, whatever the mode. Idempotent: a re-entered workflow // fast-forwards past the steps a previous attempt completed, deriving // progress from the persisted actor alone. -func (w *ActorWorkflow) SuspendActor(ctx context.Context, actorRef resources.ActorRef, mode suspendMode) (_ *ateapi.Actor, err error) { +// Fails with ABORTED if the actor does not match precondition. +func (w *ActorWorkflow) SuspendActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mode suspendMode) (_ *ateapi.Actor, err error) { ctx = preview.ContextWithOptIn(ctx) start := time.Now() var actor *ateapi.Actor @@ -101,7 +101,9 @@ func (w *ActorWorkflow) SuspendActor(ctx context.Context, actorRef resources.Act } defer lease.Close() - actor, actorTemplate, err = w.loadActorForSuspend(leaseCtx, actorRef) + // The load checks precondition before the SUSPENDED shortcut, which would + // otherwise report success for a different actor under the same name. + actor, actorTemplate, err = w.loadActorForSuspend(leaseCtx, actorRef, precondition) if err != nil { return nil, err } @@ -137,8 +139,9 @@ func (w *ActorWorkflow) SuspendActor(ctx context.Context, actorRef resources.Act return actor, nil } -// loadActorForSuspend fetches the current actor record and its template. -func (w *ActorWorkflow) loadActorForSuspend(ctx context.Context, actorRef resources.ActorRef) (_ *ateapi.Actor, _ *ateapi.ActorTemplate, err error) { +// loadActorForSuspend fetches the current actor record, checks it against +// precondition, and fetches its template. +func (w *ActorWorkflow) loadActorForSuspend(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (_ *ateapi.Actor, _ *ateapi.ActorTemplate, err error) { ctx, done := stepSpan(ctx, "LoadActorForSuspend") defer func() { err = done(err) }() @@ -146,6 +149,9 @@ func (w *ActorWorkflow) loadActorForSuspend(ctx context.Context, actorRef resour if err != nil { return nil, nil, err } + if err := checkActorPreconditions(actorRef, precondition, actor); err != nil { + return nil, nil, err + } actorTemplate, err := resolveActorTemplate(ctx, w.store, actor) if err != nil { return nil, nil, err @@ -201,10 +207,7 @@ func (w *ActorWorkflow) ensureMarkedSuspending(ctx context.Context, actorRef res return nil }) if err != nil { - if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") - } - return nil, err + return nil, actorWriteError(actorRef, actor.GetMetadata().GetUid(), err) } logActorStateChanged(ctx, storedActor, ateattr.OperationSuspend) return storedActor, nil @@ -401,7 +404,7 @@ func (w *ActorWorkflow) ensureSuspendedFinalized(ctx context.Context, actorRef r }) dUpdateActor = time.Since(t) if err != nil { - return nil, actorWriteError(actorRef, err) + return nil, actorWriteError(actorRef, latestActor.GetMetadata().GetUid(), err) } if w.workerCache != nil && released != nil { w.workerCache.Observe(released) diff --git a/cmd/ateapi/internal/controlapi/workflow_suspend_async_test.go b/cmd/ateapi/internal/controlapi/workflow_suspend_async_test.go index 08cee848c0..52a4a3b7d6 100644 --- a/cmd/ateapi/internal/controlapi/workflow_suspend_async_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_suspend_async_test.go @@ -20,6 +20,7 @@ import ( "github.com/google/go-cmp/cmp" "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" "go.ate.dev/substrate/cmd/ateapi/internal/workercache" "go.ate.dev/substrate/internal/apierror" @@ -55,7 +56,7 @@ func TestSuspendActorAsync_Finalized_NodeUnknown(t *testing.T) { }, }) - if _, err := w.SuspendActor(ctx, actorRef, suspendAsync); apierror.Code(err) != codes.FailedPrecondition { + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendAsync); apierror.Code(err) != codes.FailedPrecondition { t.Fatalf("Async SuspendActor error = %v, want FailedPrecondition for the actor it crashed", err) } if checkpoints, _ := atelet.calls(); checkpoints != 1 { @@ -114,7 +115,7 @@ func TestSuspendActorAsync_Finalized_KeepsCrashFromWorkerDelete(t *testing.T) { seedWireWorker(t, ctx, st, assignmentOf(created)) w, _ := newWireCaptureWorkflow(t, workerDeletedDuringReleaseStore{Interface: st}) - _, err := w.SuspendActor(ctx, actorRef, suspendAsync) + _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendAsync) assertConcurrentCrashKept(t, ctx, st, actorRef, err, "suspend failed: "+crashMessageWorkerPodGone) } @@ -168,7 +169,7 @@ func TestSuspendActorAsync_Finalized_RecordsFidelity(t *testing.T) { }) seedWireWorker(t, ctx, st, assignmentOf(created)) - got, err := w.SuspendActor(ctx, actorRef, suspendAsync) + got, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendAsync) if err != nil { t.Fatalf("SuspendActor: %v", err) } @@ -270,7 +271,7 @@ func TestSuspendActorAsync_Finalized_MissingSnapshotClearsAssignment(t *testing. seedWireWorker(t, ctx, st, assignmentOf(created)) updateDuringCheckpoint(t, atelet, st, actorRef, tt.clobber) - if _, err := w.SuspendActor(ctx, actorRef, suspendAsync); apierror.Code(err) != codes.FailedPrecondition { + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendAsync); apierror.Code(err) != codes.FailedPrecondition { t.Fatalf("Async SuspendActor error = %v, want FailedPrecondition for the actor it crashed", err) } got := mustReadActor(t, ctx, st, actorRef) @@ -338,7 +339,7 @@ func TestSuspendActorAsync_AteletPaused_DialFailureLeavesActorRetryable(t *testi storetest.MustCreateActor(t, ctx, persistence, actor) w := newMarkOnlyWorkflow(persistence) - _, err := w.SuspendActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "actor-1"}, suspendAsync) + _, err := w.SuspendActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "actor-1"}, store.Precondition{}, suspendAsync) assertStoppedAtDial(t, err) stored := mustReadActor(t, ctx, persistence, resources.ActorRef{Atespace: "team-a", Name: "actor-1"}) @@ -393,7 +394,7 @@ func TestSuspendActorAsync_AteletPaused_ForwardsPreferredFidelity(t *testing.T) }, }) - if _, err := w.SuspendActor(ctx, actorRef, suspendAsync); err != nil { + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendAsync); err != nil { t.Fatalf("SuspendActor: %v", err) } req := atelet.checkpointRequest() diff --git a/cmd/ateapi/internal/controlapi/workflow_suspend_test.go b/cmd/ateapi/internal/controlapi/workflow_suspend_test.go index 530d517007..db9cf40614 100644 --- a/cmd/ateapi/internal/controlapi/workflow_suspend_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_suspend_test.go @@ -37,6 +37,47 @@ import ( "k8s.io/client-go/tools/cache" ) +// TestSuspendActor_LifecycleOpNamesWorkerPool checks a successful suspend labels +// its lifecycle-op datapoint with the pool, which finalize clears from the actor. +func TestSuspendActor_LifecycleOpNamesWorkerPool(t *testing.T) { + for _, mode := range suspendModes { + t.Run(mode.name, func(t *testing.T) { + ctx := context.Background() + persistence := newTestPersistence(t) + seedSuspendTemplate(t, ctx, persistence, &ateapi.SnapshotConfig{PreferredFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY}) + w, _ := newWireCaptureWorkflow(t, persistence) + inst, reader := newTestInstruments(t) + w.instruments = inst + actorRef := resources.ActorRef{Atespace: "team-a", Name: "actor-1"} + actor := storetest.MustCreateActor(t, ctx, persistence, &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: actorRef.Atespace, Name: actorRef.Name}, + ActorTemplate: suspendTestTemplateRef(), + Status: &ateapi.ActorStatus{ + State: ateapi.ActorState_ACTOR_STATE_RUNNING, + AssignedNode: wireTestAssignment().GetNodeName(), + WorkerAssignment: wireTestAssignment(), + }, + }) + seedWireWorker(t, ctx, persistence, assignmentOf(actor)) + + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, mode.suspendMode); err != nil { + t.Fatalf("SuspendActor: %v", err) + } + + dp := singleHistogramDP(t, reader, lifecycleOpDurationMetric) + if got, ok := attrString(dp, ateattr.WorkerPoolNamespaceKey); !ok || got != wireTestAssignment().GetWorkerNamespace() { + t.Errorf("%s = %q (present %t), want %q", ateattr.WorkerPoolNamespaceKey, got, ok, wireTestAssignment().GetWorkerNamespace()) + } + if got, ok := attrString(dp, ateattr.WorkerPoolNameKey); !ok || got != wireTestAssignment().GetWorkerPool() { + t.Errorf("%s = %q (present %t), want %q", ateattr.WorkerPoolNameKey, got, ok, wireTestAssignment().GetWorkerPool()) + } + if got, ok := attrString(dp, ateattr.ErrorTypeKey); ok { + t.Errorf("%s = %q on a successful suspend, want none", ateattr.ErrorTypeKey, got) + } + }) + } +} + // TestSuspendActor_CheckpointError exercises checkpoint error policy through // the suspend workflow, including retrying the persisted snapshot. func TestSuspendActor_CheckpointError(t *testing.T) { @@ -77,7 +118,7 @@ func TestSuspendActor_CheckpointError(t *testing.T) { } return tt.err } - _, err := w.SuspendActor(callCtx, actorRef, mode.suspendMode) + _, err := w.SuspendActor(callCtx, actorRef, store.Precondition{}, mode.suspendMode) if got := apierror.Code(err); got != tt.wantCode { t.Fatalf("SuspendActor error = %v (code %v), want %v", err, got, tt.wantCode) } @@ -119,7 +160,7 @@ func TestSuspendActor_CheckpointError(t *testing.T) { atelet.mu.Lock() atelet.onCheckpoint = nil atelet.mu.Unlock() - finished, err := w.SuspendActor(ctx, actorRef, mode.suspendMode) + finished, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, mode.suspendMode) if err != nil { t.Fatalf("SuspendActor retry: %v", err) } @@ -172,7 +213,7 @@ func TestSuspendActor_MarkedSuspending_SnapshotURI(t *testing.T) { }, }) w := newMarkOnlyWorkflow(persistence) - _, err := w.SuspendActor(ctx, actorRef, suspendSync) + _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync) assertStoppedAtDial(t, err) marked := mustReadActor(t, ctx, persistence, actorRef) @@ -234,7 +275,7 @@ func TestSuspendActor_MarkedSuspending_ReentryKeepsPersistedSnapshotLocation(t * }, }, }) - suspended, err := w.SuspendActor(ctx, actorRef, tt.mode) + suspended, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, tt.mode) if err != nil { t.Fatalf("SuspendActor: %v", err) } @@ -299,7 +340,7 @@ func TestSuspendActorWorkflow_SuspendedReturnsAsIs(t *testing.T) { seedWorkflowActor(t, ctx, st, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_SUSPENDED, tc.seedOpts...) seeded := mustReadActor(t, ctx, st, actorRef) - returned, err := w.SuspendActor(ctx, actorRef, mode.suspendMode) + returned, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, mode.suspendMode) if err != nil { t.Fatalf("SuspendActor: %v", err) } @@ -334,7 +375,7 @@ func TestSuspendActor_MarkedSuspending_StateMatrix(t *testing.T) { a.Status.WorkerAssignment = wireTestAssignment() }) - _, err := w.SuspendActor(ctx, actorRef, mode.suspendMode) + _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, mode.suspendMode) stored := mustReadActor(t, ctx, persistence, actorRef) switch seedState { case ateapi.ActorState_ACTOR_STATE_RUNNING, ateapi.ActorState_ACTOR_STATE_SUSPENDING: @@ -430,7 +471,7 @@ func TestSuspendActor_AteletSuspended_DialFailureLeavesActorRetryable(t *testing storetest.MustCreateActor(t, ctx, persistence, actor) w := newMarkOnlyWorkflow(persistence) - _, err := w.SuspendActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "actor-1"}, suspendSync) + _, err := w.SuspendActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "actor-1"}, store.Precondition{}, suspendSync) assertStoppedAtDial(t, err) // A dial failure is transient from this workflow's point of view: it @@ -482,7 +523,7 @@ func TestSuspendActor_AteletSuspended_WireRequest(t *testing.T) { }, }) - if _, err := w.SuspendActor(ctx, actorRef, suspendSync); err != nil { + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync); err != nil { t.Fatalf("SuspendActor: %v", err) } req := atelet.checkpointRequest() @@ -570,7 +611,7 @@ func TestSuspendActor_Finalized_ReleasesReplacedSnapshot(t *testing.T) { } }) - stored, err := w.SuspendActor(ctx, actorRef, suspendSync) + stored, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync) if err != nil { t.Fatalf("SuspendActor: %v", err) } @@ -655,7 +696,7 @@ func TestSuspendActor_Finalized_PauseReleasesReplacedSnapshot(t *testing.T) { Object: &ateletpb.ObjectStorage{SnapshotUri: paused.String()}, }}} - stored, err := w.SuspendActor(ctx, actorRef, suspendAsync) + stored, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendAsync) if err != nil { t.Fatalf("SuspendActor: %v", err) } @@ -780,7 +821,7 @@ func TestSuspendActor_Finalized_CommitsDespiteObjectStoreFailure(t *testing.T) { }) objects.OnDelete = func(string, string) error { return errObjectStore } - stored, err := w.SuspendActor(ctx, actorRef, suspendSync) + stored, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync) if err != nil { t.Fatalf("SuspendActor: %v", err) } @@ -837,7 +878,7 @@ func TestSuspendActor_Finalized_KeepsReplacedSnapshotOnConflict(t *testing.T) { } }) - if _, err := w.SuspendActor(ctx, actorRef, suspendSync); apierror.Code(err) != codes.Aborted { + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync); apierror.Code(err) != codes.Aborted { t.Fatalf("SuspendActor = %v, want code Aborted", err) } // Every actor update conflicts, so pin that the Aborted came from finalize @@ -890,7 +931,7 @@ func TestSuspendActor_Finalized_KeepsCrashFromWorkerDelete(t *testing.T) { seedWireWorker(t, ctx, persistence, assignmentOf(created)) w, _ := newWireCaptureWorkflow(t, workerDeletedDuringReleaseStore{Interface: persistence}) - _, err := w.SuspendActor(ctx, actorRef, suspendSync) + _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync) assertConcurrentCrashKept(t, ctx, persistence, actorRef, err, "suspend failed: "+crashMessageWorkerPodGone) } @@ -953,7 +994,7 @@ func TestSuspendActor_Finalized_ReleasesOnlyOwnWorker(t *testing.T) { ActorUid: uid, }) - if _, err := w.SuspendActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "shared"}, suspendSync); err != nil { + if _, err := w.SuspendActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "shared"}, store.Precondition{}, suspendSync); err != nil { t.Fatalf("SuspendActor: %v", err) } @@ -1012,7 +1053,7 @@ func TestSuspendActor_Finalized_MissingDurableSnapshotClearsAssignment(t *testin s.Snapshots = nil }) - if _, err := w.SuspendActor(ctx, actorRef, suspendSync); apierror.Code(err) != codes.FailedPrecondition { + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync); apierror.Code(err) != codes.FailedPrecondition { t.Fatalf("SuspendActor error = %v, want FailedPrecondition for the actor it crashed", err) } got, err := st.GetActor(ctx, actorRef) @@ -1230,7 +1271,7 @@ func TestSuspendAndPause_CharacteristicMatrix(t *testing.T) { seedWireWorker(t, ctx, persistence, assignment) w, atelet := newWireCaptureWorkflow(t, persistence) - _, err := w.SuspendActor(ctx, actorRef, mode.suspendMode) + _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, mode.suspendMode) stored := mustReadActor(t, ctx, persistence, actorRef) got := suspendOutcome{ code: apierror.Code(err), @@ -1282,7 +1323,7 @@ func TestSuspendAndPause_FinalizeWithoutAssignment(t *testing.T) { s.WorkerAssignment = nil }) - returned, err := w.SuspendActor(ctx, actorRef, mode.suspendMode) + returned, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, mode.suspendMode) if got := apierror.Code(err); got != codes.FailedPrecondition { t.Fatalf("%s: code = %v (err %v), want FailedPrecondition", mode.name, got, err) } @@ -1321,7 +1362,7 @@ func TestSuspendAndPause_InvalidStorageLocationRejected(t *testing.T) { }, }) - if _, err := w.SuspendActor(ctx, actorRef, mode.suspendMode); err == nil { + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, mode.suspendMode); err == nil { t.Fatalf("%s: expected error for invalid storage location, got nil", mode.name) } stored := mustReadActor(t, ctx, persistence, actorRef) @@ -1558,7 +1599,7 @@ func TestSuspendActor_AppliesCheckpointState(t *testing.T) { return nil } - _, err := w.SuspendActor(ctx, actorRef, tt.mode) + _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, tt.mode) stored := mustReadActor(t, ctx, persistence, actorRef) if tt.wantCode != codes.OK { if got := apierror.Code(err); got != tt.wantCode { @@ -1662,7 +1703,7 @@ func TestSuspendActor_Finalized_RecordsLocalCopyWhenKept(t *testing.T) { return nil } - if _, err := w.SuspendActor(ctx, actorRef, suspendSync); err != nil { + if _, err := w.SuspendActor(ctx, actorRef, store.Precondition{}, suspendSync); err != nil { t.Fatalf("suspend: %v", err) } stored := mustReadActor(t, ctx, persistence, actorRef) diff --git a/cmd/ateapi/internal/controlapi/workflow_tag.go b/cmd/ateapi/internal/controlapi/workflow_tag.go index bb3fd2b9a9..5344c85b8f 100644 --- a/cmd/ateapi/internal/controlapi/workflow_tag.go +++ b/cmd/ateapi/internal/controlapi/workflow_tag.go @@ -126,7 +126,7 @@ func (w *ActorWorkflow) TagActorSnapshot(ctx context.Context, tag *ateapi.Tag) ( // Note that this destroys the external snapshot: an Actor created from the tag // and never suspended is still borrowing it and becomes unrecoverable. Do not // delete a tag while clones of it exist. -func (w *ActorWorkflow) DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions) (*ateapi.Tag, error) { +func (w *ActorWorkflow) DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition) (*ateapi.Tag, error) { ctx = preview.ContextWithOptIn(ctx) // Serializes against a create of the same tag, whose copy would otherwise // keep writing into the prefix this is collecting. @@ -149,7 +149,7 @@ func (w *ActorWorkflow) DeleteTag(ctx context.Context, tagRef resources.TagRef, // ensureTagMarkedForDeletion sets the tag's delete_time, checking precondition, // and returns the stored copy. Skips when a previous attempt already marked the // tag. -func (w *ActorWorkflow) ensureTagMarkedForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions) (_ *ateapi.Tag, err error) { +func (w *ActorWorkflow) ensureTagMarkedForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition) (_ *ateapi.Tag, err error) { ctx, done := stepSpan(ctx, "MarkTagForDeletion") defer func() { err = done(err) }() @@ -167,13 +167,13 @@ func (w *ActorWorkflow) ensureTagMarkedForDeletion(ctx context.Context, tagRef r } if err != nil { if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("Tag %s does not have uid %s", tagRef, precondition.UID) + return nil, apierror.Aborted("Tag %s does not have uid %s", tagRef, precondition.UID).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Tag %s not found", tagRef) + return nil, apierror.NotFound("Tag %s not found", tagRef).WithCause(err) } return nil, fmt.Errorf("while marking tag %s for deletion: %w", tagRef, err) } @@ -215,17 +215,17 @@ func (w *ActorWorkflow) finalizeTagDeleted(ctx context.Context, tag *ateapi.Tag) defer func() { err = done(err) }() tagRef := resources.TagRefFromTag(tag) - precondition := store.DeletePreconditions{UID: tag.GetMetadata().GetUid()} + precondition := store.Precondition{UID: tag.GetMetadata().GetUid()} tag, err = w.store.DeleteTag(ctx, tagRef, precondition) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Tag %s not found", tagRef) + return nil, apierror.NotFound("Tag %s not found", tagRef).WithCause(err) } if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("Tag %s does not have uid %s", tagRef, precondition.UID) + return nil, apierror.Aborted("Tag %s does not have uid %s", tagRef, precondition.UID).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } return nil, fmt.Errorf("while deleting tag %s: %w", tagRef, err) } @@ -358,7 +358,7 @@ func (w *ActorWorkflow) ensureTagSourceSnapshotDurable(ctx context.Context, acto }) if err != nil { if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } return nil, fmt.Errorf("while recording the upload of Actor %s's latest snapshot: %w", actorRef, err) } @@ -434,9 +434,9 @@ func (w *ActorWorkflow) ensureTagReserved(ctx context.Context, tagRef resources. case err == nil: return stored, nil case errors.Is(err, store.ErrFailedPrecondition): - return nil, apierror.FailedPrecondition("Atespace %s not found", tagRef.Atespace) + return nil, apierror.FailedPrecondition("Atespace %s not found", tagRef.Atespace).WithCause(err) case errors.Is(err, store.ErrAlreadyExists): - return nil, apierror.AlreadyExists("Tag %s already exists; delete it and create it again to retry", tagRef) + return nil, apierror.AlreadyExists("Tag %s already exists; delete it and create it again to retry", tagRef).WithCause(err) } return nil, fmt.Errorf("while reserving tag %s: %w", tagRef, err) } @@ -474,10 +474,10 @@ func (w *ActorWorkflow) ensureTagSnapshotRecorded(ctx context.Context, tag *atea }) if err != nil { if errors.Is(err, store.ErrVersionConflict) { - return nil, resources.SnapshotURI{}, apierror.Aborted("concurrent update conflict, please retry") + return nil, resources.SnapshotURI{}, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } if errors.Is(err, store.ErrNotFound) || errors.Is(err, store.ErrUIDConflict) { - return nil, resources.SnapshotURI{}, apierror.Aborted("Tag %s was deleted while it was being created, please retry", tagRef) + return nil, resources.SnapshotURI{}, apierror.Aborted("Tag %s was deleted while it was being created, please retry", tagRef).WithCause(err) } return nil, resources.SnapshotURI{}, fmt.Errorf("while recording the snapshot of tag %s: %w", tagRef, err) } @@ -532,10 +532,10 @@ func (w *ActorWorkflow) ensureTagFinalized(ctx context.Context, tag *ateapi.Tag, }) if err != nil { if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } if errors.Is(err, store.ErrNotFound) || errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("Tag %s was deleted while it was being created, please retry", tagRef) + return nil, apierror.Aborted("Tag %s was deleted while it was being created, please retry", tagRef).WithCause(err) } return nil, fmt.Errorf("while finalizing tag %s: %w", tagRef, err) } diff --git a/cmd/ateapi/internal/controlapi/workflow_tag_test.go b/cmd/ateapi/internal/controlapi/workflow_tag_test.go index 87ebe7fcfc..0ddfcea6cc 100644 --- a/cmd/ateapi/internal/controlapi/workflow_tag_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_tag_test.go @@ -668,7 +668,7 @@ func TestTagActorSnapshot_RecreateAfterCopyFailure(t *testing.T) { } // Deleting the tag collects the partial copy and frees the name. - if _, err := w.DeleteTag(ctx, tagRef, store.DeletePreconditions{}); err != nil { + if _, err := w.DeleteTag(ctx, tagRef, store.Precondition{}); err != nil { t.Fatalf("DeleteTag on the pending tag: %v", err) } if got := objects.Snapshot(t, strandedURI); len(got) != 0 { @@ -749,7 +749,7 @@ func TestTagActorSnapshot_RecreateAfterRecordFailure(t *testing.T) { t.Errorf("DeleteTag listed %q for a tag that records no snapshot", prefix) return nil } - if _, err := w.DeleteTag(ctx, tagRef, store.DeletePreconditions{}); err != nil { + if _, err := w.DeleteTag(ctx, tagRef, store.Precondition{}); err != nil { t.Fatalf("DeleteTag on the reserved tag: %v", err) } objects.OnList = nil @@ -791,7 +791,7 @@ func TestTagActorSnapshot_RacesDelete(t *testing.T) { return } pendingURI = mustReservedTagSnapshotURI(t, reserved).String() - _, deleteErr = w.DeleteTag(ctx, tagRef, store.DeletePreconditions{}) + _, deleteErr = w.DeleteTag(ctx, tagRef, store.Precondition{}) }) return nil } @@ -894,7 +894,7 @@ func TestDeleteTag_ReleasesExternalSnapshot(t *testing.T) { // A delete that cannot reach object storage must not drop the row: it is // the only handle left on the snapshot. objects.OnDelete = func(string, string) error { return errObjectStore } - if _, err := w.DeleteTag(ctx, tagRef, store.DeletePreconditions{}); !isObjectStoreErr(err) { + if _, err := w.DeleteTag(ctx, tagRef, store.Precondition{}); !isObjectStoreErr(err) { t.Fatalf("DeleteTag = %v, want an error wrapping %v", err, errObjectStore) } admitted, err := persistence.GetTag(ctx, tagRef) @@ -905,7 +905,7 @@ func TestDeleteTag_ReleasesExternalSnapshot(t *testing.T) { t.Fatal("a failed delete left delete_time unset") } - if _, err := w.DeleteTag(ctx, tagRef, store.DeletePreconditions{}); !isObjectStoreErr(err) { + if _, err := w.DeleteTag(ctx, tagRef, store.Precondition{}); !isObjectStoreErr(err) { t.Fatalf("retried DeleteTag = %v, want an error wrapping %v", err, errObjectStore) } retried, err := persistence.GetTag(ctx, tagRef) @@ -919,7 +919,7 @@ func TestDeleteTag_ReleasesExternalSnapshot(t *testing.T) { // Simulates a retried deletion. Now, the object deletion succeeds, // so we can remove the row from the DB. objects.OnDelete = nil - deleted, err := w.DeleteTag(ctx, tagRef, store.DeletePreconditions{}) + deleted, err := w.DeleteTag(ctx, tagRef, store.Precondition{}) if err != nil { t.Fatalf("retried DeleteTag: %v", err) } @@ -956,18 +956,18 @@ func TestDeleteTag_ReleasesPendingSnapshot(t *testing.T) { mustUpdateActorStatus(t, ctx, persistence, actor, func(s *ateapi.ActorStatus) { s.State = ateapi.ActorState_ACTOR_STATE_DELETING }) - if _, err := persistence.DeleteActor(ctx, resources.ActorRefFromActor(actor), store.DeletePreconditions{}); err != nil { + if _, err := persistence.DeleteActor(ctx, resources.ActorRefFromActor(actor), store.Precondition{}); err != nil { t.Fatalf("DeleteActor: %v", err) } objects.OnDelete = func(string, string) error { return errObjectStore } - if _, err := w.DeleteTag(ctx, tagRef, store.DeletePreconditions{}); !isObjectStoreErr(err) { + if _, err := w.DeleteTag(ctx, tagRef, store.Precondition{}); !isObjectStoreErr(err) { t.Fatalf("DeleteTag = %v, want an error wrapping %v", err, errObjectStore) } if _, err := persistence.GetTag(ctx, tagRef); err != nil { t.Fatalf("GetTag after failed cleanup: %v", err) } objects.OnDelete = nil - if _, err := w.DeleteTag(ctx, tagRef, store.DeletePreconditions{}); err != nil { + if _, err := w.DeleteTag(ctx, tagRef, store.Precondition{}); err != nil { t.Fatalf("DeleteTag: %v", err) } if got := objects.Snapshot(t, uri); len(got) != 0 { @@ -988,7 +988,7 @@ func TestDeleteTag_NotFound(t *testing.T) { storetest.MustCreateAtespace(t, ctx, persistence, testAtespace) w, _ := newFinalizeWorkflow(persistence) - _, err := w.DeleteTag(ctx, resources.TagRef{Atespace: testAtespace, Name: "missing"}, store.DeletePreconditions{}) + _, err := w.DeleteTag(ctx, resources.TagRef{Atespace: testAtespace, Name: "missing"}, store.Precondition{}) if code := apierror.Code(err); code != codes.NotFound { t.Errorf("DeleteTag = %v (code %v), want code NotFound", err, code) } @@ -1021,7 +1021,7 @@ func TestDeleteTag_Preconditions(t *testing.T) { } uid, version := observed.GetMetadata().GetUid(), observed.GetMetadata().GetVersion() - for name, precondition := range map[string]store.DeletePreconditions{ + for name, precondition := range map[string]store.Precondition{ "stale version": {UID: uid, Version: version + 1}, "foreign uid": {UID: "0f0e0d0c-0b0a-4908-8706-050403020100", Version: version}, } { @@ -1036,7 +1036,7 @@ func TestDeleteTag_Preconditions(t *testing.T) { t.Fatalf("GetTag after the rejected deletes: %v", err) } - if _, err := w.DeleteTag(ctx, tagRef, store.DeletePreconditions{UID: uid, Version: version}); err != nil { + if _, err := w.DeleteTag(ctx, tagRef, store.Precondition{UID: uid, Version: version}); err != nil { t.Fatalf("DeleteTag with matching guards: %v", err) } if got := objects.Snapshot(t, uri); len(got) != 0 { diff --git a/cmd/ateapi/internal/controlapi/workflow_template_delete.go b/cmd/ateapi/internal/controlapi/workflow_template_delete.go index 8db52ad33d..5fd9df2af2 100644 --- a/cmd/ateapi/internal/controlapi/workflow_template_delete.go +++ b/cmd/ateapi/internal/controlapi/workflow_template_delete.go @@ -30,7 +30,7 @@ import ( // DeleteActorTemplate executes the workflow to delete an ActorTemplate. The // golden actor and tag go first and the row last, so a failed attempt leaves // the row for a retry to rediscover them by. -func (w *ActorWorkflow) DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions) (*ateapi.ActorTemplate, error) { +func (w *ActorWorkflow) DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition) (*ateapi.ActorTemplate, error) { ctx = preview.ContextWithOptIn(ctx) // Serializes against the reconciler, which creates the golden actor and // tag under the same lease. @@ -59,7 +59,7 @@ func (w *ActorWorkflow) DeleteActorTemplate(ctx context.Context, templateRef res // ensureTemplateMarkedForDeletion sets the template's delete_time, checking // precondition, and returns the stored copy. Skips when a previous attempt // already marked the template. -func (w *ActorWorkflow) ensureTemplateMarkedForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions) (_ *ateapi.ActorTemplate, err error) { +func (w *ActorWorkflow) ensureTemplateMarkedForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition) (_ *ateapi.ActorTemplate, err error) { ctx, done := stepSpan(ctx, "MarkTemplateForDeletion") defer func() { err = done(err) }() @@ -77,13 +77,13 @@ func (w *ActorWorkflow) ensureTemplateMarkedForDeletion(ctx context.Context, tem } if err != nil { if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("ActorTemplate %s does not have uid %s", templateRef, precondition.UID) + return nil, apierror.Aborted("ActorTemplate %s does not have uid %s", templateRef, precondition.UID).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("ActorTemplate %s not found", templateRef) + return nil, apierror.NotFound("ActorTemplate %s not found", templateRef).WithCause(err) } return nil, fmt.Errorf("while marking actor template %s for deletion: %w", templateRef, err) } @@ -97,7 +97,7 @@ func (w *ActorWorkflow) ensureGoldenActorDeleted(ctx context.Context, goldenRef ctx, done := stepSpan(ctx, "DeleteGoldenActor") defer func() { err = done(err) }() - if _, err := w.DeleteActor(ctx, goldenRef, store.DeletePreconditions{}); err != nil { + if _, err := w.DeleteActor(ctx, goldenRef, store.Precondition{}); err != nil { if apierror.Code(err) == codes.NotFound { markSkipped(ctx, "golden actor already deleted") return nil @@ -113,7 +113,7 @@ func (w *ActorWorkflow) ensureGoldenTagDeleted(ctx context.Context, goldenTagRef ctx, done := stepSpan(ctx, "DeleteGoldenTag") defer func() { err = done(err) }() - if _, err := w.DeleteTag(ctx, goldenTagRef, store.DeletePreconditions{}); err != nil { + if _, err := w.DeleteTag(ctx, goldenTagRef, store.Precondition{}); err != nil { if apierror.Code(err) == codes.NotFound { markSkipped(ctx, "golden tag already deleted") return nil @@ -130,17 +130,17 @@ func (w *ActorWorkflow) finalizeTemplateDeleted(ctx context.Context, tmpl *ateap defer func() { err = done(err) }() templateRef := resources.ActorTemplateRefFromActorTemplate(tmpl) - precondition := store.DeletePreconditions{UID: tmpl.GetMetadata().GetUid()} + precondition := store.Precondition{UID: tmpl.GetMetadata().GetUid()} deleted, err := w.store.DeleteActorTemplate(ctx, templateRef, precondition) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("ActorTemplate %s not found", templateRef) + return nil, apierror.NotFound("ActorTemplate %s not found", templateRef).WithCause(err) } if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("ActorTemplate %s does not have uid %s", templateRef, precondition.UID) + return nil, apierror.Aborted("ActorTemplate %s does not have uid %s", templateRef, precondition.UID).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } return nil, fmt.Errorf("while deleting actor template from DB: %w", err) } diff --git a/cmd/ateapi/internal/controlapi/workflow_test.go b/cmd/ateapi/internal/controlapi/workflow_test.go index 496cbfba46..6983a0d11c 100644 --- a/cmd/ateapi/internal/controlapi/workflow_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_test.go @@ -78,7 +78,7 @@ func TestActorStateChangeRecords(t *testing.T) { }, }, transition: func(t *testing.T, w *ActorWorkflow, ref resources.ActorRef, _ *ateapi.Actor, _ *ateapi.ActorTemplate) { - if _, err := w.SuspendActor(context.Background(), ref, suspendAsync); err != nil { + if _, err := w.SuspendActor(context.Background(), ref, store.Precondition{}, suspendAsync); err != nil { t.Fatalf("SuspendActor: %v", err) } }, @@ -90,11 +90,11 @@ func TestActorStateChangeRecords(t *testing.T) { name: "delete marks the actor deleting", seedState: ateapi.ActorState_ACTOR_STATE_SUSPENDED, transition: func(t *testing.T, w *ActorWorkflow, ref resources.ActorRef, _ *ateapi.Actor, _ *ateapi.ActorTemplate) { - if _, err := w.ensureMarkedDeleting(context.Background(), ref, store.DeletePreconditions{}); err != nil { + if _, err := w.ensureMarkedDeleting(context.Background(), ref, store.Precondition{}); err != nil { t.Fatalf("ensureMarkedDeleting: %v", err) } // A retry finds the actor already marked and writes no second record. - if _, err := w.ensureMarkedDeleting(context.Background(), ref, store.DeletePreconditions{}); err != nil { + if _, err := w.ensureMarkedDeleting(context.Background(), ref, store.Precondition{}); err != nil { t.Fatalf("retried ensureMarkedDeleting: %v", err) } }, @@ -187,7 +187,7 @@ func markOnly(t *testing.T, w *ActorWorkflow, ref resources.ActorRef, actor *ate t.Fatalf("UpdateActor: %v", err) } w.dialer = newDanglingDialer() - _, err := w.SuspendActor(ctx, ref, mode) + _, err := w.SuspendActor(ctx, ref, store.Precondition{}, mode) assertStoppedAtDial(t, err) } @@ -244,12 +244,12 @@ func TestActorDeletedRecord(t *testing.T) { actorRef := resources.ActorRef{Atespace: "team-a", Name: "id1"} seedWorkflowActor(t, ctx, persistence, actorRef, "ns", "tmpl1", ateapi.ActorState_ACTOR_STATE_DELETING) - actor, err := persistence.MarkActorForDeletion(ctx, actorRef, store.DeletePreconditions{}, nil) + actor, err := persistence.MarkActorForDeletion(ctx, actorRef, store.Precondition{}, nil) if err != nil { t.Fatalf("mark actor: %v", err) } - w := &ActorWorkflow{store: persistence} + w := &ActorWorkflow{gates: testGates, store: persistence} if _, err := w.finalizeDeleted(ctx, actor); err != nil { t.Fatalf("finalizeDeleted: %v", err) } @@ -306,8 +306,8 @@ func TestActorStateChangeRecordSkippedOnConflict(t *testing.T) { t.Fatalf("bump version: %v", err) } - w := &ActorWorkflow{store: persistence} - if _, err := w.ensureMarkedDeleting(ctx, actorRef, store.DeletePreconditions{Version: stale.GetMetadata().GetVersion()}); apierror.Code(err) != codes.Aborted { + w := &ActorWorkflow{gates: testGates, store: persistence} + if _, err := w.ensureMarkedDeleting(ctx, actorRef, store.Precondition{Version: stale.GetMetadata().GetVersion()}); apierror.Code(err) != codes.Aborted { t.Fatalf("ensureMarkedDeleting with a stale guard = %v, want ABORTED", err) } if len(*records) != 0 { diff --git a/cmd/ateapi/internal/controlapi/workflow_testutil_test.go b/cmd/ateapi/internal/controlapi/workflow_testutil_test.go index 27fb25f936..70f6eb313d 100644 --- a/cmd/ateapi/internal/controlapi/workflow_testutil_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_testutil_test.go @@ -59,7 +59,7 @@ func newTestActorWorkflow(t *testing.T, st store.Interface, tmplAtespace, tmplNa }); err != nil && !errors.Is(err, store.ErrAlreadyExists) { t.Fatalf("create test ActorTemplate: %v", err) } - return NewActorWorkflow(st, nil, nil, nil, nil, "", nil, time.Minute, objectstoreplugintest.ControlClient(objectstoretest.New())) + return NewActorWorkflow(st, nil, nil, nil, nil, "", nil, time.Minute, objectstoreplugintest.ControlClient(objectstoretest.New()), testGates) } // newFinalizeWorkflow builds an ActorWorkflow over persistence with an @@ -67,7 +67,7 @@ func newTestActorWorkflow(t *testing.T, st store.Interface, tmplAtespace, tmplNa // directly rather than going through newTestActorWorkflow. func newFinalizeWorkflow(persistence store.Interface) (*ActorWorkflow, *objectstoretest.Fake) { objects := objectstoretest.New() - return &ActorWorkflow{store: persistence, workflowDeadline: time.Minute, objectStorePlugin: objectstoreplugintest.ControlClient(objects)}, objects + return &ActorWorkflow{gates: testGates, store: persistence, workflowDeadline: time.Minute, objectStorePlugin: objectstoreplugintest.ControlClient(objects)}, objects } // newWireFinalizeWorkflow is newWireCaptureWorkflow with an in-memory object @@ -339,7 +339,7 @@ func assignmentOf(actor *ateapi.Actor) *ateapi.ActorAssignment { // so a suspend stops right after its mark step and leaves the actor as that // step committed it. func newMarkOnlyWorkflow(st store.Interface) *ActorWorkflow { - return &ActorWorkflow{store: st, dialer: newDanglingDialer(), workflowDeadline: time.Minute} + return &ActorWorkflow{gates: testGates, store: st, dialer: newDanglingDialer(), workflowDeadline: time.Minute} } // assertStoppedAtDial verifies a workflow built by newMarkOnlyWorkflow failed @@ -423,7 +423,7 @@ func (s workerDeletedDuringReleaseStore) UpdateActorAndRelease(ctx context.Conte return nil, nil, err } dialer := NewAteletDialer(cache.NewIndexer(cache.MetaNamespaceKeyFunc, cache.Indexers{byNode: nil}), "", "", "") - if err := NewWorkerWorkflow(noLeaseStore(s), dialer).releaseBoundActor(ctx, worker, assignment); err != nil { + if err := NewWorkerWorkflow(noLeaseStore(s), dialer, testGates).releaseBoundActor(ctx, worker, assignment); err != nil { return nil, nil, err } return s.Interface.UpdateActorAndRelease(ctx, actorRef, precondition, mutate) diff --git a/cmd/ateapi/internal/controlapi/workflow_worker_crash.go b/cmd/ateapi/internal/controlapi/workflow_worker_crash.go index 3a4b0f9622..1ec0bf37a7 100644 --- a/cmd/ateapi/internal/controlapi/workflow_worker_crash.go +++ b/cmd/ateapi/internal/controlapi/workflow_worker_crash.go @@ -41,7 +41,7 @@ func (w *ActorWorkflow) CrashActorReportedByWorker(ctx context.Context, actorRef actor, err := w.store.GetActor(leaseCtx, actorRef) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Actor %s not found", actorRef) + return nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } return nil, fmt.Errorf("while loading actor %s: %w", actorRef, err) } diff --git a/cmd/ateapi/internal/controlapi/workflow_worker_delete.go b/cmd/ateapi/internal/controlapi/workflow_worker_delete.go index c4554dfa16..8935fcec1b 100644 --- a/cmd/ateapi/internal/controlapi/workflow_worker_delete.go +++ b/cmd/ateapi/internal/controlapi/workflow_worker_delete.go @@ -70,7 +70,7 @@ func (w *WorkerWorkflow) giveUpOnNode(nodeName string) { // record in place, and a retry fast-forwards past whatever the previous attempt // already did. An absent Worker is NOT_FOUND rather than success; idempotency // belongs to the caller, which knows whether that is the state it wanted. -func (w *WorkerWorkflow) DeleteWorker(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.Worker, error) { +func (w *WorkerWorkflow) DeleteWorker(ctx context.Context, name string, precondition store.Precondition) (*ateapi.Worker, error) { ctx = preview.ContextWithOptIn(ctx) worker, err := w.ensureMarkedForDeletion(ctx, name, precondition) if err != nil { @@ -90,7 +90,7 @@ func (w *WorkerWorkflow) DeleteWorker(ctx context.Context, name string, precondi // ensureMarkedForDeletion sets the Worker's delete_time, checking // precondition, and drains it, returning the stored copy. Skips when a // previous attempt already marked the Worker. -func (w *WorkerWorkflow) ensureMarkedForDeletion(ctx context.Context, name string, precondition store.DeletePreconditions) (_ *ateapi.Worker, err error) { +func (w *WorkerWorkflow) ensureMarkedForDeletion(ctx context.Context, name string, precondition store.Precondition) (_ *ateapi.Worker, err error) { ctx, done := stepSpan(ctx, "MarkWorkerForDeletion") defer func() { err = done(err) }() @@ -115,13 +115,13 @@ func (w *WorkerWorkflow) ensureMarkedForDeletion(ctx context.Context, name strin } if err != nil { if errors.Is(err, store.ErrUIDConflict) { - return nil, apierror.Aborted("Worker %s does not have uid %s", name, precondition.UID) + return nil, apierror.Aborted("Worker %s does not have uid %s", name, precondition.UID).WithCause(err) } if errors.Is(err, store.ErrVersionConflict) { - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) } if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Worker %s not found", name) + return nil, apierror.NotFound("Worker %s not found", name).WithCause(err) } return nil, fmt.Errorf("while marking worker for deletion: %w", err) } @@ -284,7 +284,7 @@ func releaseWriteError(name string, err error) error { case err == nil, errors.Is(err, store.ErrNotFound): return nil case errors.Is(err, store.ErrUIDConflict), errors.Is(err, store.ErrVersionConflict): - return apierror.Aborted("concurrent update conflict, please retry") + return apierror.Aborted("concurrent update conflict, please retry").WithCause(err) default: return fmt.Errorf("while releasing actor from worker %s: %w", name, err) } @@ -343,7 +343,7 @@ func (w *WorkerWorkflow) reclaimActorStateOnNode(ctx context.Context, worker *at ActorUid: actor.GetMetadata().GetUid(), ActorTemplateAtespace: actor.GetActorTemplate().GetAtespace(), ActorTemplateName: actor.GetActorTemplate().GetName(), - Spec: fallbackWorkloadSpec(actor), + Spec: fallbackWorkloadSpec(w.gates, actor), }) switch status.Code(err) { case codes.OK: @@ -369,20 +369,20 @@ func (w *WorkerWorkflow) finalizeDeleted(ctx context.Context, worker *ateapi.Wor // Only the uid guards the delete. Each actor the sweep releases updates the // Worker's allocation and moves its version. The uid still refuses a Worker // replaced by a new incarnation. - precondition := store.DeletePreconditions{UID: worker.GetMetadata().GetUid()} + precondition := store.Precondition{UID: worker.GetMetadata().GetUid()} deleted, err := w.store.DeleteWorker(ctx, name, precondition) if err != nil { switch { case errors.Is(err, store.ErrNotFound): - return nil, apierror.NotFound("Worker %s not found", name) + return nil, apierror.NotFound("Worker %s not found", name).WithCause(err) case errors.Is(err, store.ErrUIDConflict): - return nil, apierror.Aborted("Worker %s does not have uid %s", name, precondition.UID) + return nil, apierror.Aborted("Worker %s does not have uid %s", name, precondition.UID).WithCause(err) case errors.Is(err, store.ErrVersionConflict): - return nil, apierror.Aborted("concurrent update conflict, please retry") + return nil, apierror.Aborted("concurrent update conflict, please retry").WithCause(err) case errors.Is(err, store.ErrFailedPrecondition): // The sweep released every Actor that names this Worker, so a // leftover assignment means the store is inconsistent. - return nil, apierror.Internal("Worker %s still holds assignments after its Actors were released", name) + return nil, apierror.Internal("Worker %s still holds assignments after its Actors were released", name).WithCause(err) } return nil, fmt.Errorf("while deleting worker from DB: %w", err) } diff --git a/cmd/ateapi/internal/controlapi/workflow_worker_delete_test.go b/cmd/ateapi/internal/controlapi/workflow_worker_delete_test.go index ae346540a0..e65750f22e 100644 --- a/cmd/ateapi/internal/controlapi/workflow_worker_delete_test.go +++ b/cmd/ateapi/internal/controlapi/workflow_worker_delete_test.go @@ -44,7 +44,7 @@ func newWorkerDeleteWorkflow(t *testing.T) (*WorkerWorkflow, store.Interface) { t.Helper() persistence, cleanup := storetest.SetupTestStore(t) t.Cleanup(cleanup) - return NewWorkerWorkflow(persistence, newNodeAteletDialer(t, &capturingTerminator{})), persistence + return NewWorkerWorkflow(persistence, newNodeAteletDialer(t, &capturingTerminator{}), testGates), persistence } // apiActorRef names the Actor seedAPIActor stores. @@ -95,8 +95,8 @@ func TestDeleteWorkerWorkflow_DrainsBeforeSweeping(t *testing.T) { actor := seedAPIActor(t, ctx, persistence, ateapi.ActorState_ACTOR_STATE_RUNNING) assignAPIWorker(t, ctx, persistence, apiWorkerName, actor.GetMetadata().GetUid()) - wf := NewWorkerWorkflow(failingUpdateActorStore{Interface: persistence, err: errors.New("release failed")}, newNodeAteletDialer(t, &capturingTerminator{})) - if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}); err == nil { + wf := NewWorkerWorkflow(failingUpdateActorStore{Interface: persistence, err: errors.New("release failed")}, newNodeAteletDialer(t, &capturingTerminator{}), testGates) + if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}); err == nil { t.Fatal("DeleteWorker() = nil error, want the release failure reported") } @@ -123,7 +123,7 @@ func TestDeleteWorkerWorkflow_ReleasesBoundActor(t *testing.T) { }) assignAPIWorker(t, ctx, persistence, apiWorkerName, actor.GetMetadata().GetUid()) - if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker() failed: %v", err) } @@ -184,7 +184,7 @@ func TestDeleteWorkerWorkflow_ReleasedActorStateTransitions(t *testing.T) { actor := seedAPIActor(t, ctx, persistence, tc.start) assignAPIWorker(t, ctx, persistence, apiWorkerName, actor.GetMetadata().GetUid()) - if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker() failed: %v", err) } @@ -249,7 +249,7 @@ func TestDeleteWorkerWorkflow_LeftoverAssignmentFails(t *testing.T) { t.Fatalf("GetActor() failed: %v", err) } - if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}); apierror.Code(err) != codes.Internal { + if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}); apierror.Code(err) != codes.Internal { t.Fatalf("DeleteWorker() = %v (err %v), want Internal", apierror.Code(err), err) } if _, err := persistence.GetWorker(ctx, apiWorkerName); err != nil { @@ -304,8 +304,8 @@ func TestDeleteWorkerWorkflow_FailedReleaseKeepsWorker(t *testing.T) { actor := seedAPIActor(t, ctx, persistence, ateapi.ActorState_ACTOR_STATE_RUNNING) assignAPIWorker(t, ctx, persistence, apiWorkerName, actor.GetMetadata().GetUid()) - wf := NewWorkerWorkflow(failingUpdateActorStore{Interface: persistence, err: tc.updateErr}, newNodeAteletDialer(t, &capturingTerminator{})) - _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}) + wf := NewWorkerWorkflow(failingUpdateActorStore{Interface: persistence, err: tc.updateErr}, newNodeAteletDialer(t, &capturingTerminator{}), testGates) + _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}) if err == nil { t.Fatal("DeleteWorker() = nil error, want the release failure reported") } @@ -320,7 +320,7 @@ func TestDeleteWorkerWorkflow_FailedReleaseKeepsWorker(t *testing.T) { if worker.GetMetadata().GetDeleteTime() == nil { t.Errorf("a failed delete left delete_time unset") } - if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}); err == nil { + if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}); err == nil { t.Fatal("retried DeleteWorker() = nil error, want the release failure reported") } retried, err := persistence.GetWorker(ctx, apiWorkerName) @@ -348,7 +348,7 @@ func TestDeleteWorkerWorkflow_AbsentReportsNotFoundThroughStepWrap(t *testing.T) ctx := context.Background() wf, _ := newWorkerDeleteWorkflow(t) - _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}) + _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}) if got := apierror.Code(err); got != codes.NotFound { t.Fatalf("DeleteWorker() code = %v (err %v), want %v", got, err, codes.NotFound) } @@ -387,7 +387,7 @@ func TestDeleteWorkerWorkflow_DrainedWorkerIsStillAdmitted(t *testing.T) { t.Fatalf("UpdateWorker failed: %v", err) } - deleted, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}) + deleted, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}) if err != nil { t.Fatalf("DeleteWorker() failed: %v", err) } @@ -441,7 +441,7 @@ func TestDeleteWorkerWorkflow_ReclaimsActorNodeState(t *testing.T) { t.Cleanup(cleanup) atelet := &capturingTerminator{err: tt.terminateErr} - wf := NewWorkerWorkflow(persistence, newNodeAteletDialer(t, atelet)) + wf := NewWorkerWorkflow(persistence, newNodeAteletDialer(t, atelet), testGates) seedAPIWorker(t, ctx, persistence, validWorker(apiWorkerName)) seeds := []func(*ateapi.Actor){} @@ -451,7 +451,7 @@ func TestDeleteWorkerWorkflow_ReclaimsActorNodeState(t *testing.T) { actor := seedAPIActor(t, ctx, persistence, tt.state, seeds...) assignAPIWorker(t, ctx, persistence, apiWorkerName, actor.GetMetadata().GetUid()) - if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker() failed: %v", err) } @@ -486,7 +486,7 @@ func TestDeleteWorkerWorkflow_ReleasesUnderTheActorLease(t *testing.T) { t.Cleanup(cleanup) atelet := &capturingTerminator{} - wf := NewWorkerWorkflow(persistence, newNodeAteletDialer(t, atelet)) + wf := NewWorkerWorkflow(persistence, newNodeAteletDialer(t, atelet), testGates) seedAPIWorker(t, ctx, persistence, validWorker(apiWorkerName)) actor := seedAPIActor(t, ctx, persistence, ateapi.ActorState_ACTOR_STATE_SUSPENDING, func(a *ateapi.Actor) { @@ -499,7 +499,7 @@ func TestDeleteWorkerWorkflow_ReleasesUnderTheActorLease(t *testing.T) { if err != nil { t.Fatalf("AcquireLease() failed: %v", err) } - _, err = wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}) + _, err = wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}) if got := atelet.requests(); len(got) != 0 { t.Errorf("atelet received %d Terminate calls while the actor's lease was held, want none", len(got)) } @@ -518,7 +518,7 @@ func TestDeleteWorkerWorkflow_ReleasesUnderTheActorLease(t *testing.T) { } lease.Close() - if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker() once the lease is free failed: %v", err) } if got := atelet.requests(); len(got) != 1 { @@ -538,7 +538,7 @@ func TestDeleteWorkerWorkflow_BusyActorDoesNotHoldUpOthers(t *testing.T) { t.Cleanup(cleanup) atelet := &capturingTerminator{} - wf := NewWorkerWorkflow(persistence, newNodeAteletDialer(t, atelet)) + wf := NewWorkerWorkflow(persistence, newNodeAteletDialer(t, atelet), testGates) seedAPIWorker(t, ctx, persistence, validWorker(apiWorkerName)) var refs []resources.ActorRef @@ -561,7 +561,7 @@ func TestDeleteWorkerWorkflow_BusyActorDoesNotHoldUpOthers(t *testing.T) { t.Fatalf("AcquireLease() failed: %v", err) } defer lease.Close() - _, err = wf.DeleteWorker(ctx, apiWorkerName, store.DeletePreconditions{}) + _, err = wf.DeleteWorker(ctx, apiWorkerName, store.Precondition{}) if got := apierror.Code(err); got != codes.Aborted { t.Errorf("DeleteWorker() with one actor's lease held = %v, want ABORTED", err) } @@ -602,7 +602,7 @@ func TestDeleteWorkerWorkflow_HungReclaimDoesNotWedgeDelete(t *testing.T) { now := time.Now() atelet := &capturingTerminator{hang: tt.hang, err: tt.err} - wf := NewWorkerWorkflow(persistence, newNodeAteletDialer(t, atelet)) + wf := NewWorkerWorkflow(persistence, newNodeAteletDialer(t, atelet), testGates) wf.reclaimTimeout = 50 * time.Millisecond wf.now = func() time.Time { return now } @@ -630,7 +630,7 @@ func TestDeleteWorkerWorkflow_HungReclaimDoesNotWedgeDelete(t *testing.T) { // into it, and the release after it fails. rpcCtx, cancel := context.WithTimeout(ctx, 5*time.Second) defer cancel() - if _, err := wf.DeleteWorker(rpcCtx, apiWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := wf.DeleteWorker(rpcCtx, apiWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker(first) failed: %v", err) } if got := len(atelet.requests()); got != 1 { @@ -641,7 +641,7 @@ func TestDeleteWorkerWorkflow_HungReclaimDoesNotWedgeDelete(t *testing.T) { // skips Terminate without waiting out another timeout. seedAPIWorker(t, ctx, persistence, validWorker(apiOtherWorkerName)) refs = append(refs, bindRunningActor(apiOtherWorkerName, "actor-3")) - if _, err := wf.DeleteWorker(rpcCtx, apiOtherWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := wf.DeleteWorker(rpcCtx, apiOtherWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker(second) failed: %v", err) } if got := len(atelet.requests()); got != 1 { @@ -666,7 +666,7 @@ func TestDeleteWorkerWorkflow_HungReclaimDoesNotWedgeDelete(t *testing.T) { atelet.mu.Unlock() seedAPIWorker(t, ctx, persistence, validWorker(apiWorkerName)) bindRunningActor(apiWorkerName, "actor-4") - if _, err := wf.DeleteWorker(rpcCtx, apiWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := wf.DeleteWorker(rpcCtx, apiWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker(after timeout) failed: %v", err) } if got := len(atelet.requests()); got != 2 { diff --git a/cmd/ateapi/internal/controlapi/workload_spec_test.go b/cmd/ateapi/internal/controlapi/workload_spec_test.go index 69f67c82fd..fa994305d9 100644 --- a/cmd/ateapi/internal/controlapi/workload_spec_test.go +++ b/cmd/ateapi/internal/controlapi/workload_spec_test.go @@ -413,7 +413,7 @@ func TestAppendExternalVolumes(t *testing.T) { Name: "actor-123", }, Status: &ateapi.ActorStatus{ - ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{ + ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{ { Name: "vol-1", StorageVolumeId: "vol-gce-pd-123", @@ -470,7 +470,7 @@ func TestAppendExternalVolumes(t *testing.T) { Atespace: "space-abc", Name: "actor-123", }, - Status: &ateapi.ActorStatus{ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ExternalVolumeStatus{}}}, + Status: &ateapi.ActorStatus{ExternalVolumes: &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{}}}, } if err := appendExternalVolumes(&ateletpb.WorkloadSpec{}, template, missingActor, nil); err == nil { t.Errorf("appendExternalVolumes expected error for missing volume, got nil") diff --git a/cmd/ateapi/internal/defaults/defaults.go b/cmd/ateapi/internal/defaults/defaults.go index 0bffefb536..f08dd8505f 100644 --- a/cmd/ateapi/internal/defaults/defaults.go +++ b/cmd/ateapi/internal/defaults/defaults.go @@ -32,12 +32,18 @@ func Apply(m proto.Message) { applyAccessPolicyDefaults(v) case *ateapi.Actor: applyActorDefaults(v) + case *ateapi.ActorAssignment: + // ActorAssignments are server managed and don't support defaults. case *ateapi.ActorTemplate: applyActorTemplateDefaults(v) case *ateapi.Atespace: applyAtespaceDefaults(v) + case *ateapi.CsiDriver: + applyCSIDriverDefaults(v) case *ateapi.EgressPolicy: applyEgressPolicyDefaults(v) + case *ateapi.ExternalVolume: + applyExternalVolumeDefaults(v) case *ateapi.Tag: applyTagDefaults(v) case *ateapi.Worker: @@ -99,6 +105,8 @@ func applyActorDefaults(*ateapi.Actor) {} func applyAtespaceDefaults(*ateapi.Atespace) {} +func applyCSIDriverDefaults(*ateapi.CsiDriver) {} + func applyEgressPolicyDefaults(p *ateapi.EgressPolicy) { applyEgressRuleDefaults(p.GetRules()) } @@ -117,6 +125,8 @@ func applyEgressRuleDefaults(rules []*ateapi.EgressRule) { } } +func applyExternalVolumeDefaults(*ateapi.ExternalVolume) {} + func applyTagDefaults(*ateapi.Tag) {} func applyWorkerDefaults(*ateapi.Worker) {} diff --git a/cmd/ateapi/internal/defaults/defaults_test.go b/cmd/ateapi/internal/defaults/defaults_test.go index 5a1e2e441d..a5a41b6a72 100644 --- a/cmd/ateapi/internal/defaults/defaults_test.go +++ b/cmd/ateapi/internal/defaults/defaults_test.go @@ -151,6 +151,14 @@ func TestApply(t *testing.T) { {Https: &ateapi.HttpsRule{Hostnames: []string{"custom.example.com"}, Ports: &ateapi.Ports{Numbers: []int32{8443}}}}, {TlsPassthrough: &ateapi.TlsPassthroughRule{Hostnames: []string{"tcp.example.com"}}}, }}}, + }, { + name: "csi driver has no defaults", + in: &ateapi.CsiDriver{Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, DriverName: "nfs.csi.k8s.io", ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "csi-nfs", Port: 9000}}, + want: &ateapi.CsiDriver{Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, DriverName: "nfs.csi.k8s.io", ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "csi-nfs", Port: 9000}}, + }, { + name: "external volume has no defaults", + in: &ateapi.ExternalVolume{Status: &ateapi.ExternalVolumeStatus{Csi: &ateapi.CsiVolumeStatus{VolumeId: "pvc-1", DriverName: "nfs.csi.k8s.io"}}}, + want: &ateapi.ExternalVolume{Status: &ateapi.ExternalVolumeStatus{Csi: &ateapi.CsiVolumeStatus{VolumeId: "pvc-1", DriverName: "nfs.csi.k8s.io"}}}, }, { name: "tag has no defaults", in: &ateapi.Tag{Scope: ateapi.TagScope_TAG_SCOPE_PUBLISHED}, diff --git a/cmd/ateapi/internal/functionaltest/AGENTS.md b/cmd/ateapi/internal/functionaltest/AGENTS.md new file mode 100644 index 0000000000..cc043bcbae --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/AGENTS.md @@ -0,0 +1,145 @@ +# ate-api functional tests + +Each test in this directory must start with a comment that describes, in plain +language, what it does and asserts. The test implements that description. +Every test of a resource lives in `_test.go`, named by the plural, +lowercase name of the resource it asserts on (`atespaces`, `actors`, +`workers`, ...). + +## Test descriptions + +- A description states how ate-api currently behaves. When that differs from + how it should behave, describe today's behavior and add a `TODO:` paragraph + saying what the server should change to. The test follows the description, + not the TODO. +- When you change a test, update its description to match. + +## Finding gaps + +When asked to find gaps, measure which server code the tests reach and report +what is missing. Do not change tests while doing so. + +1. Run the suite with coverage of ate-api's server packages. ate-api runs + inside the test process, so its code counts: + + ```bash + go test -coverpkg=./cmd/ateapi/internal/controlapi,./cmd/ateapi/internal/workerservice,./cmd/ateapi/internal/server \ + -coverprofile=cover.out ./cmd/ateapi/internal/functionaltest/ + go tool cover -func=cover.out + ``` + +2. Classify every uncovered RPC handler or branch: + + - **Missing test:** an RPC, or a branch a client can reach through the + public API and the harness. Propose a test. + - **Harness gap:** production code the harness skips, such as a fake + plugged in below the code that would normally find it. Propose a harness + change; it needs careful review. + - **Not reachable black-box:** a branch only a store failure or a crash + between two writes can reach. Note that it belongs in the in-package + tests. + +3. Report each proposed test as its name and a plain-language description. + +Coverage measures what runs, not what is checked. Never propose a test only +to cover lines; every test describes behavior a client can observe. + +## Writing tests + +The tests are black-box: they drive ate-api only through its public gRPC API +and the harness in `harness/`, never through the store, `RPCService`, or any +other ate-api internal. + +- Start each test with `t.Parallel()` and its own `h := harness.New(t)`. The + harness starts an empty ate-api with its own database and fakes; create the + atespaces, worker pools, workers and templates the test needs. +- Reach the state a description presupposes ("a paused actor", "an existing + actor template") through the harness's fixtures, which wait as long as they + need. Make each action or check it states ("deletes", "a later Get") as an + RPC through `h.Control`, once unless its wording says otherwise. Never reach + the method named by the test through a fixture. +- Resume an actor with `h.ResumeActorWithRetries`, which retries the errors + atenet retries. A test that needs a different retry, such as one expecting + one of those errors, calls `h.Control.ResumeActor`. +- Write one test per case. Do not turn cases with different setup or recovery + into a table of functions. +- The exception is a `_ValidationError` test with several invalid requests to + one RPC, after the same setup, that each check only the code and the + message prefix. Write those cases as a table. Give each row a plain-English + `name`, run as its subtest. A case that checks more, such as that a refused + update left the resource unchanged, stays a separate test. +- Assert on whole resources: `cmp.Diff(want, got, protocmp.Transform(), ...)`. + Ignore only fields ate-api assigns, with the options in `cmp_test.go`. + - For a newly created resource, write `want` as a literal proto. A test + that creates a variant of a resource builds `want` with `mutated` from + the same literal as the resource's plain create test. + - For an operation on an existing resource, read it right before the + operation, and build `want` with `mutated`, changing only the fields the + operation should change. + - An operation that is refused must leave the resource exactly as it was: + compare with nothing ignored. +- Assert on the fakes the same way: compare whole `Sandboxes()`, + `Volumes.List()` or `ObjectStore` contents, not single entries. +- Check the calls ate-api made to a fake from a recording started right before + the operation, such as `rec := node.Atelet.RecordCalls()` or + `h.Volumes.RecordCalls()`: `assertCalls(t, rec, methods...)` for which + methods it called, and `onlyCall[*ateletpb.RestoreRequest](t, rec)` for the + request of the one call it made. +- Check an RPC's error by its gRPC code: `status.Code(err) != codes.NotFound`. + Assert on the error message only when the description explicitly asks for + something in it, and then only that the message contains it. For a + description saying the error names the invalid field, check instead that + the message starts with the field's full path and the error type: + `strings.HasPrefix(msg, "actor.metadata.name: Invalid value")`. Several + validation errors render as `[err1, err2]`, so the prefix also checks there + is only one. Never compare the whole message: the text after the prefix + comes from Kubernetes' validation library. +- Inject failures through the fakes' `On(method)` faults (`FailNext`, `Block` + and `BlockReply`), with the error presets the harness defines, such as + `harness.ErrUnavailable` and `harness.ErrSandboxFailed`. +- ate-api runs with every preview gate on, but a harness's clients do not opt + in to preview features, so ate-api rejects preview fields as it does from a + default client. A test that uses a preview feature, such as a template with + an external volume, creates its harness with + `harness.New(t, harness.WithPreviewClient())`: then `h.Control`, + `h.ClientAs` and the fixtures opt in. In such a test, + `h.ControlWithoutPreview()` checks what a client without the opt-in can do. +- Assert an RPC's outcome as soon as it returns: ate-api finishes an RPC's + work before replying. Wait with `h.Eventually`, polling public RPCs, only + for an outcome the description says happens eventually. If an assertion + fails because the outcome arrives later, report it rather than adding a + wait: whether the description should say "eventually" is a decision for a + person. +- A test that fails because ate-api behaves differently from its description + is a discrepancy to report, not a test to change: either the description is + corrected or it gets a `TODO:` for the server. + +## Authentication and authorization + +ate-api runs with authentication and authorization enforced. +Control clients authenticate with a client certificate carrying +a SPIFFE ID, as in-cluster components do; ate-api accepts no bearer tokens. + +- `h.Control` authenticates as a bootstrap owner, a global owner whatever the + stored access policies say. Use it to set up a test, and for every call + that is not about permissions. +- `h.ClientAs(name)` returns a Control client authenticating as + `harness.ClientID(name)`. Access policies name it as the member + `harness.Member(name)`. It holds no permissions until a policy grants them. +- To test a permission, grant a role to `harness.Member(name)` with an access + policy created through `h.Control`, call the RPC through `h.ClientAs(name)`, + and check the gRPC code: `OK`, or `PermissionDenied`. +- An `_Authorization` test checks one method's permission. Its + description calls `h.Control` the admin and the `h.ClientAs` client the + principal. Only the principal calls the method under test. The admin makes + every grant, replacing the principal's single binding before each step, and + makes every read that checks a refused call changed nothing. + +## Acceptance + +A change to these tests is done when all of these hold: + +- `go vet ./...` is clean and `gofmt -l .` prints nothing. +- `go test -race -count=3 -shuffle=on ./...` passes from this directory. +- Every new test was seen failing once: break one of its expected values, run + it, and restore the value. \ No newline at end of file diff --git a/cmd/ateapi/internal/functionaltest/accesspolicies_test.go b/cmd/ateapi/internal/functionaltest/accesspolicies_test.go new file mode 100644 index 0000000000..32fad6b65f --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/accesspolicies_test.go @@ -0,0 +1,1079 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "fmt" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" +) + +// accessPolicySpec is a valid access policy for an atespace or the global +// scope: both accept the viewer role. +func accessPolicySpec() *ateapi.AccessPolicy { + return &ateapi.AccessPolicy{ + Metadata: &ateapi.ResourceMetadata{Name: "default"}, + Bindings: []*ateapi.Binding{{Role: "viewer", Members: []string{harness.Member("alice")}}}, + } +} + +// setAtespaceBinding makes the atespace's access policy, as the admin, bind +// exactly member to role, creating the policy if the atespace has none. +func setAtespaceBinding(t *testing.T, h *harness.Harness, atespace *ateapi.ObjectRef, role, member string) *ateapi.AccessPolicy { + t.Helper() + bindings := []*ateapi.Binding{{Role: role, Members: []string{member}}} + current, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: atespace}) + if status.Code(err) == codes.NotFound { + created, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: atespace, AccessPolicy: &ateapi.AccessPolicy{ + Metadata: &ateapi.ResourceMetadata{Name: "default"}, + Bindings: bindings, + }}) + if err != nil { + t.Fatalf("binding %s to %s: %v", member, role, err) + } + return created + } + if err != nil { + t.Fatalf("GetAtespaceAccessPolicy: %v", err) + } + toUpdate := mutated(current, func(p *ateapi.AccessPolicy) { + p.Bindings = bindings + }) + updated, err := h.Control.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: atespace, AccessPolicy: toUpdate}) + if err != nil { + t.Fatalf("binding %s to %s: %v", member, role, err) + } + return updated +} + +// eventuallyAllowed calls call until it no longer fails with +// PermissionDenied, as a grant may take a while to apply, and fails the test +// unless that first allowed call's result has the code want. It stops at the +// first allowed call, so call may change state. +func eventuallyAllowed(t *testing.T, h *harness.Harness, what string, want codes.Code, call func() error) { + t.Helper() + var err error + h.Eventually(what+" to be allowed", func() bool { + err = call() + return status.Code(err) != codes.PermissionDenied + }) + if status.Code(err) != want { + t.Errorf("%s = %v, want %v", what, err, want) + } +} + +// setGlobalBinding makes the global access policy, as the admin, bind exactly +// member to role, creating the policy if it does not exist. +func setGlobalBinding(t *testing.T, h *harness.Harness, role, member string) *ateapi.AccessPolicy { + t.Helper() + bindings := []*ateapi.Binding{{Role: role, Members: []string{member}}} + current, err := h.Control.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}) + if status.Code(err) == codes.NotFound { + created, err := h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: &ateapi.AccessPolicy{ + Metadata: &ateapi.ResourceMetadata{Name: "default"}, + Bindings: bindings, + }}) + if err != nil { + t.Fatalf("binding %s to %s: %v", member, role, err) + } + return created + } + if err != nil { + t.Fatalf("GetGlobalAccessPolicy: %v", err) + } + toUpdate := mutated(current, func(p *ateapi.AccessPolicy) { + p.Bindings = bindings + }) + updated, err := h.Control.UpdateGlobalAccessPolicy(t.Context(), &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: toUpdate}) + if err != nil { + t.Fatalf("binding %s to %s: %v", member, role, err) + } + return updated +} + +// Creates an access policy for an existing atespace, sending output-only +// metadata, and verifies that the whole resource has the expected shape: +// ate-api ignores what was sent and assigns its own. +func TestCreateAtespaceAccessPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + + in := accessPolicySpec() + // The caller sends output-only fields, which ate-api ignores. + setOutputOnlyMetadata(in.Metadata) + created, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: in}) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + want := &ateapi.AccessPolicy{ + Metadata: &ateapi.ResourceMetadata{Name: "default"}, + Bindings: []*ateapi.Binding{{Role: "viewer", Members: []string{harness.Member("alice")}}}, + } + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created access policy (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) +} + +// Creating an access policy for an atespace that has one fails with +// ALREADY_EXISTS and leaves the existing one unchanged. +func TestCreateAtespaceAccessPolicy_AlreadyExists(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + created, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + + _, err = h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateAtespaceAccessPolicy for an atespace that has one = %v, want AlreadyExists", err) + } + got, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if err != nil { + t.Fatalf("GetAtespaceAccessPolicy: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("access policy after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an access policy with an invalid atespace name fails with +// INVALID_ARGUMENT and the error names the invalid field. +func TestCreateAtespaceAccessPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{ + Atespace: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}, + AccessPolicy: accessPolicySpec(), + }) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateAtespaceAccessPolicy with an invalid atespace name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "atespace.name: Invalid value") { + t.Errorf("CreateAtespaceAccessPolicy error %q does not start with %q", msg, "atespace.name: Invalid value") + } +} + +// Creating an access policy for an atespace that doesn't exist fails with +// FAILED_PRECONDITION. +func TestCreateAtespaceAccessPolicy_AtespaceNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{ + Atespace: &ateapi.ObjectRef{Name: "atespace-missing"}, + AccessPolicy: accessPolicySpec(), + }) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateAtespaceAccessPolicy for a missing atespace = %v, want FailedPrecondition", err) + } +} + +// Creating an atespace's access policy as a principal no access policy names +// fails with PERMISSION_DENIED, both for an atespace that exists and for one +// that does not, and no policy is created: getting it fails with NOT_FOUND. +// Once the admin creates the atespace's policy, granting the principal the +// viewer role, then the editor role, the principal still fails with +// PERMISSION_DENIED. Granted the owner role, the principal is eventually +// allowed, and fails with ALREADY_EXISTS because the policy exists. +func TestCreateAtespaceAccessPolicy_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + create := func() error { + _, err := alice.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}) + return err + } + + if err := create(); status.Code(err) != codes.PermissionDenied { + t.Errorf("CreateAtespaceAccessPolicy holding no role = %v, want PermissionDenied", err) + } + if _, err := alice.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: &ateapi.ObjectRef{Name: "team-missing"}, AccessPolicy: accessPolicySpec()}); status.Code(err) != codes.PermissionDenied { + t.Errorf("CreateAtespaceAccessPolicy for a missing atespace holding no role = %v, want PermissionDenied", err) + } + if _, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}); status.Code(err) != codes.NotFound { + t.Errorf("GetAtespaceAccessPolicy after a refused create = %v, want NotFound", err) + } + for _, role := range []string{"viewer", "editor"} { + setAtespaceBinding(t, h, as, role, harness.Member("alice")) + if err := create(); status.Code(err) != codes.PermissionDenied { + t.Errorf("CreateAtespaceAccessPolicy holding %s = %v, want PermissionDenied", role, err) + } + } + setAtespaceBinding(t, h, as, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "CreateAtespaceAccessPolicy holding owner", codes.AlreadyExists, create) +} + +// Getting an existing access policy returns exactly the resource +// CreateAtespaceAccessPolicy returned. +func TestGetAtespaceAccessPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + created, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + + got, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if err != nil { + t.Fatalf("GetAtespaceAccessPolicy: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("GetAtespaceAccessPolicy (-created +got):\n%s", diff) + } +} + +// Getting the access policy of an atespace that has none fails with +// NOT_FOUND. +func TestGetAtespaceAccessPolicy_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + + _, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetAtespaceAccessPolicy for an atespace with none = %v, want NotFound", err) + } +} + +// Getting an access policy with an invalid atespace name fails with +// INVALID_ARGUMENT and the error names the invalid field. +func TestGetAtespaceAccessPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("GetAtespaceAccessPolicy with an invalid atespace name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "atespace.name: Invalid value") { + t.Errorf("GetAtespaceAccessPolicy error %q does not start with %q", msg, "atespace.name: Invalid value") + } +} + +// After an atespace with an access policy is deleted, getting its access +// policy fails with NOT_FOUND. An atespace created again under the same name +// has no access policy either: getting it fails with NOT_FOUND. +func TestGetAtespaceAccessPolicy_AtespaceDeleted(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + if _, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}); err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + + if _, err := h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: as}); err != nil { + t.Fatalf("DeleteAtespace: %v", err) + } + _, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetAtespaceAccessPolicy of a deleted atespace = %v, want NotFound", err) + } + + h.CreateAtespace(as.GetName()) + _, err = h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetAtespaceAccessPolicy of an atespace recreated under the same name = %v, want NotFound", err) + } +} + +// Getting an atespace's access policy as a principal it does not name fails +// with PERMISSION_DENIED, as does getting the access policy of an atespace +// that does not exist. Granted the viewer role, then the editor role, then +// the owner role, by that policy, the principal eventually gets it (OK) each +// time. +func TestGetAtespaceAccessPolicy_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + return err + } + + setAtespaceBinding(t, h, as, "viewer", harness.Member("bob")) + if err := get(); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetAtespaceAccessPolicy holding no role = %v, want PermissionDenied", err) + } + if _, err := alice.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: &ateapi.ObjectRef{Name: "team-missing"}}); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetAtespaceAccessPolicy of a missing atespace holding no role = %v, want PermissionDenied", err) + } + for _, role := range []string{"viewer", "editor", "owner"} { + setAtespaceBinding(t, h, as, role, harness.Member("alice")) + eventuallyAllowed(t, h, fmt.Sprintf("GetAtespaceAccessPolicy holding %s", role), codes.OK, get) + } +} + +// Updates the bindings of an existing access policy, sending it as read. The +// result, and a later Get, is the resource as read with that field changed +// and a higher version. +func TestUpdateAtespaceAccessPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + before, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + bindings := []*ateapi.Binding{{Role: "editor", Members: []string{harness.Member("bob")}}} + + toUpdate := mutated(before, func(p *ateapi.AccessPolicy) { + p.Bindings = bindings + }) + updated, err := h.Control.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: toUpdate}) + if err != nil { + t.Fatalf("UpdateAtespaceAccessPolicy: %v", err) + } + want := mutated(before, func(p *ateapi.AccessPolicy) { + p.Bindings = bindings + }) + if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("updated access policy (-want +got):\n%s", diff) + } + if got, was := updated.GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("updated access policy has version %d, want higher than %d", got, was) + } + got, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if err != nil { + t.Fatalf("GetAtespaceAccessPolicy: %v", err) + } + if diff := cmp.Diff(updated, got, protocmp.Transform()); diff != "" { + t.Errorf("GetAtespaceAccessPolicy after update (-updated +got):\n%s", diff) + } +} + +// Updating the access policy of an atespace that has none fails with +// NOT_FOUND. +func TestUpdateAtespaceAccessPolicy_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + policy := accessPolicySpec() + policy.Metadata.Uid, policy.Metadata.Version = foreignUID, 1 + + _, err := h.Control.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: policy}) + if status.Code(err) != codes.NotFound { + t.Errorf("UpdateAtespaceAccessPolicy for an atespace with none = %v, want NotFound", err) + } +} + +// Updating an access policy with the wrong UID fails with ABORTED, and with +// the right UID but the wrong version fails with ABORTED; both leave it +// unchanged. Updating it without a UID or a version fails with +// INVALID_ARGUMENT. +func TestUpdateAtespaceAccessPolicy_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + before, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + update := func(uid string, version int64) error { + toUpdate := mutated(before, func(p *ateapi.AccessPolicy) { + p.Metadata.Uid, p.Metadata.Version = uid, version + p.Bindings = []*ateapi.Binding{{Role: "editor", Members: []string{harness.Member("bob")}}} + }) + _, err := h.Control.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: toUpdate}) + return err + } + + if err := update(foreignUID, before.GetMetadata().GetVersion()); status.Code(err) != codes.Aborted { + t.Errorf("UpdateAtespaceAccessPolicy with the wrong uid = %v, want Aborted", err) + } + if err := update(before.GetMetadata().GetUid(), before.GetMetadata().GetVersion()+1); status.Code(err) != codes.Aborted { + t.Errorf("UpdateAtespaceAccessPolicy with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if err != nil { + t.Fatalf("GetAtespaceAccessPolicy: %v", err) + } + if diff := cmp.Diff(before, got, protocmp.Transform()); diff != "" { + t.Errorf("access policy after refused updates (-want +got):\n%s", diff) + } + if err := update("", 0); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateAtespaceAccessPolicy without a uid or version = %v, want InvalidArgument", err) + } +} + +// Updating an access policy with an invalid atespace name fails with +// INVALID_ARGUMENT and the error names the invalid field. +func TestUpdateAtespaceAccessPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + policy := accessPolicySpec() + policy.Metadata.Uid, policy.Metadata.Version = foreignUID, 1 + + _, err := h.Control.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{ + Atespace: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}, + AccessPolicy: policy, + }) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateAtespaceAccessPolicy with an invalid atespace name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "atespace.name: Invalid value") { + t.Errorf("UpdateAtespaceAccessPolicy error %q does not start with %q", msg, "atespace.name: Invalid value") + } +} + +// Updating an atespace's access policy as a principal it does not name fails +// with PERMISSION_DENIED, as does updating the access policy of an atespace +// that does not exist. Granted the viewer role, then the editor role, by +// that policy, the principal still fails with PERMISSION_DENIED. Each +// refused update leaves the policy unchanged. Granted the owner role, the +// principal eventually updates it (OK). +func TestUpdateAtespaceAccessPolicy_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + update := func(policy *ateapi.AccessPolicy) error { + toUpdate := mutated(policy, func(p *ateapi.AccessPolicy) { + p.Bindings = append(p.Bindings, &ateapi.Binding{Role: "editor", Members: []string{harness.Member("carol")}}) + }) + _, err := alice.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: toUpdate}) + return err + } + refusedUpdate := func(holding string, before *ateapi.AccessPolicy) { + t.Helper() + if err := update(before); status.Code(err) != codes.PermissionDenied { + t.Errorf("UpdateAtespaceAccessPolicy holding %s = %v, want PermissionDenied", holding, err) + } + after, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if err != nil { + t.Fatalf("GetAtespaceAccessPolicy: %v", err) + } + if diff := cmp.Diff(before, after, protocmp.Transform()); diff != "" { + t.Errorf("access policy after a refused update holding %s (-want +got):\n%s", holding, diff) + } + } + + refusedUpdate("no role", setAtespaceBinding(t, h, as, "viewer", harness.Member("bob"))) + missingPolicy := accessPolicySpec() + missingPolicy.Metadata.Uid, missingPolicy.Metadata.Version = foreignUID, 1 + if _, err := alice.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: &ateapi.ObjectRef{Name: "team-missing"}, AccessPolicy: missingPolicy}); status.Code(err) != codes.PermissionDenied { + t.Errorf("UpdateAtespaceAccessPolicy of a missing atespace holding no role = %v, want PermissionDenied", err) + } + refusedUpdate("viewer", setAtespaceBinding(t, h, as, "viewer", harness.Member("alice"))) + refusedUpdate("editor", setAtespaceBinding(t, h, as, "editor", harness.Member("alice"))) + policy := setAtespaceBinding(t, h, as, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "UpdateAtespaceAccessPolicy holding owner", codes.OK, func() error { return update(policy) }) +} + +// A principal granted the viewer role by an atespace's access policy +// eventually gets the atespace (OK). After the admin updates the policy to +// no longer name the principal, getting the atespace eventually fails with +// PERMISSION_DENIED. +func TestUpdateAtespaceAccessPolicy_RevokesAccess(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: as}) + return err + } + setAtespaceBinding(t, h, as, "viewer", harness.Member("alice")) + eventuallyAllowed(t, h, "GetAtespace holding viewer", codes.OK, get) + + setAtespaceBinding(t, h, as, "viewer", harness.Member("bob")) + h.Eventually("GetAtespace to be denied once the policy no longer names the principal", func() bool { + return status.Code(get()) == codes.PermissionDenied + }) +} + +// A principal granted the owner role by an atespace's access policy +// eventually updates that policy (OK). After the admin changes the +// principal's binding to the viewer role, deleting the atespace with a UID +// that can't match, so an allowed delete changes nothing, eventually fails +// with PERMISSION_DENIED and leaves it unchanged, while getting it still +// succeeds (OK). +func TestUpdateAtespaceAccessPolicy_DowngradesAccess(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + policy := setAtespaceBinding(t, h, as, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "UpdateAtespaceAccessPolicy holding owner", codes.OK, func() error { + toUpdate := mutated(policy, func(p *ateapi.AccessPolicy) { + p.Bindings = append(p.Bindings, &ateapi.Binding{Role: "viewer", Members: []string{harness.Member("carol")}}) + }) + _, err := alice.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: toUpdate}) + return err + }) + + setAtespaceBinding(t, h, as, "viewer", harness.Member("alice")) + before, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: as}) + if err != nil { + t.Fatalf("GetAtespace: %v", err) + } + h.Eventually("DeleteAtespace to be denied once the principal is downgraded to viewer", func() bool { + _, err := alice.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: as, Options: &ateapi.DeleteOptions{Uid: foreignUID}}) + return status.Code(err) == codes.PermissionDenied + }) + after, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: as}) + if err != nil { + t.Fatalf("GetAtespace after a refused delete: %v", err) + } + if diff := cmp.Diff(before, after, protocmp.Transform()); diff != "" { + t.Errorf("atespace after a refused delete (-want +got):\n%s", diff) + } + if _, err := alice.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: as}); status.Code(err) != codes.OK { + t.Errorf("GetAtespace holding viewer = %v, want OK", err) + } +} + +// An atespace's access policy grants the viewer role to 250 principals, and +// each of them eventually gets the atespace (OK). After the admin updates +// the policy to name only the first of them, the first still gets the +// atespace (OK), and each of the other 249 eventually fails with +// PERMISSION_DENIED. 250 exceeds the 100 tuples ate-api writes to OpenFGA per +// request, so both updates span several writes. +func TestUpdateAtespaceAccessPolicy_ManyMembers(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + var members []string + var clients []ateapi.ControlClient + for i := range 250 { + subject := fmt.Sprintf("member-%03d", i) + members = append(members, harness.Member(subject)) + clients = append(clients, h.ClientAs(subject)) + } + get := func(c ateapi.ControlClient) error { + _, err := c.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: as}) + return err + } + policy, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: &ateapi.AccessPolicy{ + Metadata: &ateapi.ResourceMetadata{Name: "default"}, + Bindings: []*ateapi.Binding{{Role: "viewer", Members: members}}, + }}) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + for i, c := range clients { + eventuallyAllowed(t, h, fmt.Sprintf("GetAtespace as %s", members[i]), codes.OK, func() error { return get(c) }) + } + + toUpdate := mutated(policy, func(p *ateapi.AccessPolicy) { + p.Bindings = []*ateapi.Binding{{Role: "viewer", Members: members[:1]}} + }) + if _, err := h.Control.UpdateAtespaceAccessPolicy(t.Context(), &ateapi.UpdateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: toUpdate}); err != nil { + t.Fatalf("UpdateAtespaceAccessPolicy: %v", err) + } + if err := get(clients[0]); status.Code(err) != codes.OK { + t.Errorf("GetAtespace as %s, still named = %v, want OK", members[0], err) + } + for i, c := range clients[1:] { + h.Eventually(fmt.Sprintf("GetAtespace as %s to be denied once removed", members[i+1]), func() bool { + return status.Code(get(c)) == codes.PermissionDenied + }) + } +} + +// Deletes an existing access policy. The response is the deleted resource, +// and a later Get fails with NOT_FOUND. +func TestDeleteAtespaceAccessPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + created, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + + deleted, err := h.Control.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if err != nil { + t.Fatalf("DeleteAtespaceAccessPolicy: %v", err) + } + if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreDeleteTime); diff != "" { + t.Errorf("DeleteAtespaceAccessPolicy response (-created +deleted):\n%s", diff) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Error("DeleteAtespaceAccessPolicy response has no delete_time") + } + if _, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}); status.Code(err) != codes.NotFound { + t.Errorf("GetAtespaceAccessPolicy after delete = %v, want NotFound", err) + } +} + +// Deleting the access policy of an atespace that has none fails with +// NOT_FOUND. +func TestDeleteAtespaceAccessPolicy_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + + _, err := h.Control.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if status.Code(err) != codes.NotFound { + t.Errorf("DeleteAtespaceAccessPolicy for an atespace with none = %v, want NotFound", err) + } +} + +// Deleting an access policy with the wrong UID, with only the wrong version, or +// with the right UID but the wrong version fails with ABORTED and leaves it +// unchanged. With the right UID and version the delete succeeds. +func TestDeleteAtespaceAccessPolicy_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + created, err := h.Control.CreateAtespaceAccessPolicy(t.Context(), &ateapi.CreateAtespaceAccessPolicyRequest{Atespace: as, AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy: %v", err) + } + uid, version := created.GetMetadata().GetUid(), created.GetMetadata().GetVersion() + + _, err = h.Control.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: as, Options: &ateapi.DeleteOptions{Uid: foreignUID}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteAtespaceAccessPolicy with the wrong uid = %v, want Aborted", err) + } + _, err = h.Control.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: as, Options: &ateapi.DeleteOptions{Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteAtespaceAccessPolicy with only the wrong version = %v, want Aborted", err) + } + _, err = h.Control.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: as, Options: &ateapi.DeleteOptions{Uid: uid, Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteAtespaceAccessPolicy with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if err != nil { + t.Fatalf("GetAtespaceAccessPolicy after refused deletes: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("access policy after refused deletes (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: as, Options: &ateapi.DeleteOptions{Uid: uid, Version: version}}); err != nil { + t.Errorf("DeleteAtespaceAccessPolicy with the right uid and version: %v", err) + } +} + +// Deleting an access policy with an invalid atespace name fails with +// INVALID_ARGUMENT and the error names the invalid field. +func TestDeleteAtespaceAccessPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("DeleteAtespaceAccessPolicy with an invalid atespace name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "atespace.name: Invalid value") { + t.Errorf("DeleteAtespaceAccessPolicy error %q does not start with %q", msg, "atespace.name: Invalid value") + } +} + +// Deleting an atespace's access policy as a principal it does not name fails +// with PERMISSION_DENIED, as does deleting the access policy of an atespace +// that does not exist. Granted the viewer role, then the editor role, by +// that policy, the principal still fails with PERMISSION_DENIED. Each +// refused delete leaves the policy unchanged. Granted the owner role, the +// principal eventually deletes it (OK). +func TestDeleteAtespaceAccessPolicy_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + remove := func() error { + _, err := alice.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + return err + } + refusedDelete := func(holding string, before *ateapi.AccessPolicy) { + t.Helper() + if err := remove(); status.Code(err) != codes.PermissionDenied { + t.Errorf("DeleteAtespaceAccessPolicy holding %s = %v, want PermissionDenied", holding, err) + } + after, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: as}) + if err != nil { + t.Fatalf("GetAtespaceAccessPolicy after a refused delete holding %s: %v", holding, err) + } + if diff := cmp.Diff(before, after, protocmp.Transform()); diff != "" { + t.Errorf("access policy after a refused delete holding %s (-want +got):\n%s", holding, diff) + } + } + + refusedDelete("no role", setAtespaceBinding(t, h, as, "viewer", harness.Member("bob"))) + if _, err := alice.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: &ateapi.ObjectRef{Name: "team-missing"}}); status.Code(err) != codes.PermissionDenied { + t.Errorf("DeleteAtespaceAccessPolicy of a missing atespace holding no role = %v, want PermissionDenied", err) + } + refusedDelete("viewer", setAtespaceBinding(t, h, as, "viewer", harness.Member("alice"))) + refusedDelete("editor", setAtespaceBinding(t, h, as, "editor", harness.Member("alice"))) + setAtespaceBinding(t, h, as, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "DeleteAtespaceAccessPolicy holding owner", codes.OK, remove) +} + +// A principal granted the viewer role by an atespace's access policy +// eventually gets the atespace (OK). After the admin deletes the policy, +// getting the atespace eventually fails with PERMISSION_DENIED. +func TestDeleteAtespaceAccessPolicy_RevokesAccess(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: as}) + return err + } + setAtespaceBinding(t, h, as, "viewer", harness.Member("alice")) + eventuallyAllowed(t, h, "GetAtespace holding viewer", codes.OK, get) + + if _, err := h.Control.DeleteAtespaceAccessPolicy(t.Context(), &ateapi.DeleteAtespaceAccessPolicyRequest{Name: "default", Atespace: as}); err != nil { + t.Fatalf("DeleteAtespaceAccessPolicy: %v", err) + } + h.Eventually("GetAtespace to be denied once the policy is deleted", func() bool { + return status.Code(get()) == codes.PermissionDenied + }) +} + +// Creates the global access policy, sending output-only metadata, and verifies +// that the whole resource has the expected shape: ate-api ignores what was +// sent and assigns its own. +func TestCreateGlobalAccessPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + + in := accessPolicySpec() + // The caller sends output-only fields, which ate-api ignores. + setOutputOnlyMetadata(in.Metadata) + created, err := h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: in}) + if err != nil { + t.Fatalf("CreateGlobalAccessPolicy: %v", err) + } + want := &ateapi.AccessPolicy{ + Metadata: &ateapi.ResourceMetadata{Name: "default"}, + Bindings: []*ateapi.Binding{{Role: "viewer", Members: []string{harness.Member("alice")}}}, + } + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created global access policy (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) +} + +// Creating the global access policy when it exists fails with ALREADY_EXISTS +// and leaves the existing one unchanged. +func TestCreateGlobalAccessPolicy_AlreadyExists(t *testing.T) { + t.Parallel() + h := harness.New(t) + created, err := h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateGlobalAccessPolicy: %v", err) + } + + _, err = h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: accessPolicySpec()}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateGlobalAccessPolicy when it exists = %v, want AlreadyExists", err) + } + got, err := h.Control.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}) + if err != nil { + t.Fatalf("GetGlobalAccessPolicy: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("global access policy after a refused create (-want +got):\n%s", diff) + } +} + +// Creating the global access policy with a name other than "default" fails +// with INVALID_ARGUMENT and the error names the invalid field. +func TestCreateGlobalAccessPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + policy := accessPolicySpec() + policy.Metadata.Name = "other" + + _, err := h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: policy}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateGlobalAccessPolicy named %q = %v, want InvalidArgument", policy.GetMetadata().GetName(), err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "access_policy.metadata.name: Invalid value") { + t.Errorf("CreateGlobalAccessPolicy error %q does not start with %q", msg, "access_policy.metadata.name: Invalid value") + } +} + +// Creating the global access policy as a principal no access policy names +// fails with PERMISSION_DENIED, and no policy is created: getting it fails +// with NOT_FOUND. Once the admin creates the global policy, granting the +// principal the viewer role, the principal still fails with +// PERMISSION_DENIED. Granted the owner role, the principal is eventually +// allowed, and fails with ALREADY_EXISTS because the policy exists. +func TestCreateGlobalAccessPolicy_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + alice := h.ClientAs("alice") + create := func() error { + _, err := alice.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: accessPolicySpec()}) + return err + } + + if err := create(); status.Code(err) != codes.PermissionDenied { + t.Errorf("CreateGlobalAccessPolicy holding no role = %v, want PermissionDenied", err) + } + if _, err := h.Control.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}); status.Code(err) != codes.NotFound { + t.Errorf("GetGlobalAccessPolicy after a refused create = %v, want NotFound", err) + } + setGlobalBinding(t, h, "viewer", harness.Member("alice")) + if err := create(); status.Code(err) != codes.PermissionDenied { + t.Errorf("CreateGlobalAccessPolicy holding viewer = %v, want PermissionDenied", err) + } + setGlobalBinding(t, h, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "CreateGlobalAccessPolicy holding owner", codes.AlreadyExists, create) +} + +// Getting the global access policy returns exactly the resource +// CreateGlobalAccessPolicy returned. +func TestGetGlobalAccessPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + created, err := h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateGlobalAccessPolicy: %v", err) + } + + got, err := h.Control.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}) + if err != nil { + t.Fatalf("GetGlobalAccessPolicy: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("GetGlobalAccessPolicy (-created +got):\n%s", diff) + } +} + +// Getting the global access policy before it is created fails with +// NOT_FOUND. +func TestGetGlobalAccessPolicy_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetGlobalAccessPolicy before it is created = %v, want NotFound", err) + } +} + +// Getting the global access policy as a principal no access policy names +// fails with PERMISSION_DENIED, both before the policy exists and after the +// admin creates it without naming the principal. Granted the viewer role, +// then the owner role, by that policy, the principal eventually gets it (OK) +// each time. +func TestGetGlobalAccessPolicy_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}) + return err + } + + if err := get(); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetGlobalAccessPolicy holding no role, before the policy exists = %v, want PermissionDenied", err) + } + setGlobalBinding(t, h, "viewer", harness.Member("bob")) + if err := get(); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetGlobalAccessPolicy holding no role = %v, want PermissionDenied", err) + } + for _, role := range []string{"viewer", "owner"} { + setGlobalBinding(t, h, role, harness.Member("alice")) + eventuallyAllowed(t, h, fmt.Sprintf("GetGlobalAccessPolicy holding %s", role), codes.OK, get) + } +} + +// Updates the bindings of the global access policy, sending it as read. The +// result, and a later Get, is the resource as read with that field changed +// and a higher version. +func TestUpdateGlobalAccessPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + before, err := h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateGlobalAccessPolicy: %v", err) + } + bindings := []*ateapi.Binding{{Role: "owner", Members: []string{harness.Member("bob")}}} + + toUpdate := mutated(before, func(p *ateapi.AccessPolicy) { + p.Bindings = bindings + }) + updated, err := h.Control.UpdateGlobalAccessPolicy(t.Context(), &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: toUpdate}) + if err != nil { + t.Fatalf("UpdateGlobalAccessPolicy: %v", err) + } + want := mutated(before, func(p *ateapi.AccessPolicy) { + p.Bindings = bindings + }) + if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("updated global access policy (-want +got):\n%s", diff) + } + if got, was := updated.GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("updated global access policy has version %d, want higher than %d", got, was) + } + got, err := h.Control.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}) + if err != nil { + t.Fatalf("GetGlobalAccessPolicy: %v", err) + } + if diff := cmp.Diff(updated, got, protocmp.Transform()); diff != "" { + t.Errorf("GetGlobalAccessPolicy after update (-updated +got):\n%s", diff) + } +} + +// Updating the global access policy before it is created fails with +// NOT_FOUND. +func TestUpdateGlobalAccessPolicy_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + policy := accessPolicySpec() + policy.Metadata.Uid, policy.Metadata.Version = foreignUID, 1 + + _, err := h.Control.UpdateGlobalAccessPolicy(t.Context(), &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: policy}) + if status.Code(err) != codes.NotFound { + t.Errorf("UpdateGlobalAccessPolicy before it is created = %v, want NotFound", err) + } +} + +// Updating the global access policy with the wrong UID fails with ABORTED, +// and with the right UID but the wrong version fails with ABORTED; both +// leave it unchanged. Updating it without a UID or a version fails with +// INVALID_ARGUMENT. +func TestUpdateGlobalAccessPolicy_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + before, err := h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateGlobalAccessPolicy: %v", err) + } + update := func(uid string, version int64) error { + toUpdate := mutated(before, func(p *ateapi.AccessPolicy) { + p.Metadata.Uid, p.Metadata.Version = uid, version + p.Bindings = []*ateapi.Binding{{Role: "owner", Members: []string{harness.Member("bob")}}} + }) + _, err := h.Control.UpdateGlobalAccessPolicy(t.Context(), &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: toUpdate}) + return err + } + + if err := update(foreignUID, before.GetMetadata().GetVersion()); status.Code(err) != codes.Aborted { + t.Errorf("UpdateGlobalAccessPolicy with the wrong uid = %v, want Aborted", err) + } + if err := update(before.GetMetadata().GetUid(), before.GetMetadata().GetVersion()+1); status.Code(err) != codes.Aborted { + t.Errorf("UpdateGlobalAccessPolicy with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}) + if err != nil { + t.Fatalf("GetGlobalAccessPolicy: %v", err) + } + if diff := cmp.Diff(before, got, protocmp.Transform()); diff != "" { + t.Errorf("global access policy after refused updates (-want +got):\n%s", diff) + } + if err := update("", 0); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateGlobalAccessPolicy without a uid or version = %v, want InvalidArgument", err) + } +} + +// Updating the global access policy with a name other than "default" fails +// with INVALID_ARGUMENT and the error names the invalid field. +func TestUpdateGlobalAccessPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + before, err := h.Control.CreateGlobalAccessPolicy(t.Context(), &ateapi.CreateGlobalAccessPolicyRequest{AccessPolicy: accessPolicySpec()}) + if err != nil { + t.Fatalf("CreateGlobalAccessPolicy: %v", err) + } + toUpdate := mutated(before, func(p *ateapi.AccessPolicy) { + p.Metadata.Name = "other" + }) + + _, err = h.Control.UpdateGlobalAccessPolicy(t.Context(), &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: toUpdate}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateGlobalAccessPolicy named %q = %v, want InvalidArgument", toUpdate.GetMetadata().GetName(), err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "access_policy.metadata.name: Invalid value") { + t.Errorf("UpdateGlobalAccessPolicy error %q does not start with %q", msg, "access_policy.metadata.name: Invalid value") + } +} + +// Updating the global access policy as a principal no access policy names +// fails with PERMISSION_DENIED, both before the policy exists and after the +// admin creates it without naming the principal. Granted the viewer role by +// that policy, the principal still fails with PERMISSION_DENIED. Each +// refused update leaves the policy unchanged. Granted the owner role, the +// principal eventually updates it (OK). +func TestUpdateGlobalAccessPolicy_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + alice := h.ClientAs("alice") + update := func(policy *ateapi.AccessPolicy) error { + toUpdate := mutated(policy, func(p *ateapi.AccessPolicy) { + p.Bindings = append(p.Bindings, &ateapi.Binding{Role: "viewer", Members: []string{harness.Member("carol")}}) + }) + _, err := alice.UpdateGlobalAccessPolicy(t.Context(), &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: toUpdate}) + return err + } + refusedUpdate := func(holding string, before *ateapi.AccessPolicy) { + t.Helper() + if err := update(before); status.Code(err) != codes.PermissionDenied { + t.Errorf("UpdateGlobalAccessPolicy holding %s = %v, want PermissionDenied", holding, err) + } + after, err := h.Control.GetGlobalAccessPolicy(t.Context(), &ateapi.GetGlobalAccessPolicyRequest{Name: "default"}) + if err != nil { + t.Fatalf("GetGlobalAccessPolicy: %v", err) + } + if diff := cmp.Diff(before, after, protocmp.Transform()); diff != "" { + t.Errorf("global access policy after a refused update holding %s (-want +got):\n%s", holding, diff) + } + } + + missingPolicy := accessPolicySpec() + missingPolicy.Metadata.Uid, missingPolicy.Metadata.Version = foreignUID, 1 + if _, err := alice.UpdateGlobalAccessPolicy(t.Context(), &ateapi.UpdateGlobalAccessPolicyRequest{AccessPolicy: missingPolicy}); status.Code(err) != codes.PermissionDenied { + t.Errorf("UpdateGlobalAccessPolicy before the policy exists holding no role = %v, want PermissionDenied", err) + } + refusedUpdate("no role", setGlobalBinding(t, h, "viewer", harness.Member("bob"))) + refusedUpdate("viewer", setGlobalBinding(t, h, "viewer", harness.Member("alice"))) + policy := setGlobalBinding(t, h, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "UpdateGlobalAccessPolicy holding owner", codes.OK, func() error { return update(policy) }) +} + +// A principal granted the viewer role by the global access policy eventually +// gets an atespace that has no access policy of its own (OK). After the +// admin updates the global policy to no longer name the principal, getting +// the atespace eventually fails with PERMISSION_DENIED. +func TestUpdateGlobalAccessPolicy_RevokesInheritedAccess(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: as}) + return err + } + setGlobalBinding(t, h, "viewer", harness.Member("alice")) + eventuallyAllowed(t, h, "GetAtespace holding the global viewer role", codes.OK, get) + + setGlobalBinding(t, h, "viewer", harness.Member("bob")) + h.Eventually("GetAtespace to be denied once the global policy no longer names the principal", func() bool { + return status.Code(get()) == codes.PermissionDenied + }) +} diff --git a/cmd/ateapi/internal/functionaltest/actors_test.go b/cmd/ateapi/internal/functionaltest/actors_test.go new file mode 100644 index 0000000000..07117aa81d --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/actors_test.go @@ -0,0 +1,3772 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/json" + "slices" + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" + "go.ate.dev/substrate/internal/actoridjwt" + "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/internal/proto/ateletpb" + "go.ate.dev/substrate/internal/resources" +) + +// certificateSigningRequest is a valid CSR, for minting certificates. +func certificateSigningRequest(t *testing.T) []byte { + t.Helper() + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatalf("generating a key: %v", err) + } + csr, err := x509.CreateCertificateRequest(rand.Reader, &x509.CertificateRequest{Subject: pkix.Name{CommonName: "actor"}}, key) + if err != nil { + t.Fatalf("creating a CSR: %v", err) + } + return csr +} + +// resumingActor creates an actor from tmpl and leaves it RESUMING on w: its +// Restore fails with UNAVAILABLE, which ate-api leaves for a retry. +func resumingActor(t *testing.T, h *harness.Harness, as string, tmpl *ateapi.ActorTemplate, w *harness.Worker) *ateapi.Actor { + t.Helper() + actor := h.NewActor(as, tmpl) + w.Node.Atelet.On(harness.AteletRestore).FailNext(harness.ErrUnavailable) + if _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: harness.ActorRef(actor)}); err == nil { + t.Fatal("ResumeActor succeeded despite an unavailable atelet") + } + resuming := h.GetActor(harness.ActorRef(actor)) + if got := resuming.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RESUMING { + t.Fatalf("actor is %v after an unavailable atelet, want RESUMING", got) + } + return resuming +} + +// workerAssignment is the assignment ate-api records on an actor placed on w. +func workerAssignment(w *harness.Worker) *ateapi.WorkerAssignment { + return &ateapi.WorkerAssignment{ + Worker: w.Ref(), + WorkerNamespace: w.Namespace, + WorkerPool: w.Pool.Name, + WorkerPod: w.Pod, + WorkerPodUid: w.Name, + WorkerPodIps: []string{w.IP}, + NodeName: w.Node.Name, + WorkerEpoch: w.Epoch, + SandboxRuntime: harness.SandboxRuntime(), + } +} + +// actorSnapshot is the snapshot a suspend of actor records on node, given the +// UUID ate-api picked for it. +func actorSnapshot(actor *ateapi.Actor, uuid string, generation int32, node string, state ateapi.SnapshotStorageState) *ateapi.Snapshot { + return &ateapi.Snapshot{ + Uuid: uuid, + Generation: generation, + Owner: ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR, + Fidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + ActorTemplateUid: actor.GetStatus().GetSnapshots()[0].GetActorTemplateUid(), + Locality: node, + DurableSnapshot: &ateapi.SnapshotStorage{ + State: state, + Object: &ateapi.ObjectSnapshot{SnapshotUri: snapshotURI(actor, uuid)}, + }, + SandboxRuntime: harness.SandboxRuntime(), + } +} + +// snapshotURI is where ate-api stores actor's snapshot uuid. +func snapshotURI(actor *ateapi.Actor, uuid string) string { + return harness.StorageLocation + "/atespaces/" + actor.GetMetadata().GetAtespace() + "/actors/" + actor.GetMetadata().GetUid() + "/snapshots/" + uuid +} + +// assertRestoreOf checks that req restores snapshot from its durable copy. +func assertRestoreOf(t *testing.T, req *ateletpb.RestoreRequest, snapshot *ateapi.Snapshot) { + t.Helper() + if got, want := req.GetSnapshot().GetSnapshotUuid(), snapshot.GetUuid(); got != want { + t.Errorf("Restore snapshot = %q, want %q", got, want) + } + if got, want := req.GetSnapshot().GetObject().GetSnapshotUri(), snapshot.GetDurableSnapshot().GetObject().GetSnapshotUri(); got != want { + t.Errorf("Restore snapshot URI = %q, want %q", got, want) + } +} + +// Creates an actor, sending output-only metadata and status, and verifies that +// the whole resource has the expected shape: ate-api ignores what was sent and +// assigns its own. +func TestCreateActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + golden, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: tmpl.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag()}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + templateRef := &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()} + goldenSnapshot := mutated(golden.GetStatus().GetSnapshot(), func(s *ateapi.Snapshot) { + s.ActorTemplateUid = tmpl.GetMetadata().GetUid() + }) + + in := &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: templateRef, + } + // The caller sends output-only fields, which ate-api ignores. + setOutputOnlyMetadata(in.Metadata) + in.Status = &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_RUNNING, AssignedNode: "node-a"} + created, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: in}) + if err != nil { + t.Fatalf("CreateActor: %v", err) + } + want := &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: templateRef, + Status: &ateapi.ActorStatus{ + State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, + Snapshots: []*ateapi.Snapshot{goldenSnapshot}, + LastAssignedGeneration: goldenSnapshot.GetGeneration(), + }, + } + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created actor (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) +} + +// Creating an actor with the name of an existing one fails with +// ALREADY_EXISTS. +func TestCreateActor_AlreadyExists(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + templateRef := &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()} + created, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: templateRef, + }}) + if err != nil { + t.Fatalf("CreateActor: %v", err) + } + + _, err = h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: templateRef, + }}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateActor of an existing name = %v, want AlreadyExists", err) + } + got, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}}) + if err != nil { + t.Fatalf("GetActor: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestCreateActor_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + + _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "Not_A_Valid_Name"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + }}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateActor with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.metadata.name: Invalid value") { + t.Errorf("CreateActor error %q does not start with %q", msg, "actor.metadata.name: Invalid value") + } + listed, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actors after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor that references an actor template that doesn't exist +// fails with FAILED_PRECONDITION. +func TestCreateActor_TemplateNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-missing"}, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor with a missing template = %v, want FailedPrecondition", err) + } + listed, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actors after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor with an external volume whose storage class doesn't +// exist fails with FAILED_PRECONDITION. +func TestCreateActor_StorageClassNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + if _, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: &ateapi.ActorTemplate{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tmpl-a"}, + Containers: []*ateapi.Container{{ + Name: "main", + Image: harness.Image, + Command: []string{"/main"}, + VolumeMounts: []*ateapi.VolumeMount{{Name: "data", MountPath: "/data"}}, + }}, + Volumes: []*ateapi.Volume{{ + Name: "data", + External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ + StorageClassName: "storage-class-missing", + CapacityBytes: 1 << 30, + }}, + }}, + WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"pool": "pool1"}}, + Resources: &ateapi.ResourceRequirements{Limits: templateResources()}, + }}); err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + + _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"}, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor with a missing storage class = %v, want FailedPrecondition", err) + } + listed, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actors after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor in an atespace that doesn't exist fails with +// FAILED_PRECONDITION. +func TestCreateActor_AtespaceNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + + _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: "team-missing", Name: "actor-a"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor in a missing atespace = %v, want FailedPrecondition", err) + } + listed, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actors after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor that references a tag that doesn't exist fails with +// FAILED_PRECONDITION. +func TestCreateActor_TagNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + + _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + SourceTag: &ateapi.ObjectRef{Atespace: as, Name: "tag-missing"}, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor with a missing source tag = %v, want FailedPrecondition", err) + } + listed, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actors after a refused create (-want +got):\n%s", diff) + } +} + +// Getting an existing actor returns exactly the resource CreateActor +// returned. +func TestGetActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + + got, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: harness.ActorRef(actor)}) + if err != nil { + t.Fatalf("GetActor: %v", err) + } + if diff := cmp.Diff(actor, got, protocmp.Transform()); diff != "" { + t.Errorf("GetActor (-created +got):\n%s", diff) + } +} + +// Getting an actor that doesn't exist fails with NOT_FOUND. +func TestGetActor_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetActor of a missing actor = %v, want NotFound", err) + } +} + +// Getting an actor with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestGetActor_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("GetActor with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.name: Invalid value") { + t.Errorf("GetActor error %q does not start with %q", msg, "actor.name: Invalid value") + } +} + +// Creates N actors in one atespace and one in another, then lists the first +// atespace with pages smaller than N. The pages together hold exactly its N +// actors. +func TestListActors(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + other := h.CreateAtespace("team-b") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + otherTmpl := h.NewTemplate(other, pool) + const n, pageSize = 5, 2 + var created []*ateapi.Actor + for range n { + created = append(created, h.NewActor(as, tmpl)) + } + h.NewActor(other, otherTmpl) + + var listed []*ateapi.Actor + req := &ateapi.ListActorsRequest{Atespace: as, Options: &ateapi.ListOptions{PageSize: pageSize}} + for pages := 1; ; pages++ { + if pages > n { + t.Fatalf("listing took more than %d pages", n) + } + resp, err := h.Control.ListActors(t.Context(), req) + if err != nil { + t.Fatalf("ListActors page %d: %v", pages, err) + } + if got := len(resp.GetActors()); got > pageSize { + t.Errorf("page %d holds %d actors, want at most %d", pages, got, pageSize) + } + listed = append(listed, resp.GetActors()...) + if resp.GetNextPageToken() == "" { + break + } + req.Options.PageToken = resp.GetNextPageToken() + } + byName := cmpopts.SortSlices(func(a, b *ateapi.Actor) bool { return a.GetMetadata().GetName() < b.GetMetadata().GetName() }) + if diff := cmp.Diff(created, listed, protocmp.Transform(), byName); diff != "" { + t.Errorf("listed actors (-want +got):\n%s", diff) + } +} + +// Listing actors with a negative page size fails with INVALID_ARGUMENT and +// the error names the invalid field. +func TestListActors_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Options: &ateapi.ListOptions{PageSize: -1}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListActors with a negative page size = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "options.page_size: Invalid value") { + t.Errorf("ListActors error %q does not start with %q", msg, "options.page_size: Invalid value") + } +} + +// Listing actors with a malformed page token fails with INVALID_ARGUMENT. +func TestListActors_InvalidPageToken(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Options: &ateapi.ListOptions{PageToken: "not-a-real-token"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListActors with a malformed page token = %v, want InvalidArgument", err) + } +} + +// Listing actors in an atespace that doesn't exist succeeds with an empty +// list. +func TestListActors_AtespaceNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + listed, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: "team-missing"}) + if err != nil { + t.Fatalf("ListActors in a missing atespace: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("ListActors in a missing atespace (-want +got):\n%s", diff) + } +} + +// Updates the worker selector of an existing actor, sending it as read with a +// changed status. The result, and a later Get, is the resource as read with +// the worker selector changed and a higher version: ate-api ignores the status. +func TestUpdateActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + + before := h.GetActor(ref) + toUpdate := mutated(before, func(a *ateapi.Actor) { + a.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "1"}} + // The caller sends a changed status, which ate-api ignores. + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + }) + updated, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: toUpdate}) + if err != nil { + t.Fatalf("UpdateActor: %v", err) + } + + want := mutated(before, func(a *ateapi.Actor) { + a.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "1"}} + }) + if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("updated actor (-want +got):\n%s", diff) + } + if got, was := updated.GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("updated actor has version %d, want higher than %d", got, was) + } + if diff := cmp.Diff(updated, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("GetActor after update (-updated +got):\n%s", diff) + } +} + +// Updating an actor that doesn't exist fails with NOT_FOUND. +func TestUpdateActor_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + + _, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-missing", Uid: foreignUID, Version: 1}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + }}) + if status.Code(err) != codes.NotFound { + t.Errorf("UpdateActor of a missing actor = %v, want NotFound", err) + } +} + +// Updating an actor with the wrong UID fails with ABORTED, and with the +// right UID but the wrong version fails with ABORTED; both leave it +// unchanged. Updating it without a UID or a version fails with +// INVALID_ARGUMENT. +func TestUpdateActor_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + update := func(uid string, version int64) error { + toUpdate := mutated(before, func(a *ateapi.Actor) { + a.Metadata.Uid, a.Metadata.Version = uid, version + a.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "1"}} + }) + _, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: toUpdate}) + return err + } + + if err := update(foreignUID, before.GetMetadata().GetVersion()); status.Code(err) != codes.Aborted { + t.Errorf("UpdateActor with the wrong uid = %v, want Aborted", err) + } + if err := update(before.GetMetadata().GetUid(), before.GetMetadata().GetVersion()+1); status.Code(err) != codes.Aborted { + t.Errorf("UpdateActor with the right uid and the wrong version = %v, want Aborted", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after refused updates (-want +got):\n%s", diff) + } + if err := update("", 0); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateActor without a uid or version = %v, want InvalidArgument", err) + } +} + +// Updating an actor with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestUpdateActor_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + + _, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "Not_A_Valid_Name", Uid: foreignUID, Version: 1}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + }}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateActor with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.metadata.name: Invalid value") { + t.Errorf("UpdateActor error %q does not start with %q", msg, "actor.metadata.name: Invalid value") + } +} + +// Deletes a suspended actor. The response is the actor as read before the +// delete, marked DELETING, and a later Get fails with NOT_FOUND. +func TestDeleteActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.SuspendedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + + deleted, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("DeleteActor: %v", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_DELETING + }) + if diff := cmp.Diff(want, deleted, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreDeleteTime); diff != "" { + t.Errorf("DeleteActor response (-want +got):\n%s", diff) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Error("DeleteActor response has no delete_time") + } + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor after delete = %v, want NotFound", err) + } +} + +// Deleting an actor that doesn't exist fails with NOT_FOUND. +func TestDeleteActor_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("DeleteActor of a missing actor = %v, want NotFound", err) + } +} + +// Deleting an actor with the wrong UID, with only the wrong version, or with +// the right UID but the wrong version fails with ABORTED and leaves it +// unchanged. With the right UID and version the delete succeeds. +func TestDeleteActor_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + uid, version := before.GetMetadata().GetUid(), before.GetMetadata().GetVersion() + + _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref, Options: &ateapi.DeleteOptions{Uid: foreignUID}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActor with the wrong uid = %v, want Aborted", err) + } + _, err = h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref, Options: &ateapi.DeleteOptions{Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActor with only the wrong version = %v, want Aborted", err) + } + _, err = h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActor with the right uid and the wrong version = %v, want Aborted", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after refused deletes (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version}}); err != nil { + t.Errorf("DeleteActor with the right uid and version: %v", err) + } +} + +// Deleting an actor with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestDeleteActor_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("DeleteActor with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.name: Invalid value") { + t.Errorf("DeleteActor error %q does not start with %q", msg, "actor.name: Invalid value") + } +} + +// Deletes a running actor that holds a snapshot of its own: it was suspended +// once and resumed again. The response is the actor as read before the delete, +// marked DELETING, with no worker assignment, no assigned node, and its +// snapshot no longer local to the node. A later Get fails with NOT_FOUND. The +// atelet received exactly one Terminate and runs no sandbox. The worker is left +// with no allocation and no assignments. Object storage no longer holds the +// actor's snapshot. The resume retries while ate-api catches up. +func TestDeleteActor_Running(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + suspended := h.SuspendedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(suspended) + objectsWithoutActor := slices.DeleteFunc(h.ObjectStore.Objects(), func(o string) bool { + return strings.Contains(o, "/actors/"+suspended.GetMetadata().GetUid()+"/") + }) + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor: %v", err) + } + + before := h.GetActor(ref) + workerBefore := h.GetWorker(w) + rec := node.Atelet.RecordCalls() + deleted, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("DeleteActor: %v", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_DELETING + a.Status.WorkerAssignment = nil + a.Status.AssignedNode = "" + }) + for _, snap := range want.Status.Snapshots { + snap.Locality = "" + } + if diff := cmp.Diff(want, deleted, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreDeleteTime); diff != "" { + t.Errorf("DeleteActor response (-want +got):\n%s", diff) + } + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor after delete = %v, want NotFound", err) + } + assertCalls(t, rec, harness.AteletTerminate) + if diff := cmp.Diff([]harness.Sandbox{}, node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after delete (-want +got):\n%s", diff) + } + wantWorker := mutated(workerBefore, func(wk *ateapi.Worker) { + wk.Status.Allocated = nil + }) + if diff := cmp.Diff(wantWorker, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after delete (-want +got):\n%s", diff) + } + assignments, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("ListWorkerActorAssignments: %v", err) + } + if diff := cmp.Diff(&ateapi.ListWorkerActorAssignmentsResponse{}, assignments, protocmp.Transform()); diff != "" { + t.Errorf("worker assignments after delete (-want +got):\n%s", diff) + } + if diff := cmp.Diff(objectsWithoutActor, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after delete (-want +got):\n%s", diff) + } +} + +// Deletes a crashed actor. The response is the actor as read before the +// delete, marked DELETING, and a later Get fails with NOT_FOUND. The atelet +// received exactly one Terminate, naming no worker. +func TestDeleteActor_Crashed(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + ref := harness.ActorRef(h.CrashedActor(as, h.NewTemplate(as, pool))) + before := h.GetActor(ref) + rec := node.Atelet.RecordCalls() + + deleted, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("DeleteActor: %v", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_DELETING + }) + if diff := cmp.Diff(want, deleted, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreDeleteTime); diff != "" { + t.Errorf("DeleteActor response (-want +got):\n%s", diff) + } + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor after delete = %v, want NotFound", err) + } + if got := onlyCall[*ateletpb.TerminateRequest](t, rec).GetWorkerPodUid(); got != "" { + t.Errorf("Terminate names worker %q, want none", got) + } +} + +// Deletes the source actor of a tag. The request succeeds (OK), and object +// storage no longer holds the actor's snapshot but still holds the tag's. +func TestDeleteActor_SourceOfTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.SuspendedActor(as, h.NewTemplate(as, pool)) + source := harness.ActorRef(actor) + if _, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + }}); err != nil { + t.Fatalf("CreateTag: %v", err) + } + objectsWithoutActor := slices.DeleteFunc(h.ObjectStore.Objects(), func(o string) bool { + return strings.Contains(o, "/actors/"+actor.GetMetadata().GetUid()+"/") + }) + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: source}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + if diff := cmp.Diff(objectsWithoutActor, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after deleting the source actor (-want +got):\n%s", diff) + } +} + +// Deletes a running actor while the atelet fails the Terminate. The request +// fails with INTERNAL, and the actor becomes DELETING on its worker. Resuming +// it fails with FAILED_PRECONDITION and leaves it unchanged. Deleting it again +// succeeds (OK), and a later Get fails with NOT_FOUND. +func TestDeleteActor_TerminateFails(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + node.Atelet.On(harness.AteletTerminate).FailNext(harness.ErrSandboxFailed) + + _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("DeleteActor with a failing Terminate = %v, want Internal", err) + } + deleting := h.GetActor(ref) + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_DELETING + }) + if diff := cmp.Diff(want, deleting, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreDeleteTime); diff != "" { + t.Errorf("actor after a failed Terminate (-want +got):\n%s", diff) + } + + _, err = h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("ResumeActor of the DELETING actor = %v, want FailedPrecondition", err) + } + if diff := cmp.Diff(deleting, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor retry: %v", err) + } + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor after delete = %v, want NotFound", err) + } +} + +// Deletes an actor with an external volume left SUSPENDING by a suspend whose +// ControllerUnpublishVolume failed. The request succeeds (OK), a later Get +// fails with NOT_FOUND, and the volume plugin holds no volumes. +func TestDeleteActor_AfterVolumeDetachFails(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + ref := harness.ActorRef(h.RunningActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data")))) + h.Volumes.On(harness.VolumeUnpublish).FailNext(harness.ErrUnavailable) + if _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}); status.Code(err) != codes.Internal { + t.Fatalf("SuspendActor with a failing ControllerUnpublishVolume = %v, want Internal", err) + } + if got := h.GetActor(ref).GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDING { + t.Fatalf("actor after a failed ControllerUnpublishVolume is %v, want SUSPENDING", got) + } + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor after delete = %v, want NotFound", err) + } + if diff := cmp.Diff([]harness.Volume{}, h.Volumes.List()); diff != "" { + t.Errorf("volumes after delete (-want +got):\n%s", diff) + } +} + +// Deletes a suspended actor with two external volumes while the volume plugin +// fails DeleteVolume for the first. The request fails with INTERNAL, and the +// actor becomes DELETING. The plugin still holds the first volume and has +// deleted the second. Deleting it again succeeds (OK), a later Get fails with +// NOT_FOUND, and the volume plugin holds no volumes. +// +// TODO: The request should fail with UNAVAILABLE when the volume plugin is +// unavailable, so callers retry it. +func TestDeleteActor_VolumeDeleteFails(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.SuspendedActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"), h.WithExternalVolume("logs", "/logs"))) + ref := harness.ActorRef(actor) + h.Volumes.On(harness.VolumeDelete).FailNext(harness.ErrUnavailable) + + _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("DeleteActor with a failing DeleteVolume = %v, want Internal", err) + } + want := mutated(actor, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_DELETING + }) + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreDeleteTime); diff != "" { + t.Errorf("actor after a failed DeleteVolume (-want +got):\n%s", diff) + } + dataVolume := "substrate-" + actor.GetMetadata().GetUid() + "-data" + wantVolumes := []harness.Volume{{ID: "vol-" + dataVolume, Name: dataVolume}} + if diff := cmp.Diff(wantVolumes, h.Volumes.List(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("volumes after a failed DeleteVolume (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor retry: %v", err) + } + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor after delete = %v, want NotFound", err) + } + if diff := cmp.Diff([]harness.Volume{}, h.Volumes.List()); diff != "" { + t.Errorf("volumes after delete (-want +got):\n%s", diff) + } +} + +// Deletes an actor with an external volume crashed by the removal of its +// worker. The request succeeds (OK): the atelet received exactly one +// Terminate, naming no worker, and the volume is detached from the node the +// actor was assigned to and deleted, so the volume plugin holds no volumes. +func TestDeleteActor_WorkerRemovedDetachesVolume(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + ref := harness.ActorRef(h.RunningActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data")))) + w.Remove() + if got := h.GetActor(ref).GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_CRASHED { + t.Fatalf("actor after its worker was removed is %v, want CRASHED", got) + } + + rec := node.Atelet.RecordCalls() + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + if got := onlyCall[*ateletpb.TerminateRequest](t, rec).GetWorkerPodUid(); got != "" { + t.Errorf("Terminate names worker %q, want none", got) + } + if diff := cmp.Diff([]harness.Volume{}, h.Volumes.List()); diff != "" { + t.Errorf("volumes after delete (-want +got):\n%s", diff) + } +} + +// Deletes an actor with an external volume crashed by a Restore the atelet +// failed after the volume was attached. The crashed actor stays assigned to +// the node. Deleting it succeeds (OK), and the volume plugin holds no volumes. +// The resume retries while ate-api catches up. +func TestDeleteActor_RestoreFailedDetachesVolume(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + ref := harness.ActorRef(h.NewActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data")))) + node.Atelet.On(harness.AteletRestore).FailNext(harness.ErrSandboxFailed) + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err == nil { + t.Fatal("ResumeActor succeeded despite a failing Restore") + } + if got := h.GetActor(ref).GetStatus(); got.GetState() != ateapi.ActorState_ACTOR_STATE_CRASHED || got.GetAssignedNode() != node.Name { + t.Fatalf("actor after a failed Restore is %v assigned to %q, want CRASHED assigned to %q", got.GetState(), got.GetAssignedNode(), node.Name) + } + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + if diff := cmp.Diff([]harness.Volume{}, h.Volumes.List()); diff != "" { + t.Errorf("volumes after delete (-want +got):\n%s", diff) + } +} + +// Resumes a new actor on a pool with one worker on node a, and an unrelated +// worker on node b. The response says it resumed and matches GetActor. The +// actor becomes RUNNING with a worker assignment to the node a worker and is +// otherwise unchanged. That worker's allocation goes to one actor, with one +// assignment for this actor. The node a atelet received exactly one Restore, +// from the template's golden snapshot, with an activation UID the worker +// assignment names, and runs exactly this actor's sandbox. Node b's atelet received no calls, and object storage is +// unchanged. The resume retries while ate-api catches up. +func TestResumeActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + nodeA := h.Node("a") + w := h.AddWorker(pool, nodeA) + nodeB := h.Node("b") + recB := nodeB.Atelet.RecordCalls() + other := h.AddWorker(h.CreateWorkerPool("pool2", nil), nodeB) + tmpl := h.NewTemplate(as, pool) + golden, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: tmpl.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag()}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + + actorBefore := h.GetActor(ref) + workerBefore := h.GetWorker(w) + otherBefore := h.GetWorker(other) + objectsBefore := h.ObjectStore.Objects() + rec := nodeA.Atelet.RecordCalls() + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("ResumeActor: %v", err) + } + + if !resp.GetResumed() { + t.Errorf("ResumeActor reported resumed = false, want true") + } + got := h.GetActor(ref) + if diff := cmp.Diff(got, resp.GetActor(), protocmp.Transform()); diff != "" { + t.Errorf("ResumeActor response against GetActor (-get +response):\n%s", diff) + } + restore := onlyCall[*ateletpb.RestoreRequest](t, rec) + wantActor := mutated(actorBefore, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment = workerAssignment(w) + a.Status.WorkerAssignment.ActorActivationUid = restore.GetActivationUid() + a.Status.AssignedNode = w.Node.Name + }) + if diff := cmp.Diff(wantActor, got, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } + + wantWorker := mutated(workerBefore, func(wk *ateapi.Worker) { + wk.Status.Allocated = &ateapi.WorkerResources{Actors: 1, CpuMillicores: harness.TemplateCPUMillicores, MemoryBytes: harness.TemplateMemoryBytes} + }) + if diff := cmp.Diff(wantWorker, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after resume (-want +got):\n%s", diff) + } + assignments, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("ListWorkerActorAssignments: %v", err) + } + wantAssignments := &ateapi.ListWorkerActorAssignmentsResponse{ActorAssignments: []*ateapi.ActorAssignment{{ + Metadata: &ateapi.ResourceMetadata{Name: actor.GetMetadata().GetUid()}, + Actor: ref, + ActorUid: actor.GetMetadata().GetUid(), + Resources: templateResources(), + }}} + if diff := cmp.Diff(wantAssignments, assignments, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("worker assignments after resume (-want +got):\n%s", diff) + } + if diff := cmp.Diff(otherBefore, h.GetWorker(other), protocmp.Transform()); diff != "" { + t.Errorf("unrelated worker after resume (-want +got):\n%s", diff) + } + + if restore.GetActivationUid() == "" { + t.Errorf("Restore carries no activation UID") + } + assertRestoreOf(t, restore, golden.GetStatus().GetSnapshot()) + wantSandboxes := []harness.Sandbox{{ + ActorUID: actor.GetMetadata().GetUid(), + Atespace: as, + ActorName: actor.GetMetadata().GetName(), + WorkerUID: w.Name, + }} + if diff := cmp.Diff(wantSandboxes, nodeA.Atelet.Sandboxes()); diff != "" { + t.Errorf("node a sandboxes after resume (-want +got):\n%s", diff) + } + assertCalls(t, recB) + if diff := cmp.Diff(objectsBefore, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after resume (-want +got):\n%s", diff) + } +} + +// Resuming an actor that doesn't exist fails with NOT_FOUND. +func TestResumeActor_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("ResumeActor of a missing actor = %v, want NotFound", err) + } +} + +// Resuming an actor with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestResumeActor_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ResumeActor with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.name: Invalid value") { + t.Errorf("ResumeActor error %q does not start with %q", msg, "actor.name: Invalid value") + } +} + +// Resumes a new actor while the atelet fails the Restore with INTERNAL. The +// request fails with INTERNAL, and the actor becomes CRASHED with no worker +// assignment, still assigned to the worker's node. Its status.crash is set: a +// message naming the atelet Restore and the atelet's error, and a crash time. +// It is otherwise unchanged. The worker is left with no allocation and no +// assignments, and the atelet runs no sandbox. The resume retries while +// ate-api catches up. +func TestResumeActor_RestoreFails(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + tmpl := h.NewTemplate(as, pool) + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + node.Atelet.On(harness.AteletRestore).FailNext(status.New(codes.Internal, "injected restore failure")) + + actorBefore := h.GetActor(ref) + workerBefore := h.GetWorker(w) + rec := node.Atelet.RecordCalls() + _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("ResumeActor with a failing Restore = %v, want Internal", err) + } + + wantActor := mutated(actorBefore, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.AssignedNode = node.Name + a.Status.Crash = &ateapi.ActorCrash{} + }) + ignoreCrashDetails := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time", "message") + crashed := h.GetActor(ref) + if diff := cmp.Diff(wantActor, crashed, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashDetails); diff != "" { + t.Errorf("actor after a failed Restore (-want +got):\n%s", diff) + } + checkCrashMessage(t, crashed, "atelet Restore", "injected restore failure") + if crashed.GetStatus().GetCrash().GetCrashTime() == nil { + t.Errorf("status.crash of the crashed actor has no crash time") + } + if diff := cmp.Diff(workerBefore, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after a failed Restore (-want +got):\n%s", diff) + } + assignments, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("ListWorkerActorAssignments: %v", err) + } + if diff := cmp.Diff(&ateapi.ListWorkerActorAssignmentsResponse{}, assignments, protocmp.Transform()); diff != "" { + t.Errorf("worker assignments after a failed Restore (-want +got):\n%s", diff) + } + assertCalls(t, rec, harness.AteletRestore) + if diff := cmp.Diff([]harness.Sandbox{}, node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after a failed Restore (-want +got):\n%s", diff) + } +} + +// Resumes a new actor while the atelet fails the Restore with UNAVAILABLE. +// The request fails with UNAVAILABLE, and the actor stays RESUMING with its +// worker assignment, so a later resume can retry. The worker keeps its +// allocation of one actor and its assignment for this actor, and the atelet +// runs no sandbox. +func TestResumeActor_RestoreUnavailable(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + tmpl := h.NewTemplate(as, pool) + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + node.Atelet.On(harness.AteletRestore).FailNext(harness.ErrUnavailable) + + actorBefore := h.GetActor(ref) + workerBefore := h.GetWorker(w) + rec := node.Atelet.RecordCalls() + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Unavailable { + t.Fatalf("ResumeActor with an unavailable atelet = %v, want Unavailable", err) + } + + wantActor := mutated(actorBefore, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RESUMING + a.Status.WorkerAssignment = workerAssignment(w) + // ate-api records the worker epoch once a Restore succeeds. + a.Status.WorkerAssignment.WorkerEpoch = 0 + a.Status.AssignedNode = w.Node.Name + }) + if diff := cmp.Diff(wantActor, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("actor after an unavailable atelet (-want +got):\n%s", diff) + } + wantWorker := mutated(workerBefore, func(wk *ateapi.Worker) { + wk.Status.Allocated = &ateapi.WorkerResources{Actors: 1, CpuMillicores: harness.TemplateCPUMillicores, MemoryBytes: harness.TemplateMemoryBytes} + }) + if diff := cmp.Diff(wantWorker, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after an unavailable atelet (-want +got):\n%s", diff) + } + assignments, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("ListWorkerActorAssignments: %v", err) + } + wantAssignments := &ateapi.ListWorkerActorAssignmentsResponse{ActorAssignments: []*ateapi.ActorAssignment{{ + Metadata: &ateapi.ResourceMetadata{Name: actor.GetMetadata().GetUid()}, + Actor: ref, + ActorUid: actor.GetMetadata().GetUid(), + Resources: templateResources(), + }}} + if diff := cmp.Diff(wantAssignments, assignments, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("worker assignments after an unavailable atelet (-want +got):\n%s", diff) + } + assertCalls(t, rec, harness.AteletRestore) + if diff := cmp.Diff([]harness.Sandbox{}, node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after an unavailable atelet (-want +got):\n%s", diff) + } +} + +// Resuming a crashed actor fails with FAILED_PRECONDITION and leaves the +// actor unchanged. +func TestResumeActor_WrongState(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + crashed := h.CrashedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(crashed) + before := h.GetActor(ref) + + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("ResumeActor of a crashed actor = %v, want FailedPrecondition", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } +} + +// Resuming a running actor succeeds (OK) and reports that it did not resume +// it. The actor is unchanged and the atelet receives no call. +func TestResumeActor_AlreadyRunning(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + running := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(running) + before := h.GetActor(ref) + rec := node.Atelet.RecordCalls() + + resp, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.OK { + t.Fatalf("ResumeActor of a running actor = %v, want OK", err) + } + if resp.GetResumed() { + t.Error("ResumeActor of a running actor reported resumed = true, want false") + } + if diff := cmp.Diff(before, resp.GetActor(), protocmp.Transform()); diff != "" { + t.Errorf("ResumeActor response (-want +got):\n%s", diff) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after resuming it while running (-want +got):\n%s", diff) + } + assertCalls(t, rec) +} + +// Resumes an actor that was suspended. The request succeeds (OK), the actor +// becomes RUNNING, and the atelet receives a Restore of the actor's own +// external snapshot, not the golden one. The resume retries while ate-api +// catches up. +func TestResumeActor_FromSuspended(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + suspended := h.SuspendedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(suspended) + before := h.GetActor(ref) + rec := node.Atelet.RecordCalls() + + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.OK { + t.Fatalf("ResumeActor of a suspended actor = %v, want OK", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment = workerAssignment(w) + a.Status.AssignedNode = w.Node.Name + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } + restore := onlyCall[*ateletpb.RestoreRequest](t, rec) + own := latestSnapshot(t, before) + if own.GetOwner() != ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR { + t.Fatalf("suspended actor's latest snapshot is owned by %v, want the actor", own.GetOwner()) + } + assertRestoreOf(t, restore, own) +} + +// Resumes an actor suspended asynchronously, whose latest snapshot is local to +// node a and not uploaded, on a pool with a worker on node a and one on node +// b. The request succeeds (OK). The actor becomes RUNNING on the node a worker, +// and is otherwise unchanged. The node a atelet received exactly one Restore, +// of the local snapshot, and node b's atelet received no calls. Object storage +// is unchanged. +// The resume retries while ate-api catches up. +func TestResumeActor_FromAsyncSuspended(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + nodeA := h.Node("a") + w := h.AddWorker(pool, nodeA) + tmpl := h.NewTemplate(as, pool) + actor := h.AsyncSuspendedActor(as, tmpl) + ref := harness.ActorRef(actor) + nodeB := h.Node("b") + recB := nodeB.Atelet.RecordCalls() + h.AddWorker(pool, nodeB) + + before := h.GetActor(ref) + objectsBefore := h.ObjectStore.Objects() + rec := nodeA.Atelet.RecordCalls() + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("ResumeActor: %v", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment = workerAssignment(w) + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } + restore := onlyCall[*ateletpb.RestoreRequest](t, rec) + if got, want := restore.GetSnapshot().GetSnapshotUuid(), latestSnapshot(t, before).GetUuid(); got != want { + t.Errorf("Restore snapshot = %q, want the local snapshot %q", got, want) + } + assertCalls(t, recB) + if diff := cmp.Diff(objectsBefore, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after resume (-want +got):\n%s", diff) + } +} + +// Resumes an actor suspended asynchronously while the atelet fails the +// Restore of its local snapshot. The request fails with INTERNAL, and the +// actor becomes CRASHED with no worker assignment, still assigned to its node. +// Its status.crash names the atelet Restore and the atelet's error. The worker +// is left with no allocation. +// The resume retries while ate-api catches up. +func TestResumeActor_LocalRestoreFails(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + ref := harness.ActorRef(h.AsyncSuspendedActor(as, h.NewTemplate(as, pool))) + before := h.GetActor(ref) + workerBefore := h.GetWorker(w) + node.Atelet.On(harness.AteletRestore).FailNext(harness.ErrSandboxFailed) + + _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("ResumeActor with a failing Restore = %v, want Internal", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.Crash = &ateapi.ActorCrash{} + }) + ignoreCrashDetails := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time", "message") + crashed := h.GetActor(ref) + if diff := cmp.Diff(want, crashed, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashDetails); diff != "" { + t.Errorf("actor after a failed Restore (-want +got):\n%s", diff) + } + checkCrashMessage(t, crashed, "atelet Restore", harness.ErrSandboxFailed.Message()) + if diff := cmp.Diff(workerBefore, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after a failed Restore (-want +got):\n%s", diff) + } +} + +// Resumes an actor suspended asynchronously on node a after another actor +// took node a's only worker, while a worker on node b has room. The request +// succeeds (OK). The node a atelet received exactly one DetachActor, which +// uploaded the local snapshot and dropped it from the node. The actor becomes +// RUNNING on the node b worker, whose atelet received exactly one Restore of +// that snapshot. Object storage gains the snapshot's objects. The resume +// retries while ate-api catches up. +func TestResumeActor_DetachesFromFullNode(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + nodeA := h.Node("a") + h.AddWorker(pool, nodeA) + tmpl := h.NewTemplate(as, pool) + actor := h.AsyncSuspendedActor(as, tmpl) + ref := harness.ActorRef(actor) + h.RunningActor(as, tmpl) + nodeB := h.Node("b") + recB := nodeB.Atelet.RecordCalls() + wB := h.AddWorker(pool, nodeB) + + before := h.GetActor(ref) + local := latestSnapshot(t, before) + objectsBefore := h.ObjectStore.Objects() + recA := nodeA.Atelet.RecordCalls() + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("ResumeActor: %v", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.AssignedNode = nodeB.Name + a.Status.WorkerAssignment = workerAssignment(wB) + uploaded := a.Status.Snapshots[len(a.Status.Snapshots)-1] + uploaded.Locality = "" + uploaded.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } + assertCalls(t, recA, harness.AteletDetachActor) + if got := nodeA.Atelet.LocalSnapshot(actor.GetMetadata().GetUid()); got != "" { + t.Errorf("local snapshot on node a = %q, want none", got) + } + restore := onlyCall[*ateletpb.RestoreRequest](t, recB) + if got := restore.GetSnapshot().GetSnapshotUuid(); got != local.GetUuid() { + t.Errorf("Restore snapshot = %q, want %q", got, local.GetUuid()) + } + wantObjects := append(slices.Clone(objectsBefore), snapshotObjects(local.GetDurableSnapshot().GetObject().GetSnapshotUri())...) + if diff := cmp.Diff(wantObjects, h.ObjectStore.Objects(), cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" { + t.Errorf("object storage after resume (-want +got):\n%s", diff) + } +} + +// Resuming an actor while the pool's only worker hosts another actor fails +// with RESOURCE_EXHAUSTED, leaves the actor unchanged, and makes no atelet +// call. After the other actor is suspended, resuming succeeds (OK) on that +// worker. The resume after the suspend retries while ate-api catches up. +func TestResumeActor_WorkerFull(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + tmpl := h.NewTemplate(as, pool) + other := h.RunningActor(as, tmpl) + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + + before := h.GetActor(ref) + rec := node.Atelet.RecordCalls() + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.ResourceExhausted { + t.Fatalf("ResumeActor with the only worker full = %v, want ResourceExhausted", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } + assertCalls(t, rec) + + if _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: harness.ActorRef(other)}); err != nil { + t.Fatalf("SuspendActor: %v", err) + } + before = h.GetActor(ref) + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.OK { + t.Fatalf("ResumeActor after freeing the worker = %v, want OK", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment = workerAssignment(w) + a.Status.AssignedNode = w.Node.Name + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } +} + +// Resuming an actor while the pool's only worker is draining fails with +// RESOURCE_EXHAUSTED, leaves the actor and the draining worker unchanged, +// and makes no atelet call. After a new worker is added, resuming succeeds +// (OK) on the new worker. The resume after the new worker is added retries +// while ate-api catches up. +func TestResumeActor_WorkerDraining(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + tmpl := h.NewTemplate(as, pool) + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + w.Drain() + + before := h.GetActor(ref) + drainingBefore := h.GetWorker(w) + rec := node.Atelet.RecordCalls() + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.ResourceExhausted { + t.Fatalf("ResumeActor with the only worker draining = %v, want ResourceExhausted", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } + if diff := cmp.Diff(drainingBefore, h.GetWorker(w), protocmp.Transform()); diff != "" { + t.Errorf("draining worker after a refused resume (-want +got):\n%s", diff) + } + assertCalls(t, rec) + + fresh := h.AddWorker(pool, node) + before = h.GetActor(ref) + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.OK { + t.Fatalf("ResumeActor after adding a worker = %v, want OK", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment = workerAssignment(fresh) + a.Status.AssignedNode = fresh.Node.Name + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } +} + +// Resuming an actor after the pool's only worker was removed fails with +// RESOURCE_EXHAUSTED, leaves the actor unchanged, and makes no atelet call. +// After a new worker is added, resuming succeeds (OK) on the new worker. The +// resume after the new worker is added retries while ate-api catches up. +func TestResumeActor_WorkerRemoved(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + tmpl := h.NewTemplate(as, pool) + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + w.Remove() + + before := h.GetActor(ref) + rec := node.Atelet.RecordCalls() + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.ResourceExhausted { + t.Fatalf("ResumeActor with the only worker removed = %v, want ResourceExhausted", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } + assertCalls(t, rec) + + fresh := h.AddWorker(pool, node) + before = h.GetActor(ref) + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.OK { + t.Fatalf("ResumeActor after adding a worker = %v, want OK", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment = workerAssignment(fresh) + a.Status.AssignedNode = fresh.Node.Name + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } +} + +// An actor left RESUMING by a Restore that failed with UNAVAILABLE is +// resumed again. The request succeeds (OK), the actor becomes RUNNING on the +// same worker, and that worker still holds exactly one assignment, for this +// actor. Resuming it again retries while ate-api catches up. +func TestResumeActor_Retry(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + w := h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + before := resumingActor(t, h, as, tmpl, w) + ref := harness.ActorRef(before) + workerBefore := h.GetWorker(w) + + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.OK { + t.Fatalf("ResumeActor retry = %v, want OK", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment.WorkerEpoch = w.Epoch + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } + if diff := cmp.Diff(workerBefore, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after the retry (-want +got):\n%s", diff) + } + assignments, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("ListWorkerActorAssignments: %v", err) + } + wantAssignments := &ateapi.ListWorkerActorAssignmentsResponse{ActorAssignments: []*ateapi.ActorAssignment{{ + Metadata: &ateapi.ResourceMetadata{Name: before.GetMetadata().GetUid()}, + Actor: ref, + ActorUid: before.GetMetadata().GetUid(), + Resources: templateResources(), + }}} + if diff := cmp.Diff(wantAssignments, assignments, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("worker assignments after the retry (-want +got):\n%s", diff) + } +} + +// An actor left RESUMING by a Restore that failed with UNAVAILABLE has its +// worker drained, and is resumed again. The request fails with ABORTED, and +// the actor becomes CRASHED with no worker assignment and a crash message +// saying its worker is draining. +// +// TODO: The request should fail with INTERNAL, as other resumes that crash +// the actor do. ABORTED makes callers like the atenet router retry a resume +// that cannot succeed. +func TestResumeActor_RetryWorkerDrained(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + w := h.AddWorker(pool, h.Node("a")) + before := resumingActor(t, h, as, h.NewTemplate(as, pool), w) + ref := harness.ActorRef(before) + w.Drain() + + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Aborted { + t.Errorf("ResumeActor retry on a draining worker = %v, want Aborted", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.WorkerAssignment = nil + a.Status.Crash = &ateapi.ActorCrash{Message: "resume failed: assigned worker is draining"} + }) + ignoreCrashTime := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time") + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashTime); diff != "" { + t.Errorf("actor after a retry on a draining worker (-want +got):\n%s", diff) + } +} + +// An actor left RESUMING by a Restore that failed with UNAVAILABLE has its +// worker removed. Removing the worker crashes the actor, with no worker +// assignment and a crash message saying the worker pod went away, and +// resuming it again fails with FAILED_PRECONDITION. +func TestResumeActor_RetryWorkerRemoved(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + w := h.AddWorker(pool, h.Node("a")) + before := resumingActor(t, h, as, h.NewTemplate(as, pool), w) + ref := harness.ActorRef(before) + w.Remove() + + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.WorkerAssignment = nil + a.Status.Crash = &ateapi.ActorCrash{Message: "resume failed: worker pod went away while hosting the actor"} + }) + ignoreCrashTime := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time") + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashTime); diff != "" { + t.Errorf("actor after its worker was removed (-want +got):\n%s", diff) + } + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("ResumeActor of the crashed actor = %v, want FailedPrecondition", err) + } +} + +// An actor left RESUMING by a Restore that failed with UNAVAILABLE has its +// worker relabeled so it no longer matches the template, and is resumed +// again. The request fails with ABORTED, the actor becomes CRASHED with no +// worker assignment and a crash message saying the worker no longer +// satisfies its placement constraints, and the worker is released. +// +// TODO: The request should fail with INTERNAL, as other resumes that crash +// the actor do. ABORTED makes callers like the atenet router retry a resume +// that cannot succeed. +func TestResumeActor_RetryWorkerIneligible(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + w := h.AddWorker(pool, h.Node("a")) + before := resumingActor(t, h, as, h.NewTemplate(as, pool), w) + ref := harness.ActorRef(before) + relabeled := mutated(h.GetWorker(w), func(wk *ateapi.Worker) { + wk.Labels = map[string]string{"pool": "other"} + }) + relabeled, err := h.Control.UpdateWorker(t.Context(), &ateapi.UpdateWorkerRequest{Worker: relabeled}) + if err != nil { + t.Fatalf("UpdateWorker: %v", err) + } + + _, err = h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Aborted { + t.Errorf("ResumeActor retry on an ineligible worker = %v, want Aborted", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.WorkerAssignment = nil + a.Status.Crash = &ateapi.ActorCrash{Message: "resume failed: assigned worker no longer satisfies the actor's placement constraints"} + }) + ignoreCrashTime := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time") + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashTime); diff != "" { + t.Errorf("actor after a retry on an ineligible worker (-want +got):\n%s", diff) + } + wantWorker := mutated(relabeled, func(wk *ateapi.Worker) { + wk.Status.Allocated = nil + }) + if diff := cmp.Diff(wantWorker, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after a retry on it while ineligible (-want +got):\n%s", diff) + } +} + +// Resumes an actor whose template has an external volume. The request +// succeeds (OK), the actor's volume is CREATED, and the volume plugin holds +// that volume attached to the worker's node. The atelet received exactly one +// Restore, carrying the publish context the plugin returned for that node. +// The resume retries while ate-api catches up. +func TestResumeActor_WithVolume(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + actor := h.NewActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"))) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + rec := node.Atelet.RecordCalls() + + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.OK { + t.Fatalf("ResumeActor = %v, want OK", err) + } + volumes := onlyCall[*ateletpb.RestoreRequest](t, rec).GetSpec().GetVolumes() + if len(volumes) != 1 { + t.Fatalf("Restore volumes = %v, want exactly one", volumes) + } + if diff := cmp.Diff(map[string]string{"node": node.Name}, volumes[0].GetExternal().GetPublishContext()); diff != "" { + t.Errorf("Restore publish context (-want +got):\n%s", diff) + } + volumeName := "substrate-" + actor.GetMetadata().GetUid() + "-data" + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment = workerAssignment(w) + a.Status.AssignedNode = w.Node.Name + a.Status.ExternalVolumes = &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{ + Name: "data", + StorageVolumeId: "vol-" + volumeName, + VolumeType: h.Volumes.Driver(), + }}} + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } + wantVolumes := []harness.Volume{{ID: "vol-" + volumeName, Name: volumeName, AttachedTo: []string{node.Name}}} + if diff := cmp.Diff(wantVolumes, h.Volumes.List()); diff != "" { + t.Errorf("volumes after resume (-want +got):\n%s", diff) + } +} + +// Resumes an actor whose template has an external volume while the volume +// plugin fails CreateVolume. The request fails with INTERNAL and the actor +// stays SUSPENDED. A later resume creates and attaches the volume and +// succeeds (OK). Both resumes retry while ate-api catches up. +// +// TODO: The request should fail with UNAVAILABLE when the volume plugin is +// unavailable, so callers like the atenet router retry it. +func TestResumeActor_VolumeCreateFails(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.NewActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"))) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + h.Volumes.On(harness.VolumeCreate).FailNext(harness.ErrUnavailable) + + _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("ResumeActor with a failing CreateVolume = %v, want Internal", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("actor after a failed CreateVolume (-want +got):\n%s", diff) + } + + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); status.Code(err) != codes.OK { + t.Fatalf("ResumeActor retry = %v, want OK", err) + } + volumeName := "substrate-" + actor.GetMetadata().GetUid() + "-data" + wantVolumes := []harness.Volume{{ID: "vol-" + volumeName, Name: volumeName, AttachedTo: []string{node.Name}}} + if diff := cmp.Diff(wantVolumes, h.Volumes.List()); diff != "" { + t.Errorf("volumes after the retry (-want +got):\n%s", diff) + } +} + +// Resumes an actor whose template has an external volume while the volume +// plugin fails ControllerPublishVolume once. The request fails with INTERNAL +// and the actor stays RESUMING with its worker. A later resume attaches the +// volume and succeeds (OK). Both resumes retry while ate-api catches up. +// +// TODO: The request should fail with UNAVAILABLE when the volume plugin is +// unavailable, so callers like the atenet router retry it. +func TestResumeActor_VolumeAttachFails(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + actor := h.NewActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"))) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + h.Volumes.On(harness.VolumePublish).FailNext(harness.ErrUnavailable) + + _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("ResumeActor with a failing ControllerPublishVolume = %v, want Internal", err) + } + volumeName := "substrate-" + actor.GetMetadata().GetUid() + "-data" + createdVolume := &ateapi.ExternalVolumes{Volumes: []*ateapi.ActorExternalVolumeStatus{{ + Name: "data", + StorageVolumeId: "vol-" + volumeName, + VolumeType: h.Volumes.Driver(), + }}} + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RESUMING + a.Status.WorkerAssignment = workerAssignment(w) + // ate-api records the worker epoch once a Restore succeeds. + a.Status.WorkerAssignment.WorkerEpoch = 0 + a.Status.AssignedNode = w.Node.Name + a.Status.ExternalVolumes = createdVolume + }) + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("actor after a failed ControllerPublishVolume (-want +got):\n%s", diff) + } + + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.OK { + t.Fatalf("ResumeActor retry = %v, want OK", err) + } + wantRetried := mutated(want, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.WorkerAssignment.WorkerEpoch = w.Epoch + }) + if diff := cmp.Diff(wantRetried, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("actor after the retry (-want +got):\n%s", diff) + } + wantVolumes := []harness.Volume{{ID: "vol-" + volumeName, Name: volumeName, AttachedTo: []string{node.Name}}} + if diff := cmp.Diff(wantVolumes, h.Volumes.List()); diff != "" { + t.Errorf("volumes after the retry (-want +got):\n%s", diff) + } +} + +// Resumes an actor whose template has two external volumes while the volume +// plugin fails the second CreateVolume. The request fails with INTERNAL, and +// the actor stays SUSPENDED, recording the volume that was created. Deleting +// the actor succeeds (OK) and leaves the volume plugin with no volumes. The +// resume retries while ate-api catches up. +func TestResumeActor_VolumeCreateFailsThenDelete(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"), h.WithExternalVolume("logs", "/logs")) + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + gate := h.Volumes.On(harness.VolumeCreate).Block() + h.Volumes.On(harness.VolumeCreate).FailNext(harness.ErrUnavailable) + + resumed := make(chan error, 1) + go func() { + _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + resumed <- err + }() + gate.Wait(t) + gate.Release() + if err := <-resumed; status.Code(err) != codes.Internal { + t.Fatalf("ResumeActor with a failing CreateVolume = %v, want Internal", err) + } + dataVolume := "substrate-" + actor.GetMetadata().GetUid() + "-data" + want := mutated(actor, func(a *ateapi.Actor) { + a.Status.ExternalVolumes.Volumes[0].StorageVolumeId = "vol-" + dataVolume + }) + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("actor after a failed CreateVolume (-want +got):\n%s", diff) + } + wantVolumes := []harness.Volume{{ID: "vol-" + dataVolume, Name: dataVolume}} + if diff := cmp.Diff(wantVolumes, h.Volumes.List(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("volumes after a failed CreateVolume (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + if diff := cmp.Diff([]harness.Volume{}, h.Volumes.List()); diff != "" { + t.Errorf("volumes after delete (-want +got):\n%s", diff) + } +} + +// Resumes an actor whose template has an external volume while the volume +// plugin fails ControllerPublishVolume, leaving the actor RESUMING on its +// worker. Deleting the actor succeeds (OK): the volume plugin holds no volumes, +// and the worker is left with no allocation. The resume retries while ate-api +// catches up. +func TestResumeActor_VolumeAttachFailsThenDelete(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + w := h.AddWorker(pool, h.Node("a")) + ref := harness.ActorRef(h.NewActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data")))) + workerBefore := h.GetWorker(w) + h.Volumes.On(harness.VolumePublish).FailNext(harness.ErrUnavailable) + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); status.Code(err) != codes.Internal { + t.Fatalf("ResumeActor with a failing ControllerPublishVolume = %v, want Internal", err) + } + if got := h.GetActor(ref).GetStatus(); got.GetState() != ateapi.ActorState_ACTOR_STATE_RESUMING || got.GetWorkerAssignment().GetWorker().GetName() != w.Name { + t.Fatalf("actor after a failed ControllerPublishVolume is %v on worker %q, want RESUMING on %q", got.GetState(), got.GetWorkerAssignment().GetWorker().GetName(), w.Name) + } + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + if diff := cmp.Diff([]harness.Volume{}, h.Volumes.List()); diff != "" { + t.Errorf("volumes after delete (-want +got):\n%s", diff) + } + if diff := cmp.Diff(workerBefore, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after delete (-want +got):\n%s", diff) + } +} + +// Resumes an actor whose template has two external volumes while the volume +// plugin fails the second ControllerPublishVolume. The request fails with +// INTERNAL, the actor stays RESUMING, and only the first volume is attached to +// the node. A later resume succeeds (OK) and both volumes are attached to the +// node. Both resumes retry while ate-api catches up. +func TestResumeActor_PartialVolumeAttachFails(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + actor := h.NewActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"), h.WithExternalVolume("logs", "/logs"))) + ref := harness.ActorRef(actor) + gate := h.Volumes.On(harness.VolumePublish).Block() + h.Volumes.On(harness.VolumePublish).FailNext(harness.ErrUnavailable) + + resumed := make(chan error, 1) + go func() { + _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + resumed <- err + }() + gate.Wait(t) + gate.Release() + if err := <-resumed; status.Code(err) != codes.Internal { + t.Fatalf("ResumeActor with a failing ControllerPublishVolume = %v, want Internal", err) + } + dataVolume := "substrate-" + actor.GetMetadata().GetUid() + "-data" + logsVolume := "substrate-" + actor.GetMetadata().GetUid() + "-logs" + want := mutated(actor, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RESUMING + a.Status.AssignedNode = node.Name + a.Status.WorkerAssignment = workerAssignment(w) + a.Status.WorkerAssignment.WorkerEpoch = 0 + a.Status.ExternalVolumes.Volumes[0].StorageVolumeId = "vol-" + dataVolume + a.Status.ExternalVolumes.Volumes[1].StorageVolumeId = "vol-" + logsVolume + }) + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("actor after a failed ControllerPublishVolume (-want +got):\n%s", diff) + } + wantVolumes := []harness.Volume{ + {ID: "vol-" + dataVolume, Name: dataVolume, AttachedTo: []string{node.Name}}, + {ID: "vol-" + logsVolume, Name: logsVolume}, + } + if diff := cmp.Diff(wantVolumes, h.Volumes.List(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("volumes after a failed ControllerPublishVolume (-want +got):\n%s", diff) + } + + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor retry: %v", err) + } + wantVolumes[1].AttachedTo = []string{node.Name} + if diff := cmp.Diff(wantVolumes, h.Volumes.List()); diff != "" { + t.Errorf("volumes after the retry (-want +got):\n%s", diff) + } +} + +// Resumes an actor with an external volume that was suspended asynchronously +// on node a, after another actor took node a's only worker, while a worker on +// node b has room. The request succeeds (OK), the actor runs on node b, and +// its volume is attached to node b only. Node b's atelet received exactly one +// Restore, carrying the publish context the plugin returned for node b. The +// resume retries while ate-api catches up. +func TestResumeActor_WithVolumeOnAnotherNode(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.AsyncSuspendedActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"))) + ref := harness.ActorRef(actor) + h.RunningActor(as, h.NewTemplate(as, pool)) + nodeB := h.Node("b") + wB := h.AddWorker(pool, nodeB) + + before := h.GetActor(ref) + rec := nodeB.Atelet.RecordCalls() + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("ResumeActor: %v", err) + } + volumes := onlyCall[*ateletpb.RestoreRequest](t, rec).GetSpec().GetVolumes() + if len(volumes) != 1 { + t.Fatalf("Restore volumes = %v, want exactly one", volumes) + } + if diff := cmp.Diff(map[string]string{"node": nodeB.Name}, volumes[0].GetExternal().GetPublishContext()); diff != "" { + t.Errorf("Restore publish context (-want +got):\n%s", diff) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_RUNNING + a.Status.AssignedNode = nodeB.Name + a.Status.WorkerAssignment = workerAssignment(wB) + uploaded := a.Status.Snapshots[len(a.Status.Snapshots)-1] + uploaded.Locality = "" + uploaded.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreActivationUID); diff != "" { + t.Errorf("resumed actor (-want +got):\n%s", diff) + } + volumeName := "substrate-" + actor.GetMetadata().GetUid() + "-data" + wantVolumes := []harness.Volume{{ID: "vol-" + volumeName, Name: volumeName, AttachedTo: []string{nodeB.Name}}} + if diff := cmp.Diff(wantVolumes, h.Volumes.List()); diff != "" { + t.Errorf("volumes after resume (-want +got):\n%s", diff) + } +} + +// Resumes an actor whose template limits it to 500m of CPU and 1Gi of +// memory, on a worker reporting room for them. The request succeeds (OK), +// the atelet's Restore carries those limits, and the worker's allocation +// includes them. The resume retries while ate-api catches up. +func TestResumeActor_WithResourceLimits(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node, harness.WithResourceCapacity("2", "4Gi")) + limits := resources.CPUMemory(500, 1<<30) + tmpl := h.NewTemplate(as, pool, func(tmpl *ateapi.ActorTemplate) { + tmpl.Resources = &ateapi.ResourceRequirements{Limits: limits} + }) + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + workerBefore := h.GetWorker(w) + rec := node.Atelet.RecordCalls() + + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); status.Code(err) != codes.OK { + t.Fatalf("ResumeActor = %v, want OK", err) + } + restore := onlyCall[*ateletpb.RestoreRequest](t, rec) + wantLimits := &ateletpb.ResourceRequirements{Limits: &ateletpb.Resources{CpuMillicores: 500, MemoryBytes: 1 << 30}} + if diff := cmp.Diff(wantLimits, restore.GetResources(), protocmp.Transform()); diff != "" { + t.Errorf("Restore resources (-want +got):\n%s", diff) + } + wantWorker := mutated(workerBefore, func(wk *ateapi.Worker) { + wk.Status.Allocated = &ateapi.WorkerResources{Actors: 1, CpuMillicores: 500, MemoryBytes: 1 << 30} + }) + if diff := cmp.Diff(wantWorker, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after resume (-want +got):\n%s", diff) + } +} + +// Resumes an actor while a first resume of it is held at the atelet's +// Restore. The second request fails with ABORTED. Once the first is released +// it succeeds (OK), and the node runs exactly one sandbox for the actor. The +// first resume retries while ate-api catches up. +func TestResumeActor_Concurrent(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + + gate := node.Atelet.On(harness.AteletRestore).Block() + first := make(chan error, 1) + go func() { + _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + first <- err + }() + gate.Wait(t) + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Aborted { + t.Errorf("second ResumeActor while the first is held = %v, want Aborted", err) + } + gate.Release() + if err := <-first; status.Code(err) != codes.OK { + t.Fatalf("first ResumeActor = %v, want OK", err) + } + wantSandboxes := []harness.Sandbox{{ + ActorUID: actor.GetMetadata().GetUid(), + Atespace: as, + ActorName: actor.GetMetadata().GetName(), + WorkerUID: w.Name, + }} + if diff := cmp.Diff(wantSandboxes, node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after both resumes (-want +got):\n%s", diff) + } +} + +// Resumes a new actor after its template's golden snapshot was deleted from +// object storage. The request fails with INTERNAL, and the actor becomes +// CRASHED with a crash message naming the atelet Restore. The resume retries +// while ate-api catches up. +func TestResumeActor_GoldenSnapshotMissing(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + tmpl := h.NewTemplate(as, pool) + golden, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: tmpl.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag()}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + goldenURI := golden.GetStatus().GetSnapshot().GetDurableSnapshot().GetObject().GetSnapshotUri() + if err := h.ObjectStore.DeleteSnapshot(goldenURI); err != nil { + t.Fatalf("DeleteSnapshot: %v", err) + } + actor := h.NewActor(as, tmpl) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + + _, err = h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("ResumeActor with the golden snapshot missing = %v, want Internal", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.AssignedNode = node.Name + a.Status.Crash = &ateapi.ActorCrash{} + }) + ignoreCrashDetails := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time", "message") + crashed := h.GetActor(ref) + if diff := cmp.Diff(want, crashed, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashDetails); diff != "" { + t.Errorf("actor after a missing golden snapshot (-want +got):\n%s", diff) + } + checkCrashMessage(t, crashed, "atelet Restore") +} + +// Suspending an actor that doesn't exist fails with NOT_FOUND. +func TestSuspendActor_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("SuspendActor of a missing actor = %v, want NotFound", err) + } +} + +// Suspending an actor with an invalid name fails with INVALID_ARGUMENT and +// the error names the invalid field. +func TestSuspendActor_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("SuspendActor with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.name: Invalid value") { + t.Errorf("SuspendActor error %q does not start with %q", msg, "actor.name: Invalid value") + } +} + +// Suspending a crashed actor fails with FAILED_PRECONDITION and leaves the +// actor unchanged. +func TestSuspendActor_WrongState(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.CrashedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + + _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("SuspendActor of a crashed actor = %v, want FailedPrecondition", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused SuspendActor (-want +got):\n%s", diff) + } +} + +// Suspends a running actor synchronously. The response matches GetActor. The +// actor becomes SUSPENDED with no worker assignment, still assigned to its +// node, and holds one snapshot of its own: the next generation, local to that +// node, with a completed upload. The worker is left with no allocation and no +// assignments. The atelet received exactly one Checkpoint, uploading +// immediately, runs no sandbox, and keeps the snapshot locally. Object storage +// gains the snapshot's objects. +func TestSuspendActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + + before := h.GetActor(ref) + workerBefore := h.GetWorker(w) + objectsBefore := h.ObjectStore.Objects() + rec := node.Atelet.RecordCalls() + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{ + Actor: ref, + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, + }) + if err != nil { + t.Fatalf("SuspendActor: %v", err) + } + + got := h.GetActor(ref) + if diff := cmp.Diff(got, resp.GetActor(), protocmp.Transform()); diff != "" { + t.Errorf("SuspendActor response against GetActor (-get +response):\n%s", diff) + } + uuid := latestSnapshot(t, got).GetUuid() + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_SUSPENDED + a.Status.WorkerAssignment = nil + a.Status.Snapshots = []*ateapi.Snapshot{actorSnapshot(before, uuid, 2, node.Name, ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED)} + a.Status.LastAssignedGeneration = 2 + }) + if diff := cmp.Diff(want, got, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("suspended actor (-want +got):\n%s", diff) + } + + wantWorker := mutated(workerBefore, func(wk *ateapi.Worker) { + wk.Status.Allocated = nil + }) + if diff := cmp.Diff(wantWorker, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after suspend (-want +got):\n%s", diff) + } + assignments, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("ListWorkerActorAssignments: %v", err) + } + if diff := cmp.Diff(&ateapi.ListWorkerActorAssignmentsResponse{}, assignments, protocmp.Transform()); diff != "" { + t.Errorf("worker assignments after suspend (-want +got):\n%s", diff) + } + + checkpoint := onlyCall[*ateletpb.CheckpointRequest](t, rec) + if got := checkpoint.GetUploadConfig().GetMode(); got != ateletpb.UploadMode_UPLOAD_MODE_IMMEDIATE { + t.Errorf("Checkpoint upload mode = %v, want IMMEDIATE", got) + } + if diff := cmp.Diff([]harness.Sandbox{}, node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after suspend (-want +got):\n%s", diff) + } + if got := node.Atelet.LocalSnapshot(actor.GetMetadata().GetUid()); got != uuid { + t.Errorf("local snapshot on node a = %q, want %q", got, uuid) + } + wantObjects := append(slices.Clone(objectsBefore), snapshotObjects(snapshotURI(before, uuid))...) + if diff := cmp.Diff(wantObjects, h.ObjectStore.Objects(), cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" { + t.Errorf("object storage after suspend (-want +got):\n%s", diff) + } +} + +// Suspends a running actor without a mode, which suspends it asynchronously. +// The actor becomes SUSPENDED with no worker assignment, still assigned to its +// node. It keeps the template's golden snapshot and gains one of its own: the +// next generation, local to that node, with a pending upload. The atelet +// received exactly one Checkpoint, deferring the upload, runs no sandbox, and +// keeps the snapshot locally. Object storage is unchanged. +func TestSuspendActor_Async(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + + before := h.GetActor(ref) + objectsBefore := h.ObjectStore.Objects() + rec := node.Atelet.RecordCalls() + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("SuspendActor: %v", err) + } + + uuid := latestSnapshot(t, resp.GetActor()).GetUuid() + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_SUSPENDED + a.Status.WorkerAssignment = nil + a.Status.Snapshots = append(a.Status.Snapshots, actorSnapshot(before, uuid, 2, node.Name, ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING)) + a.Status.LastAssignedGeneration = 2 + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("suspended actor (-want +got):\n%s", diff) + } + + checkpoint := onlyCall[*ateletpb.CheckpointRequest](t, rec) + if got := checkpoint.GetUploadConfig().GetMode(); got != ateletpb.UploadMode_UPLOAD_MODE_DEFERRED { + t.Errorf("Checkpoint upload mode = %v, want DEFERRED", got) + } + if diff := cmp.Diff([]harness.Sandbox{}, node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after suspend (-want +got):\n%s", diff) + } + if got := node.Atelet.LocalSnapshot(actor.GetMetadata().GetUid()); got != uuid { + t.Errorf("local snapshot on node a = %q, want %q", got, uuid) + } + if diff := cmp.Diff(objectsBefore, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after suspend (-want +got):\n%s", diff) + } +} + +// Suspends an actor that is already suspended with a node-local snapshot, +// once synchronously and once without a mode. Both succeed (OK) and return the +// actor unchanged. The atelet receives no call and keeps the local snapshot. +func TestSuspendActor_AlreadySuspended(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.AsyncSuspendedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + rec := node.Atelet.RecordCalls() + + for _, mode := range []ateapi.DurabilityMode{ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS, ateapi.DurabilityMode_DURABILITY_MODE_UNSPECIFIED} { + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref, Options: &ateapi.SuspendOptions{Mode: mode}}) + if err != nil { + t.Fatalf("SuspendActor in mode %v: %v", mode, err) + } + if diff := cmp.Diff(before, resp.GetActor(), protocmp.Transform()); diff != "" { + t.Errorf("SuspendActor in mode %v response (-want +got):\n%s", mode, diff) + } + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after suspending it again (-want +got):\n%s", diff) + } + assertCalls(t, rec) + if got, want := node.Atelet.LocalSnapshot(actor.GetMetadata().GetUid()), latestSnapshot(t, before).GetUuid(); got != want { + t.Errorf("local snapshot on node a = %q, want %q", got, want) + } +} + +// Suspends a running actor while the atelet fails the Checkpoint. The request +// fails with INTERNAL, and the actor becomes CRASHED with no worker +// assignment, still assigned to its node. It keeps the pending snapshot the +// suspend started, the next generation with no locality. Its status.crash is +// set: a message naming the atelet Checkpoint and the atelet's error, and a +// crash time. It is otherwise unchanged. The worker is left with no +// allocation. +func TestSuspendActor_CheckpointFails(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + workerBefore := h.GetWorker(w) + node.Atelet.On(harness.AteletCheckpoint).FailNext(harness.ErrSandboxFailed) + + _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Errorf("SuspendActor with a failing Checkpoint = %v, want Internal", err) + } + crashed := h.GetActor(ref) + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.WorkerAssignment = nil + a.Status.Snapshots = append(a.Status.Snapshots, actorSnapshot(before, latestSnapshot(t, crashed).GetUuid(), 2, "", ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING)) + a.Status.LastAssignedGeneration = 2 + a.Status.Crash = &ateapi.ActorCrash{} + }) + ignoreCrashDetails := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time", "message") + if diff := cmp.Diff(want, crashed, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashDetails); diff != "" { + t.Errorf("actor after a failed Checkpoint (-want +got):\n%s", diff) + } + checkCrashMessage(t, crashed, "atelet Checkpoint", harness.ErrSandboxFailed.Message()) + if crashed.GetStatus().GetCrash().GetCrashTime() == nil { + t.Errorf("status.crash of the crashed actor has no crash time") + } + wantWorker := mutated(workerBefore, func(wk *ateapi.Worker) { + wk.Status.Allocated = nil + }) + if diff := cmp.Diff(wantWorker, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after a failed Checkpoint (-want +got):\n%s", diff) + } +} + +// Suspends a running actor while the atelet reports a snapshot conflict +// (ABORTED) on the Checkpoint. The request fails with ABORTED, and the actor +// becomes SUSPENDING on its worker, keeping its last completed snapshot and +// gaining a pending one. Suspending it again sends the same pending snapshot, +// succeeds (OK), and the actor is SUSPENDED. +func TestSuspendActor_CheckpointConflict(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + node.Atelet.On(harness.AteletCheckpoint).FailNext(status.New(codes.Aborted, "injected snapshot conflict")) + rec := node.Atelet.RecordCalls() + + _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if status.Code(err) != codes.Aborted { + t.Fatalf("SuspendActor with a conflicting Checkpoint = %v, want Aborted", err) + } + suspending := h.GetActor(ref) + pending := latestSnapshot(t, suspending) + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_SUSPENDING + a.Status.Snapshots = append(a.Status.Snapshots, actorSnapshot(before, pending.GetUuid(), 2, "", ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING)) + a.Status.LastAssignedGeneration = 2 + }) + if diff := cmp.Diff(want, suspending, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("actor after a conflicting Checkpoint (-want +got):\n%s", diff) + } + + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("SuspendActor retry: %v", err) + } + if got := resp.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { + t.Errorf("actor after the retry is %v, want SUSPENDED", got) + } + assertCalls(t, rec, harness.AteletCheckpoint, harness.AteletCheckpoint) + for i, call := range rec.Calls() { + if got := call.Request.(*ateletpb.CheckpointRequest).GetSnapshot().GetSnapshotUuid(); got != pending.GetUuid() { + t.Errorf("Checkpoint %d of snapshot %q, want %q", i, got, pending.GetUuid()) + } + } +} + +// Suspends a running actor while the atelet is unavailable for the +// Checkpoint. The request fails with UNAVAILABLE, and the actor becomes +// SUSPENDING on its worker. Resuming it fails with FAILED_PRECONDITION and +// leaves it unchanged. Suspending it again succeeds (OK), and the actor is +// SUSPENDED. +func TestSuspendActor_CheckpointUnavailable(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + node.Atelet.On(harness.AteletCheckpoint).FailNext(harness.ErrUnavailable) + + _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if status.Code(err) != codes.Unavailable { + t.Fatalf("SuspendActor with an unavailable atelet = %v, want Unavailable", err) + } + suspending := h.GetActor(ref) + if got := suspending.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDING { + t.Fatalf("actor after an unavailable atelet is %v, want SUSPENDING", got) + } + if diff := cmp.Diff(actor.GetStatus().GetWorkerAssignment(), suspending.GetStatus().GetWorkerAssignment(), protocmp.Transform()); diff != "" { + t.Errorf("worker assignment after an unavailable atelet (-want +got):\n%s", diff) + } + + _, err = h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("ResumeActor of the SUSPENDING actor = %v, want FailedPrecondition", err) + } + if diff := cmp.Diff(suspending, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } + + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("SuspendActor retry: %v", err) + } + if got := resp.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { + t.Errorf("actor after the retry is %v, want SUSPENDED", got) + } +} + +// Suspends a running actor with an external volume synchronously. The request +// succeeds (OK), the actor keeps its volume in its status, and the volume +// plugin holds the volume attached to no node. +func TestSuspendActor_WithVolume(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.RunningActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"))) + ref := harness.ActorRef(actor) + + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{ + Actor: ref, + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, + }) + if err != nil { + t.Fatalf("SuspendActor: %v", err) + } + if diff := cmp.Diff(actor.GetStatus().GetExternalVolumes(), resp.GetActor().GetStatus().GetExternalVolumes(), protocmp.Transform()); diff != "" { + t.Errorf("external volumes of the suspended actor (-want +got):\n%s", diff) + } + volumeName := "substrate-" + actor.GetMetadata().GetUid() + "-data" + if diff := cmp.Diff([]harness.Volume{{ID: "vol-" + volumeName, Name: volumeName}}, h.Volumes.List(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("volumes after suspend (-want +got):\n%s", diff) + } +} + +// Suspends a running actor with an external volume while the volume plugin +// fails ControllerUnpublishVolume. The request fails with INTERNAL, and the +// actor becomes SUSPENDING on its worker, with its volume still attached to the +// node. Suspending it again succeeds (OK): the actor is SUSPENDED and its +// volume is attached to no node. +// +// TODO: The request should fail with UNAVAILABLE when the volume plugin is +// unavailable, so callers retry it. +func TestSuspendActor_VolumeDetachFails(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"))) + ref := harness.ActorRef(actor) + h.Volumes.On(harness.VolumeUnpublish).FailNext(harness.ErrUnavailable) + + _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("SuspendActor with a failing ControllerUnpublishVolume = %v, want Internal", err) + } + suspending := h.GetActor(ref) + if got := suspending.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDING { + t.Errorf("actor after a failed ControllerUnpublishVolume is %v, want SUSPENDING", got) + } + if diff := cmp.Diff(actor.GetStatus().GetWorkerAssignment(), suspending.GetStatus().GetWorkerAssignment(), protocmp.Transform()); diff != "" { + t.Errorf("worker assignment after a failed ControllerUnpublishVolume (-want +got):\n%s", diff) + } + volumeName := "substrate-" + actor.GetMetadata().GetUid() + "-data" + wantVolumes := []harness.Volume{{ID: "vol-" + volumeName, Name: volumeName, AttachedTo: []string{node.Name}}} + if diff := cmp.Diff(wantVolumes, h.Volumes.List()); diff != "" { + t.Errorf("volumes after a failed ControllerUnpublishVolume (-want +got):\n%s", diff) + } + + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("SuspendActor retry: %v", err) + } + if got := resp.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { + t.Errorf("actor after the retry is %v, want SUSPENDED", got) + } + wantVolumes[0].AttachedTo = nil + if diff := cmp.Diff(wantVolumes, h.Volumes.List(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("volumes after the retry (-want +got):\n%s", diff) + } +} + +// Resumes an actor while a suspend of it is held at the atelet's Checkpoint. +// The resume fails with ABORTED and leaves the actor unchanged. Once the +// Checkpoint is released, the suspend succeeds (OK). +func TestResumeActor_SuspendInProgress(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + + gate := node.Atelet.On(harness.AteletCheckpoint).Block() + suspended := make(chan error, 1) + go func() { + _, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{Actor: ref}) + suspended <- err + }() + gate.Wait(t) + before := h.GetActor(ref) + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Aborted { + t.Errorf("ResumeActor while a suspend is held = %v, want Aborted", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } + gate.Release() + if err := <-suspended; err != nil { + t.Errorf("SuspendActor: %v", err) + } +} + +// Reverts a running actor that was suspended once and resumed again. The +// response matches GetActor. The actor becomes SUSPENDED with no worker +// assignment and no assigned node, keeping the snapshot its suspend wrote, +// which is no longer local to the node. It is otherwise unchanged. The atelet +// received exactly one Terminate and no Checkpoint, and runs no sandbox. The +// worker is left with no allocation, and object storage is unchanged. The +// resume retries while ate-api catches up. +func TestRevertActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + ref := harness.ActorRef(h.SuspendedActor(as, h.NewTemplate(as, pool))) + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor: %v", err) + } + + before := h.GetActor(ref) + workerBefore := h.GetWorker(w) + objectsBefore := h.ObjectStore.Objects() + rec := node.Atelet.RecordCalls() + resp, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("RevertActor: %v", err) + } + + got := h.GetActor(ref) + if diff := cmp.Diff(got, resp.GetActor(), protocmp.Transform()); diff != "" { + t.Errorf("RevertActor response against GetActor (-get +response):\n%s", diff) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_SUSPENDED + a.Status.WorkerAssignment = nil + a.Status.AssignedNode = "" + }) + for _, snap := range want.Status.Snapshots { + snap.Locality = "" + } + if diff := cmp.Diff(want, got, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("reverted actor (-want +got):\n%s", diff) + } + assertCalls(t, rec, harness.AteletTerminate) + if diff := cmp.Diff([]harness.Sandbox{}, node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after revert (-want +got):\n%s", diff) + } + wantWorker := mutated(workerBefore, func(wk *ateapi.Worker) { + wk.Status.Allocated = nil + }) + if diff := cmp.Diff(wantWorker, h.GetWorker(w), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker after revert (-want +got):\n%s", diff) + } + if diff := cmp.Diff(objectsBefore, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after revert (-want +got):\n%s", diff) + } +} + +// Reverts an actor suspended asynchronously, whose latest snapshot is local to +// its node and not uploaded. The request succeeds (OK). The actor is SUSPENDED +// with no assigned node, holding only the template's golden snapshot, and is +// otherwise unchanged. The atelet received exactly one Terminate and no longer +// holds the local snapshot. +func TestRevertActor_FromAsyncSuspended(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.AsyncSuspendedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + rec := node.Atelet.RecordCalls() + + resp, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("RevertActor: %v", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.AssignedNode = "" + a.Status.Snapshots = a.Status.Snapshots[:1] + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("reverted actor (-want +got):\n%s", diff) + } + assertCalls(t, rec, harness.AteletTerminate) + if got := node.Atelet.LocalSnapshot(actor.GetMetadata().GetUid()); got != "" { + t.Errorf("local snapshot on node a = %q, want none", got) + } +} + +// Reverts an actor crashed by a failed suspend Checkpoint. The request succeeds +// (OK). The actor is SUSPENDED with no crash and no assigned node, holding only +// the template's golden snapshot: the pending snapshot of the failed suspend is +// discarded. It is otherwise unchanged. A later resume succeeds (OK). The +// resume retries while ate-api catches up. +func TestRevertActor_FromCrashed(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + ref := harness.ActorRef(h.CrashedActor(as, h.NewTemplate(as, pool))) + before := h.GetActor(ref) + + resp, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("RevertActor: %v", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_SUSPENDED + a.Status.Crash = nil + a.Status.AssignedNode = "" + a.Status.Snapshots = a.Status.Snapshots[:1] + }) + if diff := cmp.Diff(want, resp.GetActor(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("reverted actor (-want +got):\n%s", diff) + } + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Errorf("ResumeActor after revert: %v", err) + } +} + +// Reverts an actor with an external volume crashed by the removal of its +// worker. The request succeeds (OK). The actor is SUSPENDED with no assigned +// node, and its volume is attached to no node. +func TestRevertActor_WorkerRemovedDetachesVolume(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + w := h.AddWorker(pool, h.Node("a")) + actor := h.RunningActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data"))) + ref := harness.ActorRef(actor) + w.Remove() + if got := h.GetActor(ref).GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_CRASHED { + t.Fatalf("actor after its worker was removed is %v, want CRASHED", got) + } + + resp, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("RevertActor: %v", err) + } + if got := resp.GetActor().GetStatus(); got.GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED || got.GetAssignedNode() != "" { + t.Errorf("reverted actor is %v assigned to %q, want SUSPENDED with no assigned node", got.GetState(), got.GetAssignedNode()) + } + volumeName := "substrate-" + actor.GetMetadata().GetUid() + "-data" + if diff := cmp.Diff([]harness.Volume{{ID: "vol-" + volumeName, Name: volumeName}}, h.Volumes.List(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("volumes after revert (-want +got):\n%s", diff) + } +} + +// Reverts a running actor while the atelet fails the Terminate. The request +// fails with INTERNAL, and the actor becomes REVERTING on its worker. Resuming +// it fails with FAILED_PRECONDITION and leaves it unchanged. Reverting it again +// succeeds (OK), and the actor is SUSPENDED with no worker assignment. +func TestRevertActor_TerminateFails(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + node.Atelet.On(harness.AteletTerminate).FailNext(harness.ErrSandboxFailed) + + _, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: ref}) + if status.Code(err) != codes.Internal { + t.Fatalf("RevertActor with a failing Terminate = %v, want Internal", err) + } + reverting := h.GetActor(ref) + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_REVERTING + }) + if diff := cmp.Diff(want, reverting, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("actor after a failed Terminate (-want +got):\n%s", diff) + } + + _, err = h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("ResumeActor of the REVERTING actor = %v, want FailedPrecondition", err) + } + if diff := cmp.Diff(reverting, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } + + resp, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("RevertActor retry: %v", err) + } + if got := resp.GetActor().GetStatus(); got.GetState() != ateapi.ActorState_ACTOR_STATE_SUSPENDED || got.GetWorkerAssignment() != nil { + t.Errorf("actor after the retry is %v with assignment %v, want SUSPENDED with none", got.GetState(), got.GetWorkerAssignment()) + } +} + +// Reverting an actor that doesn't exist fails with NOT_FOUND. +func TestRevertActor_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("RevertActor of a missing actor = %v, want NotFound", err) + } +} + +// Reverting an actor with an invalid name fails with INVALID_ARGUMENT and +// the error names the invalid field. +func TestRevertActor_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("RevertActor with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.name: Invalid value") { + t.Errorf("RevertActor error %q does not start with %q", msg, "actor.name: Invalid value") + } +} + +// Reverting a new actor, which is SUSPENDED with no node-local snapshot, +// fails with FAILED_PRECONDITION and leaves the actor unchanged. +func TestRevertActor_WrongState(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + + _, err := h.Control.RevertActor(t.Context(), &ateapi.RevertActorRequest{Actor: ref}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("RevertActor of a new actor = %v, want FailedPrecondition", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused RevertActor (-want +got):\n%s", diff) + } +} + +// Minting a JWT for an actor that doesn't exist fails with NOT_FOUND. +func TestMintActorJwt_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.EgressGateway().MintActorJwt(t.Context(), &ateapi.MintActorJwtRequest{ + Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}, + Audiences: []string{"https://audience.example"}, + ExpirationSeconds: 600, + }) + if status.Code(err) != codes.NotFound { + t.Errorf("MintActorJwt for a missing actor = %v, want NotFound", err) + } +} + +// Minting a JWT for an actor with an invalid name fails with +// INVALID_ARGUMENT and the error names the invalid field. +func TestMintActorJwt_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.EgressGateway().MintActorJwt(t.Context(), &ateapi.MintActorJwtRequest{ + Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}, + Audiences: []string{"https://audience.example"}, + ExpirationSeconds: 600, + }) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("MintActorJwt with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.name: Invalid value") { + t.Errorf("MintActorJwt error %q does not start with %q", msg, "actor.name: Invalid value") + } +} + +// Minting a worker certificate, as a node's atelet, for an actor that +// doesn't exist fails with NOT_FOUND. +func TestMintWorkerActorCertificate_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + node := h.Node("a") + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), node) + + _, err := node.WorkerService().MintWorkerActorCertificate(t.Context(), &ateapi.MintWorkerActorCertificateRequest{ + Worker: w.Ref(), + Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}, + ActorUid: foreignUID, + CertificateSigningRequest: certificateSigningRequest(t), + }) + if status.Code(err) != codes.NotFound { + t.Errorf("MintWorkerActorCertificate for a missing actor = %v, want NotFound", err) + } +} + +// Minting a worker certificate, as a node's atelet, for an actor with an +// invalid name fails with INVALID_ARGUMENT and the error names the invalid +// field. +func TestMintWorkerActorCertificate_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + node := h.Node("a") + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), node) + + _, err := node.WorkerService().MintWorkerActorCertificate(t.Context(), &ateapi.MintWorkerActorCertificateRequest{ + Worker: w.Ref(), + Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}, + ActorUid: foreignUID, + CertificateSigningRequest: certificateSigningRequest(t), + }) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("MintWorkerActorCertificate with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.name: Invalid value") { + t.Errorf("MintWorkerActorCertificate error %q does not start with %q", msg, "actor.name: Invalid value") + } +} + +// Requesting, as a node's atelet, the suspend of an actor that doesn't exist +// fails with NOT_FOUND. +func TestRequestActorSuspend_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + node := h.Node("a") + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), node) + + _, err := node.WorkerService().RequestActorSuspend(t.Context(), &ateapi.RequestActorSuspendRequest{ + Worker: w.Ref(), + Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}, + ActorUid: foreignUID, + }) + if status.Code(err) != codes.NotFound { + t.Errorf("RequestActorSuspend of a missing actor = %v, want NotFound", err) + } +} + +// Requesting, as a node's atelet, the suspend of an actor with an invalid +// name fails with INVALID_ARGUMENT and the error names the invalid field. +func TestRequestActorSuspend_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + node := h.Node("a") + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), node) + + _, err := node.WorkerService().RequestActorSuspend(t.Context(), &ateapi.RequestActorSuspendRequest{ + Worker: w.Ref(), + Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}, + ActorUid: foreignUID, + }) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("RequestActorSuspend with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor.name: Invalid value") { + t.Errorf("RequestActorSuspend error %q does not start with %q", msg, "actor.name: Invalid value") + } +} + +// createTag tags the snapshot of source, a suspended actor, as name in its +// atespace. +func createTag(t *testing.T, h *harness.Harness, source *ateapi.Actor, name string) *ateapi.Tag { + t.Helper() + tag, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: source.GetMetadata().GetAtespace(), Name: name}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: harness.ActorRef(source), + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + return tag +} + +// withDataFidelity makes the template's actors snapshot only their volumes. +func withDataFidelity(tmpl *ateapi.ActorTemplate) { + tmpl.SnapshotConfig = &ateapi.SnapshotConfig{PreferredFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES} +} + +// Creates an actor in another atespace from a tag scoped to its own atespace. +// The request fails with FAILED_PRECONDITION and no actor is created. After the +// tag is updated to published, the same request succeeds (OK) and the actor +// holds the tag's snapshot. +func TestCreateActor_FromTagInAnotherAtespace(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + other := h.CreateAtespace("team-b") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + tag := createTag(t, h, h.SuspendedActor(as, tmpl), "tag-a") + spec := &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: other, Name: "clone"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + SourceTag: &ateapi.ObjectRef{Atespace: as, Name: "tag-a"}, + } + + _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: spec}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor from an unpublished tag = %v, want FailedPrecondition", err) + } + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: harness.ActorRef(spec)}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor after a refused create = %v, want NotFound", err) + } + + toUpdate := mutated(tag, func(tg *ateapi.Tag) { + tg.Scope = ateapi.TagScope_TAG_SCOPE_PUBLISHED + }) + if _, err := h.Control.UpdateTag(t.Context(), &ateapi.UpdateTagRequest{Tag: toUpdate}); err != nil { + t.Fatalf("UpdateTag: %v", err) + } + created, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: spec}) + if err != nil { + t.Fatalf("CreateActor from a published tag: %v", err) + } + snapshot := mutated(tag.GetStatus().GetSnapshot(), func(s *ateapi.Snapshot) { + s.ActorTemplateUid = tmpl.GetMetadata().GetUid() + }) + want := mutated(spec, func(a *ateapi.Actor) { + a.Status = &ateapi.ActorStatus{ + State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, + Snapshots: []*ateapi.Snapshot{snapshot}, + LastAssignedGeneration: snapshot.GetGeneration(), + } + }) + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created actor (-want +got):\n%s", diff) + } +} + +// Creates an actor from a tag of a suspended actor and verifies that the whole +// resource has the expected shape: SUSPENDED, naming the tag as its source, +// and holding the tag's snapshot. +func TestCreateActor_FromTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + tag := createTag(t, h, h.SuspendedActor(as, tmpl), "tag-a") + tagRef := &ateapi.ObjectRef{Atespace: as, Name: "tag-a"} + templateRef := &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()} + + created, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "clone"}, + ActorTemplate: templateRef, + SourceTag: tagRef, + }}) + if err != nil { + t.Fatalf("CreateActor: %v", err) + } + snapshot := mutated(tag.GetStatus().GetSnapshot(), func(s *ateapi.Snapshot) { + s.ActorTemplateUid = tmpl.GetMetadata().GetUid() + }) + want := &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "clone"}, + ActorTemplate: templateRef, + SourceTag: tagRef, + Status: &ateapi.ActorStatus{ + State: ateapi.ActorState_ACTOR_STATE_SUSPENDED, + Snapshots: []*ateapi.Snapshot{snapshot}, + LastAssignedGeneration: snapshot.GetGeneration(), + }, + } + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created actor (-want +got):\n%s", diff) + } +} + +// Creating an actor from a tag holding a volume-fidelity snapshot, with a +// template other than the one the tag was taken under, fails with +// FAILED_PRECONDITION, and no actor is created. +func TestCreateActor_FromDataTagOfAnotherTemplate(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool, withDataFidelity) + other := h.NewTemplate(as, pool) + source := h.SuspendedActor(as, tmpl) + createTag(t, h, source, "tag-a") + before, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + + _, err = h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "clone"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: other.GetMetadata().GetName()}, + SourceTag: &ateapi.ObjectRef{Atespace: as, Name: "tag-a"}, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor from a data tag of another template = %v, want FailedPrecondition", err) + } + after, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + if diff := cmp.Diff(before, after, protocmp.Transform()); diff != "" { + t.Errorf("actors after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor from a tag with a template that has an external volume +// fails with FAILED_PRECONDITION. +func TestCreateActor_FromTagWithExternalVolumes(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data")) + createTag(t, h, h.SuspendedActor(as, tmpl), "tag-a") + + _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "clone"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + SourceTag: &ateapi.ObjectRef{Atespace: as, Name: "tag-a"}, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor from a tag with external volumes = %v, want FailedPrecondition", err) + } +} + +// Creates an actor from a tag while the tag's create is held at the object +// store's CopySnapshot. The actor create fails with FAILED_PRECONDITION and +// the error says the tag is still being created, and once the CopySnapshot is +// released, the tag create succeeds (OK). +func TestCreateActor_FromPendingTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + tmpl := h.NewTemplate(as, pool) + source := h.AsyncSuspendedActor(as, tmpl) + + gate := h.ObjectStore.On(harness.ObjectStoreCopySnapshot).Block() + tagged := make(chan error, 1) + go func() { + _, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: harness.ActorRef(source), + }}) + tagged <- err + }() + gate.Wait(t) + _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "clone"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + SourceTag: &ateapi.ObjectRef{Atespace: as, Name: "tag-a"}, + }}) + if status.Code(err) != codes.FailedPrecondition || !strings.Contains(status.Convert(err).Message(), "still being created") { + t.Errorf("CreateActor from a tag still being created = %v, want FailedPrecondition saying the tag is still being created", err) + } + gate.Release() + if err := <-tagged; err != nil { + t.Errorf("CreateTag: %v", err) + } +} + +// Updates the template of an existing actor to another template with the same +// volumes, sending it as read. The result, and a later Get, is the resource as +// read with that field changed and a higher version. +func TestUpdateActor_ActorTemplate(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + other := h.NewTemplate(as, pool) + ref := harness.ActorRef(actor) + otherRef := &ateapi.ObjectRef{Atespace: as, Name: other.GetMetadata().GetName()} + + before := h.GetActor(ref) + toUpdate := mutated(before, func(a *ateapi.Actor) { + a.ActorTemplate = otherRef + }) + updated, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: toUpdate}) + if err != nil { + t.Fatalf("UpdateActor: %v", err) + } + want := mutated(before, func(a *ateapi.Actor) { + a.ActorTemplate = otherRef + }) + if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("updated actor (-want +got):\n%s", diff) + } + if got, was := updated.GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("updated actor has version %d, want higher than %d", got, was) + } + if diff := cmp.Diff(updated, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("GetActor after update (-updated +got):\n%s", diff) + } +} + +// Updating an actor's template to one that doesn't exist fails with +// FAILED_PRECONDITION and leaves the actor unchanged. +func TestUpdateActor_ActorTemplateNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + ref := harness.ActorRef(h.NewActor(as, h.NewTemplate(as, pool))) + before := h.GetActor(ref) + + toUpdate := mutated(before, func(a *ateapi.Actor) { + a.ActorTemplate = &ateapi.ObjectRef{Atespace: as, Name: "tmpl-missing"} + }) + _, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: toUpdate}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("UpdateActor to a missing template = %v, want FailedPrecondition", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused update (-want +got):\n%s", diff) + } +} + +// Updating an actor's template to one with different volumes, and to one that +// mounts the same volume at a different path, each fails with +// FAILED_PRECONDITION and leaves the actor unchanged. +func TestUpdateActor_ActorTemplateIncompatibleVolumes(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + ref := harness.ActorRef(h.NewActor(as, h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data")))) + otherVolumes := h.NewTemplate(as, pool, h.WithExternalVolume("logs", "/data")) + otherMounts := h.NewTemplate(as, pool, h.WithExternalVolume("data", "/mnt")) + before := h.GetActor(ref) + + for _, other := range []*ateapi.ActorTemplate{otherVolumes, otherMounts} { + toUpdate := mutated(before, func(a *ateapi.Actor) { + a.ActorTemplate = &ateapi.ObjectRef{Atespace: as, Name: other.GetMetadata().GetName()} + }) + _, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: toUpdate}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("UpdateActor to template %s = %v, want FailedPrecondition", other.GetMetadata().GetName(), err) + } + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after refused updates (-want +got):\n%s", diff) + } +} + +// Updating an actor left DELETING by a Terminate the atelet failed fails with +// FAILED_PRECONDITION and leaves the actor unchanged. +func TestUpdateActor_Deleting(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + ref := harness.ActorRef(h.RunningActor(as, h.NewTemplate(as, pool))) + node.Atelet.On(harness.AteletTerminate).FailNext(harness.ErrSandboxFailed) + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err == nil { + t.Fatal("DeleteActor succeeded despite a failing Terminate") + } + before := h.GetActor(ref) + if got := before.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_DELETING { + t.Fatalf("actor after a failed delete is %v, want DELETING", got) + } + + toUpdate := mutated(before, func(a *ateapi.Actor) { + a.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "1"}} + }) + _, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: toUpdate}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("UpdateActor of a DELETING actor = %v, want FailedPrecondition", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused update (-want +got):\n%s", diff) + } +} + +// Resumes an actor whose worker selector matches pool p2, from a template +// whose selector matches pool p1, with a worker in each. The request fails +// with RESOURCE_EXHAUSTED and leaves the actor unchanged: no worker matches +// both selectors. After a worker is added to a pool matching both, resuming +// succeeds (OK) on that worker. The resume after the worker is added retries +// while ate-api catches up. +func TestResumeActor_BothSelectorsMustMatch(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + p1 := h.CreateWorkerPool("p1", map[string]string{"app": "x"}) + p2 := h.CreateWorkerPool("p2", map[string]string{"tier": "2"}) + h.AddWorker(p1, h.Node("a")) + h.AddWorker(p2, h.Node("b")) + tmpl := h.NewTemplate(as, p1) + actor := h.NewActor(as, tmpl, func(a *ateapi.Actor) { + a.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"tier": "2"}} + }) + ref := harness.ActorRef(actor) + before := h.GetActor(ref) + + _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.ResourceExhausted { + t.Errorf("ResumeActor with no worker matching both selectors = %v, want ResourceExhausted", err) + } + if diff := cmp.Diff(before, h.GetActor(ref), protocmp.Transform()); diff != "" { + t.Errorf("actor after a refused resume (-want +got):\n%s", diff) + } + + both := h.AddWorker(h.CreateWorkerPool("p3", map[string]string{"app": "x", "tier": "2"}), h.Node("c")) + resp, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("ResumeActor after adding a matching worker: %v", err) + } + if got := resp.GetActor().GetStatus().GetWorkerAssignment().GetWorker().GetName(); got != both.Name { + t.Errorf("actor runs on worker %q, want %q", got, both.Name) + } +} + +// An actor left RESUMING on the pool p1 worker by a Restore that failed with +// UNAVAILABLE has its worker selector updated to match only pool p2, and is +// resumed again. The request fails with ABORTED, the actor becomes CRASHED +// with no worker assignment and a crash message saying the worker no longer +// satisfies its placement constraints, and the p1 worker is left with no +// allocation. +// +// TODO: The request should fail with INTERNAL, as other resumes that crash +// the actor do. ABORTED makes callers like the atenet router retry a resume +// that cannot succeed. +func TestResumeActor_RetryAfterWorkerSelectorChange(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + p1 := h.CreateWorkerPool("p1", map[string]string{"app": "x", "pool": "p1"}) + p2 := h.CreateWorkerPool("p2", map[string]string{"app": "x", "pool": "p2"}) + w1 := h.AddWorker(p1, h.Node("a")) + h.AddWorker(p2, h.Node("b")) + tmpl := h.NewTemplate(as, h.CreateWorkerPool("any", map[string]string{"app": "x"})) + idle := h.GetWorker(w1) + actor := h.NewActor(as, tmpl, func(a *ateapi.Actor) { + a.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"pool": "p1"}} + }) + ref := harness.ActorRef(actor) + w1.Node.Atelet.On(harness.AteletRestore).FailNext(harness.ErrUnavailable) + if _, err := h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); status.Code(err) != codes.Unavailable { + t.Fatalf("ResumeActor with an unavailable atelet = %v, want Unavailable", err) + } + toUpdate := mutated(h.GetActor(ref), func(a *ateapi.Actor) { + a.WorkerSelector = &ateapi.Selector{MatchLabels: map[string]string{"pool": "p2"}} + }) + updated, err := h.Control.UpdateActor(t.Context(), &ateapi.UpdateActorRequest{Actor: toUpdate}) + if err != nil { + t.Fatalf("UpdateActor: %v", err) + } + + _, err = h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}) + if status.Code(err) != codes.Aborted { + t.Errorf("ResumeActor retry after the selector change = %v, want Aborted", err) + } + want := mutated(updated, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.WorkerAssignment = nil + a.Status.Crash = &ateapi.ActorCrash{Message: "resume failed: assigned worker no longer satisfies the actor's placement constraints"} + }) + ignoreCrashTime := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time") + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashTime); diff != "" { + t.Errorf("actor after the retry (-want +got):\n%s", diff) + } + if diff := cmp.Diff(idle, h.GetWorker(w1), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("p1 worker after the retry (-want +got):\n%s", diff) + } +} + +// Creates actors in two atespaces and lists actors with no atespace. The list +// holds exactly the actors of both atespaces. +func TestListActors_AllAtespaces(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + other := h.CreateAtespace("team-b") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + created := []*ateapi.Actor{ + h.NewActor(as, h.NewTemplate(as, pool)), + h.NewActor(other, h.NewTemplate(other, pool)), + } + + listed, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + byName := cmpopts.SortSlices(func(a, b *ateapi.Actor) bool { return a.GetMetadata().GetName() < b.GetMetadata().GetName() }) + if diff := cmp.Diff(created, listed.GetActors(), protocmp.Transform(), byName); diff != "" { + t.Errorf("listed actors (-want +got):\n%s", diff) + } +} + +// Mints a JWT, as the egress gateway, for an existing actor. The request +// succeeds (OK) with a JWT whose header names type JWT, and whose claims name +// ate-api's issuer, the requested audience, and the actor by name and UID. The +// JWT expires at the response's expire_time, after the requested lifetime. +func TestMintActorJwt(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + + resp, err := h.EgressGateway().MintActorJwt(t.Context(), &ateapi.MintActorJwtRequest{ + Actor: ref, + Audiences: []string{"https://audience.example"}, + ExpirationSeconds: 600, + }) + if err != nil { + t.Fatalf("MintActorJwt: %v", err) + } + segments := strings.Split(resp.GetActorJwt(), ".") + if len(segments) != 3 { + t.Fatalf("actor JWT has %d segments, want 3", len(segments)) + } + var header struct { + Type string `json:"typ"` + } + decodeJWTSegment(t, segments[0], &header) + if header.Type != "JWT" { + t.Errorf("JWT typ = %q, want JWT", header.Type) + } + var claims actoridjwt.WireClaims + decodeJWTSegment(t, segments[1], &claims) + if claims.Issuer != harness.ActorJWTIssuer { + t.Errorf("JWT iss = %q, want %q", claims.Issuer, harness.ActorJWTIssuer) + } + if !strings.Contains(string(claims.Audiences), "https://audience.example") { + t.Errorf("JWT aud = %s, want it to hold https://audience.example", claims.Audiences) + } + if want := "actor/" + as + "/" + ref.GetName(); claims.Subject != want { + t.Errorf("JWT sub = %q, want %q", claims.Subject, want) + } + kind, substrate, ok := claims.Substrate() + if !ok || kind != actoridjwt.KindActor { + t.Fatalf("JWT kind = %v (ok %v), want KindActor", kind, ok) + } + if want := actor.GetMetadata().GetUid(); substrate.ActorUID != want { + t.Errorf("JWT actor UID = %q, want %q", substrate.ActorUID, want) + } + if got, exp := resp.GetExpireTime().AsTime(), time.Unix(int64(claims.Expiration), 0); !got.Equal(exp) { + t.Errorf("expire_time = %v, want the exp claim %v", got, exp) + } + if got := claims.Expiration - claims.IssuedAt; got != 600 { + t.Errorf("exp - iat = %v seconds, want 600", got) + } +} + +// decodeJWTSegment decodes one base64url segment of a JWT into v. +func decodeJWTSegment(t *testing.T, segment string, v any) { + t.Helper() + raw, err := base64.RawURLEncoding.DecodeString(segment) + if err != nil { + t.Fatalf("decoding JWT segment: %v", err) + } + if err := json.Unmarshal(raw, v); err != nil { + t.Fatalf("unmarshaling JWT segment: %v", err) + } +} + +// Resumes a new actor whose template sets a literal environment variable. The +// request succeeds (OK), and the atelet's Restore carries the variable in the +// container's spec. The resume retries while ate-api catches up. +func TestResumeActor_LiteralEnv(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + tmpl := h.NewTemplate(as, pool, func(tmpl *ateapi.ActorTemplate) { + tmpl.Containers[0].Env = []*ateapi.EnvVar{{Name: "LITERAL", Value: "plain"}} + }) + ref := harness.ActorRef(h.NewActor(as, tmpl)) + rec := node.Atelet.RecordCalls() + + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor: %v", err) + } + restore := onlyCall[*ateletpb.RestoreRequest](t, rec) + containers := restore.GetSpec().GetContainers() + if len(containers) != 1 { + t.Fatalf("Restore spec has %d containers, want 1", len(containers)) + } + want := []*ateletpb.EnvVar{{Name: "LITERAL", Value: "plain"}} + if diff := cmp.Diff(want, containers[0].GetEnv(), protocmp.Transform()); diff != "" { + t.Errorf("Restore container env (-want +got):\n%s", diff) + } +} + +// deletingTag leaves the tag ref marked for deletion: its DeleteTag fails +// while object storage fails to clean up the tag's snapshot. +func deletingTag(t *testing.T, h *harness.Harness, ref *ateapi.ObjectRef) { + t.Helper() + h.ObjectStore.On(harness.ObjectStoreCleanupSnapshot).FailNext(harness.ErrStorageFailed) + if _, err := h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: ref}); err == nil { + t.Fatal("DeleteTag succeeded despite failing object storage") + } + tag, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag after a failed delete: %v", err) + } + if tag.GetMetadata().GetDeleteTime() == nil { + t.Fatalf("tag %s after a failed delete has no delete time", ref.GetName()) + } +} + +// Creating an actor from a tag whose delete failed partway, leaving it marked +// for deletion, fails with FAILED_PRECONDITION and creates no actor. +func TestCreateActor_FromDeletingTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + createTag(t, h, h.SuspendedActor(as, tmpl), "tag-a") + tagRef := &ateapi.ObjectRef{Atespace: as, Name: "tag-a"} + deletingTag(t, h, tagRef) + before, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + + _, err = h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "clone"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + SourceTag: tagRef, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor from a deleting tag = %v, want FailedPrecondition", err) + } + after, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + if diff := cmp.Diff(before, after, protocmp.Transform()); diff != "" { + t.Errorf("actors after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor from a template whose golden tag's delete failed partway, +// leaving it marked for deletion, fails with FAILED_PRECONDITION. A +// DeleteActorTemplate that fails to clean up the golden tag's snapshot leaves +// the golden tag in that state. +func TestCreateActor_GoldenTagDeleting(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + tmplRef := &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()} + h.ObjectStore.On(harness.ObjectStoreCleanupSnapshot).FailNext(harness.ErrStorageFailed) + if _, err := h.Control.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: tmplRef}); err == nil { + t.Fatal("DeleteActorTemplate succeeded despite failing object storage") + } + golden, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: tmpl.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag()}) + if err != nil { + t.Fatalf("GetTag of the golden tag after a failed template delete: %v", err) + } + if golden.GetMetadata().GetDeleteTime() == nil { + t.Fatal("golden tag after a failed template delete has no delete time") + } + + _, err = h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: tmplRef, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActor while the golden tag is being deleted = %v, want FailedPrecondition", err) + } +} + +// Suspends, synchronously, a resumed actor that holds a snapshot of its own. +// The request succeeds (OK) with a new snapshot of the actor's own, and object +// storage holds the new snapshot in place of the one it replaces. The resume +// retries while ate-api catches up. +func TestSuspendActor_ReplacesOwnSnapshot(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + first := h.SuspendedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(first) + replacedURI := latestSnapshot(t, first).GetDurableSnapshot().GetObject().GetSnapshotUri() + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor: %v", err) + } + objectsBefore := h.ObjectStore.Objects() + + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{ + Actor: ref, + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, + }) + if err != nil { + t.Fatalf("SuspendActor: %v", err) + } + fresh := latestSnapshot(t, resp.GetActor()) + freshURI := fresh.GetDurableSnapshot().GetObject().GetSnapshotUri() + if fresh.GetOwner() != ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR || freshURI == replacedURI { + t.Errorf("snapshot after the suspend = %v, want a new one of the actor's own replacing %q", fresh, replacedURI) + } + replaced := snapshotObjects(replacedURI) + wantObjects := append(slices.DeleteFunc(objectsBefore, func(o string) bool { return slices.Contains(replaced, o) }), snapshotObjects(freshURI)...) + if diff := cmp.Diff(wantObjects, h.ObjectStore.Objects(), cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" { + t.Errorf("object storage after the suspend (-want +got):\n%s", diff) + } +} + +// Suspends, synchronously, an actor that holds a snapshot of its own, while +// object storage fails to clean up the snapshot the suspend replaces. The +// request succeeds (OK) with a new snapshot of the actor's own, and object +// storage still holds the replaced one. A later resume restores the new +// snapshot. Deleting the actor then succeeds (OK) and leaves object storage +// with neither snapshot. +// The resume retries while ate-api catches up. +func TestSuspendActor_ReplacedSnapshotReleaseFails(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + first := h.SuspendedActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(first) + replacedURI := latestSnapshot(t, first).GetDurableSnapshot().GetObject().GetSnapshotUri() + objectsBeforeActor := slices.DeleteFunc(h.ObjectStore.Objects(), func(o string) bool { + return strings.Contains(o, "/actors/"+first.GetMetadata().GetUid()+"/") + }) + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor: %v", err) + } + h.ObjectStore.On(harness.ObjectStoreCleanupSnapshot).FailNext(harness.ErrStorageFailed) + + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{ + Actor: ref, + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, + }) + if err != nil { + t.Fatalf("SuspendActor: %v", err) + } + fresh := latestSnapshot(t, resp.GetActor()) + if fresh.GetOwner() != ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR || fresh.GetDurableSnapshot().GetObject().GetSnapshotUri() == replacedURI { + t.Errorf("snapshot after the suspend = %v, want a new one of the actor's own replacing %q", fresh, replacedURI) + } + if names, err := h.ObjectStore.Snapshot(replacedURI); err != nil || len(names) == 0 { + t.Errorf("replaced snapshot %q in object storage = %v, %v; want it kept", replacedURI, names, err) + } + + rec := node.Atelet.RecordCalls() + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor after the suspend: %v", err) + } + restore := onlyCall[*ateletpb.RestoreRequest](t, rec) + assertRestoreOf(t, restore, fresh) + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: ref}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + if diff := cmp.Diff(objectsBeforeActor, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after delete (-want +got):\n%s", diff) + } +} + +// Creating an actor from a template with an external volume, as a client that +// does not opt in to preview features, fails with INVALID_ARGUMENT and the +// error names the preview opt-in header. No actor is created. +func TestCreateActor_ExternalVolumesWithoutPreview(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data")) + + _, err := h.ControlWithoutPreview().CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()}, + }}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateActor without preview opt-in = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.Contains(msg, preview.Header) { + t.Errorf("CreateActor error %q does not name the preview header %s", msg, preview.Header) + } + listed, err := h.Control.ListActors(t.Context(), &ateapi.ListActorsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActors: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actors after a refused create (-want +got):\n%s", diff) + } +} + +// checkCrashMessage fails the test unless the actor's crash message contains +// each of parts. +func checkCrashMessage(t *testing.T, actor *ateapi.Actor, parts ...string) { + t.Helper() + msg := actor.GetStatus().GetCrash().GetMessage() + for _, part := range parts { + if !strings.Contains(msg, part) { + t.Errorf("crash message %q does not contain %q", msg, part) + } + } +} diff --git a/cmd/ateapi/internal/functionaltest/actortemplates_test.go b/cmd/ateapi/internal/functionaltest/actortemplates_test.go new file mode 100644 index 0000000000..d51cdacb23 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/actortemplates_test.go @@ -0,0 +1,712 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "fmt" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" + "go.ate.dev/substrate/internal/resources" +) + +// templateSpec is a valid ActorTemplate named name in atespace. +func templateSpec(atespace, name string) *ateapi.ActorTemplate { + return &ateapi.ActorTemplate{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: name}, + Containers: []*ateapi.Container{{Name: "main", Image: harness.Image, Command: []string{"/main"}}}, + WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"tier": "1"}}, + Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(harness.TemplateCPUMillicores, harness.TemplateMemoryBytes)}, + } +} + +// createdTemplate is the ActorTemplate ate-api creates from +// templateSpec(atespace, "tmpl-a"), without the metadata it assigns. +func createdTemplate(atespace string) *ateapi.ActorTemplate { + return &ateapi.ActorTemplate{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: "tmpl-a"}, + SnapshotConfig: &ateapi.SnapshotConfig{ + PreferredFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + GoldenSnapshotConfig: &ateapi.GoldenSnapshotConfig{Mode: ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_ENABLED}, + }, + Containers: []*ateapi.Container{{Name: "main", Image: harness.Image, Command: []string{"/main"}}}, + WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"tier": "1"}}, + Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(harness.TemplateCPUMillicores, harness.TemplateMemoryBytes)}, + Status: &ateapi.ActorTemplateStatus{}, + } +} + +// Creates an actor template, sending output-only metadata and status, and +// verifies that the whole resource has the expected shape: ate-api ignores what +// was sent and assigns its own. +func TestCreateActorTemplate(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + in := templateSpec(as, "tmpl-a") + // The caller sends output-only fields, which ate-api ignores. + setOutputOnlyMetadata(in.Metadata) + in.Status = &ateapi.ActorTemplateStatus{GoldenSnapshotStatus: &ateapi.GoldenSnapshotStatus{GoldenTag: &ateapi.ObjectRef{Atespace: as, Name: "tag-a"}}} + created, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: in}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + if diff := cmp.Diff(createdTemplate(as), created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created actor template (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) +} + +// Creating an actor template for an existing name fails with ALREADY_EXISTS +// and leaves the existing one unchanged. +func TestCreateActorTemplate_AlreadyExists(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + created, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: templateSpec(as, "tmpl-a")}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + + _, err = h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: templateSpec(as, "tmpl-a")}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateActorTemplate of an existing name = %v, want AlreadyExists", err) + } + got, err := h.Control.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"}}) + if err != nil { + t.Fatalf("GetActorTemplate: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("actor template after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor template with an invalid name fails with +// INVALID_ARGUMENT and the error names the invalid field. +func TestCreateActorTemplate_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: templateSpec(as, "Not_A_Valid_Name")}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateActorTemplate with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor_template.metadata.name: Invalid value") { + t.Errorf("CreateActorTemplate error %q does not start with %q", msg, "actor_template.metadata.name: Invalid value") + } +} + +// Creating an actor template in an atespace that doesn't exist fails with +// FAILED_PRECONDITION, and no template is created. +func TestCreateActorTemplate_AtespaceNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: templateSpec("team-missing", "tmpl-a")}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActorTemplate in a missing atespace = %v, want FailedPrecondition", err) + } + listed, err := h.Control.ListActorTemplates(t.Context(), &ateapi.ListActorTemplatesRequest{}) + if err != nil { + t.Fatalf("ListActorTemplates: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorTemplatesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actor templates after a refused create (-want +got):\n%s", diff) + } +} + +// Getting an existing actor template returns exactly the resource +// CreateActorTemplate returned. +func TestGetActorTemplate(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + created, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: templateSpec(as, "tmpl-a")}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + + got, err := h.Control.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"}}) + if err != nil { + t.Fatalf("GetActorTemplate: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("GetActorTemplate (-created +got):\n%s", diff) + } +} + +// Getting an actor template that doesn't exist fails with NOT_FOUND. +func TestGetActorTemplate_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetActorTemplate of a missing template = %v, want NotFound", err) + } +} + +// Getting an actor template with an invalid name fails with INVALID_ARGUMENT +// and the error names the invalid field. +func TestGetActorTemplate_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("GetActorTemplate with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor_template.name: Invalid value") { + t.Errorf("GetActorTemplate error %q does not start with %q", msg, "actor_template.name: Invalid value") + } +} + +// Creates N actor templates in one atespace and one in another, then lists +// the first atespace with pages smaller than N. The pages together hold +// exactly its N actor templates. Listing every atespace, with an empty +// atespace and the same page size, returns pages that together hold exactly +// all N+1 actor templates. +func TestListActorTemplates(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + other := h.CreateAtespace("team-b") + const n, pageSize = 5, 2 + var created []*ateapi.ActorTemplate + for i := range n { + tmpl, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: templateSpec(as, fmt.Sprintf("tmpl-%d", i))}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + created = append(created, tmpl) + } + createdOther, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: templateSpec(other, "tmpl-other")}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + + listAll := func(atespace string) []*ateapi.ActorTemplate { + t.Helper() + var listed []*ateapi.ActorTemplate + req := &ateapi.ListActorTemplatesRequest{Atespace: atespace, Options: &ateapi.ListOptions{PageSize: pageSize}} + for pages := 1; ; pages++ { + if pages > n+1 { + t.Fatalf("listing atespace %q took more than %d pages", atespace, n+1) + } + resp, err := h.Control.ListActorTemplates(t.Context(), req) + if err != nil { + t.Fatalf("ListActorTemplates of atespace %q, page %d: %v", atespace, pages, err) + } + if got := len(resp.GetActorTemplates()); got > pageSize { + t.Errorf("page %d of atespace %q holds %d templates, want at most %d", pages, atespace, got, pageSize) + } + listed = append(listed, resp.GetActorTemplates()...) + if resp.GetNextPageToken() == "" { + return listed + } + req.Options.PageToken = resp.GetNextPageToken() + } + } + byName := cmpopts.SortSlices(func(a, b *ateapi.ActorTemplate) bool { return a.GetMetadata().GetName() < b.GetMetadata().GetName() }) + if diff := cmp.Diff(created, listAll(as), protocmp.Transform(), byName); diff != "" { + t.Errorf("listed actor templates of %s (-want +got):\n%s", as, diff) + } + if diff := cmp.Diff(append(created, createdOther), listAll(""), protocmp.Transform(), byName); diff != "" { + t.Errorf("listed actor templates of every atespace (-want +got):\n%s", diff) + } +} + +// Listing actor templates with a negative page size fails with +// INVALID_ARGUMENT and the error names the invalid field. +func TestListActorTemplates_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListActorTemplates(t.Context(), &ateapi.ListActorTemplatesRequest{Options: &ateapi.ListOptions{PageSize: -1}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListActorTemplates with a negative page size = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "options.page_size: Invalid value") { + t.Errorf("ListActorTemplates error %q does not start with %q", msg, "options.page_size: Invalid value") + } +} + +// Listing actor templates with a malformed page token fails with +// INVALID_ARGUMENT. +func TestListActorTemplates_InvalidPageToken(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListActorTemplates(t.Context(), &ateapi.ListActorTemplatesRequest{Options: &ateapi.ListOptions{PageToken: "not-a-real-token"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListActorTemplates with a malformed page token = %v, want InvalidArgument", err) + } +} + +// Listing actor templates in an atespace that doesn't exist succeeds with an +// empty list. +func TestListActorTemplates_AtespaceNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + listed, err := h.Control.ListActorTemplates(t.Context(), &ateapi.ListActorTemplatesRequest{Atespace: "team-missing"}) + if err != nil { + t.Fatalf("ListActorTemplates in a missing atespace: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorTemplatesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("ListActorTemplates in a missing atespace (-want +got):\n%s", diff) + } +} + +// Deletes an existing actor template, retrying while the delete fails with +// ABORTED. The response is the deleted resource, and a later Get fails +// with NOT_FOUND. +func TestDeleteActorTemplate(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + ref := &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"} + created, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: templateSpec(as, "tmpl-a")}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + + var deleted *ateapi.ActorTemplate + if err := harness.RetryAborted(t.Context(), func() (err error) { + deleted, err = h.Control.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: ref}) + return err + }); err != nil { + t.Fatalf("DeleteActorTemplate: %v", err) + } + if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreDeleteTime); diff != "" { + t.Errorf("DeleteActorTemplate response (-created +deleted):\n%s", diff) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Error("DeleteActorTemplate response has no delete_time") + } + if _, err := h.Control.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetActorTemplate after delete = %v, want NotFound", err) + } +} + +// Deleting an actor template that doesn't exist fails with NOT_FOUND. +func TestDeleteActorTemplate_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("DeleteActorTemplate of a missing template = %v, want NotFound", err) + } +} + +// Deleting an actor template with golden snapshots disabled, which no +// background reconciler touches, with the wrong UID, with only the wrong +// version, or with the right UID but the wrong version fails with ABORTED and +// leaves it unchanged. With the right UID and version the delete succeeds (OK). +func TestDeleteActorTemplate_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + ref := &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"} + spec := templateSpec(as, "tmpl-a") + spec.SnapshotConfig = &ateapi.SnapshotConfig{GoldenSnapshotConfig: &ateapi.GoldenSnapshotConfig{Mode: ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_DISABLED}} + created, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: spec}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + uid, version := created.GetMetadata().GetUid(), created.GetMetadata().GetVersion() + + _, err = h.Control.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: ref, Options: &ateapi.DeleteOptions{Uid: foreignUID}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActorTemplate with the wrong uid = %v, want Aborted", err) + } + _, err = h.Control.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: ref, Options: &ateapi.DeleteOptions{Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActorTemplate with only the wrong version = %v, want Aborted", err) + } + _, err = h.Control.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActorTemplate with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: ref}) + if err != nil { + t.Fatalf("GetActorTemplate after refused deletes: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("actor template after refused deletes (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version}}); err != nil { + t.Errorf("DeleteActorTemplate with the right uid and version: %v", err) + } +} + +// Deleting an actor template with any of the invalid requests below fails +// with INVALID_ARGUMENT, and the error names the invalid field. +func TestDeleteActorTemplate_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + for _, tc := range []struct { + name string + req *ateapi.DeleteActorTemplateRequest + prefix string + }{ + { + name: "an invalid name", + req: &ateapi.DeleteActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}, + prefix: "actor_template.name: Invalid value", + }, + { + name: "a precondition uid that is not a UUID", + req: &ateapi.DeleteActorTemplateRequest{ + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"}, + Options: &ateapi.DeleteOptions{Uid: "not-a-uuid"}, + }, + prefix: "options.uid: Invalid value", + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := h.Control.DeleteActorTemplate(t.Context(), tc.req) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("DeleteActorTemplate = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, tc.prefix) { + t.Errorf("DeleteActorTemplate error %q does not start with %q", msg, tc.prefix) + } + }) + } +} + +// A new actor template eventually gets a golden tag, holding an uploaded +// snapshot, and getting its golden actor fails with NOT_FOUND. Deleting the +// template, retrying while the delete fails with ABORTED, succeeds (OK); +// getting its golden tag fails with NOT_FOUND, and object storage no longer +// holds the tag's snapshot. +func TestActorTemplate_GoldenTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + tagRef := tmpl.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag() + tag, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: tagRef}) + if err != nil { + t.Fatalf("GetTag of the golden tag: %v", err) + } + uri := tag.GetStatus().GetSnapshot().GetDurableSnapshot().GetObject().GetSnapshotUri() + if names, err := h.ObjectStore.Snapshot(uri); err != nil || len(names) == 0 { + t.Fatalf("golden snapshot %q in object storage = %v, %v; want it present", uri, names, err) + } + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: tagRef}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor of the golden actor = %v, want NotFound", err) + } + + ref := &ateapi.ObjectRef{Atespace: as, Name: tmpl.GetMetadata().GetName()} + if err := harness.RetryAborted(t.Context(), func() error { + _, err := h.Control.DeleteActorTemplate(t.Context(), &ateapi.DeleteActorTemplateRequest{ActorTemplate: ref}) + return err + }); err != nil { + t.Fatalf("DeleteActorTemplate: %v", err) + } + if _, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: tagRef}); status.Code(err) != codes.NotFound { + t.Errorf("GetTag of the golden tag after delete = %v, want NotFound", err) + } + if names, err := h.ObjectStore.Snapshot(uri); err != nil || len(names) != 0 { + t.Errorf("golden snapshot %q in object storage after delete = %v, %v; want none", uri, names, err) + } +} + +// An actor created before its template has a golden tag holds no snapshot, and +// still holds none once the template eventually gets one. Resuming it succeeds +// (OK) with exactly one atelet Run. The resume retries while ate-api catches +// up. +func TestActorTemplate_ActorCreatedBeforeGoldenTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + // The pool gets its first worker only after the actor is created. Until + // then the golden actor can't run, so the template has no golden tag. + pool := h.CreateWorkerPool("pool1", nil) + spec := templateSpec(as, "tmpl-a") + spec.WorkerSelector = &ateapi.Selector{MatchLabels: pool.Labels} + spec.Containers[0].WakeupProbe = &ateapi.WakeupProbe{HttpGet: &ateapi.HttpGetAction{Path: "/healthz", Port: 8080}} + if _, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: spec}); err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + tmplRef := &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"} + actor, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: tmplRef, + }}) + if err != nil { + t.Fatalf("CreateActor: %v", err) + } + if snaps := actor.GetStatus().GetSnapshots(); len(snaps) != 0 { + t.Errorf("new actor holds snapshots %v, want none", snaps) + } + + node := h.Node("a") + h.AddWorker(pool, node) + h.Eventually("the template's golden tag", func() bool { + got, err := h.Control.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: tmplRef}) + return err == nil && got.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag() != nil + }) + ref := harness.ActorRef(actor) + if snaps := h.GetActor(ref).GetStatus().GetSnapshots(); len(snaps) != 0 { + t.Errorf("actor holds snapshots %v after the golden tag, want none", snaps) + } + rec := node.Atelet.RecordCalls() + + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor: %v", err) + } + assertCalls(t, rec, harness.AteletRun) +} + +// An actor created from a template with golden snapshots disabled holds no +// snapshot. Resuming it succeeds (OK) with exactly one atelet Run, and a +// synchronous suspend then succeeds (OK) with a snapshot of its own. Once a +// template with golden snapshots enabled has its golden snapshot, the +// disabled template still has an empty status, and Getting its golden actor +// and golden tag fails with NOT_FOUND. The resume retries while ate-api +// catches up. +func TestActorTemplate_GoldenSnapshotDisabled(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + tmpl := templateSpec(as, "tmpl-a") + tmpl.WorkerSelector = &ateapi.Selector{MatchLabels: pool.Labels} + tmpl.SnapshotConfig = &ateapi.SnapshotConfig{GoldenSnapshotConfig: &ateapi.GoldenSnapshotConfig{Mode: ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_DISABLED}} + if _, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}); err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + actor, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "actor-a"}, + ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"}, + }}) + if err != nil { + t.Fatalf("CreateActor: %v", err) + } + if snaps := actor.GetStatus().GetSnapshots(); len(snaps) != 0 { + t.Errorf("new actor holds snapshots %v, want none", snaps) + } + ref := &ateapi.ObjectRef{Atespace: as, Name: "actor-a"} + rec := node.Atelet.RecordCalls() + + if _, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor: %v", err) + } + assertCalls(t, rec, harness.AteletRun) + resp, err := h.Control.SuspendActor(t.Context(), &ateapi.SuspendActorRequest{ + Actor: ref, + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, + }) + if err != nil { + t.Fatalf("SuspendActor: %v", err) + } + snaps := resp.GetActor().GetStatus().GetSnapshots() + if len(snaps) != 1 || snaps[0].GetOwner() != ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR { + t.Errorf("suspended actor holds snapshots %v, want one of its own", snaps) + } + + h.AddWorker(pool, node) + h.NewTemplate(as, pool) + disabled, err := h.Control.GetActorTemplate(t.Context(), &ateapi.GetActorTemplateRequest{ActorTemplate: &ateapi.ObjectRef{Atespace: as, Name: "tmpl-a"}}) + if err != nil { + t.Fatalf("GetActorTemplate: %v", err) + } + if diff := cmp.Diff(&ateapi.ActorTemplateStatus{}, disabled.GetStatus(), protocmp.Transform()); diff != "" { + t.Errorf("disabled template's status (-want +got):\n%s", diff) + } + golden := &ateapi.ObjectRef{Atespace: as, Name: disabled.GetMetadata().GetUid()} + if _, err := h.Control.GetActor(t.Context(), &ateapi.GetActorRequest{Actor: golden}); status.Code(err) != codes.NotFound { + t.Errorf("GetActor of the disabled template's golden actor = %v, want NotFound", err) + } + if _, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: golden}); status.Code(err) != codes.NotFound { + t.Errorf("GetTag of the disabled template's golden tag = %v, want NotFound", err) + } +} + +// Creates, opted in to preview features, an actor template with a golden +// egress policy, and verifies that the whole resource has the expected shape. +func TestCreateActorTemplate_GoldenEgressPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + tmpl := templateSpec(as, "tmpl-a") + tmpl.GoldenEgressPolicy = &ateapi.EgressPolicyTemplate{Rules: []*ateapi.EgressRule{{Http: &ateapi.HttpRule{Hostnames: []string{"api.example.com"}}}}} + + created, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + want := mutated(createdTemplate(as), func(tmpl *ateapi.ActorTemplate) { + tmpl.GoldenEgressPolicy = &ateapi.EgressPolicyTemplate{Rules: []*ateapi.EgressRule{{Http: &ateapi.HttpRule{ + Hostnames: []string{"api.example.com"}, + Ports: &ateapi.Ports{Numbers: []int32{80}}, + }}}} + }) + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created actor template (-want +got):\n%s", diff) + } +} + +// Creating an actor template with a golden egress policy, as a client that +// does not opt in to preview features, fails with INVALID_ARGUMENT, the error +// names the invalid field, and no template is created. +func TestCreateActorTemplate_GoldenEgressPolicyWithoutPreview(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + tmpl := templateSpec(as, "tmpl-a") + tmpl.GoldenEgressPolicy = &ateapi.EgressPolicyTemplate{Rules: []*ateapi.EgressRule{{Http: &ateapi.HttpRule{Hostnames: []string{"api.example.com"}}}}} + + _, err := h.ControlWithoutPreview().CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateActorTemplate with a golden egress policy without preview opt-in = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor_template.golden_egress_policy: Forbidden") { + t.Errorf("CreateActorTemplate error %q does not start with %q", msg, "actor_template.golden_egress_policy: Forbidden") + } + listed, err := h.Control.ListActorTemplates(t.Context(), &ateapi.ListActorTemplatesRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActorTemplates: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorTemplatesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actor templates after a refused create (-want +got):\n%s", diff) + } +} + +// Creates, opted in to preview features, an actor template with its own +// snapshot storage location, and verifies that the whole resource has the +// expected shape. +func TestCreateActorTemplate_StorageLocation(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + tmpl := templateSpec(as, "tmpl-a") + tmpl.SnapshotConfig = &ateapi.SnapshotConfig{StorageLocation: "gs://other-bucket/snapshots"} + + created, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}) + if err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + want := mutated(createdTemplate(as), func(tmpl *ateapi.ActorTemplate) { + tmpl.SnapshotConfig.StorageLocation = "gs://other-bucket/snapshots" + }) + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created actor template (-want +got):\n%s", diff) + } +} + +// Creating an actor template with its own snapshot storage location, as a +// client that does not opt in to preview features, fails with +// INVALID_ARGUMENT, the error names the invalid field, and no template is +// created. +func TestCreateActorTemplate_StorageLocationWithoutPreview(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + tmpl := templateSpec(as, "tmpl-a") + tmpl.SnapshotConfig = &ateapi.SnapshotConfig{StorageLocation: "gs://other-bucket/snapshots"} + + _, err := h.ControlWithoutPreview().CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateActorTemplate with a storage location without preview opt-in = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor_template.snapshot_config.storage_location: Forbidden") { + t.Errorf("CreateActorTemplate error %q does not start with %q", msg, "actor_template.snapshot_config.storage_location: Forbidden") + } + listed, err := h.Control.ListActorTemplates(t.Context(), &ateapi.ListActorTemplatesRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActorTemplates: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorTemplatesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actor templates after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor template with a golden egress policy and golden snapshots +// disabled fails with INVALID_ARGUMENT, the error names the golden egress +// policy, and no template is created. +func TestCreateActorTemplate_GoldenEgressPolicyWithGoldenSnapshotsDisabled(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + tmpl := templateSpec(as, "tmpl-a") + tmpl.GoldenEgressPolicy = &ateapi.EgressPolicyTemplate{Rules: []*ateapi.EgressRule{{Http: &ateapi.HttpRule{Hostnames: []string{"api.example.com"}}}}} + tmpl.SnapshotConfig = &ateapi.SnapshotConfig{GoldenSnapshotConfig: &ateapi.GoldenSnapshotConfig{Mode: ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_DISABLED}} + + _, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateActorTemplate with a golden egress policy and golden snapshots disabled = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor_template.golden_egress_policy: Forbidden") { + t.Errorf("CreateActorTemplate error %q does not start with %q", msg, "actor_template.golden_egress_policy: Forbidden") + } + listed, err := h.Control.ListActorTemplates(t.Context(), &ateapi.ListActorTemplatesRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActorTemplates: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorTemplatesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actor templates after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an actor template with an external volume, as a client that does +// not opt in to preview features, fails with INVALID_ARGUMENT, the error names +// the invalid field, and no template is created. +func TestCreateActorTemplate_ExternalVolumeWithoutPreview(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + as := h.CreateAtespace("team-a") + tmpl := templateSpec(as, "tmpl-a") + h.WithExternalVolume("data", "/data")(tmpl) + + _, err := h.ControlWithoutPreview().CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateActorTemplate with an external volume without preview opt-in = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "actor_template.volumes[0].external: Forbidden") { + t.Errorf("CreateActorTemplate error %q does not start with %q", msg, "actor_template.volumes[0].external: Forbidden") + } + listed, err := h.Control.ListActorTemplates(t.Context(), &ateapi.ListActorTemplatesRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListActorTemplates: %v", err) + } + if diff := cmp.Diff(&ateapi.ListActorTemplatesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("actor templates after a refused create (-want +got):\n%s", diff) + } +} diff --git a/cmd/ateapi/internal/functionaltest/api_test.go b/cmd/ateapi/internal/functionaltest/api_test.go new file mode 100644 index 0000000000..c756a551d9 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/api_test.go @@ -0,0 +1,52 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/encoding/protowire" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" +) + +// A request carrying a field the server does not know fails with +// INVALID_ARGUMENT. +func TestRejectUnknownFields(t *testing.T) { + t.Parallel() + h := harness.New(t) + req := &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: "team-a"}, + }} + unknown := protowire.AppendTag(nil, 9999, protowire.VarintType) + req.ProtoReflect().SetUnknown(protowire.AppendVarint(unknown, 42)) + + _, err := h.Control.CreateAtespace(t.Context(), req) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateAtespace with an unknown field = %v, want InvalidArgument", err) + } + listed, err := h.Control.ListAtespaces(t.Context(), &ateapi.ListAtespacesRequest{}) + if err != nil { + t.Fatalf("ListAtespaces: %v", err) + } + if diff := cmp.Diff(&ateapi.ListAtespacesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("atespaces after a refused create (-want +got):\n%s", diff) + } +} diff --git a/cmd/ateapi/internal/functionaltest/atespaces_test.go b/cmd/ateapi/internal/functionaltest/atespaces_test.go new file mode 100644 index 0000000000..4a3fc66fc0 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/atespaces_test.go @@ -0,0 +1,572 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "fmt" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" + "go.ate.dev/substrate/internal/resources" +) + +// Creates an atespace, sending output-only metadata, and verifies that the +// whole resource has the expected shape: ate-api ignores what was sent and +// assigns its own. +func TestCreateAtespace(t *testing.T) { + t.Parallel() + h := harness.New(t) + + in := &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "team-a"}} + // The caller sends output-only fields, which ate-api ignores. + setOutputOnlyMetadata(in.Metadata) + created, err := h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: in}) + if err != nil { + t.Fatalf("CreateAtespace: %v", err) + } + want := &ateapi.Atespace{Metadata: &ateapi.ResourceMetadata{Name: "team-a"}} + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created atespace (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) +} + +// Creating an atespace with the name of an existing one fails with +// ALREADY_EXISTS. +func TestCreateAtespace_AlreadyExists(t *testing.T) { + t.Parallel() + h := harness.New(t) + created, err := h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: "team-a"}, + }}) + if err != nil { + t.Fatalf("CreateAtespace: %v", err) + } + + _, err = h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: "team-a"}, + }}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateAtespace of an existing name = %v, want AlreadyExists", err) + } + got, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}}) + if err != nil { + t.Fatalf("GetAtespace: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("atespace after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an atespace with an invalid name fails with INVALID_ARGUMENT. +func TestCreateAtespace_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: "Not_A_Valid_Name"}, + }}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateAtespace with an invalid name = %v, want InvalidArgument", err) + } + listed, err := h.Control.ListAtespaces(t.Context(), &ateapi.ListAtespacesRequest{}) + if err != nil { + t.Fatalf("ListAtespaces: %v", err) + } + if diff := cmp.Diff(&ateapi.ListAtespacesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("atespaces after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an atespace as a principal no access policy names fails with +// PERMISSION_DENIED. Granted the viewer role by the global access policy, +// the principal still fails with PERMISSION_DENIED. In both cases no +// atespace is created: getting it fails with NOT_FOUND. Granted the owner +// role instead, the principal eventually creates the atespace (OK). +func TestCreateAtespace_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: "team-a"} + alice := h.ClientAs("alice") + create := func() error { + _, err := alice.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: ref.GetName()}, + }}) + return err + } + refusedCreate := func(holding string) { + t.Helper() + if err := create(); status.Code(err) != codes.PermissionDenied { + t.Errorf("CreateAtespace holding %s = %v, want PermissionDenied", holding, err) + } + if _, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetAtespace after a refused create holding %s = %v, want NotFound", holding, err) + } + } + + refusedCreate("no role") + setGlobalBinding(t, h, "viewer", harness.Member("alice")) + refusedCreate("viewer") + setGlobalBinding(t, h, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "CreateAtespace holding owner", codes.OK, create) +} + +// Getting an existing atespace returns exactly the resource CreateAtespace +// returned. +func TestGetAtespace(t *testing.T) { + t.Parallel() + h := harness.New(t) + created, err := h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: "team-a"}, + }}) + if err != nil { + t.Fatalf("CreateAtespace: %v", err) + } + + got, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a"}}) + if err != nil { + t.Fatalf("GetAtespace: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("GetAtespace (-created +got):\n%s", diff) + } +} + +// Getting an atespace that doesn't exist fails with NOT_FOUND. +func TestGetAtespace_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetAtespace of a missing atespace = %v, want NotFound", err) + } +} + +// Getting an atespace with any of the invalid requests below fails with +// INVALID_ARGUMENT, and the error names the invalid field. +func TestGetAtespace_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + for _, tc := range []struct { + name string + req *ateapi.GetAtespaceRequest + prefix string + }{ + { + name: "an invalid name", + req: &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}}, + prefix: "atespace.name: Invalid value", + }, + { + name: "a ref that sets atespace, which an atespace's ref must leave empty", + req: &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a", Atespace: "team-b"}}, + prefix: "atespace.atespace: Forbidden", + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := h.Control.GetAtespace(t.Context(), tc.req) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("GetAtespace = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, tc.prefix) { + t.Errorf("GetAtespace error %q does not start with %q", msg, tc.prefix) + } + }) + } +} + +// Getting an atespace as a principal no access policy names fails with +// PERMISSION_DENIED, both for an atespace that exists and for one that does +// not. Granted the viewer role, then the editor role, then the owner role, +// by the atespace's access policy, the principal eventually gets the +// atespace (OK) each time. +func TestGetAtespace_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}) + return err + } + + if err := get(); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetAtespace holding no role = %v, want PermissionDenied", err) + } + if _, err := alice.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-missing"}}); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetAtespace of a missing atespace holding no role = %v, want PermissionDenied", err) + } + for _, role := range []string{"viewer", "editor", "owner"} { + setAtespaceBinding(t, h, ref, role, harness.Member("alice")) + eventuallyAllowed(t, h, fmt.Sprintf("GetAtespace holding %s", role), codes.OK, get) + } +} + +// A principal granted the viewer role by an atespace's access policy +// eventually gets the atespace (OK). After the admin deletes the atespace +// and creates it again under the same name, getting it as the principal +// eventually fails with PERMISSION_DENIED, and the new atespace has no +// access policy: getting the policy fails with NOT_FOUND. +func TestGetAtespace_AtespaceRecreated(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}) + return err + } + setAtespaceBinding(t, h, ref, "viewer", harness.Member("alice")) + eventuallyAllowed(t, h, "GetAtespace holding viewer", codes.OK, get) + + if _, err := h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref}); err != nil { + t.Fatalf("DeleteAtespace: %v", err) + } + h.CreateAtespace(ref.GetName()) + h.Eventually("GetAtespace of the recreated atespace to be denied", func() bool { + return status.Code(get()) == codes.PermissionDenied + }) + if _, err := h.Control.GetAtespaceAccessPolicy(t.Context(), &ateapi.GetAtespaceAccessPolicyRequest{Name: "default", Atespace: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetAtespaceAccessPolicy of the recreated atespace = %v, want NotFound", err) + } +} + +// Creates N atespaces and lists them with pages smaller than N. +func TestListAtespaces(t *testing.T) { + t.Parallel() + h := harness.New(t) + const n, pageSize = 5, 2 + var created []*ateapi.Atespace + for i := range n { + atespace, err := h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: fmt.Sprintf("team-%d", i)}, + }}) + if err != nil { + t.Fatalf("CreateAtespace: %v", err) + } + created = append(created, atespace) + } + + var listed []*ateapi.Atespace + req := &ateapi.ListAtespacesRequest{Options: &ateapi.ListOptions{PageSize: pageSize}} + for pages := 1; ; pages++ { + if pages > n { + t.Fatalf("listing took more than %d pages", n) + } + resp, err := h.Control.ListAtespaces(t.Context(), req) + if err != nil { + t.Fatalf("ListAtespaces page %d: %v", pages, err) + } + if got := len(resp.GetAtespaces()); got > pageSize { + t.Errorf("page %d holds %d atespaces, want at most %d", pages, got, pageSize) + } + listed = append(listed, resp.GetAtespaces()...) + if resp.GetNextPageToken() == "" { + break + } + req.Options.PageToken = resp.GetNextPageToken() + } + byName := cmpopts.SortSlices(func(a, b *ateapi.Atespace) bool { return a.GetMetadata().GetName() < b.GetMetadata().GetName() }) + if diff := cmp.Diff(created, listed, protocmp.Transform(), byName); diff != "" { + t.Errorf("listed atespaces (-want +got):\n%s", diff) + } +} + +// Listing atespaces with a negative page size fails with INVALID_ARGUMENT +// and the error names the invalid field. +func TestListAtespaces_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListAtespaces(t.Context(), &ateapi.ListAtespacesRequest{Options: &ateapi.ListOptions{PageSize: -1}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListAtespaces with a negative page size = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "options.page_size: Invalid value") { + t.Errorf("ListAtespaces error %q does not start with %q", msg, "options.page_size: Invalid value") + } +} + +// Listing atespaces with a malformed page token fails with INVALID_ARGUMENT. +func TestListAtespaces_InvalidPageToken(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListAtespaces(t.Context(), &ateapi.ListAtespacesRequest{Options: &ateapi.ListOptions{PageToken: "not-a-real-token"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListAtespaces with a malformed page token = %v, want InvalidArgument", err) + } +} + +// Listing atespaces as a principal no access policy names fails with +// PERMISSION_DENIED. Granted the viewer role, then the owner role, by the +// global access policy, the principal eventually lists atespaces (OK) each +// time. +func TestListAtespaces_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + h.CreateAtespace("team-a") + alice := h.ClientAs("alice") + list := func() error { + _, err := alice.ListAtespaces(t.Context(), &ateapi.ListAtespacesRequest{}) + return err + } + + if err := list(); status.Code(err) != codes.PermissionDenied { + t.Errorf("ListAtespaces holding no role = %v, want PermissionDenied", err) + } + for _, role := range []string{"viewer", "owner"} { + setGlobalBinding(t, h, role, harness.Member("alice")) + eventuallyAllowed(t, h, fmt.Sprintf("ListAtespaces holding %s", role), codes.OK, list) + } +} + +// Deletes an empty atespace. The response is the deleted atespace, and a +// later Get fails with NOT_FOUND. +func TestDeleteAtespace(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: "team-a"} + created, err := h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: "team-a"}, + }}) + if err != nil { + t.Fatalf("CreateAtespace: %v", err) + } + + deleted, err := h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref}) + if err != nil { + t.Fatalf("DeleteAtespace: %v", err) + } + if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreDeleteTime); diff != "" { + t.Errorf("DeleteAtespace response (-created +deleted):\n%s", diff) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Error("DeleteAtespace response has no delete_time") + } + if _, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetAtespace after delete = %v, want NotFound", err) + } +} + +// Deleting an atespace that doesn't exist fails with NOT_FOUND. +func TestDeleteAtespace_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("DeleteAtespace of a missing atespace = %v, want NotFound", err) + } +} + +// Deleting an atespace with the wrong UID, with only the wrong version, or with +// the right UID but the wrong version fails with ABORTED and leaves it +// unchanged. With the right UID and version the delete succeeds, and deleting +// it again fails with NOT_FOUND. +func TestDeleteAtespace_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: "team-a"} + created, err := h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: "team-a"}, + }}) + if err != nil { + t.Fatalf("CreateAtespace: %v", err) + } + uid, version := created.GetMetadata().GetUid(), created.GetMetadata().GetVersion() + + _, err = h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref, Options: &ateapi.DeleteOptions{Uid: foreignUID}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteAtespace with the wrong uid = %v, want Aborted", err) + } + _, err = h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref, Options: &ateapi.DeleteOptions{Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteAtespace with only the wrong version = %v, want Aborted", err) + } + _, err = h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteAtespace with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}) + if err != nil { + t.Fatalf("GetAtespace after refused deletes: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("atespace after refused deletes (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version}}); err != nil { + t.Fatalf("DeleteAtespace with the right uid and version: %v", err) + } + _, err = h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version}}) + if status.Code(err) != codes.NotFound { + t.Errorf("DeleteAtespace after delete = %v, want NotFound", err) + } +} + +// Deleting an atespace that holds an actor template fails with +// FAILED_PRECONDITION. +func TestDeleteAtespace_HasChildren(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: "team-a"} + created, err := h.Control.CreateAtespace(t.Context(), &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: "team-a"}, + }}) + if err != nil { + t.Fatalf("CreateAtespace: %v", err) + } + if _, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: &ateapi.ActorTemplate{ + Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "tmpl-a"}, + Containers: []*ateapi.Container{{Name: "main", Image: harness.Image, Command: []string{"/main"}}}, + WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"pool": "pool1"}}, + Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(harness.TemplateCPUMillicores, harness.TemplateMemoryBytes)}, + }}); err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + + _, err = h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("DeleteAtespace holding an actor template = %v, want FailedPrecondition", err) + } + got, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}) + if err != nil { + t.Fatalf("GetAtespace after a refused delete: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("atespace after a refused delete (-want +got):\n%s", diff) + } +} + +// Deleting an atespace with any of the invalid requests below fails with +// INVALID_ARGUMENT, and the error names the invalid field. +func TestDeleteAtespace_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + for _, tc := range []struct { + name string + req *ateapi.DeleteAtespaceRequest + prefix string + }{ + { + name: "an invalid name", + req: &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}}, + prefix: "atespace.name: Invalid value", + }, + { + name: "a ref that sets atespace, which an atespace's ref must leave empty", + req: &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-a", Atespace: "team-b"}}, + prefix: "atespace.atespace: Forbidden", + }, + { + name: "a precondition uid that is not a UUID", + req: &ateapi.DeleteAtespaceRequest{ + Atespace: &ateapi.ObjectRef{Name: "team-a"}, + Options: &ateapi.DeleteOptions{Uid: "not-a-uuid"}, + }, + prefix: "options.uid: Invalid value", + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := h.Control.DeleteAtespace(t.Context(), tc.req) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("DeleteAtespace = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, tc.prefix) { + t.Errorf("DeleteAtespace error %q does not start with %q", msg, tc.prefix) + } + }) + } +} + +// Deleting an atespace as a principal no access policy names fails with +// PERMISSION_DENIED, both for an atespace that exists and for one that does +// not. Granted the viewer role, then the editor role, by the atespace's +// access policy, the principal still fails with PERMISSION_DENIED, and the +// atespace is unchanged. Granted the owner role instead, the principal +// eventually deletes the atespace (OK). +func TestDeleteAtespace_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + refusedDelete := func(holding string) { + t.Helper() + before, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}) + if err != nil { + t.Fatalf("GetAtespace: %v", err) + } + if _, err := alice.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref}); status.Code(err) != codes.PermissionDenied { + t.Errorf("DeleteAtespace holding %s = %v, want PermissionDenied", holding, err) + } + after, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}) + if err != nil { + t.Fatalf("GetAtespace after a refused delete holding %s: %v", holding, err) + } + if diff := cmp.Diff(before, after, protocmp.Transform()); diff != "" { + t.Errorf("atespace after a refused delete holding %s (-want +got):\n%s", holding, diff) + } + } + + refusedDelete("no role") + if _, err := alice.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: &ateapi.ObjectRef{Name: "team-missing"}}); status.Code(err) != codes.PermissionDenied { + t.Errorf("DeleteAtespace of a missing atespace holding no role = %v, want PermissionDenied", err) + } + for _, role := range []string{"viewer", "editor"} { + setAtespaceBinding(t, h, ref, role, harness.Member("alice")) + refusedDelete(role) + } + setAtespaceBinding(t, h, ref, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "DeleteAtespace holding owner", codes.OK, func() error { + _, err := alice.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref}) + return err + }) +} + +// Deletes an empty atespace while another atespace holds an actor template. +// The request succeeds (OK), and a later Get fails with NOT_FOUND. +func TestDeleteAtespace_OtherAtespaceNotEmpty(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + other := h.CreateAtespace("team-b") + if _, err := h.Control.CreateActorTemplate(t.Context(), &ateapi.CreateActorTemplateRequest{ActorTemplate: &ateapi.ActorTemplate{ + Metadata: &ateapi.ResourceMetadata{Atespace: other, Name: "tmpl-a"}, + Containers: []*ateapi.Container{{Name: "main", Image: harness.Image, Command: []string{"/main"}}}, + WorkerSelector: &ateapi.Selector{MatchLabels: map[string]string{"pool": "pool1"}}, + Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(harness.TemplateCPUMillicores, harness.TemplateMemoryBytes)}, + }}); err != nil { + t.Fatalf("CreateActorTemplate: %v", err) + } + + if _, err := h.Control.DeleteAtespace(t.Context(), &ateapi.DeleteAtespaceRequest{Atespace: ref}); err != nil { + t.Fatalf("DeleteAtespace: %v", err) + } + if _, err := h.Control.GetAtespace(t.Context(), &ateapi.GetAtespaceRequest{Atespace: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetAtespace after delete = %v, want NotFound", err) + } +} diff --git a/cmd/ateapi/internal/functionaltest/cmp_test.go b/cmd/ateapi/internal/functionaltest/cmp_test.go new file mode 100644 index 0000000000..e5d2272619 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/cmp_test.go @@ -0,0 +1,140 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/testing/protocmp" + "google.golang.org/protobuf/types/known/timestamppb" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness/grpcfake" + "go.ate.dev/substrate/internal/resources" +) + +// cmp options, used with protocmp.Transform, that skip the resource metadata +// ate-api assigns. +var ( + // ignoreVersion and ignoreUpdateTime skip what ate-api changes on every + // write, for comparing a resource before and after an operation. + ignoreVersion = protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "version") + ignoreUpdateTime = protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "update_time") + // ignoreDeleteTime skips the time ate-api stamps on a deleted resource. + ignoreDeleteTime = protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "delete_time") + // ignoreCreatedMetadata skips what ate-api assigns when it creates a + // resource, for comparing a new resource against a literal. + ignoreCreatedMetadata = protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "uid", "version", "create_time", "update_time") + // ignoreActivationUID skips the UID ate-api assigns each activation it + // starts. + ignoreActivationUID = protocmp.IgnoreFields(&ateapi.WorkerAssignment{}, "actor_activation_uid") +) + +// foreignUID is a valid UID no resource has, for preconditions that must miss. +const foreignUID = "0f0e0d0c-0b0a-4908-8706-050403020100" + +// callerVersion and callerTime are output-only values a caller sends, which +// ate-api must not store. +var ( + callerVersion int64 = 7 + callerTime = timestamppb.New(time.Date(2000, 1, 1, 0, 0, 0, 0, time.UTC)) +) + +// setOutputOnlyMetadata sets the metadata fields ate-api assigns on create to +// values a caller could send. +func setOutputOnlyMetadata(m *ateapi.ResourceMetadata) { + m.Uid = foreignUID + m.Version = callerVersion + m.CreateTime = callerTime + m.UpdateTime = callerTime + m.DeleteTime = callerTime +} + +// assertAssignedMetadata checks that ate-api replaced every field +// setOutputOnlyMetadata sets. +func assertAssignedMetadata(t *testing.T, m *ateapi.ResourceMetadata) { + t.Helper() + if m.GetUid() == foreignUID || m.GetVersion() == callerVersion || proto.Equal(m.GetCreateTime(), callerTime) || proto.Equal(m.GetUpdateTime(), callerTime) || m.GetDeleteTime() != nil { + t.Errorf("created metadata %v keeps output-only fields the caller sent", m) + } +} + +// mutated returns a copy of m with mutate applied. +func mutated[M proto.Message](m M, mutate func(M)) M { + c := proto.CloneOf(m) + mutate(c) + return c +} + +// templateResources is the size of the actors of harness templates. +func templateResources() *ateapi.Resources { + return resources.CPUMemory(harness.TemplateCPUMillicores, harness.TemplateMemoryBytes) +} + +// latestSnapshot is the actor's snapshot with the highest generation. +func latestSnapshot(t *testing.T, actor *ateapi.Actor) *ateapi.Snapshot { + t.Helper() + var latest *ateapi.Snapshot + for _, s := range actor.GetStatus().GetSnapshots() { + if s.GetGeneration() >= latest.GetGeneration() { + latest = s + } + } + if latest == nil { + t.Fatalf("actor %s has no snapshot", actor.GetMetadata().GetName()) + } + return latest +} + +// snapshotObjects are the objects the fake atelet uploads for the snapshot at +// uri. +func snapshotObjects(uri string) []string { + prefix := strings.TrimPrefix(uri, "gs://") + return []string{prefix + "/manifest.json", prefix + "/memory.zst"} +} + +// assertCalls checks that a fake received calls to exactly methods since rec +// started, in order. With no methods, it checks that the fake received none. +func assertCalls[M ~string](t *testing.T, rec *grpcfake.Recording[M], methods ...M) { + t.Helper() + var got []M + for _, call := range rec.Calls() { + got = append(got, call.Method) + } + if diff := cmp.Diff(methods, got, cmpopts.EquateEmpty()); diff != "" { + t.Errorf("calls (-want +got):\n%s", diff) + } +} + +// onlyCall checks that a fake received exactly one call since rec started, with +// a request of type R, and returns that request. +func onlyCall[R any, M ~string](t *testing.T, rec *grpcfake.Recording[M]) R { + t.Helper() + calls := rec.Calls() + if len(calls) == 1 { + if req, ok := calls[0].Request.(R); ok { + return req + } + } + var zero R + t.Fatalf("received %v, want exactly one %T", calls, zero) + return zero +} diff --git a/cmd/ateapi/internal/functionaltest/csidrivers_test.go b/cmd/ateapi/internal/functionaltest/csidrivers_test.go new file mode 100644 index 0000000000..bbeb76d7ab --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/csidrivers_test.go @@ -0,0 +1,568 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "fmt" + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/testing/protocmp" + "google.golang.org/protobuf/types/known/timestamppb" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" + "go.ate.dev/substrate/internal/preview" +) + +func newCSIDriver(name, driverName string) *ateapi.CsiDriver { + return &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: name}, + DriverName: driverName, + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "csi-nfs-controller.csi-nfs.svc", Port: 12345}, + Tls: &ateapi.CsiDriverTlsConfig{ServerName: "csi-nfs-controller.csi-nfs.svc"}, + } +} + +func createCSIDriver(t *testing.T, h *harness.Harness, name, driverName string) *ateapi.CsiDriver { + t.Helper() + created, err := h.Control.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{ + CsiDriver: newCSIDriver(name, driverName), + }) + if err != nil { + t.Fatalf("CreateCsiDriver(%s): %v", name, err) + } + return created +} + +// Creates a CsiDriver, sending output-only metadata, and verifies that ate-api +// assigns its own metadata, GetCsiDriver returns the same resource, duplicate +// name fails with ALREADY_EXISTS, duplicate driver_name fails with +// FAILED_PRECONDITION, and a client without preview opt-in fails with +// FAILED_PRECONDITION on Create and Update while Get, List, and Delete continue +// to work so existing drivers are not stranded. +func TestCreateCSIDriver(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + + in := newCSIDriver("csi-nfs", "nfs.csi.k8s.io") + setOutputOnlyMetadata(in.Metadata) + created, err := h.Control.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{ + CsiDriver: in, + }) + if err != nil { + t.Fatalf("CreateCsiDriver: %v", err) + } + if diff := cmp.Diff(newCSIDriver("csi-nfs", "nfs.csi.k8s.io"), created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("CreateCsiDriver mismatch (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) + + got, err := h.Control.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{ + CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}, + }) + if err != nil { + t.Fatalf("GetCsiDriver: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("GetCsiDriver mismatch (-created +got):\n%s", diff) + } + + _, err = h.Control.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{ + CsiDriver: newCSIDriver("csi-nfs", "other.csi.k8s.io"), + }) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("duplicate name CreateCsiDriver = %v, want AlreadyExists", err) + } + + _, err = h.Control.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{ + CsiDriver: newCSIDriver("csi-nfs-2", "nfs.csi.k8s.io"), + }) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("duplicate driver_name CreateCsiDriver = %v, want FailedPrecondition", err) + } + + // Without preview opt-in, Create and Update are rejected while Get, List, + // and Delete still work so existing drivers can be inspected and removed. + noPreview := h.ControlWithoutPreview() + for name, call := range map[string]func() error{ + "Create": func() error { + _, err := noPreview.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{ + CsiDriver: newCSIDriver("csi-other", "other.csi.k8s.io"), + }) + return err + }, + "Update": func() error { + _, err := noPreview.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{ + CsiDriver: proto.CloneOf(created), + }) + return err + }, + } { + err := call() + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("%sCsiDriver without preview = %v, want FailedPrecondition", name, err) + } + if msg := status.Convert(err).Message(); !strings.Contains(msg, string(preview.GateExternalVolumes)) || !strings.Contains(msg, preview.Header) { + t.Errorf("%sCsiDriver without preview error %q does not name gate and header", name, msg) + } + } + if _, err := noPreview.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{ + CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}, + }); err != nil { + t.Errorf("GetCsiDriver without preview: %v", err) + } + if _, err := noPreview.ListCsiDrivers(t.Context(), &ateapi.ListCsiDriversRequest{}); err != nil { + t.Errorf("ListCsiDrivers without preview: %v", err) + } + if _, err := noPreview.DeleteCsiDriver(t.Context(), &ateapi.DeleteCsiDriverRequest{ + CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}, + }); err != nil { + t.Errorf("DeleteCsiDriver without preview: %v", err) + } +} + +// Creating a CsiDriver requires the global owner role. No role and global +// viewer are denied without creating the driver. +func TestCreateCSIDriver_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + ref := &ateapi.ObjectRef{Name: "csi-nfs"} + alice := h.ClientAs("alice") + create := func() error { + _, err := alice.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{ + CsiDriver: newCSIDriver(ref.GetName(), "nfs.csi.k8s.io"), + }) + return err + } + refusedCreate := func(holding string) { + t.Helper() + if err := create(); status.Code(err) != codes.PermissionDenied { + t.Errorf("CreateCsiDriver holding %s = %v, want PermissionDenied", holding, err) + } + if _, err := h.Control.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{CsiDriver: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetCsiDriver after refused create holding %s = %v, want NotFound", holding, err) + } + } + + refusedCreate("no role") + setGlobalBinding(t, h, "viewer", harness.Member("alice")) + refusedCreate("viewer") + setGlobalBinding(t, h, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "CreateCsiDriver holding owner", codes.OK, create) +} + +// Getting a missing CsiDriver fails with NOT_FOUND; listing paginates in name +// order; an invalid page token fails with INVALID_ARGUMENT. +func TestGetAndListCSIDrivers(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + + _, err := h.Control.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{ + CsiDriver: &ateapi.ObjectRef{Name: "missing"}, + }) + if status.Code(err) != codes.NotFound { + t.Errorf("GetCsiDriver(missing) = %v, want NotFound", err) + } + + for _, item := range []struct{ name, driver string }{ + {"drv-c", "c.csi.k8s.io"}, + {"drv-a", "a.csi.k8s.io"}, + {"drv-b", "b.csi.k8s.io"}, + } { + createCSIDriver(t, h, item.name, item.driver) + } + + var got []string + for token := ""; ; { + resp, err := h.Control.ListCsiDrivers(t.Context(), &ateapi.ListCsiDriversRequest{ + Options: &ateapi.ListOptions{PageSize: 2, PageToken: token}, + }) + if err != nil { + t.Fatalf("ListCsiDrivers: %v", err) + } + for _, driver := range resp.GetCsiDrivers() { + got = append(got, driver.GetMetadata().GetName()) + } + if token = resp.GetNextPageToken(); token == "" { + break + } + } + if diff := cmp.Diff([]string{"drv-a", "drv-b", "drv-c"}, got); diff != "" { + t.Errorf("listed drivers mismatch (-want +got):\n%s", diff) + } + + _, err = h.Control.ListCsiDrivers(t.Context(), &ateapi.ListCsiDriversRequest{ + Options: &ateapi.ListOptions{PageToken: "%%%"}, + }) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListCsiDrivers(invalid token) = %v, want InvalidArgument", err) + } +} + +// Getting a CsiDriver requires the global viewer role, both for an existing +// driver and for a missing one. +func TestGetCSIDriver_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + createCSIDriver(t, h, "csi-nfs", "nfs.csi.k8s.io") + ref := &ateapi.ObjectRef{Name: "csi-nfs"} + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{CsiDriver: ref}) + return err + } + + if err := get(); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetCsiDriver holding no role = %v, want PermissionDenied", err) + } + if _, err := alice.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: "missing"}}); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetCsiDriver(missing) holding no role = %v, want PermissionDenied", err) + } + for _, role := range []string{"viewer", "owner"} { + setGlobalBinding(t, h, role, harness.Member("alice")) + eventuallyAllowed(t, h, fmt.Sprintf("GetCsiDriver holding %s", role), codes.OK, get) + } +} + +// Listing CsiDrivers requires the global viewer role. +func TestListCSIDrivers_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + createCSIDriver(t, h, "csi-nfs", "nfs.csi.k8s.io") + alice := h.ClientAs("alice") + list := func() error { + _, err := alice.ListCsiDrivers(t.Context(), &ateapi.ListCsiDriversRequest{}) + return err + } + + if err := list(); status.Code(err) != codes.PermissionDenied { + t.Errorf("ListCsiDrivers holding no role = %v, want PermissionDenied", err) + } + for _, role := range []string{"viewer", "owner"} { + setGlobalBinding(t, h, role, harness.Member("alice")) + eventuallyAllowed(t, h, fmt.Sprintf("ListCsiDrivers holding %s", role), codes.OK, list) + } +} + +// Updating a CsiDriver replaces mutable fields while preserving server-managed +// metadata, clears omitted optional fields, enforces optimistic-concurrency +// preconditions, and rejects immutable or invalid updates and callers without +// preview opt-in. +func TestUpdateCSIDriver(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + + created := createCSIDriver(t, h, "csi-nfs", "nfs.csi.k8s.io") + uid := created.GetMetadata().GetUid() + + reqDriver := proto.CloneOf(created) + reqDriver.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "10.0.0.2", Port: 9000} + reqDriver.Tls = &ateapi.CsiDriverTlsConfig{ServerName: "alt-nfs.csi-nfs.svc"} + reqDriver.Metadata.CreateTime = timestamppb.New(time.Unix(1, 0)) + reqDriver.Metadata.UpdateTime = timestamppb.New(time.Unix(2, 0)) + reqDriver.Metadata.DeleteTime = timestamppb.New(time.Unix(3, 0)) + + updated, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: reqDriver}) + if err != nil { + t.Fatalf("UpdateCsiDriver: %v", err) + } + md := updated.GetMetadata() + if md.GetVersion() != 2 || md.GetUid() != uid || + !md.GetCreateTime().AsTime().Equal(created.GetMetadata().GetCreateTime().AsTime()) || + md.GetUpdateTime().AsTime().Before(created.GetMetadata().GetUpdateTime().AsTime()) || + md.GetDeleteTime() != nil { + t.Errorf("updated metadata = %v, created = %v", md, created.GetMetadata()) + } + + clearedReq := proto.CloneOf(updated) + clearedReq.Tls = nil + cleared, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: clearedReq}) + if err != nil { + t.Fatalf("UpdateCsiDriver(clear optional): %v", err) + } + if cleared.GetMetadata().GetVersion() != 3 || cleared.GetTls() != nil { + t.Errorf("cleared driver = %v, want version 3 with nil tls", cleared) + } + + noUID := proto.CloneOf(cleared) + noUID.Metadata.Uid = "" + if _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: noUID}); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateCsiDriver without uid = %v, want InvalidArgument", err) + } + + noVer := proto.CloneOf(cleared) + noVer.Metadata.Version = 0 + if _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: noVer}); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateCsiDriver without version = %v, want InvalidArgument", err) + } + + stale := proto.CloneOf(cleared) + stale.Metadata.Version = 1 + if _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: stale}); status.Code(err) != codes.Aborted { + t.Errorf("UpdateCsiDriver stale version = %v, want Aborted", err) + } + + wrongUID := proto.CloneOf(cleared) + wrongUID.Metadata.Uid = foreignUID + if _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: wrongUID}); status.Code(err) != codes.Aborted { + t.Errorf("UpdateCsiDriver wrong uid = %v, want Aborted", err) + } + + missing := newCSIDriver("does-not-exist", "other.csi.k8s.io") + missing.Metadata.Uid = foreignUID + missing.Metadata.Version = 1 + if _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: missing}); status.Code(err) != codes.NotFound { + t.Errorf("UpdateCsiDriver missing = %v, want NotFound", err) + } + + changedDriver := proto.CloneOf(cleared) + changedDriver.DriverName = "other.csi.k8s.io" + if _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: changedDriver}); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateCsiDriver changed driver_name = %v, want InvalidArgument", err) + } + + badEndpoint := proto.CloneOf(cleared) + badEndpoint.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "http://10.0.0.2", Port: 9000} + if _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: badEndpoint}); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateCsiDriver bad endpoint = %v, want InvalidArgument", err) + } + + badTLS := proto.CloneOf(cleared) + badTLS.Tls = &ateapi.CsiDriverTlsConfig{} + if _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: badTLS}); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateCsiDriver bad tls = %v, want InvalidArgument", err) + } + + if _, err := h.ControlWithoutPreview().UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: proto.CloneOf(cleared)}); status.Code(err) != codes.FailedPrecondition { + t.Errorf("UpdateCsiDriver without preview = %v, want FailedPrecondition", err) + } +} + +// Updating a CsiDriver requires the global owner role. No role and global +// viewer are denied without mutating the driver. +func TestUpdateCSIDriver_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + created := createCSIDriver(t, h, "csi-nfs", "nfs.csi.k8s.io") + alice := h.ClientAs("alice") + update := func() error { + reqDriver := proto.CloneOf(created) + reqDriver.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "10.0.0.2", Port: 9000} + _, err := alice.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{CsiDriver: reqDriver}) + return err + } + refusedUpdate := func(holding string) { + t.Helper() + if err := update(); status.Code(err) != codes.PermissionDenied { + t.Errorf("UpdateCsiDriver holding %s = %v, want PermissionDenied", holding, err) + } + got, err := h.Control.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}}) + if err != nil || got.GetMetadata().GetVersion() != created.GetMetadata().GetVersion() { + t.Errorf("GetCsiDriver after refused update holding %s = (%v, %v), want unchanged version %d", holding, got, err, created.GetMetadata().GetVersion()) + } + } + + refusedUpdate("no role") + setGlobalBinding(t, h, "viewer", harness.Member("alice")) + refusedUpdate("viewer") + setGlobalBinding(t, h, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "UpdateCsiDriver holding owner", codes.OK, update) +} + +// Deleting a CsiDriver rejects mismatched preconditions with ABORTED and +// succeeds with matching preconditions. +func TestDeleteCSIDriver(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + + ref := &ateapi.ObjectRef{Name: "csi-nfs"} + del := func(opts *ateapi.DeleteOptions) (*ateapi.CsiDriver, error) { + return h.Control.DeleteCsiDriver(t.Context(), &ateapi.DeleteCsiDriverRequest{ + CsiDriver: ref, + Options: opts, + }) + } + + created := createCSIDriver(t, h, "csi-nfs", "nfs.csi.k8s.io") + uid, version := created.GetMetadata().GetUid(), created.GetMetadata().GetVersion() + + if _, err := del(&ateapi.DeleteOptions{Uid: uid, Version: version + 1}); status.Code(err) != codes.Aborted { + t.Errorf("DeleteCsiDriver stale version = %v, want Aborted", err) + } + if _, err := del(&ateapi.DeleteOptions{Uid: foreignUID}); status.Code(err) != codes.Aborted { + t.Errorf("DeleteCsiDriver wrong uid = %v, want Aborted", err) + } + + deleted, err := del(&ateapi.DeleteOptions{Uid: uid, Version: version}) + if err != nil { + t.Fatalf("DeleteCsiDriver: %v", err) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Errorf("deleted driver = %v, want delete_time populated", deleted.GetMetadata()) + } + if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreDeleteTime); diff != "" { + t.Errorf("DeleteCsiDriver mismatch (-created +deleted):\n%s", diff) + } + if _, err := h.Control.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{CsiDriver: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetCsiDriver after delete = %v, want NotFound", err) + } + if _, err := del(nil); status.Code(err) != codes.NotFound { + t.Errorf("second DeleteCsiDriver = %v, want NotFound", err) + } +} + +// Deleting a CsiDriver requires the global owner role. No role and global +// viewer are denied without deleting the driver. +func TestDeleteCSIDriver_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + createCSIDriver(t, h, "csi-nfs", "nfs.csi.k8s.io") + ref := &ateapi.ObjectRef{Name: "csi-nfs"} + alice := h.ClientAs("alice") + del := func() error { + _, err := alice.DeleteCsiDriver(t.Context(), &ateapi.DeleteCsiDriverRequest{CsiDriver: ref}) + return err + } + refusedDelete := func(holding string) { + t.Helper() + if err := del(); status.Code(err) != codes.PermissionDenied { + t.Errorf("DeleteCsiDriver holding %s = %v, want PermissionDenied", holding, err) + } + if _, err := h.Control.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{CsiDriver: ref}); err != nil { + t.Errorf("GetCsiDriver after refused delete holding %s = %v, want OK", holding, err) + } + } + + refusedDelete("no role") + setGlobalBinding(t, h, "viewer", harness.Member("alice")) + refusedDelete("viewer") + setGlobalBinding(t, h, "owner", harness.Member("alice")) + eventuallyAllowed(t, h, "DeleteCsiDriver holding owner", codes.OK, del) +} + +// Invalid CsiDriver CRUD requests fail with INVALID_ARGUMENT and name the +// invalid field. +func TestCSIDriver_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t, harness.WithPreviewClient()) + + cases := []struct { + name string + call func() error + wantContains string + }{ + { + name: "atespace forbidden on create", + call: func() error { + bad := newCSIDriver("csi-nfs", "nfs.csi.k8s.io") + bad.Metadata.Atespace = "team-a" + _, err := h.Control.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{CsiDriver: bad}) + return err + }, + wantContains: "atespace: Forbidden", + }, + { + name: "invalid driver_name on create", + call: func() error { + bad := newCSIDriver("csi-nfs", "Bad_Driver") + _, err := h.Control.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{CsiDriver: bad}) + return err + }, + wantContains: "driver_name: Invalid value", + }, + { + name: "invalid controller_endpoint on create", + call: func() error { + bad := newCSIDriver("csi-nfs", "nfs.csi.k8s.io") + bad.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "tcp://no-port", Port: 9000} + _, err := h.Control.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{CsiDriver: bad}) + return err + }, + wantContains: "controller_endpoint.host: Invalid value", + }, + { + name: "invalid tls on create", + call: func() error { + bad := newCSIDriver("csi-nfs", "nfs.csi.k8s.io") + bad.Tls = &ateapi.CsiDriverTlsConfig{} + _, err := h.Control.CreateCsiDriver(t.Context(), &ateapi.CreateCsiDriverRequest{CsiDriver: bad}) + return err + }, + wantContains: "server_name: Required value", + }, + { + name: "missing ref on get", + call: func() error { + _, err := h.Control.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{}) + return err + }, + wantContains: "csi_driver.name: Required value", + }, + { + name: "atespace forbidden on get", + call: func() error { + _, err := h.Control.GetCsiDriver(t.Context(), &ateapi.GetCsiDriverRequest{ + CsiDriver: &ateapi.ObjectRef{Atespace: "team-a", Name: "csi-nfs"}, + }) + return err + }, + wantContains: "atespace: Forbidden", + }, + { + name: "negative page size on list", + call: func() error { + _, err := h.Control.ListCsiDrivers(t.Context(), &ateapi.ListCsiDriversRequest{ + Options: &ateapi.ListOptions{PageSize: -1}, + }) + return err + }, + wantContains: "page_size: Invalid value", + }, + { + name: "missing driver on update", + call: func() error { + _, err := h.Control.UpdateCsiDriver(t.Context(), &ateapi.UpdateCsiDriverRequest{}) + return err + }, + wantContains: "csi_driver", + }, + { + name: "missing ref on delete", + call: func() error { + _, err := h.Control.DeleteCsiDriver(t.Context(), &ateapi.DeleteCsiDriverRequest{}) + return err + }, + wantContains: "csi_driver.name: Required value", + }, + } + + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + err := tc.call() + if status.Code(err) != codes.InvalidArgument { + t.Errorf("err = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.Contains(msg, tc.wantContains) { + t.Errorf("error message = %q, want substring %q", msg, tc.wantContains) + } + }) + } +} diff --git a/cmd/ateapi/internal/functionaltest/egresspolicies_test.go b/cmd/ateapi/internal/functionaltest/egresspolicies_test.go new file mode 100644 index 0000000000..3670532876 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/egresspolicies_test.go @@ -0,0 +1,574 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" +) + +// egressPolicySpec is a valid egress policy for an actor in atespace. +func egressPolicySpec(atespace string) *ateapi.EgressPolicy { + return &ateapi.EgressPolicy{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: "default"}, + Rules: []*ateapi.EgressRule{{Http: &ateapi.HttpRule{Hostnames: []string{"api.example.com"}}}}, + } +} + +// egressPolicyActor creates an actor for an egress policy to belong to. +func egressPolicyActor(h *harness.Harness, as string) *ateapi.ObjectRef { + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + return harness.ActorRef(h.NewActor(as, h.NewTemplate(as, pool))) +} + +// Creates an egress policy for an existing actor, sending output-only +// metadata, and verifies that the whole resource has the expected shape: +// ate-api ignores what was sent and assigns its own. +func TestCreateActorEgressPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + + in := egressPolicySpec(as) + // The caller sends output-only fields, which ate-api ignores. + setOutputOnlyMetadata(in.Metadata) + created, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: in}) + if err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + want := &ateapi.EgressPolicy{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "default"}, + Rules: []*ateapi.EgressRule{{Http: &ateapi.HttpRule{ + Hostnames: []string{"api.example.com"}, + Ports: &ateapi.Ports{Numbers: []int32{80}}, + }}}, + } + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created egress policy (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) +} + +// Creating an egress policy for an existing actor name fails with +// ALREADY_EXISTS and leaves the existing one unchanged. +func TestCreateActorEgressPolicy_AlreadyExists(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + created, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}) + if err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + + _, err = h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateActorEgressPolicy for an actor that has one = %v, want AlreadyExists", err) + } + got, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if err != nil { + t.Fatalf("GetActorEgressPolicy: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("egress policy after a refused create (-want +got):\n%s", diff) + } +} + +// Creating an egress policy with any of the invalid requests below fails with +// INVALID_ARGUMENT, and the error names the invalid field. +func TestCreateActorEgressPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + for _, tc := range []struct { + name string + req *ateapi.CreateActorEgressPolicyRequest + prefix string + }{ + { + name: "an invalid actor name", + req: &ateapi.CreateActorEgressPolicyRequest{ + Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}, + EgressPolicy: egressPolicySpec(as), + }, + prefix: "actor.name: Invalid value", + }, + { + name: "a policy in another atespace than its actor", + req: &ateapi.CreateActorEgressPolicyRequest{ + Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}, + EgressPolicy: egressPolicySpec("team-b"), + }, + prefix: "egress_policy.metadata.atespace: Invalid value", + }, + // The https rule sets no ports, so it ties with the http rule only on + // its default port 443. This checks that Create applies defaults + // before it validates. + { + name: "an https rule that ties with an http rule once it defaults to port 443", + req: &ateapi.CreateActorEgressPolicyRequest{ + Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}, + EgressPolicy: mutated(egressPolicySpec(as), func(p *ateapi.EgressPolicy) { + p.Rules = []*ateapi.EgressRule{ + {Http: &ateapi.HttpRule{Hostnames: []string{"api.example.com"}, Ports: &ateapi.Ports{Numbers: []int32{443}}}}, + {Https: &ateapi.HttpsRule{Hostnames: []string{"api.example.com"}}}, + } + }), + }, + prefix: "egress_policy.rules[1].https.hostnames[0]: Invalid value", + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := h.Control.CreateActorEgressPolicy(t.Context(), tc.req) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateActorEgressPolicy = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, tc.prefix) { + t.Errorf("CreateActorEgressPolicy error %q does not start with %q", msg, tc.prefix) + } + }) + } +} + +// Creating an egress policy for an actor that doesn't exist fails with +// FAILED_PRECONDITION. +func TestCreateActorEgressPolicy_ActorNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{ + Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}, + EgressPolicy: egressPolicySpec(as), + }) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateActorEgressPolicy for a missing actor = %v, want FailedPrecondition", err) + } +} + +// Getting an existing egress policy returns exactly the resource +// CreateActorEgressPolicy returned. +func TestGetActorEgressPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + created, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}) + if err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + + got, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if err != nil { + t.Fatalf("GetActorEgressPolicy: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("GetActorEgressPolicy (-created +got):\n%s", diff) + } +} + +// Getting an egress policy that doesn't exist fails with NOT_FOUND. +func TestGetActorEgressPolicy_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + + _, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetActorEgressPolicy for an actor with none = %v, want NotFound", err) + } +} + +// Getting an egress policy with any of the invalid requests below fails with +// INVALID_ARGUMENT, and the error names the invalid field. +func TestGetActorEgressPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + for _, tc := range []struct { + name string + req *ateapi.GetActorEgressPolicyRequest + prefix string + }{ + { + name: "an invalid actor name", + req: &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}, + prefix: "actor.name: Invalid value", + }, + { + name: `a policy named other than "default"`, + req: &ateapi.GetActorEgressPolicyRequest{Name: "other", Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}}, + prefix: "name: Invalid value", + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := h.Control.GetActorEgressPolicy(t.Context(), tc.req) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("GetActorEgressPolicy = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, tc.prefix) { + t.Errorf("GetActorEgressPolicy error %q does not start with %q", msg, tc.prefix) + } + }) + } +} + +// After an actor with an egress policy is deleted, getting its egress policy +// fails with NOT_FOUND. An actor created again under the same name has no +// egress policy either: getting it fails with NOT_FOUND. +func TestGetActorEgressPolicy_ActorDeleted(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + if _, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}); err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + template := h.GetActor(actor).GetActorTemplate() + + if _, err := h.Control.DeleteActor(t.Context(), &ateapi.DeleteActorRequest{Actor: actor}); err != nil { + t.Fatalf("DeleteActor: %v", err) + } + _, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetActorEgressPolicy of a deleted actor = %v, want NotFound", err) + } + + if _, err := h.Control.CreateActor(t.Context(), &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: actor.GetAtespace(), Name: actor.GetName()}, + ActorTemplate: template, + }}); err != nil { + t.Fatalf("CreateActor under the same name: %v", err) + } + _, err = h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetActorEgressPolicy of an actor recreated under the same name = %v, want NotFound", err) + } +} + +// Updates the rules of an existing egress policy, sending it as read. The +// result, and a later Get, is the resource as read with that field changed +// and a higher version. +func TestUpdateActorEgressPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + before, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}) + if err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + rules := []*ateapi.EgressRule{{TlsPassthrough: &ateapi.TlsPassthroughRule{Hostnames: []string{"*"}, Ports: &ateapi.Ports{Numbers: []int32{443}}}}} + + toUpdate := mutated(before, func(p *ateapi.EgressPolicy) { + p.Rules = rules + }) + updated, err := h.Control.UpdateActorEgressPolicy(t.Context(), &ateapi.UpdateActorEgressPolicyRequest{Actor: actor, EgressPolicy: toUpdate}) + if err != nil { + t.Fatalf("UpdateActorEgressPolicy: %v", err) + } + want := mutated(before, func(p *ateapi.EgressPolicy) { + p.Rules = rules + }) + if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("updated egress policy (-want +got):\n%s", diff) + } + if got, was := updated.GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("updated egress policy has version %d, want higher than %d", got, was) + } + got, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if err != nil { + t.Fatalf("GetActorEgressPolicy: %v", err) + } + if diff := cmp.Diff(updated, got, protocmp.Transform()); diff != "" { + t.Errorf("GetActorEgressPolicy after update (-updated +got):\n%s", diff) + } +} + +// Updating an egress policy that doesn't exist fails with NOT_FOUND. +func TestUpdateActorEgressPolicy_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + policy := egressPolicySpec(as) + policy.Metadata.Uid, policy.Metadata.Version = foreignUID, 1 + + _, err := h.Control.UpdateActorEgressPolicy(t.Context(), &ateapi.UpdateActorEgressPolicyRequest{Actor: actor, EgressPolicy: policy}) + if status.Code(err) != codes.NotFound { + t.Errorf("UpdateActorEgressPolicy for an actor with none = %v, want NotFound", err) + } +} + +// Updating an egress policy with the wrong UID fails with ABORTED, and with +// the right UID but the wrong version fails with ABORTED; both leave it +// unchanged. Updating it without a UID or a version fails with +// INVALID_ARGUMENT. +func TestUpdateActorEgressPolicy_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + before, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}) + if err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + update := func(uid string, version int64) error { + toUpdate := mutated(before, func(p *ateapi.EgressPolicy) { + p.Metadata.Uid, p.Metadata.Version = uid, version + p.Rules = []*ateapi.EgressRule{{Http: &ateapi.HttpRule{Hostnames: []string{"other.example.com"}}}} + }) + _, err := h.Control.UpdateActorEgressPolicy(t.Context(), &ateapi.UpdateActorEgressPolicyRequest{Actor: actor, EgressPolicy: toUpdate}) + return err + } + + if err := update(foreignUID, before.GetMetadata().GetVersion()); status.Code(err) != codes.Aborted { + t.Errorf("UpdateActorEgressPolicy with the wrong uid = %v, want Aborted", err) + } + if err := update(before.GetMetadata().GetUid(), before.GetMetadata().GetVersion()+1); status.Code(err) != codes.Aborted { + t.Errorf("UpdateActorEgressPolicy with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if err != nil { + t.Fatalf("GetActorEgressPolicy: %v", err) + } + if diff := cmp.Diff(before, got, protocmp.Transform()); diff != "" { + t.Errorf("egress policy after refused updates (-want +got):\n%s", diff) + } + if err := update("", 0); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateActorEgressPolicy without a uid or version = %v, want InvalidArgument", err) + } +} + +// Updating an egress policy with any of the invalid requests below fails with +// INVALID_ARGUMENT, and the error names the invalid field. +func TestUpdateActorEgressPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + for _, tc := range []struct { + name string + req *ateapi.UpdateActorEgressPolicyRequest + prefix string + }{ + { + name: "an invalid actor name", + req: &ateapi.UpdateActorEgressPolicyRequest{ + Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}, + EgressPolicy: mutated(egressPolicySpec(as), func(p *ateapi.EgressPolicy) { + p.Metadata.Uid, p.Metadata.Version = foreignUID, 1 + }), + }, + prefix: "actor.name: Invalid value", + }, + { + name: "a policy in another atespace than its actor", + req: &ateapi.UpdateActorEgressPolicyRequest{ + Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}, + EgressPolicy: mutated(egressPolicySpec("team-b"), func(p *ateapi.EgressPolicy) { + p.Metadata.Uid, p.Metadata.Version = foreignUID, 1 + }), + }, + prefix: "egress_policy.metadata.atespace: Invalid value", + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := h.Control.UpdateActorEgressPolicy(t.Context(), tc.req) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateActorEgressPolicy = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, tc.prefix) { + t.Errorf("UpdateActorEgressPolicy error %q does not start with %q", msg, tc.prefix) + } + }) + } +} + +// Updates an existing egress policy to an http rule on port 443 and an https +// rule for the same hostname that sets no ports. The update fails with +// INVALID_ARGUMENT, because the https rule defaults to port 443 and then ties +// with the http rule, and the error names the tied hostname. The policy is +// unchanged. +func TestUpdateActorEgressPolicy_RulesTieOnDefaultPort(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + before, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}) + if err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + + // The https rule sets no ports, so the request is valid as sent and ties + // with the http rule only on its default port 443. This checks that Update + // validates the policy again after it applies defaults. + toUpdate := mutated(before, func(p *ateapi.EgressPolicy) { + p.Rules = []*ateapi.EgressRule{ + {Http: &ateapi.HttpRule{Hostnames: []string{"api.example.com"}, Ports: &ateapi.Ports{Numbers: []int32{443}}}}, + {Https: &ateapi.HttpsRule{Hostnames: []string{"api.example.com"}}}, + } + }) + _, err = h.Control.UpdateActorEgressPolicy(t.Context(), &ateapi.UpdateActorEgressPolicyRequest{Actor: actor, EgressPolicy: toUpdate}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateActorEgressPolicy with rules that tie on the default port = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "egress_policy.rules[1].https.hostnames[0]: Invalid value") { + t.Errorf("UpdateActorEgressPolicy error %q does not start with %q", msg, "egress_policy.rules[1].https.hostnames[0]: Invalid value") + } + got, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if err != nil { + t.Fatalf("GetActorEgressPolicy: %v", err) + } + if diff := cmp.Diff(before, got, protocmp.Transform()); diff != "" { + t.Errorf("egress policy after a refused update (-want +got):\n%s", diff) + } +} + +// Deletes an existing egress policy. The response is the deleted resource, +// and a later Get fails with NOT_FOUND. +func TestDeleteActorEgressPolicy(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + created, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}) + if err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + + deleted, err := h.Control.DeleteActorEgressPolicy(t.Context(), &ateapi.DeleteActorEgressPolicyRequest{Name: "default", Actor: actor}) + if err != nil { + t.Fatalf("DeleteActorEgressPolicy: %v", err) + } + if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreDeleteTime); diff != "" { + t.Errorf("DeleteActorEgressPolicy response (-created +deleted):\n%s", diff) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Error("DeleteActorEgressPolicy response has no delete_time") + } + if _, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}); status.Code(err) != codes.NotFound { + t.Errorf("GetActorEgressPolicy after delete = %v, want NotFound", err) + } +} + +// Deleting an egress policy that doesn't exist fails with NOT_FOUND. +func TestDeleteActorEgressPolicy_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + + _, err := h.Control.DeleteActorEgressPolicy(t.Context(), &ateapi.DeleteActorEgressPolicyRequest{Name: "default", Actor: actor}) + if status.Code(err) != codes.NotFound { + t.Errorf("DeleteActorEgressPolicy for an actor with none = %v, want NotFound", err) + } +} + +// Deleting an egress policy with the wrong UID, with only the wrong version, or +// with the right UID but the wrong version fails with ABORTED and leaves it +// unchanged. With the right UID and version the delete succeeds. +func TestDeleteActorEgressPolicy_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + actor := egressPolicyActor(h, as) + created, err := h.Control.CreateActorEgressPolicy(t.Context(), &ateapi.CreateActorEgressPolicyRequest{Actor: actor, EgressPolicy: egressPolicySpec(as)}) + if err != nil { + t.Fatalf("CreateActorEgressPolicy: %v", err) + } + uid, version := created.GetMetadata().GetUid(), created.GetMetadata().GetVersion() + + _, err = h.Control.DeleteActorEgressPolicy(t.Context(), &ateapi.DeleteActorEgressPolicyRequest{Name: "default", Actor: actor, Options: &ateapi.DeleteOptions{Uid: foreignUID}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActorEgressPolicy with the wrong uid = %v, want Aborted", err) + } + _, err = h.Control.DeleteActorEgressPolicy(t.Context(), &ateapi.DeleteActorEgressPolicyRequest{Name: "default", Actor: actor, Options: &ateapi.DeleteOptions{Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActorEgressPolicy with only the wrong version = %v, want Aborted", err) + } + _, err = h.Control.DeleteActorEgressPolicy(t.Context(), &ateapi.DeleteActorEgressPolicyRequest{Name: "default", Actor: actor, Options: &ateapi.DeleteOptions{Uid: uid, Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteActorEgressPolicy with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetActorEgressPolicy(t.Context(), &ateapi.GetActorEgressPolicyRequest{Name: "default", Actor: actor}) + if err != nil { + t.Fatalf("GetActorEgressPolicy after refused deletes: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("egress policy after refused deletes (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteActorEgressPolicy(t.Context(), &ateapi.DeleteActorEgressPolicyRequest{Name: "default", Actor: actor, Options: &ateapi.DeleteOptions{Uid: uid, Version: version}}); err != nil { + t.Errorf("DeleteActorEgressPolicy with the right uid and version: %v", err) + } +} + +// Deleting an egress policy with any of the invalid requests below fails with +// INVALID_ARGUMENT, and the error names the invalid field. +func TestDeleteActorEgressPolicy_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + for _, tc := range []struct { + name string + req *ateapi.DeleteActorEgressPolicyRequest + prefix string + }{ + { + name: "an invalid actor name", + req: &ateapi.DeleteActorEgressPolicyRequest{Name: "default", Actor: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}, + prefix: "actor.name: Invalid value", + }, + { + name: `a policy named other than "default"`, + req: &ateapi.DeleteActorEgressPolicyRequest{Name: "other", Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}}, + prefix: "name: Invalid value", + }, + { + name: "a precondition uid that is not a UUID", + req: &ateapi.DeleteActorEgressPolicyRequest{ + Name: "default", + Actor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}, + Options: &ateapi.DeleteOptions{Uid: "not-a-uuid"}, + }, + prefix: "options.uid: Invalid value", + }, + } { + t.Run(tc.name, func(t *testing.T) { + _, err := h.Control.DeleteActorEgressPolicy(t.Context(), tc.req) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("DeleteActorEgressPolicy = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, tc.prefix) { + t.Errorf("DeleteActorEgressPolicy error %q does not start with %q", msg, tc.prefix) + } + }) + } +} diff --git a/cmd/ateapi/internal/functionaltest/externalvolumes_test.go b/cmd/ateapi/internal/functionaltest/externalvolumes_test.go new file mode 100644 index 0000000000..eb27e59f91 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/externalvolumes_test.go @@ -0,0 +1,154 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" +) + +// The ExternalVolume RPCs are not behind the ExternalVolumes preview gate, and +// the harness clients here do not opt in to preview features. +// +// TODO(#1637): Nothing creates an ExternalVolume yet, so these tests cover +// only the missing and empty cases. Add tests that get and list existing +// volumes once the server creates them. + +// Getting an external volume that doesn't exist fails with NOT_FOUND. +func TestGetExternalVolume_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + atespace := h.CreateAtespace("team-a") + + _, err := h.Control.GetExternalVolume(t.Context(), &ateapi.GetExternalVolumeRequest{ExternalVolume: &ateapi.ObjectRef{Atespace: atespace, Name: "vol-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetExternalVolume of a missing volume = %v, want NotFound", err) + } +} + +// Getting an external volume with an invalid name fails with +// INVALID_ARGUMENT, and the error names the invalid field. +func TestGetExternalVolume_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + atespace := h.CreateAtespace("team-a") + + _, err := h.Control.GetExternalVolume(t.Context(), &ateapi.GetExternalVolumeRequest{ExternalVolume: &ateapi.ObjectRef{Atespace: atespace, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("GetExternalVolume with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "external_volume.name: Invalid value") { + t.Errorf("GetExternalVolume error %q does not start with %q", msg, "external_volume.name: Invalid value") + } +} + +// Getting a missing external volume as a principal no access policy names +// fails with PERMISSION_DENIED. Granted the viewer role by the atespace's +// access policy, the principal eventually fails with NOT_FOUND instead. +func TestGetExternalVolume_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + atespace := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + get := func() error { + _, err := alice.GetExternalVolume(t.Context(), &ateapi.GetExternalVolumeRequest{ExternalVolume: &ateapi.ObjectRef{Atespace: atespace.GetName(), Name: "vol-missing"}}) + return err + } + + if err := get(); status.Code(err) != codes.PermissionDenied { + t.Errorf("GetExternalVolume holding no role = %v, want PermissionDenied", err) + } + setAtespaceBinding(t, h, atespace, "viewer", harness.Member("alice")) + eventuallyAllowed(t, h, "GetExternalVolume holding viewer", codes.NotFound, get) +} + +// Listing the external volumes of an atespace, and of every atespace, +// returns an empty list. +func TestListExternalVolumes(t *testing.T) { + t.Parallel() + h := harness.New(t) + atespace := h.CreateAtespace("team-a") + + listed, err := h.Control.ListExternalVolumes(t.Context(), &ateapi.ListExternalVolumesRequest{Atespace: atespace}) + if err != nil { + t.Fatalf("ListExternalVolumes(%s): %v", atespace, err) + } + if diff := cmp.Diff(&ateapi.ListExternalVolumesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("ListExternalVolumes(%s) (-want +got):\n%s", atespace, diff) + } + + listed, err = h.Control.ListExternalVolumes(t.Context(), &ateapi.ListExternalVolumesRequest{}) + if err != nil { + t.Fatalf("ListExternalVolumes of every atespace: %v", err) + } + if diff := cmp.Diff(&ateapi.ListExternalVolumesResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("ListExternalVolumes of every atespace (-want +got):\n%s", diff) + } +} + +// Listing external volumes with a negative page size fails with +// INVALID_ARGUMENT, and the error names the invalid field. +func TestListExternalVolumes_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListExternalVolumes(t.Context(), &ateapi.ListExternalVolumesRequest{Options: &ateapi.ListOptions{PageSize: -1}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListExternalVolumes with a negative page size = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "options.page_size: Invalid value") { + t.Errorf("ListExternalVolumes error %q does not start with %q", msg, "options.page_size: Invalid value") + } +} + +// Listing external volumes with a malformed page token fails with +// INVALID_ARGUMENT. +func TestListExternalVolumes_InvalidPageToken(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListExternalVolumes(t.Context(), &ateapi.ListExternalVolumesRequest{Options: &ateapi.ListOptions{PageToken: "not-a-real-token"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListExternalVolumes with a malformed page token = %v, want InvalidArgument", err) + } +} + +// Listing the external volumes of an atespace as a principal no access +// policy names fails with PERMISSION_DENIED. Granted the viewer role by the +// atespace's access policy, the principal eventually lists them (OK). +func TestListExternalVolumes_Authorization(t *testing.T) { + t.Parallel() + h := harness.New(t) + atespace := &ateapi.ObjectRef{Name: h.CreateAtespace("team-a")} + alice := h.ClientAs("alice") + list := func() error { + _, err := alice.ListExternalVolumes(t.Context(), &ateapi.ListExternalVolumesRequest{Atespace: atespace.GetName()}) + return err + } + + if err := list(); status.Code(err) != codes.PermissionDenied { + t.Errorf("ListExternalVolumes holding no role = %v, want PermissionDenied", err) + } + setAtespaceBinding(t, h, atespace, "viewer", harness.Member("alice")) + eventuallyAllowed(t, h, "ListExternalVolumes holding viewer", codes.OK, list) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/atelet.go b/cmd/ateapi/internal/functionaltest/harness/atelet.go new file mode 100644 index 0000000000..b0c59758a8 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/atelet.go @@ -0,0 +1,303 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "cmp" + "context" + "fmt" + "slices" + "sync" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness/grpcfake" + "go.ate.dev/substrate/internal/proto/ateletpb" +) + +// AteletMethod is the gRPC full name of an atelet RPC a fault can be injected +// into. +type AteletMethod string + +const ( + AteletRun = AteletMethod(ateletpb.Atelet_Run_FullMethodName) + AteletCheckpoint = AteletMethod(ateletpb.Atelet_Checkpoint_FullMethodName) + AteletRestore = AteletMethod(ateletpb.Atelet_Restore_FullMethodName) + AteletPromoteSnapshot = AteletMethod(ateletpb.Atelet_PromoteSnapshot_FullMethodName) + AteletDetachActor = AteletMethod(ateletpb.Atelet_DetachActor_FullMethodName) + AteletTerminate = AteletMethod(ateletpb.Atelet_Terminate_FullMethodName) +) + +// ErrSandboxFailed is the sandbox itself failing an operation: ateom or runsc +// returned an error. A real atelet sends most failures as codes.Internal. +var ErrSandboxFailed = status.New(codes.Internal, "harness: sandbox operation failed") + +// snapshotObjects names the objects a fake upload writes. Nothing in ate-api +// reads them; it copies and deletes whatever shares a snapshot's prefix. +var snapshotObjects = []string{"manifest.json", "memory.zst"} + +// Sandbox is an actor's workload running on a worker. +type Sandbox struct { + ActorUID string + Atespace string + ActorName string + // WorkerUID is the worker's pod UID, which is its Worker's name. + WorkerUID string +} + +// Atelet is the fake atelet of one node. It keeps the sandboxes running on the +// node's workers and each actor's latest local snapshot, and uploads snapshots +// to the test's ObjectStore. It never uploads or detaches on its own: a +// deferred snapshot stays local until ate-api promotes or detaches it. It +// refuses what a real atelet cannot do, such as checkpointing an actor that is +// not running here. +type Atelet struct { + objectStore *ObjectStore + fake *grpcfake.Service[AteletMethod] + + mu sync.Mutex + epochsByWorkerUID map[string]int64 + sandboxesByActorUID map[string]Sandbox + localSnapshotByActorUID map[string]*ateletpb.Snapshot +} + +func newAtelet(objectStore *ObjectStore) *Atelet { + return &Atelet{ + objectStore: objectStore, + fake: grpcfake.NewService(AteletRun, AteletCheckpoint, AteletRestore, AteletPromoteSnapshot, AteletDetachActor, AteletTerminate), + epochsByWorkerUID: map[string]int64{}, + sandboxesByActorUID: map[string]Sandbox{}, + localSnapshotByActorUID: map[string]*ateletpb.Snapshot{}, + } +} + +// ateletServer serves an Atelet's RPCs to ate-api. +type ateletServer struct { + ateletpb.UnimplementedAteletServer + atelet *Atelet +} + +// grpcServer returns a gRPC server of a's RPCs, which applies a's faults and +// records its calls. Tests hold only the Atelet, so they reach its RPCs only +// through ate-api. +func (a *Atelet) grpcServer() *grpc.Server { + srv := a.fake.NewServer() + ateletpb.RegisterAteletServer(srv, ateletServer{atelet: a}) + return srv +} + +// On returns the Fault deciding how calls to method behave. +func (a *Atelet) On(method AteletMethod) *grpcfake.Fault { + return a.fake.On(method) +} + +// Sandboxes returns the sandboxes running on this node, sorted by actor UID. +func (a *Atelet) Sandboxes() []Sandbox { + a.mu.Lock() + defer a.mu.Unlock() + out := make([]Sandbox, 0, len(a.sandboxesByActorUID)) + for _, s := range a.sandboxesByActorUID { + out = append(out, s) + } + slices.SortFunc(out, func(x, y Sandbox) int { return cmp.Compare(x.ActorUID, y.ActorUID) }) + return out +} + +// LocalSnapshot returns the UUID of the snapshot this node holds for the +// actor, or "" if it holds none. +func (a *Atelet) LocalSnapshot(actorUID string) string { + a.mu.Lock() + defer a.mu.Unlock() + return a.localSnapshotByActorUID[actorUID].GetSnapshotUuid() +} + +// RecordCalls starts recording the calls a receives from now on. +func (a *Atelet) RecordCalls() *grpcfake.Recording[AteletMethod] { + return a.fake.Record() +} + +// registerWorker records the epoch a worker process on this node registered +// with, as atelet learns it when forwarding the registration. +func (a *Atelet) registerWorker(workerUID string, epoch int64) { + a.mu.Lock() + defer a.mu.Unlock() + a.epochsByWorkerUID[workerUID] = epoch +} + +// restartWorker records the epoch a worker's new process registered with, and +// drops the sandboxes its old process ran. +func (a *Atelet) restartWorker(workerUID string, epoch int64) { + a.mu.Lock() + defer a.mu.Unlock() + a.epochsByWorkerUID[workerUID] = epoch + for uid, s := range a.sandboxesByActorUID { + if s.WorkerUID == workerUID { + delete(a.sandboxesByActorUID, uid) + } + } +} + +func (s ateletServer) Run(_ context.Context, req *ateletpb.RunRequest) (*ateletpb.RunResponse, error) { + a := s.atelet + a.mu.Lock() + defer a.mu.Unlock() + epoch, ok := a.epochsByWorkerUID[req.GetWorkerPodUid()] + if !ok { + return nil, status.Errorf(codes.Unavailable, "while running the workload: no worker %s on this node", req.GetWorkerPodUid()) + } + a.sandboxesByActorUID[req.GetActorUid()] = Sandbox{ + ActorUID: req.GetActorUid(), Atespace: req.GetAtespace(), ActorName: req.GetActorName(), WorkerUID: req.GetWorkerPodUid(), + } + return &ateletpb.RunResponse{WorkerEpoch: epoch}, nil +} + +// Checkpoint takes the snapshot locally, replacing the actor's older local +// snapshot, and under UPLOAD_MODE_IMMEDIATE also uploads it. A retry of a +// Checkpoint that took the snapshot is answered from it, as atelet does. +func (s ateletServer) Checkpoint(_ context.Context, req *ateletpb.CheckpointRequest) (*ateletpb.CheckpointResponse, error) { + a := s.atelet + a.mu.Lock() + defer a.mu.Unlock() + uid := req.GetActorUid() + snap := req.GetSnapshot() + sandbox, ok := a.sandboxesByActorUID[uid] + retry := !ok && a.localSnapshotByActorUID[uid].GetSnapshotUuid() == snap.GetSnapshotUuid() + if !retry && (!ok || sandbox.WorkerUID != req.GetWorkerPodUid()) { + return nil, status.Errorf(codes.Internal, "while checkpointing the workload: actor %s is not running on worker %s", uid, req.GetWorkerPodUid()) + } + state := &ateletpb.ActorSnapshotState{LatestLocal: &ateletpb.SnapshotReport{Snapshot: proto.CloneOf(snap)}} + switch req.GetUploadConfig().GetMode() { + case ateletpb.UploadMode_UPLOAD_MODE_DEFERRED: + case ateletpb.UploadMode_UPLOAD_MODE_IMMEDIATE: + if err := a.objectStore.writeSnapshot(snap.GetObject().GetSnapshotUri(), snapshotObjects...); err != nil { + return nil, status.Errorf(codes.Internal, "while uploading the snapshot: %v", err) + } + state.LatestDurable = &ateletpb.SnapshotReport{Snapshot: proto.CloneOf(snap)} + default: + return nil, status.Errorf(codes.InvalidArgument, "unsupported upload mode %v", req.GetUploadConfig().GetMode()) + } + a.localSnapshotByActorUID[uid] = proto.CloneOf(snap) + delete(a.sandboxesByActorUID, uid) + return &ateletpb.CheckpointResponse{State: state}, nil +} + +// Restore reads the snapshot's local copy if this node holds it, and its +// durable copy otherwise. +func (s ateletServer) Restore(_ context.Context, req *ateletpb.RestoreRequest) (*ateletpb.RestoreResponse, error) { + a := s.atelet + uid := req.GetActorUid() + snap := req.GetSnapshot() + if a.LocalSnapshot(uid) != snap.GetSnapshotUuid() { + uri := snap.GetObject().GetSnapshotUri() + names, err := a.objectStore.Snapshot(uri) + if err != nil { + return nil, status.Errorf(codes.Internal, "while fetching the snapshot manifest: %v", err) + } + // atelet keeps the object-store plugin's code for a missing manifest. + if len(names) == 0 { + return nil, status.Errorf(codes.NotFound, "while fetching the snapshot manifest: %s not found", uri) + } + } + a.mu.Lock() + defer a.mu.Unlock() + epoch, ok := a.epochsByWorkerUID[req.GetWorkerPodUid()] + if !ok { + return nil, status.Errorf(codes.Unavailable, "while restoring the workload: no worker %s on this node", req.GetWorkerPodUid()) + } + a.sandboxesByActorUID[uid] = Sandbox{ + ActorUID: uid, Atespace: req.GetAtespace(), ActorName: req.GetActorName(), WorkerUID: req.GetWorkerPodUid(), + } + return &ateletpb.RestoreResponse{WorkerEpoch: epoch}, nil +} + +// PromoteSnapshot uploads the actor's local snapshot and keeps the local copy. +// A snapshot already durable is answered from object storage. +func (s ateletServer) PromoteSnapshot(_ context.Context, req *ateletpb.PromoteSnapshotRequest) (*ateletpb.PromoteSnapshotResponse, error) { + a := s.atelet + snap := req.GetSnapshot() + uri := snap.GetObject().GetSnapshotUri() + state := &ateletpb.ActorSnapshotState{LatestDurable: &ateletpb.SnapshotReport{Snapshot: proto.CloneOf(snap)}} + if a.LocalSnapshot(req.GetActorUid()) == snap.GetSnapshotUuid() { + if err := a.objectStore.writeSnapshot(uri, snapshotObjects...); err != nil { + return nil, status.Errorf(codes.Internal, "while uploading the snapshot: %v", err) + } + state.LatestLocal = &ateletpb.SnapshotReport{Snapshot: proto.CloneOf(snap)} + return &ateletpb.PromoteSnapshotResponse{State: state}, nil + } + names, err := a.objectStore.Snapshot(uri) + if err != nil { + return nil, status.Errorf(codes.Internal, "while fetching the snapshot manifest: %v", err) + } + if len(names) == 0 { + return nil, status.Errorf(codes.NotFound, "snapshot %s is neither on this node nor in object storage", snap.GetSnapshotUuid()) + } + return &ateletpb.PromoteSnapshotResponse{State: state}, nil +} + +// upload writes the actor's local snapshot to object storage, keeping the +// local copy, as a background upload does. It returns the snapshot's UUID. +func (a *Atelet) upload(uid string) (string, error) { + a.mu.Lock() + snap, ok := a.localSnapshotByActorUID[uid] + a.mu.Unlock() + if !ok { + return "", fmt.Errorf("actor %s has no local snapshot on this node", uid) + } + if err := a.objectStore.writeSnapshot(snap.GetObject().GetSnapshotUri(), snapshotObjects...); err != nil { + return "", err + } + return snap.GetSnapshotUuid(), nil +} + +// DetachActor uploads the actor's local snapshot, then deletes it from the +// node. An actor with no local snapshot here returns an empty state. +func (s ateletServer) DetachActor(_ context.Context, req *ateletpb.DetachActorRequest) (*ateletpb.DetachActorResponse, error) { + state, err := s.atelet.detach(req.GetActorUid()) + if err != nil { + return nil, err + } + return &ateletpb.DetachActorResponse{State: state}, nil +} + +func (a *Atelet) detach(uid string) (*ateletpb.ActorSnapshotState, error) { + a.mu.Lock() + defer a.mu.Unlock() + if _, ok := a.sandboxesByActorUID[uid]; ok { + return nil, status.Errorf(codes.Aborted, "actor %s is running on this node", uid) + } + snap, ok := a.localSnapshotByActorUID[uid] + if !ok { + return &ateletpb.ActorSnapshotState{}, nil + } + if err := a.objectStore.writeSnapshot(snap.GetObject().GetSnapshotUri(), snapshotObjects...); err != nil { + return nil, status.Errorf(codes.Internal, "while uploading the snapshot: %v", err) + } + delete(a.localSnapshotByActorUID, uid) + return &ateletpb.ActorSnapshotState{LatestDurable: &ateletpb.SnapshotReport{Snapshot: snap}}, nil +} + +// Terminate stops the actor's sandbox, if any, and drops its local snapshot +// on this node. Terminating an actor that is not running succeeds. +func (s ateletServer) Terminate(_ context.Context, req *ateletpb.TerminateRequest) (*ateletpb.TerminateResponse, error) { + a := s.atelet + a.mu.Lock() + defer a.mu.Unlock() + delete(a.sandboxesByActorUID, req.GetActorUid()) + delete(a.localSnapshotByActorUID, req.GetActorUid()) + return &ateletpb.TerminateResponse{}, nil +} diff --git a/cmd/ateapi/internal/functionaltest/harness/atelet_test.go b/cmd/ateapi/internal/functionaltest/harness/atelet_test.go new file mode 100644 index 0000000000..3ae4f09d8f --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/atelet_test.go @@ -0,0 +1,378 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "go.ate.dev/substrate/internal/proto/ateletpb" + "go.ate.dev/substrate/internal/resources" +) + +func TestAtelet(t *testing.T) { + const ( + uid = "0f0e0d0c-0b0a-4908-8706-050403020100" + worker = "worker-uid" + snapshotUUID = "9c2f7b41-6d05-4e83-a1f7-3b8c0d5e2a94" + epoch = 3 + ) + uri, err := resources.NewActorSnapshotURI(StorageLocation, "ns", uid, snapshotUUID) + if err != nil { + t.Fatalf("NewActorSnapshotURI: %v", err) + } + snapshotURI := uri.String() + snapshot := &ateletpb.Snapshot{ + SnapshotUuid: snapshotUUID, + Generation: 1, + Fidelity: ateletpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + Object: &ateletpb.ObjectStorage{SnapshotUri: snapshotURI}, + } + client := func(t *testing.T, a *Atelet) ateletpb.AteletClient { + t.Helper() + return ateletpb.NewAteletClient(dialInMemory(t, serveInMemory(t, a.grpcServer()))) + } + newAteletWithWorker := func(store *ObjectStore) *Atelet { + a := newAtelet(store) + a.registerWorker(worker, epoch) + return a + } + run := &ateletpb.RunRequest{WorkerPodUid: worker, ActorUid: uid, Atespace: "ns", ActorName: "actor-1"} + checkpoint := func(mode ateletpb.UploadMode) *ateletpb.CheckpointRequest { + return &ateletpb.CheckpointRequest{ + WorkerPodUid: worker, ActorUid: uid, Atespace: "ns", ActorName: "actor-1", + Snapshot: snapshot, + UploadConfig: &ateletpb.UploadConfig{Mode: mode}, + } + } + deferred := checkpoint(ateletpb.UploadMode_UPLOAD_MODE_DEFERRED) + immediate := checkpoint(ateletpb.UploadMode_UPLOAD_MODE_IMMEDIATE) + restore := &ateletpb.RestoreRequest{WorkerPodUid: worker, ActorUid: uid, Atespace: "ns", ActorName: "actor-1", Snapshot: snapshot} + running := []Sandbox{{ActorUID: uid, Atespace: "ns", ActorName: "actor-1", WorkerUID: worker}} + assertSandboxes := func(t *testing.T, a *Atelet, want []Sandbox) { + t.Helper() + if diff := cmp.Diff(want, a.Sandboxes(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("sandboxes (-want +got):\n%s", diff) + } + } + assertUploaded := func(t *testing.T, store *ObjectStore, want []string) { + t.Helper() + got, err := store.Snapshot(snapshotURI) + if err != nil { + t.Fatalf("Snapshot: %v", err) + } + if diff := cmp.Diff(want, got, cmpopts.EquateEmpty()); diff != "" { + t.Errorf("objects of %s (-want +got):\n%s", snapshotURI, diff) + } + } + + t.Run("refuses to run on a worker that did not register", func(t *testing.T) { + a := newAtelet(newObjectStore()) + c := client(t, a) + if _, err := c.Run(t.Context(), run); status.Code(err) != codes.Unavailable { + t.Fatalf("Run on a worker that is not on the node = %v, want Unavailable", err) + } + assertSandboxes(t, a, nil) + }) + + t.Run("run returns the worker's epoch", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + resp, err := c.Run(t.Context(), run) + if err != nil { + t.Fatalf("Run: %v", err) + } + if got := resp.GetWorkerEpoch(); got != epoch { + t.Errorf("Run epoch = %d, want %d", got, epoch) + } + assertSandboxes(t, a, running) + }) + + t.Run("refuses to checkpoint an actor that is not running", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + if _, err := c.Checkpoint(t.Context(), deferred); err == nil { + t.Fatal("Checkpoint succeeded with no sandbox running") + } + }) + + t.Run("refuses to checkpoint an actor running on another worker", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + elsewhere := checkpoint(ateletpb.UploadMode_UPLOAD_MODE_DEFERRED) + elsewhere.WorkerPodUid = "other-worker" + if _, err := c.Checkpoint(t.Context(), elsewhere); err == nil { + t.Fatal("Checkpoint succeeded on a worker the actor does not run on") + } + assertSandboxes(t, a, running) + }) + + t.Run("deferred checkpoint keeps the snapshot local and restores from it", func(t *testing.T) { + store := newObjectStore() + a := newAteletWithWorker(store) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + if _, err := c.Checkpoint(t.Context(), deferred); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + assertSandboxes(t, a, nil) + assertUploaded(t, store, nil) + if got := a.LocalSnapshot(uid); got != snapshotUUID { + t.Errorf("LocalSnapshot after Checkpoint = %q, want %q", got, snapshotUUID) + } + resp, err := c.Restore(t.Context(), restore) + if err != nil { + t.Fatalf("Restore: %v", err) + } + if got := resp.GetWorkerEpoch(); got != epoch { + t.Errorf("Restore epoch = %d, want %d", got, epoch) + } + assertSandboxes(t, a, running) + }) + + t.Run("immediate checkpoint uploads the snapshot", func(t *testing.T) { + store := newObjectStore() + a := newAteletWithWorker(store) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + resp, err := c.Checkpoint(t.Context(), immediate) + if err != nil { + t.Fatalf("Checkpoint: %v", err) + } + if got := resp.GetState().GetLatestDurable().GetSnapshot().GetSnapshotUuid(); got != snapshotUUID { + t.Errorf("Checkpoint latest durable = %q, want %q", got, snapshotUUID) + } + assertUploaded(t, store, snapshotObjects) + }) + + t.Run("a retried checkpoint is answered from the snapshot it took", func(t *testing.T) { + store := newObjectStore() + a := newAteletWithWorker(store) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + if _, err := c.Checkpoint(t.Context(), deferred); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + resp, err := c.Checkpoint(t.Context(), immediate) + if err != nil { + t.Fatalf("retried Checkpoint: %v", err) + } + if got := resp.GetState().GetLatestDurable().GetSnapshot().GetSnapshotUuid(); got != snapshotUUID { + t.Errorf("retried Checkpoint latest durable = %q, want %q", got, snapshotUUID) + } + assertUploaded(t, store, snapshotObjects) + assertSandboxes(t, a, nil) + }) + + t.Run("restores from object storage without a local copy", func(t *testing.T) { + store := newObjectStore() + a := newAteletWithWorker(store) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + if _, err := c.Checkpoint(t.Context(), immediate); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + other := newAteletWithWorker(store) + otherClient := client(t, other) + if _, err := otherClient.Restore(t.Context(), restore); err != nil { + t.Fatalf("Restore: %v", err) + } + assertSandboxes(t, other, running) + }) + + t.Run("refuses to restore a snapshot neither local nor in object storage", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + if _, err := c.Restore(t.Context(), restore); status.Code(err) != codes.NotFound { + t.Fatalf("Restore from a snapshot that is nowhere = %v, want NotFound", err) + } + assertSandboxes(t, a, nil) + }) + + t.Run("promote uploads the local snapshot and keeps it", func(t *testing.T) { + store := newObjectStore() + a := newAteletWithWorker(store) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + if _, err := c.Checkpoint(t.Context(), deferred); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + if _, err := c.PromoteSnapshot(t.Context(), &ateletpb.PromoteSnapshotRequest{ActorUid: uid, Atespace: "ns", ActorName: "actor-1", Snapshot: snapshot}); err != nil { + t.Fatalf("PromoteSnapshot: %v", err) + } + assertUploaded(t, store, snapshotObjects) + if got := a.LocalSnapshot(uid); got != snapshotUUID { + t.Errorf("LocalSnapshot after PromoteSnapshot = %q, want %q", got, snapshotUUID) + } + }) + + t.Run("refuses to promote a snapshot it neither holds nor finds durable", func(t *testing.T) { + store := newObjectStore() + a := newAteletWithWorker(store) + c := client(t, a) + _, err := c.PromoteSnapshot(t.Context(), &ateletpb.PromoteSnapshotRequest{ActorUid: uid, Atespace: "ns", ActorName: "actor-1", Snapshot: snapshot}) + if status.Code(err) != codes.NotFound { + t.Fatalf("PromoteSnapshot = %v, want NotFound", err) + } + assertUploaded(t, store, nil) + }) + + t.Run("detach uploads the local snapshot and drops it", func(t *testing.T) { + store := newObjectStore() + a := newAteletWithWorker(store) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + if _, err := c.Checkpoint(t.Context(), deferred); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + resp, err := c.DetachActor(t.Context(), &ateletpb.DetachActorRequest{ActorUid: uid, Atespace: "ns", ActorName: "actor-1"}) + if err != nil { + t.Fatalf("DetachActor: %v", err) + } + if got := resp.GetState().GetLatestDurable().GetSnapshot().GetSnapshotUuid(); got != snapshotUUID { + t.Errorf("DetachActor latest durable = %q, want %q", got, snapshotUUID) + } + assertUploaded(t, store, snapshotObjects) + if got := a.LocalSnapshot(uid); got != "" { + t.Errorf("LocalSnapshot after DetachActor = %q, want none", got) + } + }) + + t.Run("refuses to detach a running actor", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + _, err := c.DetachActor(t.Context(), &ateletpb.DetachActorRequest{ActorUid: uid, Atespace: "ns", ActorName: "actor-1"}) + if status.Code(err) != codes.Aborted { + t.Fatalf("DetachActor = %v, want Aborted", err) + } + }) + + t.Run("a call failed by a fault leaves no effect", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + a.On(AteletRun).FailNext(ErrSandboxFailed) + if _, err := c.Run(t.Context(), run); status.Code(err) != codes.Internal { + t.Fatalf("Run = %v, want ErrSandboxFailed", err) + } + assertSandboxes(t, a, nil) + }) + + t.Run("terminate drops the sandbox and the local snapshot", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + if _, err := c.Checkpoint(t.Context(), deferred); err != nil { + t.Fatalf("Checkpoint: %v", err) + } + if _, err := c.Terminate(t.Context(), &ateletpb.TerminateRequest{WorkerPodUid: worker, ActorUid: uid}); err != nil { + t.Fatalf("Terminate: %v", err) + } + if got := a.LocalSnapshot(uid); got != "" { + t.Errorf("LocalSnapshot after Terminate = %q, want none", got) + } + }) + + t.Run("terminating an actor that is not running succeeds", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + if _, err := c.Terminate(t.Context(), &ateletpb.TerminateRequest{WorkerPodUid: worker, ActorUid: uid}); err != nil { + t.Errorf("Terminate of an actor that is not running = %v, want no error", err) + } + }) + + t.Run("a blocked call takes effect only once released", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + gate := a.On(AteletRun).Block() + done := make(chan error) + go func() { + _, err := c.Run(t.Context(), run) + done <- err + }() + gate.Wait(t) + assertSandboxes(t, a, nil) + gate.Release() + if err := <-done; err != nil { + t.Fatalf("Run: %v", err) + } + assertSandboxes(t, a, running) + }) + + t.Run("a held reply comes after the call took effect", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + gate := a.On(AteletRun).BlockReply() + done := make(chan error) + go func() { + _, err := c.Run(t.Context(), run) + done <- err + }() + gate.Wait(t) + assertSandboxes(t, a, running) + select { + case err := <-done: + t.Fatalf("Run replied (%v) before its reply was released", err) + default: + } + gate.Release() + if err := <-done; err != nil { + t.Fatalf("Run: %v", err) + } + }) + + t.Run("records every call after RecordCalls, faulted or not", func(t *testing.T) { + a := newAteletWithWorker(newObjectStore()) + c := client(t, a) + if _, err := c.Terminate(t.Context(), &ateletpb.TerminateRequest{WorkerPodUid: worker, ActorUid: uid}); err != nil { + t.Fatalf("Terminate: %v", err) + } + rec := a.RecordCalls() + a.On(AteletRun).FailNext(ErrSandboxFailed) + if _, err := c.Run(t.Context(), run); err == nil { + t.Fatal("Run succeeded despite the fault") + } + if _, err := c.Run(t.Context(), run); err != nil { + t.Fatalf("Run: %v", err) + } + calls := rec.Calls() + if len(calls) != 2 || calls[0].Method != AteletRun || calls[1].Method != AteletRun { + t.Errorf("recorded calls = %v, want two Run", calls) + } + }) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/authn.go b/cmd/ateapi/internal/functionaltest/harness/authn.go new file mode 100644 index 0000000000..062b008233 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/authn.go @@ -0,0 +1,56 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "context" + "errors" + + "go.ate.dev/substrate/cmd/ateapi/internal/apiauthn" +) + +const ( + // clientTrustDomain is the SPIFFE trust domain of the identities the + // harness's Control clients authenticate as. + clientTrustDomain = "clients.harness.local" + // clientName is who the default Control client authenticates as. It is a + // bootstrap owner, so it may call every RPC. + clientName = "harness-client" +) + +// ClientID is the identity the client ClientAs(name) returns authenticates as: +// the SPIFFE ID its certificate carries, as an in-cluster component's does. +func ClientID(name string) string { + return "spiffe://" + clientTrustDomain + "/" + name +} + +// Member is how access policies name the client ClientAs(name) returns. +func Member(name string) string { + return "user:" + ClientID(name) +} + +// noTokens is ate-api's token authentication: a provider for an issuer no +// client uses, rejecting every token. Clients authenticate with certificates, +// as in-cluster components do, and ate-api requires at least one provider. The +// bearer-token path is covered by apiauthn's and oidcjwt's own tests. +func noTokens() apiauthn.ServerConfig { + return apiauthn.ServerConfig{JWTProviders: []apiauthn.JWTProvider{{ + Name: "none", + Issuer: "https://no-tokens." + clientTrustDomain, + Verify: func(context.Context, string) (string, error) { + return "", errors.New("harness clients authenticate with certificates") + }, + }}} +} diff --git a/cmd/ateapi/internal/functionaltest/harness/authn_test.go b/cmd/ateapi/internal/functionaltest/harness/authn_test.go new file mode 100644 index 0000000000..7955d47bc4 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/authn_test.go @@ -0,0 +1,76 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "testing" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "go.ate.dev/substrate/api/ateapi/v1" +) + +func TestControlClientAuthenticates(t *testing.T) { + t.Parallel() + h := New(t) + list := func(c ateapi.ControlClient) error { + _, err := c.ListAtespaces(t.Context(), &ateapi.ListAtespacesRequest{}) + return err + } + + if err := list(ateapi.NewControlClient(h.dialAteAPI(h.pki.clientTLS()))); status.Code(err) != codes.Unauthenticated { + t.Errorf("ListAtespaces without a client certificate = %v, want Unauthenticated", err) + } + if err := list(h.Control); err != nil { + t.Errorf("ListAtespaces as the harness client: %v", err) + } + if err := list(h.ControlWithoutPreview()); err != nil { + t.Errorf("ListAtespaces as the harness client without preview opt-in: %v", err) + } + if err := list(h.ClientAs("alice")); status.Code(err) != codes.PermissionDenied { + t.Errorf("ListAtespaces as a principal no policy names = %v, want PermissionDenied", err) + } + + noIdentity, err := h.pki.issue(&x509.Certificate{ + Subject: pkix.Name{CommonName: "no-identity"}, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, + }) + if err != nil { + t.Fatal(err) + } + if err := list(ateapi.NewControlClient(h.dialAteAPI(h.pki.clientTLS(noIdentity)))); status.Code(err) != codes.Unauthenticated { + t.Errorf("ListAtespaces with a certificate carrying no identity = %v, want Unauthenticated", err) + } + + otherCA, err := newPKI() + if err != nil { + t.Fatal(err) + } + foreign, err := otherCA.clientCert(ClientID(clientName)) + if err != nil { + t.Fatal(err) + } + // GetClientCertificate presents the certificate whatever CAs ate-api asks + // for, as a client set on impersonating the owner would. + impersonating := h.pki.clientTLS() + impersonating.GetClientCertificate = func(*tls.CertificateRequestInfo) (*tls.Certificate, error) { return &foreign, nil } + if err := list(ateapi.NewControlClient(h.dialAteAPI(impersonating))); err == nil { + t.Error("ListAtespaces with the bootstrap owner's identity, certified by another CA, succeeded") + } +} diff --git a/cmd/ateapi/internal/functionaltest/harness/cluster.go b/cmd/ateapi/internal/functionaltest/harness/cluster.go new file mode 100644 index 0000000000..2f602798c4 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/cluster.go @@ -0,0 +1,482 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "context" + "fmt" + "net" + "strconv" + "sync/atomic" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/protobuf/proto" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/api/resource" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/uuid" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/utils/ptr" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/atelet" + "go.ate.dev/substrate/internal/hardware" + "go.ate.dev/substrate/internal/installdefaults" + "go.ate.dev/substrate/internal/preview" +) + +// workerNamespace is the k8s namespace of the worker pods. +const workerNamespace = "workers" + +// ipCount hands out pod IPs unique within the process. Nothing routes to them: +// ate-api's dialer resolves an atelet's IP and the harness serves the +// connection in memory. +var ipCount atomic.Uint32 + +func nextPodIP() string { + n := ipCount.Add(1) + return fmt.Sprintf("10.%d.%d.%d", byte(n>>16), byte(n>>8), byte(n)) +} + +// Node is a k8s node with an atelet on it. +type Node struct { + // Name is the node's name in the cluster. + Name string + // Atelet is the node's fake atelet. + Atelet *Atelet + + // workerService is how the node's atelet reaches ate-api's + // WorkerService, presenting the atelet's pod identity. + workerService ateapi.WorkerServiceClient + + h *Harness + ateletPod string + ateletAddr string + server *grpc.Server +} + +// WorkerService is a client of ate-api's WorkerService that authenticates as +// the node's atelet, as atelet's calls on behalf of the node's workers do. +func (n *Node) WorkerService() ateapi.WorkerServiceClient { + return n.workerService +} + +// Node returns the node called name in this test, creating it and its atelet +// on first use. +func (h *Harness) Node(name string) *Node { + h.t.Helper() + h.mu.Lock() + n, ok := h.nodesByTestName[name] + h.mu.Unlock() + if ok { + return n + } + + nodeName := "node-" + name + podName := "atelet-" + nodeName + ip := nextPodIP() + addr := net.JoinHostPort(ip, strconv.Itoa(atelet.DefaultPort)) + n = &Node{Name: nodeName, Atelet: newAtelet(h.ObjectStore), h: h, ateletPod: podName, ateletAddr: addr} + + if _, err := h.k8s.CoreV1().Nodes().Create(h.ctx, &corev1.Node{ObjectMeta: metav1.ObjectMeta{Name: nodeName}}, metav1.CreateOptions{}); err != nil { + h.t.Fatalf("creating node %s: %v", nodeName, err) + } + + n.server = n.Atelet.grpcServer() + lis := serveInMemory(h.t, n.server) + h.mu.Lock() + h.ateletListenersByAddr[addr] = lis + h.mu.Unlock() + + pod := h.createRunningPod(installdefaults.SystemNamespace, podName, nodeName, ip, map[string]string{"app": "atelet"}) + + cert, err := h.pki.ateletCert(podName, string(pod.UID), nodeName) + if err != nil { + h.t.Fatal(err) + } + n.workerService = ateapi.NewWorkerServiceClient(h.dialAteAPI(h.pki.clientTLS(cert), preview.DialOptionsWithOptIn()...)) + + h.mu.Lock() + h.nodesByTestName[name] = n + h.mu.Unlock() + return n +} + +// StopAtelet takes the node's atelet down and deletes its pod, as when atelet +// crashes or is evicted. ate-api's calls to it fail, and once ate-api sees the +// pod deleted it finds no atelet on the node. The node stays in the cluster. +func (n *Node) StopAtelet() { + n.h.t.Helper() + n.h.mu.Lock() + delete(n.h.ateletListenersByAddr, n.ateletAddr) + n.h.mu.Unlock() + n.server.Stop() + if err := n.h.k8s.CoreV1().Pods(installdefaults.SystemNamespace).Delete(n.h.ctx, n.ateletPod, metav1.DeleteOptions{ + GracePeriodSeconds: ptr.To[int64](0), + }); err != nil && !apierrors.IsNotFound(err) { + n.h.t.Fatalf("deleting atelet pod %s: %v", n.ateletPod, err) + } +} + +// FinishUpload does what the node's atelet does once the deferred upload of +// actor's local snapshot completes: it writes the snapshot to object storage +// and reports it to ate-api as the actor's latest local and durable snapshot. +func (n *Node) FinishUpload(actor *ateapi.Actor) { + n.h.t.Helper() + uuid, err := n.Atelet.upload(actor.GetMetadata().GetUid()) + if err != nil { + n.h.t.Fatalf("uploading the local snapshot of actor %s: %v", actor.GetMetadata().GetName(), err) + } + report := snapshotReport(n.h.t, actor, uuid) + n.reportSnapshotState(actor, &ateapi.ActorSnapshotState{LatestLocal: report, LatestDurable: report}) +} + +// DetachSnapshot does what the node's atelet does when it uploads actor's +// local snapshot and drops it from the node on its own, as under disk +// pressure: it reports the snapshot to ate-api as durable and no longer local. +func (n *Node) DetachSnapshot(actor *ateapi.Actor) { + n.h.t.Helper() + state, err := n.Atelet.detach(actor.GetMetadata().GetUid()) + if err != nil { + n.h.t.Fatalf("detaching the local snapshot of actor %s: %v", actor.GetMetadata().GetName(), err) + } + uuid := state.GetLatestDurable().GetSnapshot().GetSnapshotUuid() + n.reportSnapshotState(actor, &ateapi.ActorSnapshotState{LatestDurable: snapshotReport(n.h.t, actor, uuid)}) +} + +// snapshotReport describes actor's snapshot uuid as atelet reports it. +func snapshotReport(t *testing.T, actor *ateapi.Actor, uuid string) *ateapi.SnapshotReport { + t.Helper() + for _, s := range actor.GetStatus().GetSnapshots() { + if s.GetUuid() == uuid { + return &ateapi.SnapshotReport{Uuid: uuid, Generation: s.GetGeneration(), Fidelity: s.GetFidelity(), Object: s.GetDurableSnapshot().GetObject()} + } + } + t.Fatalf("actor %s records no snapshot %s", actor.GetMetadata().GetName(), uuid) + return nil +} + +// reportSnapshotState reports actor's snapshot state to ate-api as the node's +// atelet. +func (n *Node) reportSnapshotState(actor *ateapi.Actor, state *ateapi.ActorSnapshotState) { + n.h.t.Helper() + if err := RetryAborted(n.h.ctx, func() error { + _, err := n.WorkerService().ReportActorSnapshotState(n.h.ctx, &ateapi.ReportActorSnapshotStateRequest{ + Actor: &ateapi.ObjectRef{Atespace: actor.GetMetadata().GetAtespace(), Name: actor.GetMetadata().GetName()}, + ActorUid: actor.GetMetadata().GetUid(), + State: state, + }) + return err + }); err != nil { + n.h.t.Fatalf("reporting the snapshot state of actor %s: %v", actor.GetMetadata().GetName(), err) + } +} + +// Remove deletes the node from the cluster, and its atelet with it, as when +// the node is drained and scaled away. Remove the node's workers first. +func (n *Node) Remove() { + n.h.t.Helper() + n.StopAtelet() + if err := n.h.k8s.CoreV1().Nodes().Delete(n.h.ctx, n.Name, metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) { + n.h.t.Fatalf("deleting node %s: %v", n.Name, err) + } +} + +// WorkerPool is the shape a group of workers shares. Templates select a pool +// by its labels. +type WorkerPool struct { + Name string + Labels map[string]string +} + +// CreateWorkerPool describes a pool of workers. Without labels, the pool is +// labeled pool=name. +func (h *Harness) CreateWorkerPool(name string, labels map[string]string) *WorkerPool { + if labels == nil { + labels = map[string]string{"pool": name} + } + return &WorkerPool{Name: name, Labels: labels} +} + +// Worker is a worker pod and the Worker ate-api records for it. +type Worker struct { + // Name is the Worker's name, which is its pod's UID. + Name string + // Pod is the worker pod's name. + Pod string + // Node is the node the worker runs on. + Node *Node + // Pool is the pool the worker belongs to. + Pool *WorkerPool + // Namespace is the k8s namespace of the worker pod. + Namespace string + // IP is the worker pod's IP. + IP string + // Epoch is the epoch the worker process registered with. + Epoch int64 + + capacity *ateapi.WorkerResources + + h *Harness +} + +// Ref is the Worker's reference in the Control API. +func (w *Worker) Ref() *ateapi.ObjectRef { + return &ateapi.ObjectRef{Name: w.Name} +} + +// WorkerOption customizes a worker added by AddWorker. +type WorkerOption func(*workerOptions) + +type workerOptions struct { + capacity *ateapi.WorkerResources + runtime *ateapi.ActorSandboxRuntime + restorable []*ateapi.ActorSandboxRuntime +} + +// WithActorCapacity makes the worker report room for n actors. The default +// is one. +func WithActorCapacity(n int32) WorkerOption { + return func(o *workerOptions) { o.capacity.Actors = n } +} + +// WithResourceCapacity makes the worker report room for cpu and memory, given +// as Kubernetes quantities such as "2" and "4Gi". By default a worker reports +// room for as many actors of NewTemplate's size as its actor capacity. +func WithResourceCapacity(cpu, memory string) WorkerOption { + return func(o *workerOptions) { + c, m := resource.MustParse(cpu), resource.MustParse(memory) + o.capacity.CpuMillicores = c.MilliValue() + o.capacity.MemoryBytes = m.Value() + } +} + +// WithSandboxRuntime makes the worker run actors under rt, and restore +// snapshots taken under any of restorable at full fidelity. By default a +// worker runs SandboxRuntime and restores no other. +func WithSandboxRuntime(rt *ateapi.ActorSandboxRuntime, restorable ...*ateapi.ActorSandboxRuntime) WorkerOption { + return func(o *workerOptions) { o.runtime, o.restorable = rt, restorable } +} + +// SandboxRuntime is the runtime a harness worker runs actors under unless +// WithSandboxRuntime says otherwise, and so the one ate-api stamps on their +// assignments and snapshots. +func SandboxRuntime() *ateapi.ActorSandboxRuntime { + return &ateapi.ActorSandboxRuntime{ + SandboxClass: "gvisor", + Version: &ateapi.VersionedSandboxCompat{ + SchemaVersion: hardware.SchemaVersionV1, + Attributes: []*ateapi.AttributeEntry{ + {Key: hardware.AttrArchitecture, Value: "amd64"}, + {Key: hardware.AttrSandboxBundleHash, Value: "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"}, + }, + }, + } +} + +// AddWorker does what the worker syncer and the worker's atelet do for a new +// worker pod: it creates the pod and the Worker, and registers the worker +// process with its IP, capacity and sandbox runtime over WorkerService. +func (h *Harness) AddWorker(pool *WorkerPool, node *Node, opts ...WorkerOption) *Worker { + h.t.Helper() + o := workerOptions{capacity: &ateapi.WorkerResources{Actors: 1}, runtime: SandboxRuntime()} + for _, opt := range opts { + opt(&o) + } + if o.capacity.CpuMillicores == 0 && o.capacity.MemoryBytes == 0 { + o.capacity.CpuMillicores = int64(o.capacity.Actors) * TemplateCPUMillicores + o.capacity.MemoryBytes = int64(o.capacity.Actors) * TemplateMemoryBytes + } + + podName := fmt.Sprintf("%s-worker-%d", pool.Name, h.next()) + ip := nextPodIP() + pod := h.createRunningPod(workerNamespace, podName, node.Name, ip, map[string]string{"ate.dev/worker-pool": pool.Name}) + w := &Worker{Name: string(pod.UID), Pod: podName, Node: node, Pool: pool, Namespace: workerNamespace, IP: ip, capacity: o.capacity, h: h} + + if _, err := h.Control.CreateWorker(h.ctx, &ateapi.CreateWorkerRequest{Worker: &ateapi.Worker{ + Metadata: &ateapi.ResourceMetadata{Name: w.Name}, + WorkerNamespace: workerNamespace, + WorkerPool: pool.Name, + WorkerPod: podName, + WorkerPodUid: w.Name, + NodeName: node.Name, + Labels: pool.Labels, + }}); err != nil { + h.t.Fatalf("registering worker %s: %v", podName, err) + } + h.mu.Lock() + h.workersByName[w.Name] = w + h.mu.Unlock() + + if _, err := h.Control.MarkWorkerAvailable(h.ctx, &ateapi.MarkWorkerAvailableRequest{Worker: w.Ref()}); err != nil { + h.t.Fatalf("marking worker %s available: %v", podName, err) + } + + // The worker process registers through its atelet, which retries while + // ate-api's reconciler holds the Worker. + ws := node.WorkerService() + acquired, err := ws.AcquireWorkerEpoch(h.ctx, &ateapi.AcquireWorkerEpochRequest{Worker: w.Ref()}) + if err != nil { + h.t.Fatalf("acquiring an epoch for worker %s: %v", podName, err) + } + epoch := acquired.GetEpoch() + if err := RetryAborted(h.ctx, func() error { + _, err := ws.RegisterWorker(h.ctx, &ateapi.RegisterWorkerRequest{ + Worker: w.Ref(), Epoch: epoch, Ips: []string{ip}, Capacity: o.capacity, + }) + return err + }); err != nil { + h.t.Fatalf("registering worker %s: %v", podName, err) + } + w.Epoch = epoch + w.reportSandboxRuntimes(o.runtime, o.restorable) + node.Atelet.registerWorker(w.Name, epoch) + // ate-api's reconciler updates the Worker once it observes the epoch; a + // test's own update of the Worker would race it. + h.Eventually(fmt.Sprintf("ate-api to observe the epoch of worker %s", podName), func() bool { + return h.GetWorker(w).GetStatus().GetObservedEpoch() >= epoch + }) + return w +} + +// Drain marks the worker DRAINING, as the worker syncer does when its pod +// starts terminating. +func (w *Worker) Drain() { + h := w.h + h.t.Helper() + if _, err := h.Control.DrainWorker(h.ctx, &ateapi.DrainWorkerRequest{Worker: w.Ref()}); err != nil { + h.t.Fatalf("draining worker %s: %v", w.Pod, err) + } +} + +// Restart replaces the worker's process, as when it crashes and its pod +// restarts it: the new process acquires a new epoch and registers, and the +// sandboxes the old one ran are gone. Like a real new process, it has not +// reported its sandbox runtimes; call SetSandboxRuntime for that. ate-api's +// reconciler observes the new epoch in the background, once no operation on +// the worker's actors holds them. +func (w *Worker) Restart() { + h := w.h + h.t.Helper() + ws := w.Node.WorkerService() + acquired, err := ws.AcquireWorkerEpoch(h.ctx, &ateapi.AcquireWorkerEpochRequest{Worker: w.Ref()}) + if err != nil { + h.t.Fatalf("acquiring a new epoch for worker %s: %v", w.Pod, err) + } + epoch := acquired.GetEpoch() + if err := RetryAborted(h.ctx, func() error { + _, err := ws.RegisterWorker(h.ctx, &ateapi.RegisterWorkerRequest{ + Worker: w.Ref(), Epoch: epoch, Ips: []string{w.IP}, Capacity: w.capacity, + }) + return err + }); err != nil { + h.t.Fatalf("registering worker %s again: %v", w.Pod, err) + } + w.Node.Atelet.restartWorker(w.Name, epoch) + w.Epoch = epoch +} + +// SetSandboxRuntime has the worker report rt as the runtime it runs actors +// under, and restorable as the runtimes it restores at full fidelity, as a +// worker does after its sandbox is upgraded. It waits until the Worker shows +// them. +func (w *Worker) SetSandboxRuntime(rt *ateapi.ActorSandboxRuntime, restorable ...*ateapi.ActorSandboxRuntime) { + w.h.t.Helper() + want := w.reportSandboxRuntimes(rt, restorable) + w.h.Eventually(fmt.Sprintf("worker %s to report its new sandbox runtime", w.Pod), func() bool { + return proto.Equal(want, w.h.GetWorker(w).GetStatus().GetSandboxClasses()[0]) + }) +} + +// reportSandboxRuntimes reports the worker's runtimes through its atelet, and +// returns the class it reported. +func (w *Worker) reportSandboxRuntimes(rt *ateapi.ActorSandboxRuntime, restorable []*ateapi.ActorSandboxRuntime) *ateapi.WorkerSandboxClass { + w.h.t.Helper() + class := &ateapi.WorkerSandboxClass{ + SandboxClass: rt.GetSandboxClass(), + DefaultRuntime: &ateapi.WorkerSandboxRuntime{Version: rt.GetVersion()}, + } + for _, r := range restorable { + class.RestorableRuntimes = append(class.RestorableRuntimes, &ateapi.WorkerSandboxRuntime{Version: r.GetVersion()}) + } + if err := RetryAborted(w.h.ctx, func() error { + _, err := w.Node.WorkerService().SetWorkerSandboxRuntimes(w.h.ctx, &ateapi.SetWorkerSandboxRuntimesRequest{ + Worker: w.Ref(), Epoch: w.Epoch, SandboxClasses: []*ateapi.WorkerSandboxClass{class}, + }) + return err + }); err != nil { + w.h.t.Fatalf("reporting the sandbox runtimes of worker %s: %v", w.Pod, err) + } + return class +} + +// Remove deletes the worker pod and its Worker, as the worker syncer does once +// the pod is gone. +func (w *Worker) Remove() { + h := w.h + h.t.Helper() + if err := h.k8s.CoreV1().Pods(workerNamespace).Delete(h.ctx, w.Pod, metav1.DeleteOptions{ + GracePeriodSeconds: ptr.To[int64](0), + }); err != nil { + h.t.Fatalf("deleting worker pod %s: %v", w.Pod, err) + } + if _, err := h.Control.DeleteWorker(h.ctx, &ateapi.DeleteWorkerRequest{Worker: w.Ref()}); err != nil { + h.t.Fatalf("deleting worker %s: %v", w.Pod, err) + } +} + +// worker returns the Worker the test added under name, or nil. +func (h *Harness) worker(name string) *Worker { + h.mu.Lock() + defer h.mu.Unlock() + return h.workersByName[name] +} + +// createRunningPod creates a pod on nodeName that is already running and +// ready at ip, so ate-api never sees it without an IP. +func (h *Harness) createRunningPod(namespace, name, nodeName, ip string, labels map[string]string) *corev1.Pod { + h.t.Helper() + created, err := h.k8s.CoreV1().Pods(namespace).Create(h.ctx, &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: name, Namespace: namespace, Labels: labels, UID: uuid.NewUUID()}, + Spec: corev1.PodSpec{ + NodeName: nodeName, + Containers: []corev1.Container{{Name: "main", Image: "harness"}}, + }, + Status: corev1.PodStatus{ + Phase: corev1.PodRunning, + PodIP: ip, + PodIPs: []corev1.PodIP{{IP: ip}}, + Conditions: []corev1.PodCondition{{Type: corev1.PodReady, Status: corev1.ConditionTrue}}, + }, + }, metav1.CreateOptions{}) + if err != nil { + h.t.Fatalf("creating pod %s/%s: %v", namespace, name, err) + } + return created +} + +// Eventually polls cond until it holds, failing the test after a timeout. +// Tests use it to wait for an outcome ate-api reaches asynchronously. +func (h *Harness) Eventually(what string, cond func() bool) { + h.t.Helper() + if err := wait.PollUntilContextTimeout(h.ctx, 10*time.Millisecond, waitTimeout, true, func(context.Context) (bool, error) { + return cond(), nil + }); err != nil { + h.t.Fatalf("waiting for %s: %v", what, err) + } +} diff --git a/cmd/ateapi/internal/functionaltest/harness/cluster_test.go b/cmd/ateapi/internal/functionaltest/harness/cluster_test.go new file mode 100644 index 0000000000..3e62d9bcab --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/cluster_test.go @@ -0,0 +1,203 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "errors" + "testing" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/testing/protocmp" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/installdefaults" +) + +func TestWorker(t *testing.T) { + t.Parallel() + h := New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + nodeA := h.Node("a") + if again := h.Node("a"); again != nodeA { + t.Errorf("Node(a) returned %p the second time, want the first node %p", again, nodeA) + } + + w := h.AddWorker(pool, nodeA, WithActorCapacity(3), WithResourceCapacity("2", "4Gi")) + want := &ateapi.Worker{ + Metadata: &ateapi.ResourceMetadata{Name: w.Name}, + WorkerNamespace: w.Namespace, + WorkerPool: "pool1", + WorkerPod: w.Pod, + WorkerPodUid: w.Name, + NodeName: nodeA.Name, + Labels: map[string]string{"pool": "pool1"}, + Status: &ateapi.WorkerStatus{ + State: ateapi.WorkerState_WORKER_STATE_ACTIVE, + Capacity: &ateapi.WorkerResources{Actors: 3, CpuMillicores: 2000, MemoryBytes: 4 << 30}, + Ips: []string{w.IP}, + IssuedEpoch: 1, + RegisteredEpoch: 1, + ObservedEpoch: 1, + SandboxClasses: []*ateapi.WorkerSandboxClass{{ + SandboxClass: "gvisor", + DefaultRuntime: &ateapi.WorkerSandboxRuntime{Version: SandboxRuntime().GetVersion()}, + }}, + }, + } + ignoreCreatedMetadata := protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "uid", "version", "create_time", "update_time") + if diff := cmp.Diff(want, h.GetWorker(w), protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("registered worker (-want +got):\n%s", diff) + } + + other := h.AddWorker(pool, h.Node("b")) + wantDefault := &ateapi.WorkerResources{Actors: 1, CpuMillicores: TemplateCPUMillicores, MemoryBytes: TemplateMemoryBytes} + if diff := cmp.Diff(wantDefault, h.GetWorker(other).GetStatus().GetCapacity(), protocmp.Transform()); diff != "" { + t.Errorf("default capacity (-want +got):\n%s", diff) + } + + actor := h.NewActor(as, h.NewTemplate(as, pool)) + w.Drain() + other.Remove() + var err error + h.Eventually("ResumeActor to find no worker", func() bool { + _, err = h.Control.ResumeActor(t.Context(), &ateapi.ResumeActorRequest{Actor: ActorRef(actor)}) + return status.Code(err) == codes.ResourceExhausted + }) +} + +func TestNode(t *testing.T) { + t.Parallel() + h := New(t) + n := h.Node("a") + if _, err := h.k8s.CoreV1().Nodes().Get(t.Context(), n.Name, metav1.GetOptions{}); err != nil { + t.Fatalf("getting node %s: %v", n.Name, err) + } + + n.StopAtelet() + if _, err := h.dialAtelet(t.Context(), n.ateletAddr); !errors.Is(err, errNoAtelet) { + t.Errorf("dialing the stopped atelet = %v, want %v", err, errNoAtelet) + } + if _, err := h.k8s.CoreV1().Pods(installdefaults.SystemNamespace).Get(t.Context(), n.ateletPod, metav1.GetOptions{}); !apierrors.IsNotFound(err) { + t.Errorf("getting the stopped atelet's pod = %v, want NotFound", err) + } + if _, err := h.k8s.CoreV1().Nodes().Get(t.Context(), n.Name, metav1.GetOptions{}); err != nil { + t.Errorf("getting node %s after its atelet stopped: %v", n.Name, err) + } + + n.Remove() + if _, err := h.k8s.CoreV1().Nodes().Get(t.Context(), n.Name, metav1.GetOptions{}); !apierrors.IsNotFound(err) { + t.Errorf("getting removed node %s = %v, want NotFound", n.Name, err) + } +} + +func TestWorkerSandboxRuntime(t *testing.T) { + t.Parallel() + h := New(t) + rtA := SandboxRuntime() + rtB := proto.CloneOf(rtA) + rtB.Version.Attributes[1].Value = "hash-b" + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), h.Node("a"), WithSandboxRuntime(rtB, rtA)) + want := []*ateapi.WorkerSandboxClass{{ + SandboxClass: "gvisor", + DefaultRuntime: &ateapi.WorkerSandboxRuntime{Version: rtB.GetVersion()}, + RestorableRuntimes: []*ateapi.WorkerSandboxRuntime{{Version: rtA.GetVersion()}}, + }} + if diff := cmp.Diff(want, h.GetWorker(w).GetStatus().GetSandboxClasses(), protocmp.Transform()); diff != "" { + t.Errorf("registered sandbox classes (-want +got):\n%s", diff) + } + + w.SetSandboxRuntime(rtA) + want = []*ateapi.WorkerSandboxClass{{SandboxClass: "gvisor", DefaultRuntime: &ateapi.WorkerSandboxRuntime{Version: rtA.GetVersion()}}} + if diff := cmp.Diff(want, h.GetWorker(w).GetStatus().GetSandboxClasses(), protocmp.Transform()); diff != "" { + t.Errorf("sandbox classes after the change (-want +got):\n%s", diff) + } +} + +func TestNodeFinishUpload(t *testing.T) { + t.Parallel() + h := New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.AsyncSuspendedActor(as, h.NewTemplate(as, pool)) + snaps := actor.GetStatus().GetSnapshots() + local := snaps[len(snaps)-1] + + node.FinishUpload(actor) + got := h.GetActor(ActorRef(actor)).GetStatus().GetSnapshots() + if state := got[len(got)-1].GetDurableSnapshot().GetState(); state != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED { + t.Errorf("snapshot after the upload is %v, want COMPLETED", state) + } + if names, err := h.ObjectStore.Snapshot(local.GetDurableSnapshot().GetObject().GetSnapshotUri()); err != nil || len(names) == 0 { + t.Errorf("uploaded snapshot in object storage = %v, %v; want it present", names, err) + } + if uuid := node.Atelet.LocalSnapshot(actor.GetMetadata().GetUid()); uuid != local.GetUuid() { + t.Errorf("local snapshot after the upload = %q, want %q kept", uuid, local.GetUuid()) + } +} + +func TestWorkerRestart(t *testing.T) { + t.Parallel() + h := New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + w := h.AddWorker(pool, node) + h.RunningActor(as, h.NewTemplate(as, pool)) + before := w.Epoch + + w.Restart() + if w.Epoch <= before { + t.Errorf("epoch after restart = %d, want above %d", w.Epoch, before) + } + if got := h.GetWorker(w).GetStatus().GetRegisteredEpoch(); got != w.Epoch { + t.Errorf("registered epoch = %d, want %d", got, w.Epoch) + } + if diff := cmp.Diff([]Sandbox{}, node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after restart (-want +got):\n%s", diff) + } +} + +func TestNodeDetachSnapshot(t *testing.T) { + t.Parallel() + h := New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + actor := h.AsyncSuspendedActor(as, h.NewTemplate(as, pool)) + snaps := actor.GetStatus().GetSnapshots() + local := snaps[len(snaps)-1] + + node.DetachSnapshot(actor) + got := h.GetActor(ActorRef(actor)).GetStatus().GetSnapshots() + detached := got[len(got)-1] + if detached.GetDurableSnapshot().GetState() != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED || detached.GetLocality() != "" { + t.Errorf("snapshot after the detach is %v local to %q, want COMPLETED and not local", detached.GetDurableSnapshot().GetState(), detached.GetLocality()) + } + if names, err := h.ObjectStore.Snapshot(local.GetDurableSnapshot().GetObject().GetSnapshotUri()); err != nil || len(names) == 0 { + t.Errorf("detached snapshot in object storage = %v, %v; want it present", names, err) + } + if uuid := node.Atelet.LocalSnapshot(actor.GetMetadata().GetUid()); uuid != "" { + t.Errorf("local snapshot after the detach = %q, want none", uuid) + } +} diff --git a/cmd/ateapi/internal/functionaltest/harness/fixtures.go b/cmd/ateapi/internal/functionaltest/harness/fixtures.go new file mode 100644 index 0000000000..aca7275afe --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/fixtures.go @@ -0,0 +1,283 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "context" + "fmt" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/resources" +) + +// retryInterval is how long ResumeActorWithRetries and RetryAborted wait +// between attempts. +const retryInterval = 20 * time.Millisecond + +const ( + // StorageLocation is where ate-api keeps snapshots. + StorageLocation = "gs://harness-snapshots" + // Image is the image of the container harness templates run. + Image = "main@sha256:e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + // TemplateCPUMillicores and TemplateMemoryBytes are the resource limits + // of NewTemplate's actors. + TemplateCPUMillicores = 1000 + TemplateMemoryBytes = 512 << 20 +) + +// TemplateOption customizes a template created by NewTemplate. +type TemplateOption func(*ateapi.ActorTemplate) + +// WithExternalVolume gives the template an external volume, provisioned by +// the harness's volume plugin and mounted at mountPath in its container. +func (h *Harness) WithExternalVolume(name, mountPath string) TemplateOption { + return func(tmpl *ateapi.ActorTemplate) { + tmpl.Volumes = append(tmpl.Volumes, &ateapi.Volume{ + Name: name, + External: &ateapi.ExternalVolumeSource{Template: &ateapi.ExternalVolumeTemplate{ + StorageClassName: h.Volumes.StorageClass(), + CapacityBytes: 1 << 30, + }}, + }) + c := tmpl.Containers[0] + c.VolumeMounts = append(c.VolumeMounts, &ateapi.VolumeMount{Name: name, MountPath: mountPath}) + } +} + +// CreateAtespace creates the atespace name. +func (h *Harness) CreateAtespace(name string) string { + h.t.Helper() + if _, err := h.Control.CreateAtespace(h.ctx, &ateapi.CreateAtespaceRequest{Atespace: &ateapi.Atespace{ + Metadata: &ateapi.ResourceMetadata{Name: name}, + }}); err != nil { + h.t.Fatalf("creating atespace %s: %v", name, err) + } + return name +} + +// NewTemplate creates an ActorTemplate in atespace that places its actors on +// pool, and waits for ate-api to publish its golden snapshot. The pool needs a +// worker with room for the golden actor. An option that sets a preview field +// needs a harness WithPreviewClient. +func (h *Harness) NewTemplate(atespace string, pool *WorkerPool, opts ...TemplateOption) *ateapi.ActorTemplate { + h.t.Helper() + tmpl := &ateapi.ActorTemplate{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: fmt.Sprintf("tmpl-%d", h.next())}, + Containers: []*ateapi.Container{{ + Name: "main", + Image: Image, + Command: []string{"/main"}, + // A wakeup probe on every container lets the golden snapshot be + // taken as soon as the golden actor runs, with no warmup wait. + WakeupProbe: &ateapi.WakeupProbe{ + HttpGet: &ateapi.HttpGetAction{Path: "/healthz", Port: 8080}, + }, + }}, + WorkerSelector: &ateapi.Selector{MatchLabels: pool.Labels}, + Resources: &ateapi.ResourceRequirements{Limits: resources.CPUMemory(TemplateCPUMillicores, TemplateMemoryBytes)}, + } + for _, opt := range opts { + opt(tmpl) + } + created, err := h.Control.CreateActorTemplate(h.ctx, &ateapi.CreateActorTemplateRequest{ActorTemplate: tmpl}) + if err != nil { + h.t.Fatalf("creating template %s: %v", tmpl.GetMetadata().GetName(), err) + } + ref := &ateapi.ObjectRef{Atespace: created.GetMetadata().GetAtespace(), Name: created.GetMetadata().GetName()} + + var ready *ateapi.ActorTemplate + h.Eventually(fmt.Sprintf("the golden snapshot of template %s", ref.GetName()), func() bool { + got, err := h.Control.GetActorTemplate(h.ctx, &ateapi.GetActorTemplateRequest{ActorTemplate: ref}) + if err != nil { + return false + } + if msg := got.GetStatus().GetGoldenSnapshotStatus().GetErrorMessage(); msg != "" { + h.t.Fatalf("golden snapshot of template %s failed: %s", ref.GetName(), msg) + } + ready = got + return got.GetStatus().GetGoldenSnapshotStatus().GetGoldenTag() != nil + }) + return ready +} + +// ActorOption customizes an actor created by NewActor. +type ActorOption func(*ateapi.Actor) + +// NewActor creates a SUSPENDED actor from tmpl in atespace. +func (h *Harness) NewActor(atespace string, tmpl *ateapi.ActorTemplate, opts ...ActorOption) *ateapi.Actor { + h.t.Helper() + actor := &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: fmt.Sprintf("actor-%d", h.next())}, + ActorTemplate: &ateapi.ObjectRef{ + Atespace: tmpl.GetMetadata().GetAtespace(), + Name: tmpl.GetMetadata().GetName(), + }, + } + for _, opt := range opts { + opt(actor) + } + created, err := h.Control.CreateActor(h.ctx, &ateapi.CreateActorRequest{Actor: actor}) + if err != nil { + h.t.Fatalf("creating actor %s: %v", actor.GetMetadata().GetName(), err) + } + return created +} + +// RunningActor creates an actor from tmpl in atespace and resumes it. +func (h *Harness) RunningActor(atespace string, tmpl *ateapi.ActorTemplate, opts ...ActorOption) *ateapi.Actor { + h.t.Helper() + actor := h.NewActor(atespace, tmpl, opts...) + resp, err := h.ResumeActorWithRetries(h.ctx, &ateapi.ResumeActorRequest{Actor: ActorRef(actor)}) + if err != nil { + h.t.Fatalf("resuming actor %s: %v", actor.GetMetadata().GetName(), err) + } + return resp.GetActor() +} + +// SuspendedActor creates an actor from tmpl in atespace, resumes it, and +// suspends it synchronously, so it holds a durable snapshot of its own. +func (h *Harness) SuspendedActor(atespace string, tmpl *ateapi.ActorTemplate, opts ...ActorOption) *ateapi.Actor { + h.t.Helper() + running := h.RunningActor(atespace, tmpl, opts...) + resp, err := h.Control.SuspendActor(h.ctx, &ateapi.SuspendActorRequest{ + Actor: ActorRef(running), + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, + }) + if err != nil { + h.t.Fatalf("suspending actor %s: %v", running.GetMetadata().GetName(), err) + } + return resp.GetActor() +} + +// AsyncSuspendedActor creates an actor from tmpl in atespace, resumes it, and +// suspends it asynchronously, so its latest snapshot is local to its node and +// not uploaded. +func (h *Harness) AsyncSuspendedActor(atespace string, tmpl *ateapi.ActorTemplate, opts ...ActorOption) *ateapi.Actor { + h.t.Helper() + running := h.RunningActor(atespace, tmpl, opts...) + resp, err := h.Control.SuspendActor(h.ctx, &ateapi.SuspendActorRequest{ + Actor: ActorRef(running), + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS}, + }) + if err != nil { + h.t.Fatalf("suspending actor %s: %v", running.GetMetadata().GetName(), err) + } + return resp.GetActor() +} + +// CrashedActor creates an actor from tmpl in atespace, resumes it, and crashes +// it by failing the checkpoint of a suspend. +func (h *Harness) CrashedActor(atespace string, tmpl *ateapi.ActorTemplate, opts ...ActorOption) *ateapi.Actor { + h.t.Helper() + running := h.RunningActor(atespace, tmpl, opts...) + w := h.WorkerOf(running) + w.Node.Atelet.On(AteletCheckpoint).FailNext(ErrSandboxFailed) + if _, err := h.Control.SuspendActor(h.ctx, &ateapi.SuspendActorRequest{Actor: ActorRef(running)}); err == nil { + h.t.Fatalf("suspending actor %s succeeded despite a failing checkpoint", running.GetMetadata().GetName()) + } + crashed := h.GetActor(ActorRef(running)) + if got := crashed.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_CRASHED { + h.t.Fatalf("actor %s is %v after a failed checkpoint, want CRASHED", running.GetMetadata().GetName(), got) + } + return crashed +} + +// ResumeActorWithRetries calls Control.ResumeActor, retrying the errors atenet +// retries while it parks a request. Any other error is returned at once. +func (h *Harness) ResumeActorWithRetries(ctx context.Context, req *ateapi.ResumeActorRequest) (*ateapi.ResumeActorResponse, error) { + deadline := time.Now().Add(waitTimeout) + for { + resp, err := h.Control.ResumeActor(ctx, req) + if err == nil || !retryable(err) || time.Now().After(deadline) { + return resp, err + } + select { + case <-ctx.Done(): + return nil, err + case <-time.After(retryInterval): + } + } +} + +// RetryAborted calls call, retrying as a client does while it fails with +// ABORTED, such as while another operation holds the resource's lease. Any +// other result is returned at once. +func RetryAborted(ctx context.Context, call func() error) error { + deadline := time.Now().Add(waitTimeout) + for { + err := call() + if status.Code(err) != codes.Aborted || time.Now().After(deadline) { + return err + } + select { + case <-ctx.Done(): + return err + case <-time.After(retryInterval): + } + } +} + +// retryable reports whether atenet's ActorResumer retries err while it parks +// a request. +func retryable(err error) bool { + switch status.Code(err) { + case codes.Aborted, codes.ResourceExhausted, codes.Unavailable: + return true + } + return false +} + +// GetActor reads the actor through the Control API, failing the test if it +// cannot. +func (h *Harness) GetActor(ref *ateapi.ObjectRef) *ateapi.Actor { + h.t.Helper() + actor, err := h.Control.GetActor(h.ctx, &ateapi.GetActorRequest{Actor: ref}) + if err != nil { + h.t.Fatalf("getting actor %s/%s: %v", ref.GetAtespace(), ref.GetName(), err) + } + return actor +} + +// GetWorker reads the worker through the Control API, failing the test if it +// cannot. +func (h *Harness) GetWorker(w *Worker) *ateapi.Worker { + h.t.Helper() + worker, err := h.Control.GetWorker(h.ctx, &ateapi.GetWorkerRequest{Worker: w.Ref()}) + if err != nil { + h.t.Fatalf("getting worker %s: %v", w.Pod, err) + } + return worker +} + +// WorkerOf returns the worker the actor is assigned to, as its status says, +// failing the test if it has none. +func (h *Harness) WorkerOf(actor *ateapi.Actor) *Worker { + h.t.Helper() + name := actor.GetStatus().GetWorkerAssignment().GetWorker().GetName() + w := h.worker(name) + if w == nil { + h.t.Fatalf("actor %s is assigned to worker %q, which the test did not add", actor.GetMetadata().GetName(), name) + } + return w +} + +// ActorRef is the actor's reference in the Control API. +func ActorRef(actor *ateapi.Actor) *ateapi.ObjectRef { + return &ateapi.ObjectRef{Atespace: actor.GetMetadata().GetAtespace(), Name: actor.GetMetadata().GetName()} +} diff --git a/cmd/ateapi/internal/functionaltest/harness/fixtures_test.go b/cmd/ateapi/internal/functionaltest/harness/fixtures_test.go new file mode 100644 index 0000000000..0fc92f3d94 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/fixtures_test.go @@ -0,0 +1,100 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "context" + "testing" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "go.ate.dev/substrate/api/ateapi/v1" +) + +func TestFixtures(t *testing.T) { + t.Parallel() + h := New(t, WithPreviewClient()) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a"), WithActorCapacity(4)) + tmpl := h.NewTemplate(as, pool, h.WithExternalVolume("data", "/data")) + + running := h.RunningActor(as, tmpl) + if got := running.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_RUNNING { + t.Errorf("RunningActor is %v, want RUNNING", got) + } + h.WorkerOf(running) + + suspended := h.SuspendedActor(as, tmpl) + if got := suspended.GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { + t.Errorf("SuspendedActor is %v, want SUSPENDED", got) + } + snapshots := suspended.GetStatus().GetSnapshots() + if len(snapshots) == 0 { + t.Fatal("SuspendedActor holds no snapshot") + } + if names, _ := h.ObjectStore.Snapshot(snapshots[len(snapshots)-1].GetDurableSnapshot().GetObject().GetSnapshotUri()); len(names) == 0 { + t.Error("SuspendedActor holds no durable snapshot in object storage") + } + + crashed := h.CrashedActor(as, tmpl) + if crashed.GetStatus().GetWorkerAssignment() != nil { + t.Errorf("CrashedActor holds worker assignment %v, want none", crashed.GetStatus().GetWorkerAssignment()) + } +} + +func TestRetryAborted(t *testing.T) { + t.Parallel() + aborted := status.Error(codes.Aborted, "lease held") + + t.Run("retries while the call fails with ABORTED", func(t *testing.T) { + calls := 0 + err := RetryAborted(t.Context(), func() error { + calls++ + if calls < 3 { + return aborted + } + return nil + }) + if err != nil || calls != 3 { + t.Errorf("RetryAborted = %v after %d calls, want nil after 3", err, calls) + } + }) + + t.Run("returns any other error at once", func(t *testing.T) { + calls := 0 + err := RetryAborted(t.Context(), func() error { + calls++ + return status.Error(codes.FailedPrecondition, "wrong state") + }) + if status.Code(err) != codes.FailedPrecondition || calls != 1 { + t.Errorf("RetryAborted = %v after %d calls, want FailedPrecondition after 1", err, calls) + } + }) + + t.Run("returns ABORTED once the context ends", func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + calls := 0 + err := RetryAborted(ctx, func() error { + calls++ + cancel() + return aborted + }) + if status.Code(err) != codes.Aborted || calls != 1 { + t.Errorf("RetryAborted = %v after %d calls, want Aborted after 1", err, calls) + } + }) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/grpcfake/doc.go b/cmd/ateapi/internal/functionaltest/harness/grpcfake/doc.go new file mode 100644 index 0000000000..0515ef757d --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/grpcfake/doc.go @@ -0,0 +1,42 @@ +// Copyright 2026 The Agent Substrate 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 grpcfake adds fault injection and call recording to fake gRPC +// services, for tests that call a fake through a real gRPC client. +// +// A fake creates a Service for the methods it instruments, named by their +// generated full method names, and registers its own implementation on the +// server NewServer returns: +// +// svc := grpcfake.NewService(pb.Foo_Bar_FullMethodName) +// srv := svc.NewServer() +// pb.RegisterFooServer(srv, impl) +// +// The server's unary interceptor handles every call to an instrumented +// method. It adds the call, with a copy of its request, to every Recording +// started with Record. Then it makes the call as the method's Fault says. The +// faults apply to the next calls, one each, in the order they were added: +// - FailNext fails the call with a status, without making it. +// - Block holds the call before it reaches the implementation. +// - BlockReply makes the call and holds its reply. +// +// Block and BlockReply return a Gate. Gate.Wait waits until the held call +// arrives, and Gate.Release lets it go on. A held call whose caller gives up +// ends with the caller's context error. Calls to other methods, and streaming +// calls, reach the implementation unchanged and are not recorded. +// +// A fake usually names its methods with its own string type, such as +// type FooMethod string, so the compiler rejects another fake's method in On +// or in a Recording. +package grpcfake diff --git a/cmd/ateapi/internal/functionaltest/harness/grpcfake/fault.go b/cmd/ateapi/internal/functionaltest/harness/grpcfake/fault.go new file mode 100644 index 0000000000..8fb8c75119 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/grpcfake/fault.go @@ -0,0 +1,141 @@ +// Copyright 2026 The Agent Substrate 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 grpcfake + +import ( + "context" + "sync" + "testing" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// gateTimeout bounds how long Gate.Wait waits for the blocked call to arrive. +const gateTimeout = 10 * time.Second + +// Fault decides how the calls to one operation of a fake behave. Its faults +// apply to the next calls, one each, in the order they were added. A call with +// no fault left succeeds. +type Fault struct { + mu sync.Mutex + queue []*action +} + +// action is one queued fault: fail with st, hold the call at gate, or hold +// its reply at reply. +type action struct { + st *status.Status + gate *Gate + reply *Gate +} + +// FailNext fails the next call with st, without applying its effect. It +// panics if st is nil or OK. +func (f *Fault) FailNext(st *status.Status) { + if st.Code() == codes.OK { + panic("grpcfake: FailNext needs a status with an error code") + } + f.mu.Lock() + defer f.mu.Unlock() + f.queue = append(f.queue, &action{st: st}) +} + +// Block holds the next call until the returned Gate is released. +func (f *Fault) Block() *Gate { + g := &Gate{arrived: make(chan struct{}, 1), released: make(chan struct{}, 1)} + f.mu.Lock() + defer f.mu.Unlock() + f.queue = append(f.queue, &action{gate: g}) + return g +} + +// BlockReply lets the next call take effect, then holds its reply until the +// returned Gate is released, as when the reply is slow to reach the caller. +func (f *Fault) BlockReply() *Gate { + g := &Gate{arrived: make(chan struct{}, 1), released: make(chan struct{}, 1)} + f.mu.Lock() + defer f.mu.Unlock() + f.queue = append(f.queue, &action{reply: g}) + return g +} + +// run makes one call to the faulted operation through call, as the next +// queued fault says: it fails the call without making it, holds the call until +// released, or makes the call and holds its reply. With no fault queued it +// makes the call. A held call or reply fails with the context's error if ctx +// ends first. +func (f *Fault) run(ctx context.Context, call func() (any, error)) (any, error) { + f.mu.Lock() + var next *action + if len(f.queue) > 0 { + next = f.queue[0] + f.queue = f.queue[1:] + } + f.mu.Unlock() + + switch { + case next == nil: + return call() + case next.gate != nil: + if err := next.gate.hold(ctx); err != nil { + return nil, err + } + return call() + case next.reply != nil: + resp, err := call() + if holdErr := next.reply.hold(ctx); holdErr != nil { + return nil, holdErr + } + return resp, err + default: + return nil, next.st.Err() + } +} + +// Gate holds one call to a faulted operation, or its reply, until the test +// releases it. +type Gate struct { + arrived chan struct{} + released chan struct{} +} + +// Wait blocks until the held call, or its reply, arrives. +func (g *Gate) Wait(t testing.TB) { + t.Helper() + select { + case <-g.arrived: + case <-time.After(gateTimeout): + t.Fatalf("no call reached the gate within %v", gateTimeout) + } +} + +// Release lets the held call proceed as if it had not been faulted. +func (g *Gate) Release() { + g.released <- struct{}{} +} + +// hold signals that a call reached g, and waits until g is released or ctx +// ends. +func (g *Gate) hold(ctx context.Context) error { + g.arrived <- struct{}{} + select { + case <-g.released: + return nil + case <-ctx.Done(): + return status.FromContextError(ctx.Err()).Err() + } +} diff --git a/cmd/ateapi/internal/functionaltest/harness/grpcfake/service.go b/cmd/ateapi/internal/functionaltest/harness/grpcfake/service.go new file mode 100644 index 0000000000..9859943a68 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/grpcfake/service.go @@ -0,0 +1,108 @@ +// Copyright 2026 The Agent Substrate 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 grpcfake + +import ( + "context" + "slices" + "sync" + + "google.golang.org/grpc" + "google.golang.org/protobuf/proto" +) + +// Service faults and records the calls to the instrumented methods of a fake +// gRPC service. It does so in a server interceptor, so the fake's +// implementation holds only its state and behavior. +type Service[M ~string] struct { + faults map[M]*Fault + log callLog[M] +} + +// NewService returns a Service for methods. +func NewService[M ~string](methods ...M) *Service[M] { + s := &Service[M]{faults: map[M]*Fault{}} + for _, method := range methods { + s.faults[method] = &Fault{} + } + return s +} + +// NewServer returns a gRPC server that applies s to its calls. +func (s *Service[M]) NewServer() *grpc.Server { + return grpc.NewServer(grpc.UnaryInterceptor(s.intercept)) +} + +// On returns the Fault deciding how calls to method behave. +func (s *Service[M]) On(method M) *Fault { + return s.faults[method] +} + +// Record starts a recording of the calls to s's methods from now on. +func (s *Service[M]) Record() *Recording[M] { + return s.log.record() +} + +// intercept records a call to one of s's methods and makes it as the method's +// Fault says. +func (s *Service[M]) intercept(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + method := M(info.FullMethod) + fault, isInstrumented := s.faults[method] + if !isInstrumented { + return handler(ctx, req) + } + s.log.add(method, req.(proto.Message)) + return fault.run(ctx, func() (any, error) { return handler(ctx, req) }) +} + +// Call is one call a fake received, faulted or not. +type Call[M ~string] struct { + Method M + Request proto.Message +} + +// callLog records the calls a fake receives, in order. +type callLog[M ~string] struct { + mu sync.Mutex + calls []Call[M] +} + +// add records a call to method with a copy of req. +func (l *callLog[M]) add(method M, req proto.Message) { + req = proto.Clone(req) + l.mu.Lock() + defer l.mu.Unlock() + l.calls = append(l.calls, Call[M]{Method: method, Request: req}) +} + +// record starts a recording of the calls l receives from now on. +func (l *callLog[M]) record() *Recording[M] { + l.mu.Lock() + defer l.mu.Unlock() + return &Recording[M]{log: l, start: len(l.calls)} +} + +// Recording holds the calls a fake receives from the moment it is started. +type Recording[M ~string] struct { + log *callLog[M] + start int +} + +// Calls returns the calls the fake received since r started, in order. +func (r *Recording[M]) Calls() []Call[M] { + r.log.mu.Lock() + defer r.log.mu.Unlock() + return slices.Clone(r.log.calls[r.start:]) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/grpcfake/service_test.go b/cmd/ateapi/internal/functionaltest/harness/grpcfake/service_test.go new file mode 100644 index 0000000000..572b30fdf0 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/grpcfake/service_test.go @@ -0,0 +1,263 @@ +// Copyright 2026 The Agent Substrate 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 grpcfake_test + +import ( + "context" + "net" + "sync" + "testing" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials/insecure" + healthpb "google.golang.org/grpc/health/grpc_health_v1" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness/grpcfake" +) + +type method string + +const ( + healthCheck = method(healthpb.Health_Check_FullMethodName) + healthList = method(healthpb.Health_List_FullMethodName) +) + +// healthServer counts the calls that reach it. Check overwrites its request, +// so a recording that kept the request it was given would see the change. +type healthServer struct { + healthpb.UnimplementedHealthServer + mu sync.Mutex + calls int +} + +func (s *healthServer) Check(_ context.Context, req *healthpb.HealthCheckRequest) (*healthpb.HealthCheckResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.calls++ + req.Service = "changed by the handler" + return &healthpb.HealthCheckResponse{Status: healthpb.HealthCheckResponse_SERVING}, nil +} + +func (s *healthServer) List(context.Context, *healthpb.HealthListRequest) (*healthpb.HealthListResponse, error) { + s.mu.Lock() + defer s.mu.Unlock() + s.calls++ + return &healthpb.HealthListResponse{}, nil +} + +// made returns how many calls reached s. +func (s *healthServer) made() int { + s.mu.Lock() + defer s.mu.Unlock() + return s.calls +} + +// fixture is a health server behind a Service that instruments Check, and a +// client connected to it in memory. +type fixture struct { + svc *grpcfake.Service[method] + srv *grpc.Server + health *healthServer + client healthpb.HealthClient +} + +func newFixture(t *testing.T) *fixture { + t.Helper() + f := &fixture{svc: grpcfake.NewService(healthCheck), health: &healthServer{}} + f.srv = f.svc.NewServer() + healthpb.RegisterHealthServer(f.srv, f.health) + lis := bufconn.Listen(1 << 20) + go func() { _ = f.srv.Serve(lis) }() + t.Cleanup(f.srv.Stop) + conn, err := grpc.NewClient("passthrough:///in-memory", + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { return lis.DialContext(ctx) })) + if err != nil { + t.Fatalf("connecting in memory: %v", err) + } + t.Cleanup(func() { conn.Close() }) + f.client = healthpb.NewHealthClient(conn) + return f +} + +// check calls Check for service. +func (f *fixture) check(ctx context.Context, service string) error { + _, err := f.client.Check(ctx, &healthpb.HealthCheckRequest{Service: service}) + return err +} + +// checkAsync calls Check in the background and returns its error on the +// channel. +func (f *fixture) checkAsync(ctx context.Context) <-chan error { + done := make(chan error, 1) + go func() { done <- f.check(ctx, "") }() + return done +} + +func TestService(t *testing.T) { + t.Run("a call with no fault reaches the service", func(t *testing.T) { + f := newFixture(t) + if err := f.check(t.Context(), ""); err != nil || f.health.made() != 1 { + t.Errorf("Check = %v after %d calls; want OK after one call", err, f.health.made()) + } + }) + + t.Run("FailNext fails exactly one call without reaching the service", func(t *testing.T) { + f := newFixture(t) + f.svc.On(healthCheck).FailNext(status.New(codes.Unavailable, "injected")) + if err := f.check(t.Context(), ""); status.Code(err) != codes.Unavailable || f.health.made() != 0 { + t.Errorf("first Check = %v after %d calls; want Unavailable and no call", err, f.health.made()) + } + if err := f.check(t.Context(), ""); err != nil || f.health.made() != 1 { + t.Errorf("second Check = %v after %d calls; want OK after one call", err, f.health.made()) + } + }) + + t.Run("faults apply to the next calls in the order they were added", func(t *testing.T) { + f := newFixture(t) + f.svc.On(healthCheck).FailNext(status.New(codes.Unavailable, "injected")) + f.svc.On(healthCheck).FailNext(status.New(codes.Internal, "injected")) + var got []codes.Code + for range 3 { + got = append(got, status.Code(f.check(t.Context(), ""))) + } + if diff := cmp.Diff([]codes.Code{codes.Unavailable, codes.Internal, codes.OK}, got); diff != "" { + t.Errorf("codes (-want +got):\n%s", diff) + } + }) + + t.Run("FailNext panics on a status that is nil or OK", func(t *testing.T) { + for _, st := range []*status.Status{nil, status.New(codes.OK, "")} { + func() { + defer func() { + if recover() == nil { + t.Errorf("FailNext(%v) did not panic", st) + } + }() + newFixture(t).svc.On(healthCheck).FailNext(st) + }() + } + }) + + t.Run("Block holds the call until Release", func(t *testing.T) { + f := newFixture(t) + gate := f.svc.On(healthCheck).Block() + done := f.checkAsync(t.Context()) + gate.Wait(t) + select { + case err := <-done: + t.Fatalf("Check returned %v before Release", err) + default: + } + if f.health.made() != 0 { + t.Errorf("a blocked call reached the service") + } + gate.Release() + if err := <-done; err != nil || f.health.made() != 1 { + t.Errorf("released Check = %v after %d calls; want OK after one call", err, f.health.made()) + } + }) + + t.Run("a blocked call ends with its context without reaching the service", func(t *testing.T) { + f := newFixture(t) + gate := f.svc.On(healthCheck).Block() + ctx, cancel := context.WithCancel(t.Context()) + done := f.checkAsync(ctx) + gate.Wait(t) + cancel() + if err := <-done; status.Code(err) != codes.Canceled { + t.Errorf("canceled Check = %v, want Canceled", err) + } + // GracefulStop waits for the server to finish the canceled call. + f.srv.GracefulStop() + if f.health.made() != 0 { + t.Errorf("a canceled blocked call reached the service") + } + }) + + t.Run("BlockReply lets the call reach the service and holds its reply until Release", func(t *testing.T) { + f := newFixture(t) + gate := f.svc.On(healthCheck).BlockReply() + done := f.checkAsync(t.Context()) + gate.Wait(t) + if f.health.made() != 1 { + t.Errorf("a call whose reply is held made %d calls, want 1", f.health.made()) + } + select { + case err := <-done: + t.Fatalf("Check returned %v before Release", err) + default: + } + gate.Release() + if err := <-done; err != nil { + t.Errorf("released Check = %v, want OK", err) + } + }) + + t.Run("a held reply ends with its context after the call reached the service", func(t *testing.T) { + f := newFixture(t) + gate := f.svc.On(healthCheck).BlockReply() + ctx, cancel := context.WithCancel(t.Context()) + done := f.checkAsync(ctx) + gate.Wait(t) + cancel() + if err := <-done; status.Code(err) != codes.Canceled { + t.Errorf("canceled Check = %v, want Canceled", err) + } + // GracefulStop waits for the server to finish the canceled call. + f.srv.GracefulStop() + if f.health.made() != 1 { + t.Errorf("a canceled call whose reply was held made %d calls, want 1", f.health.made()) + } + }) + + t.Run("Record holds a copy of every call from then on, faulted or not", func(t *testing.T) { + f := newFixture(t) + if err := f.check(t.Context(), "before"); err != nil { + t.Fatalf("Check: %v", err) + } + rec := f.svc.Record() + f.svc.On(healthCheck).FailNext(status.New(codes.Unavailable, "injected")) + if err := f.check(t.Context(), "faulted"); err == nil { + t.Fatal("faulted Check succeeded") + } + if err := f.check(t.Context(), "made"); err != nil { + t.Fatalf("Check: %v", err) + } + want := []grpcfake.Call[method]{ + {Method: healthCheck, Request: &healthpb.HealthCheckRequest{Service: "faulted"}}, + {Method: healthCheck, Request: &healthpb.HealthCheckRequest{Service: "made"}}, + } + if diff := cmp.Diff(want, rec.Calls(), protocmp.Transform()); diff != "" { + t.Errorf("recorded calls (-want +got):\n%s", diff) + } + }) + + t.Run("a method the Service does not instrument passes through unrecorded", func(t *testing.T) { + f := newFixture(t) + rec := f.svc.Record() + if _, err := f.client.List(t.Context(), &healthpb.HealthListRequest{}); err != nil || f.health.made() != 1 { + t.Errorf("List = %v after %d calls; want OK after one call", err, f.health.made()) + } + if calls := rec.Calls(); len(calls) != 0 { + t.Errorf("recorded %v, want no calls", calls) + } + }) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/harness.go b/cmd/ateapi/internal/functionaltest/harness/harness.go new file mode 100644 index 0000000000..dabe39c60f --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/harness.go @@ -0,0 +1,354 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "context" + "crypto/tls" + "errors" + "fmt" + "net" + "sync" + "testing" + "time" + + "go.opentelemetry.io/otel/metric/noop" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/status" + "google.golang.org/grpc/test/bufconn" + storagev1 "k8s.io/api/storage/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/kubernetes" + kubefake "k8s.io/client-go/kubernetes/fake" + + "go.ate.dev/substrate/api/ateapi/v1" + atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" + objectstorev1 "go.ate.dev/substrate/api/objectstore/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/authz" + "go.ate.dev/substrate/cmd/ateapi/internal/controlapi" + "go.ate.dev/substrate/cmd/ateapi/internal/server" + "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" + "go.ate.dev/substrate/internal/installdefaults" + "go.ate.dev/substrate/internal/localca" + "go.ate.dev/substrate/internal/localjwtauthority" + "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/pkg/client/clientset/versioned" + atefake "go.ate.dev/substrate/pkg/client/clientset/versioned/fake" +) + +const ( + // bufSize is the buffer of each in-memory listener. + bufSize = 1 << 20 + // templateResync is how often the ActorTemplateReconciler lists templates, + // which bounds how long a new template waits for its golden snapshot. + templateResync = 100 * time.Millisecond + // waitTimeout bounds every wait and retry the harness does. + waitTimeout = 10 * time.Second + // ActorJWTIssuer is the issuer of the actor JWTs ate-api mints. + ActorJWTIssuer = "https://idp.harness.test" +) + +// Harness is one ate-api and the fakes it talks to. Tests change and observe +// ate-api only through Control and the harness's methods. +type Harness struct { + // Control is a client of ate-api's Control service. It opts in to preview + // features only in a harness created WithPreviewClient. + Control ateapi.ControlClient + // ObjectStore is the blob storage ate-api and the atelets share. + ObjectStore *ObjectStore + // Volumes is the CSI driver behind its StorageClass. + Volumes *Volumes + + // preview makes the harness's Control clients opt in to preview features. + preview bool + + t *testing.T + ctx context.Context + pki *pki + k8s kubernetes.Interface + listener *bufconn.Listener + + mu sync.Mutex + nodesByTestName map[string]*Node + workersByName map[string]*Worker + ateletListenersByAddr map[string]*bufconn.Listener + counter int +} + +// Option configures a harness. +type Option func(*Harness) + +// WithPreviewClient makes the harness's Control clients, and so its fixtures, +// opt in to preview features, as kubectl ate --preview does. Every preview +// gate is on in ate-api, so a test needs it to use a preview feature, such as +// a template with an external volume. +func WithPreviewClient() Option { + return func(h *Harness) { h.preview = true } +} + +// New starts an empty ate-api for t, built as ate-api's main builds it, with +// its own database and fakes. Everything is torn down when t ends. +func New(t *testing.T, opts ...Option) *Harness { + t.Helper() + if !mainStarted { + t.Fatal("harness.Main must run from the package's TestMain") + } + ctx, cancel := context.WithCancel(context.Background()) + + h := &Harness{ + ObjectStore: newObjectStore(), + Volumes: newVolumes("volumes.harness.ate.dev", "harness-volumes"), + t: t, + ctx: ctx, + nodesByTestName: map[string]*Node{}, + workersByName: map[string]*Worker{}, + ateletListenersByAddr: map[string]*bufconn.Listener{}, + } + for _, opt := range opts { + opt(h) + } + + var err error + if h.pki, err = newPKI(); err != nil { + t.Fatal(err) + } + h.k8s = kubefake.NewClientset() + ac := atefake.NewSimpleClientset() + // Before ate-api starts, so its informers see the driver's config and + // StorageClass from the start. + h.serveVolumes(ac) + + persistence := storetest.SetupPostgresPersistenceWithoutAuthz(t) + fgaServer, err := authz.NewOpenFGAServer(persistence.Pool()) + if err != nil { + t.Fatalf("creating the OpenFGA server: %v", err) + } + t.Cleanup(fgaServer.Close) + ns := installdefaults.SystemNamespace + authorizer, policyManager, err := authz.New(ctx, persistence.Pool(), fgaServer, []string{ClientID(clientName)}, authz.SystemPrincipals{ + ControllerSPIFFEID: installdefaults.ControllerSPIFFEID(ns), + EgressGatewaySPIFFEIDs: []string{installdefaults.EgressSPIFFEID(ns)}, + IngressRouterSPIFFEIDs: []string{installdefaults.RouterSPIFFEID(ns)}, + AteletSPIFFEID: installdefaults.AteletSPIFFEID(ns), + APIServerSidecarSPIFFEID: installdefaults.APIServerSPIFFEID(ns), + }) + if err != nil { + t.Fatalf("initializing authorization: %v", err) + } + persistence.SetPolicyManager(policyManager) + // Registered after the store's and OpenFGA's own cleanups, so the caches + // and reconcilers stop before their database goes away. + t.Cleanup(cancel) + + jwtAuthority, err := localjwtauthority.GenerateAuthority("ES256", "1") + if err != nil { + t.Fatalf("generating the actor JWT authority: %v", err) + } + actorCA, err := localca.GenerateCA("1", localca.KeyTypeECDSAP256, 24*time.Hour) + if err != nil { + t.Fatalf("generating the actor CA: %v", err) + } + serverTLS, err := h.pki.serverTLS() + if err != nil { + t.Fatal(err) + } + + srv, err := server.New(ctx, ctx, server.Config{ + Store: persistence, + KubeClient: h.k8s, + SubstrateCRDClient: ac, + AteletNamespace: ns, + AteletSPIFFEID: installdefaults.AteletSPIFFEID(ns), + // Atelets are dialed in memory and without TLS, through the real + // lookup, dial and connection-cache path. + AteletDialerOptions: []controlapi.DialerOption{ + controlapi.WithDialCredentials(func(string) (credentials.TransportCredentials, error) { + return insecure.NewCredentials(), nil + }), + controlapi.WithContextDialer(h.dialAtelet), + }, + ServerCreds: credentials.NewTLS(serverTLS), + Authn: noTokens(), + Authorizer: authorizer, + ObjectStorePlugin: objectstorev1.NewControlProviderClient(dialInMemory(t, serveInMemory(t, h.ObjectStore.grpcServer()))), + SnapshotLocation: StorageLocation, + ActorJWTIssuer: ActorJWTIssuer, + ActorJWTAuthorities: &localjwtauthority.ConcretePool{Authorities: []*localjwtauthority.Authority{jwtAuthority}, ActiveForSigning: "1"}, + ActorIDCAs: &localca.ConcretePool{CAs: []*localca.CA{actorCA}, ActiveForSigning: "1"}, + ActorWorkflowDeadline: 30 * time.Second, + TemplateResyncInterval: templateResync, + TemplateReconcilerWorkers: controlapi.DefaultTemplateReconcilerWorkers, + // Every gate is on, and a test uses a preview feature only through a + // harness WithPreviewClient, whose clients opt in. + // + // TODO: Start ate-api with no gates, as ate-api-server does, and let + // each test enable the ones it needs when it creates the harness, such + // as New(t, WithPreviewServer(preview.GateExternalVolumes)). + PreviewGates: preview.NewForTest(t, preview.All), + Meter: noop.NewMeterProvider().Meter("ateapi"), + }) + if err != nil { + t.Fatalf("building ate-api: %v", err) + } + srv.StartReconcilers(ctx) + h.listener = bufconn.Listen(bufSize) + go func() { _ = srv.GRPC.Serve(h.listener) }() + t.Cleanup(srv.GRPC.Stop) + + h.Control = h.ClientAs(clientName) + return h +} + +// ClientAs returns a Control client that authenticates with a certificate for +// ClientID(name). Access policies name it as Member(name). Unlike Control, it +// holds no permissions until a policy grants them. +func (h *Harness) ClientAs(name string) ateapi.ControlClient { + h.t.Helper() + var opts []grpc.DialOption + if h.preview { + opts = preview.DialOptionsWithOptIn() + } + return h.controlClient(ClientID(name), opts...) +} + +// ControlWithoutPreview returns a Control client that authenticates as Control +// does but never opts in to preview features, for a test WithPreviewClient to +// check what a client without the opt-in can do. +func (h *Harness) ControlWithoutPreview() ateapi.ControlClient { + h.t.Helper() + return h.controlClient(ClientID(clientName)) +} + +// EgressGateway returns a Control client that authenticates as atenet-egress, +// which holds the egress_gateway role, such as for minting actor JWTs. +func (h *Harness) EgressGateway() ateapi.ControlClient { + h.t.Helper() + return h.controlClient(installdefaults.EgressSPIFFEID(installdefaults.SystemNamespace), preview.DialOptionsWithOptIn()...) +} + +// controlClient returns a Control client that authenticates with a +// certificate for the SPIFFE ID id. +func (h *Harness) controlClient(id string, opts ...grpc.DialOption) ateapi.ControlClient { + h.t.Helper() + cert, err := h.pki.clientCert(id) + if err != nil { + h.t.Fatal(err) + } + return ateapi.NewControlClient(h.dialAteAPI(h.pki.clientTLS(cert), opts...)) +} + +// dialAteAPI connects to ate-api over TLS configured by tlsConfig. The +// connection is closed when the test ends. +func (h *Harness) dialAteAPI(tlsConfig *tls.Config, opts ...grpc.DialOption) *grpc.ClientConn { + h.t.Helper() + opts = append([]grpc.DialOption{ + grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { + return h.listener.DialContext(ctx) + }), + }, opts...) + conn, err := grpc.NewClient("passthrough:///"+serverName, opts...) + if err != nil { + h.t.Fatalf("connecting to ate-api: %v", err) + } + h.t.Cleanup(func() { conn.Close() }) + return conn +} + +// serveInMemory serves srv on an in-memory listener until the test ends. +func serveInMemory(t testing.TB, srv *grpc.Server) *bufconn.Listener { + lis := bufconn.Listen(bufSize) + go func() { _ = srv.Serve(lis) }() + t.Cleanup(srv.Stop) + return lis +} + +// dialInMemory connects to lis without TLS. The connection is closed when the +// test ends. +func dialInMemory(t testing.TB, lis *bufconn.Listener) *grpc.ClientConn { + t.Helper() + conn, err := grpc.NewClient("passthrough:///in-memory", + grpc.WithTransportCredentials(insecure.NewCredentials()), + grpc.WithContextDialer(func(ctx context.Context, _ string) (net.Conn, error) { + return lis.DialContext(ctx) + })) + if err != nil { + t.Fatalf("connecting in memory: %v", err) + } + t.Cleanup(func() { conn.Close() }) + return conn +} + +// serveVolumes serves the Volumes as a CSI driver on a loopback TCP port, and +// creates the CSIDriverConfig through which ate-api dials it, without TLS, and +// the StorageClass it provisions. +func (h *Harness) serveVolumes(ac versioned.Interface) { + h.t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + h.t.Fatalf("listening for the CSI driver: %v", err) + } + srv := h.Volumes.grpcServer() + go func() { _ = srv.Serve(lis) }() + h.t.Cleanup(srv.Stop) + + driver := h.Volumes.Driver() + if _, err := ac.AteV1().CSIDriverConfigs().Create(h.ctx, &atev1.CSIDriverConfig{ + ObjectMeta: metav1.ObjectMeta{Name: driver}, + Spec: atev1.CSIDriverConfigSpec{ + DriverName: driver, + ControllerEndpoint: "tcp://" + lis.Addr().String(), + }, + }, metav1.CreateOptions{}); err != nil { + h.t.Fatalf("creating CSIDriverConfig %s: %v", driver, err) + } + storageClass := h.Volumes.StorageClass() + if _, err := h.k8s.StorageV1().StorageClasses().Create(h.ctx, &storagev1.StorageClass{ + ObjectMeta: metav1.ObjectMeta{Name: storageClass}, + Provisioner: driver, + }, metav1.CreateOptions{}); err != nil { + h.t.Fatalf("creating StorageClass %s: %v", storageClass, err) + } +} + +// ErrUnavailable is the transport failing: the atelet, the object-store plugin +// or the volume plugin is restarting or unreachable. +var ErrUnavailable = status.New(codes.Unavailable, "harness: unavailable") + +// errNoAtelet is ate-api dialing an atelet the test stopped, before ate-api +// has seen its pod deleted. +var errNoAtelet = errors.New("harness: no atelet listening") + +// dialAtelet connects ate-api to the fake atelet serving addr. +func (h *Harness) dialAtelet(ctx context.Context, addr string) (net.Conn, error) { + h.mu.Lock() + lis, ok := h.ateletListenersByAddr[addr] + h.mu.Unlock() + if !ok { + return nil, fmt.Errorf("%w at %s", errNoAtelet, addr) + } + return lis.DialContext(ctx) +} + +// next returns a number unique within the harness, for resource names. +func (h *Harness) next() int { + h.mu.Lock() + defer h.mu.Unlock() + h.counter++ + return h.counter +} diff --git a/cmd/ateapi/internal/functionaltest/harness/main.go b/cmd/ateapi/internal/functionaltest/harness/main.go new file mode 100644 index 0000000000..618130a4b5 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/main.go @@ -0,0 +1,39 @@ +// Copyright 2026 The Agent Substrate 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 harness runs ate-api against fakes of everything it talks to, for +// functional tests that drive it only through its public API. +// +// Each test gets its own ate-api, database, fake Kubernetes clients, nodes, +// atelets, object store and volume plugin, so tests run in parallel. A test package +// using the harness calls Main from its TestMain. +package harness + +import ( + "os" + "testing" + + "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" +) + +// mainStarted records that Main set up the process for the harness. +var mainStarted bool + +// Main runs the package's tests and tears the PostgreSQL container down. +func Main(m *testing.M) { + mainStarted = true + code := m.Run() + storetest.Shutdown() + os.Exit(code) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/main_test.go b/cmd/ateapi/internal/functionaltest/harness/main_test.go new file mode 100644 index 0000000000..e52ca0dad7 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/main_test.go @@ -0,0 +1,21 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import "testing" + +func TestMain(m *testing.M) { + Main(m) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/objectstore.go b/cmd/ateapi/internal/functionaltest/harness/objectstore.go new file mode 100644 index 0000000000..dc46dac59c --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/objectstore.go @@ -0,0 +1,132 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "context" + "fmt" + "strings" + + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + objectstorev1 "go.ate.dev/substrate/api/objectstore/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness/grpcfake" + "go.ate.dev/substrate/internal/objectstore" + "go.ate.dev/substrate/internal/objectstore/objectstoretest" + "go.ate.dev/substrate/internal/objectstoreplugin" + "go.ate.dev/substrate/internal/resources" +) + +// ObjectStoreMethod is the gRPC full name of a ControlProvider RPC ate-api +// calls on the object-store plugin, which a fault can be injected into. +type ObjectStoreMethod string + +const ( + ObjectStoreCleanupSnapshot = ObjectStoreMethod(objectstorev1.ControlProvider_CleanupSnapshot_FullMethodName) + ObjectStoreCopySnapshot = ObjectStoreMethod(objectstorev1.ControlProvider_CopySnapshot_FullMethodName) +) + +// ErrStorageFailed is object storage failing a request, as the plugin reports +// a failure it does not recognize. +var ErrStorageFailed = status.New(codes.Internal, "harness: storage request failed") + +// ObjectStore is the in-memory blob storage shared by ate-api and every fake +// atelet in a test, as one bucket is shared in a real cluster. ate-api reaches +// it through the object-store plugin's ControlProvider service. +type ObjectStore struct { + fake *grpcfake.Service[ObjectStoreMethod] + store *objectstoretest.Fake +} + +func newObjectStore() *ObjectStore { + return &ObjectStore{ + fake: grpcfake.NewService(ObjectStoreCleanupSnapshot, ObjectStoreCopySnapshot), + store: objectstoretest.New(), + } +} + +// On returns the Fault deciding how ate-api's calls to method behave. The fake +// atelets' uploads are not faulted. +func (s *ObjectStore) On(method ObjectStoreMethod) *grpcfake.Fault { + return s.fake.On(method) +} + +// grpcServer returns a gRPC server of the object-store plugin's +// ControlProvider on s, which applies s's faults and records its calls. +// Tests hold only the ObjectStore, so they reach its server side only through +// ate-api. +func (s *ObjectStore) grpcServer() *grpc.Server { + srv := s.fake.NewServer() + objectstorev1.RegisterControlProviderServer(srv, objectstoreplugin.NewControlPlugin(s.store)) + return srv +} + +// RecordCalls starts recording the calls ate-api makes to s from now on. +func (s *ObjectStore) RecordCalls() *grpcfake.Recording[ObjectStoreMethod] { + return s.fake.Record() +} + +// Objects returns every object as "bucket/object", sorted. +func (s *ObjectStore) Objects() []string { + return s.store.Objects() +} + +// Snapshot returns the names, relative to snapshotURI, of the objects the +// external snapshot there is made of. Empty means the snapshot is not there. +func (s *ObjectStore) Snapshot(snapshotURI string) ([]string, error) { + prefix, err := snapshotPrefix(snapshotURI) + if err != nil { + return nil, err + } + bucket, object, err := objectstore.BucketPrefix(prefix) + if err != nil { + return nil, err + } + objects, err := s.store.List(context.Background(), bucket, object) + if err != nil { + return nil, err + } + names := make([]string, 0, len(objects)) + for _, o := range objects { + names = append(names, strings.TrimPrefix(o, object)) + } + return names, nil +} + +// DeleteSnapshot removes every object of the external snapshot at snapshotURI, +// as if it had been lost from blob storage. +func (s *ObjectStore) DeleteSnapshot(snapshotURI string) error { + prefix, err := snapshotPrefix(snapshotURI) + if err != nil { + return err + } + return objectstore.DeletePrefix(context.Background(), s.store, prefix) +} + +// writeSnapshot records the objects of the external snapshot at snapshotURI, +// as an atelet checkpoint or upload writes them. +func (s *ObjectStore) writeSnapshot(snapshotURI string, names ...string) error { + return s.store.WriteSnapshot(snapshotURI, names...) +} + +func snapshotPrefix(snapshotURI string) (resources.StoragePrefix, error) { + uri, err := resources.ParseSnapshotURI(snapshotURI) + if err != nil { + return resources.StoragePrefix{}, fmt.Errorf("while parsing the snapshot URI %q: %w", snapshotURI, err) + } + return uri.Prefix(), nil +} diff --git a/cmd/ateapi/internal/functionaltest/harness/objectstore_test.go b/cmd/ateapi/internal/functionaltest/harness/objectstore_test.go new file mode 100644 index 0000000000..e404f88115 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/objectstore_test.go @@ -0,0 +1,163 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + objectstorev1 "go.ate.dev/substrate/api/objectstore/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness/grpcfake" + "go.ate.dev/substrate/internal/resources" +) + +func TestObjectStore(t *testing.T) { + snapshotURI := func(t *testing.T, snapshotUID string) string { + t.Helper() + uri, err := resources.NewActorSnapshotURI(StorageLocation, "ns", "0f0e0d0c-0b0a-4908-8706-050403020100", snapshotUID) + if err != nil { + t.Fatalf("NewActorSnapshotURI: %v", err) + } + return uri.String() + } + withObjects := func(keys ...string) *ObjectStore { + s := newObjectStore() + for _, k := range keys { + bucket, object, _ := strings.Cut(k, "/") + s.store.Put(bucket, object, "") + } + return s + } + assertObjects := func(t *testing.T, s *ObjectStore, want []string) { + t.Helper() + if diff := cmp.Diff(want, s.Objects(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("objects (-want +got):\n%s", diff) + } + } + + client := func(t *testing.T, s *ObjectStore) objectstorev1.ControlProviderClient { + t.Helper() + return objectstorev1.NewControlProviderClient(dialInMemory(t, serveInMemory(t, s.grpcServer()))) + } + cleanup := func(t *testing.T, s *ObjectStore, uri string) error { + t.Helper() + _, err := client(t, s).CleanupSnapshot(t.Context(), &objectstorev1.CleanupSnapshotRequest{SnapshotUri: uri}) + return err + } + copySnapshot := func(t *testing.T, s *ObjectStore, src, dst string) error { + t.Helper() + _, err := client(t, s).CopySnapshot(t.Context(), &objectstorev1.CopySnapshotRequest{SrcUri: src, DstUri: dst}) + return err + } + + t.Run("Objects lists every bucket's objects, sorted", func(t *testing.T) { + s := withObjects("b2/y", "b1/x") + assertObjects(t, s, []string{"b1/x", "b2/y"}) + }) + + t.Run("a faulted CleanupSnapshot fails and keeps the objects", func(t *testing.T) { + s := withObjects("b1/root/x") + s.On(ObjectStoreCleanupSnapshot).FailNext(ErrStorageFailed) + if err := cleanup(t, s, "gs://b1/root"); status.Code(err) != codes.Internal { + t.Errorf("faulted CleanupSnapshot = %v, want Internal", err) + } + assertObjects(t, s, []string{"b1/root/x"}) + }) + + t.Run("a faulted CopySnapshot fails and copies nothing", func(t *testing.T) { + s := withObjects("b1/src/x") + s.On(ObjectStoreCopySnapshot).FailNext(ErrStorageFailed) + if err := copySnapshot(t, s, "gs://b1/src", "gs://b2/dst"); status.Code(err) != codes.Internal { + t.Errorf("faulted CopySnapshot = %v, want Internal", err) + } + assertObjects(t, s, []string{"b1/src/x"}) + }) + + t.Run("records every call after RecordCalls, faulted or not", func(t *testing.T) { + s := withObjects("b1/src/x") + if err := cleanup(t, s, "gs://b1/other"); err != nil { + t.Fatalf("CleanupSnapshot: %v", err) + } + rec := s.RecordCalls() + s.On(ObjectStoreCopySnapshot).FailNext(ErrStorageFailed) + if err := copySnapshot(t, s, "gs://b1/src", "gs://b2/dst"); err == nil { + t.Fatal("faulted CopySnapshot succeeded") + } + if err := cleanup(t, s, "gs://b1/src"); err != nil { + t.Fatalf("CleanupSnapshot: %v", err) + } + want := []grpcfake.Call[ObjectStoreMethod]{ + {Method: ObjectStoreCopySnapshot, Request: &objectstorev1.CopySnapshotRequest{SrcUri: "gs://b1/src", DstUri: "gs://b2/dst"}}, + {Method: ObjectStoreCleanupSnapshot, Request: &objectstorev1.CleanupSnapshotRequest{SnapshotUri: "gs://b1/src"}}, + } + if diff := cmp.Diff(want, rec.Calls(), protocmp.Transform()); diff != "" { + t.Errorf("recorded calls (-want +got):\n%s", diff) + } + }) + + t.Run("a written snapshot is listed relative to its URI", func(t *testing.T) { + s := newObjectStore() + uri := snapshotURI(t, "9c2f7b41-6d05-4e83-a1f7-3b8c0d5e2a94") + if err := s.writeSnapshot(uri, "memory.zst", "manifest.json"); err != nil { + t.Fatalf("writeSnapshot: %v", err) + } + got, err := s.Snapshot(uri) + if err != nil { + t.Fatalf("Snapshot: %v", err) + } + if diff := cmp.Diff([]string{"manifest.json", "memory.zst"}, got); diff != "" { + t.Errorf("Snapshot (-want +got):\n%s", diff) + } + }) + + t.Run("a snapshot that was never written is empty", func(t *testing.T) { + got, err := newObjectStore().Snapshot(snapshotURI(t, "9c2f7b41-6d05-4e83-a1f7-3b8c0d5e2a94")) + if err != nil || len(got) != 0 { + t.Errorf("Snapshot of a missing snapshot = %v, %v; want empty", got, err) + } + }) + + t.Run("DeleteSnapshot removes that snapshot only", func(t *testing.T) { + s := newObjectStore() + lost := snapshotURI(t, "9c2f7b41-6d05-4e83-a1f7-3b8c0d5e2a94") + kept := snapshotURI(t, "1d4e5f60-7a8b-4c9d-8e0f-a1b2c3d4e5f6") + for _, uri := range []string{lost, kept} { + if err := s.writeSnapshot(uri, snapshotObjects...); err != nil { + t.Fatalf("writeSnapshot: %v", err) + } + } + if err := s.DeleteSnapshot(lost); err != nil { + t.Fatalf("DeleteSnapshot: %v", err) + } + if got, _ := s.Snapshot(lost); len(got) != 0 { + t.Errorf("Snapshot after DeleteSnapshot = %v, want empty", got) + } + if got, _ := s.Snapshot(kept); len(got) != len(snapshotObjects) { + t.Errorf("other snapshot after DeleteSnapshot = %v, want %v", got, snapshotObjects) + } + }) + + t.Run("a malformed snapshot URI is refused", func(t *testing.T) { + if _, err := newObjectStore().Snapshot("not-a-snapshot-uri"); err == nil { + t.Error("Snapshot of a malformed URI succeeded") + } + }) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/pki.go b/cmd/ateapi/internal/functionaltest/harness/pki.go new file mode 100644 index 0000000000..2c63a6c07b --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/pki.go @@ -0,0 +1,140 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "fmt" + "net/url" + "time" + + "go.ate.dev/substrate/internal/installdefaults" + "go.ate.dev/substrate/internal/localca" + "go.ate.dev/substrate/internal/substratex509" +) + +// serverName is the name ate-api's serving certificate is issued for. +const serverName = "ateapi.harness.local" + +// pki is the pod-identity CA of one test. It issues ate-api's serving +// certificate and the certificates atelets present to WorkerService. +type pki struct { + ca *localca.ConcretePool + pool *x509.CertPool +} + +func newPKI() (*pki, error) { + ca, err := localca.GenerateCA("harness", localca.KeyTypeECDSAP256, 24*time.Hour) + if err != nil { + return nil, fmt.Errorf("generating the pod-identity CA: %w", err) + } + p := &pki{ca: &localca.ConcretePool{CAs: []*localca.CA{ca}, ActiveForSigning: ca.ID}, pool: x509.NewCertPool()} + p.pool.AddCert(ca.RootCertificate) + return p, nil +} + +// issue signs a leaf from template with a fresh key. +func (p *pki) issue(template *x509.Certificate) (tls.Certificate, error) { + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + return tls.Certificate{}, fmt.Errorf("generating a leaf key: %w", err) + } + template.NotBefore = time.Now() + template.NotAfter = time.Now().Add(24 * time.Hour) + template.KeyUsage = x509.KeyUsageDigitalSignature + chain, err := p.ca.CreateCertificate(template, &key.PublicKey) + if err != nil { + return tls.Certificate{}, fmt.Errorf("creating a leaf certificate: %w", err) + } + return tls.Certificate{Certificate: chain, PrivateKey: key}, nil +} + +// servingCert is a serving certificate for name. +func (p *pki) servingCert(name string) (tls.Certificate, error) { + return p.issue(&x509.Certificate{ + Subject: pkix.Name{CommonName: name}, + DNSNames: []string{name}, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + }) +} + +// serverTLS is ate-api's transport config. As in production, client +// certificates are optional. Control clients present a certificate carrying +// their SPIFFE ID, and atelets present their pod identity. +func (p *pki) serverTLS() (*tls.Config, error) { + cert, err := p.servingCert(serverName) + if err != nil { + return nil, err + } + return &tls.Config{ + Certificates: []tls.Certificate{cert}, + ClientAuth: tls.VerifyClientCertIfGiven, + ClientCAs: p.pool, + }, nil +} + +// clientTLS is the transport config of a client of ate-api, presenting certs. +func (p *pki) clientTLS(certs ...tls.Certificate) *tls.Config { + return &tls.Config{ + RootCAs: p.pool, + ServerName: serverName, + Certificates: certs, + } +} + +// clientCert is the certificate of a Control client authenticating as id, a +// SPIFFE ID. +func (p *pki) clientCert(id string) (tls.Certificate, error) { + uri, err := url.Parse(id) + if err != nil { + return tls.Certificate{}, fmt.Errorf("parsing the client ID %q: %w", id, err) + } + return p.issue(&x509.Certificate{ + Subject: pkix.Name{CommonName: uri.Path}, + URIs: []*url.URL{uri}, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, + }) +} + +// ateletCert is the pod-identity certificate of the atelet pod podName on +// nodeName, which WorkerService authenticates. +func (p *pki) ateletCert(podName, podUID, nodeName string) (tls.Certificate, error) { + spiffeID, err := url.Parse(installdefaults.AteletSPIFFEID(installdefaults.SystemNamespace)) + if err != nil { + return tls.Certificate{}, fmt.Errorf("parsing the atelet SPIFFE ID: %w", err) + } + template := &x509.Certificate{ + Subject: pkix.Name{CommonName: podName}, + URIs: []*url.URL{spiffeID}, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth}, + } + if err := substratex509.AddPodIdentityToCertificate(&substratex509.PodIdentity{ + Namespace: installdefaults.SystemNamespace, + ServiceAccountName: installdefaults.AteletServiceAccount, + ServiceAccountUID: "harness-atelet-sa", + PodName: podName, + PodUID: podUID, + NodeName: nodeName, + NodeUID: "harness-node-" + nodeName, + }, template); err != nil { + return tls.Certificate{}, err + } + return p.issue(template) +} diff --git a/cmd/ateapi/internal/functionaltest/harness/volumes.go b/cmd/ateapi/internal/functionaltest/harness/volumes.go new file mode 100644 index 0000000000..98a1cac0bb --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/volumes.go @@ -0,0 +1,214 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "cmp" + "context" + "slices" + "sync" + + "github.com/container-storage-interface/spec/lib/go/csi" + "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness/grpcfake" +) + +// VolumeMethod is the gRPC full name of a CSI Controller RPC ate-api calls on +// the volume plugin, which a fault can be injected into. +type VolumeMethod string + +const ( + VolumeCreate = VolumeMethod(csi.Controller_CreateVolume_FullMethodName) + VolumeDelete = VolumeMethod(csi.Controller_DeleteVolume_FullMethodName) + VolumePublish = VolumeMethod(csi.Controller_ControllerPublishVolume_FullMethodName) + VolumeUnpublish = VolumeMethod(csi.Controller_ControllerUnpublishVolume_FullMethodName) +) + +// Volume is a volume the fake plugin holds. +type Volume struct { + ID string + Name string + // AttachedTo lists the nodes the volume is published to, sorted. + AttachedTo []string +} + +// Volumes is a stateful fake of a CSI driver's Identity and Controller +// services, which ate-api finds through a CSIDriverConfig. +type Volumes struct { + driver string + storageClass string + + fake *grpcfake.Service[VolumeMethod] + + mu sync.Mutex + volumesByID map[string]*Volume +} + +// volumeServer serves Volumes to ate-api as a CSI driver. +type volumeServer struct { + csi.UnimplementedIdentityServer + csi.UnimplementedControllerServer + volumes *Volumes +} + +func newVolumes(driver, storageClass string) *Volumes { + return &Volumes{ + driver: driver, + storageClass: storageClass, + fake: grpcfake.NewService(VolumeCreate, VolumeDelete, VolumePublish, VolumeUnpublish), + volumesByID: map[string]*Volume{}, + } +} + +// Driver returns the CSI driver name the fake serves. +func (v *Volumes) Driver() string { return v.driver } + +// StorageClass returns the name of the StorageClass the fake provisions. +func (v *Volumes) StorageClass() string { return v.storageClass } + +// On returns the Fault deciding how calls to method behave. +func (v *Volumes) On(method VolumeMethod) *grpcfake.Fault { + return v.fake.On(method) +} + +// grpcServer returns a gRPC server of the CSI driver v serves to ate-api, +// which applies v's faults and records its calls. Tests hold only the +// Volumes, so they reach the driver only through ate-api. +func (v *Volumes) grpcServer() *grpc.Server { + srv := v.fake.NewServer() + csi.RegisterIdentityServer(srv, &volumeServer{volumes: v}) + csi.RegisterControllerServer(srv, &volumeServer{volumes: v}) + return srv +} + +// RecordCalls starts recording the Controller calls ate-api makes to v from +// now on. The Identity and capability calls ate-api makes when it connects +// are neither faulted nor recorded. +func (v *Volumes) RecordCalls() *grpcfake.Recording[VolumeMethod] { + return v.fake.Record() +} + +// List returns every volume that exists, sorted by ID. +func (v *Volumes) List() []Volume { + v.mu.Lock() + defer v.mu.Unlock() + out := make([]Volume, 0, len(v.volumesByID)) + for _, vol := range v.volumesByID { + out = append(out, Volume{ID: vol.ID, Name: vol.Name, AttachedTo: slices.Clone(vol.AttachedTo)}) + } + slices.SortFunc(out, func(a, b Volume) int { return cmp.Compare(a.ID, b.ID) }) + return out +} + +// GetPluginInfo implements csi.IdentityServer. +func (s *volumeServer) GetPluginInfo(context.Context, *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) { + return &csi.GetPluginInfoResponse{Name: s.volumes.driver, VendorVersion: "1"}, nil +} + +// ControllerGetCapabilities implements csi.ControllerServer. The fake creates, +// deletes, publishes and unpublishes volumes. +func (s *volumeServer) ControllerGetCapabilities(context.Context, *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) { + var caps []*csi.ControllerServiceCapability + for _, rpc := range []csi.ControllerServiceCapability_RPC_Type{ + csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME, + csi.ControllerServiceCapability_RPC_PUBLISH_UNPUBLISH_VOLUME, + } { + caps = append(caps, &csi.ControllerServiceCapability{ + Type: &csi.ControllerServiceCapability_Rpc{Rpc: &csi.ControllerServiceCapability_RPC{Type: rpc}}, + }) + } + return &csi.ControllerGetCapabilitiesResponse{Capabilities: caps}, nil +} + +// CreateVolume implements csi.ControllerServer. Creating a volume that exists +// returns it again, as CreateVolume is idempotent by name. +func (s *volumeServer) CreateVolume(_ context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) { + v := s.volumes + id := "vol-" + req.GetName() + v.mu.Lock() + if _, ok := v.volumesByID[id]; !ok { + v.volumesByID[id] = &Volume{ID: id, Name: req.GetName()} + } + v.mu.Unlock() + return &csi.CreateVolumeResponse{Volume: &csi.Volume{ + VolumeId: id, + CapacityBytes: req.GetCapacityRange().GetRequiredBytes(), + VolumeContext: req.GetParameters(), + }}, nil +} + +// DeleteVolume implements csi.ControllerServer. Deleting a missing volume +// succeeds; deleting a published one fails, as a real driver refuses. +func (s *volumeServer) DeleteVolume(_ context.Context, req *csi.DeleteVolumeRequest) (*csi.DeleteVolumeResponse, error) { + v := s.volumes + v.mu.Lock() + defer v.mu.Unlock() + if vol, ok := v.volumesByID[req.GetVolumeId()]; ok { + if len(vol.AttachedTo) > 0 { + return nil, status.Errorf(codes.FailedPrecondition, "volume %s is still published to %v", req.GetVolumeId(), vol.AttachedTo) + } + delete(v.volumesByID, req.GetVolumeId()) + } + return &csi.DeleteVolumeResponse{}, nil +} + +// ControllerPublishVolume implements csi.ControllerServer. Its publish context +// names the node, as a driver's device path is specific to it. Publishing is +// idempotent. Publishing a SINGLE_NODE_WRITER volume to a second node fails, +// as a real driver refuses. +func (s *volumeServer) ControllerPublishVolume(_ context.Context, req *csi.ControllerPublishVolumeRequest) (*csi.ControllerPublishVolumeResponse, error) { + v := s.volumes + v.mu.Lock() + defer v.mu.Unlock() + vol, ok := v.volumesByID[req.GetVolumeId()] + if !ok { + return nil, status.Errorf(codes.NotFound, "volume %s not found", req.GetVolumeId()) + } + if err := checkSingleNodeWriter(vol, req); err != nil { + return nil, err + } + if !slices.Contains(vol.AttachedTo, req.GetNodeId()) { + vol.AttachedTo = append(vol.AttachedTo, req.GetNodeId()) + slices.Sort(vol.AttachedTo) + } + return &csi.ControllerPublishVolumeResponse{PublishContext: map[string]string{"node": req.GetNodeId()}}, nil +} + +// checkSingleNodeWriter returns FailedPrecondition if req publishes a +// SINGLE_NODE_WRITER volume that is already published to another node. +func checkSingleNodeWriter(vol *Volume, req *csi.ControllerPublishVolumeRequest) error { + if req.GetVolumeCapability().GetAccessMode().GetMode() != csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER { + return nil + } + if slices.ContainsFunc(vol.AttachedTo, func(n string) bool { return n != req.GetNodeId() }) { + return status.Errorf(codes.FailedPrecondition, "volume %s is already published to %v", req.GetVolumeId(), vol.AttachedTo) + } + return nil +} + +// ControllerUnpublishVolume implements csi.ControllerServer. Unpublishing a +// volume that is not published, or does not exist, succeeds. +func (s *volumeServer) ControllerUnpublishVolume(_ context.Context, req *csi.ControllerUnpublishVolumeRequest) (*csi.ControllerUnpublishVolumeResponse, error) { + v := s.volumes + v.mu.Lock() + defer v.mu.Unlock() + if vol, ok := v.volumesByID[req.GetVolumeId()]; ok { + vol.AttachedTo = slices.DeleteFunc(vol.AttachedTo, func(n string) bool { return n == req.GetNodeId() }) + } + return &csi.ControllerUnpublishVolumeResponse{}, nil +} diff --git a/cmd/ateapi/internal/functionaltest/harness/volumes_test.go b/cmd/ateapi/internal/functionaltest/harness/volumes_test.go new file mode 100644 index 0000000000..fbf1467e32 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/harness/volumes_test.go @@ -0,0 +1,251 @@ +// Copyright 2026 The Agent Substrate 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 harness + +import ( + "testing" + + "github.com/container-storage-interface/spec/lib/go/csi" + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness/grpcfake" +) + +func TestVolumes(t *testing.T) { + const driver = "volumes.example.com" + // fresh returns new Volumes and a client of its CSI Controller service. + fresh := func(t *testing.T) (*Volumes, csi.ControllerClient) { + t.Helper() + v := newVolumes(driver, "volumes") + return v, csi.NewControllerClient(dialInMemory(t, serveInMemory(t, v.grpcServer()))) + } + createRequest := func(name string) *csi.CreateVolumeRequest { + return &csi.CreateVolumeRequest{Name: name, CapacityRange: &csi.CapacityRange{RequiredBytes: 1 << 30}} + } + create := func(t *testing.T, c csi.ControllerClient, name string) string { + t.Helper() + resp, err := c.CreateVolume(t.Context(), createRequest(name)) + if err != nil { + t.Fatalf("CreateVolume(%s): %v", name, err) + } + return resp.GetVolume().GetVolumeId() + } + publish := func(t *testing.T, c csi.ControllerClient, id, node string) (*csi.ControllerPublishVolumeResponse, error) { + t.Helper() + return c.ControllerPublishVolume(t.Context(), &csi.ControllerPublishVolumeRequest{VolumeId: id, NodeId: node}) + } + unpublish := func(t *testing.T, c csi.ControllerClient, id, node string) error { + t.Helper() + _, err := c.ControllerUnpublishVolume(t.Context(), &csi.ControllerUnpublishVolumeRequest{VolumeId: id, NodeId: node}) + return err + } + deleteVolume := func(t *testing.T, c csi.ControllerClient, id string) error { + t.Helper() + _, err := c.DeleteVolume(t.Context(), &csi.DeleteVolumeRequest{VolumeId: id}) + return err + } + assertVolumes := func(t *testing.T, v *Volumes, want []Volume) { + t.Helper() + if diff := cmp.Diff(want, v.List(), cmpopts.EquateEmpty()); diff != "" { + t.Errorf("volumes (-want +got):\n%s", diff) + } + } + + t.Run("create, publish, unpublish and delete", func(t *testing.T) { + v, c := fresh(t) + id := create(t, c, "vol") + assertVolumes(t, v, []Volume{{ID: id, Name: "vol"}}) + attached, err := publish(t, c, id, "node-a") + if err != nil { + t.Fatalf("ControllerPublishVolume: %v", err) + } + if diff := cmp.Diff(map[string]string{"node": "node-a"}, attached.GetPublishContext()); diff != "" { + t.Errorf("ControllerPublishVolume publish context (-want +got):\n%s", diff) + } + assertVolumes(t, v, []Volume{{ID: id, Name: "vol", AttachedTo: []string{"node-a"}}}) + if err := unpublish(t, c, id, "node-a"); err != nil { + t.Fatalf("ControllerUnpublishVolume: %v", err) + } + assertVolumes(t, v, []Volume{{ID: id, Name: "vol"}}) + if err := deleteVolume(t, c, id); err != nil { + t.Fatalf("DeleteVolume: %v", err) + } + assertVolumes(t, v, nil) + }) + + t.Run("records every call after RecordCalls, faulted or not", func(t *testing.T) { + v, c := fresh(t) + id := create(t, c, "vol") + rec := v.RecordCalls() + v.On(VolumePublish).FailNext(ErrUnavailable) + if _, err := publish(t, c, id, "node-a"); err == nil { + t.Fatal("faulted ControllerPublishVolume succeeded") + } + if err := unpublish(t, c, id, "node-a"); err != nil { + t.Fatalf("ControllerUnpublishVolume: %v", err) + } + if err := deleteVolume(t, c, id); err != nil { + t.Fatalf("DeleteVolume: %v", err) + } + want := []grpcfake.Call[VolumeMethod]{ + {Method: VolumePublish, Request: &csi.ControllerPublishVolumeRequest{VolumeId: id, NodeId: "node-a"}}, + {Method: VolumeUnpublish, Request: &csi.ControllerUnpublishVolumeRequest{VolumeId: id, NodeId: "node-a"}}, + {Method: VolumeDelete, Request: &csi.DeleteVolumeRequest{VolumeId: id}}, + } + if diff := cmp.Diff(want, rec.Calls(), protocmp.Transform()); diff != "" { + t.Errorf("recorded calls (-want +got):\n%s", diff) + } + }) + + t.Run("deleting a published volume fails and keeps it", func(t *testing.T) { + v, c := fresh(t) + id := create(t, c, "vol") + if _, err := publish(t, c, id, "node-a"); err != nil { + t.Fatalf("ControllerPublishVolume: %v", err) + } + if err := deleteVolume(t, c, id); status.Code(err) != codes.FailedPrecondition { + t.Errorf("DeleteVolume of a published volume = %v, want FailedPrecondition", err) + } + assertVolumes(t, v, []Volume{{ID: id, Name: "vol", AttachedTo: []string{"node-a"}}}) + }) + + t.Run("creating a volume twice returns the same volume", func(t *testing.T) { + v, c := fresh(t) + first := create(t, c, "vol") + if second := create(t, c, "vol"); second != first { + t.Errorf("second CreateVolume = %q, want the first's %q", second, first) + } + assertVolumes(t, v, []Volume{{ID: first, Name: "vol"}}) + }) + + t.Run("deleting a missing volume succeeds", func(t *testing.T) { + _, c := fresh(t) + if err := deleteVolume(t, c, "vol-missing"); err != nil { + t.Errorf("DeleteVolume of a missing volume = %v, want no error", err) + } + }) + + t.Run("publishing twice publishes once", func(t *testing.T) { + v, c := fresh(t) + id := create(t, c, "vol") + for range 2 { + if _, err := publish(t, c, id, "node-a"); err != nil { + t.Fatalf("ControllerPublishVolume: %v", err) + } + } + assertVolumes(t, v, []Volume{{ID: id, Name: "vol", AttachedTo: []string{"node-a"}}}) + }) + + t.Run("publishing a SINGLE_NODE_WRITER volume to a second node fails and keeps the first", func(t *testing.T) { + v, c := fresh(t) + id := create(t, c, "vol") + publishTo := func(node string) error { + _, err := c.ControllerPublishVolume(t.Context(), &csi.ControllerPublishVolumeRequest{ + VolumeId: id, + NodeId: node, + VolumeCapability: &csi.VolumeCapability{ + AccessMode: &csi.VolumeCapability_AccessMode{Mode: csi.VolumeCapability_AccessMode_SINGLE_NODE_WRITER}, + }, + }) + return err + } + for range 2 { + if err := publishTo("node-a"); err != nil { + t.Fatalf("ControllerPublishVolume to node-a: %v", err) + } + } + if err := publishTo("node-b"); status.Code(err) != codes.FailedPrecondition { + t.Errorf("ControllerPublishVolume to node-b = %v, want FailedPrecondition", err) + } + assertVolumes(t, v, []Volume{{ID: id, Name: "vol", AttachedTo: []string{"node-a"}}}) + }) + + t.Run("publishing a missing volume fails with NotFound", func(t *testing.T) { + v, c := fresh(t) + if _, err := publish(t, c, "vol-missing", "node-a"); status.Code(err) != codes.NotFound { + t.Errorf("ControllerPublishVolume of a missing volume = %v, want NotFound", err) + } + assertVolumes(t, v, nil) + }) + + t.Run("unpublishing a volume that is not published or does not exist succeeds", func(t *testing.T) { + v, c := fresh(t) + id := create(t, c, "vol") + if err := unpublish(t, c, id, "node-a"); err != nil { + t.Errorf("ControllerUnpublishVolume of a volume that is not published = %v, want no error", err) + } + if err := unpublish(t, c, "vol-missing", "node-a"); err != nil { + t.Errorf("ControllerUnpublishVolume of a missing volume = %v, want no error", err) + } + assertVolumes(t, v, []Volume{{ID: id, Name: "vol"}}) + }) + + t.Run("List sorts volumes by ID and their nodes by name", func(t *testing.T) { + v, c := fresh(t) + b := create(t, c, "b") + a := create(t, c, "a") + for _, node := range []string{"node-b", "node-a"} { + if _, err := publish(t, c, b, node); err != nil { + t.Fatalf("ControllerPublishVolume: %v", err) + } + } + assertVolumes(t, v, []Volume{ + {ID: a, Name: "a"}, + {ID: b, Name: "b", AttachedTo: []string{"node-a", "node-b"}}, + }) + }) + + t.Run("a call failed by a fault leaves no effect", func(t *testing.T) { + v, c := fresh(t) + v.On(VolumeCreate).FailNext(ErrUnavailable) + if _, err := c.CreateVolume(t.Context(), createRequest("vol")); status.Code(err) != codes.Unavailable { + t.Fatalf("CreateVolume = %v, want ErrUnavailable", err) + } + assertVolumes(t, v, nil) + id := create(t, c, "vol") + assertVolumes(t, v, []Volume{{ID: id, Name: "vol"}}) + }) + + t.Run("a blocked call takes effect only once released", func(t *testing.T) { + v, c := fresh(t) + id := create(t, c, "vol") + gate := v.On(VolumePublish).Block() + done := make(chan error) + go func() { + _, err := publish(t, c, id, "node-a") + done <- err + }() + gate.Wait(t) + assertVolumes(t, v, []Volume{{ID: id, Name: "vol"}}) + gate.Release() + if err := <-done; err != nil { + t.Fatalf("ControllerPublishVolume: %v", err) + } + assertVolumes(t, v, []Volume{{ID: id, Name: "vol", AttachedTo: []string{"node-a"}}}) + }) + + t.Run("serves its driver name", func(t *testing.T) { + v := newVolumes(driver, "volumes") + identity := csi.NewIdentityClient(dialInMemory(t, serveInMemory(t, v.grpcServer()))) + resp, err := identity.GetPluginInfo(t.Context(), &csi.GetPluginInfoRequest{}) + if err != nil || resp.GetName() != driver { + t.Errorf("GetPluginInfo = %v, %v; want name %q", resp, err, driver) + } + }) +} diff --git a/cmd/ateapi/internal/functionaltest/main_test.go b/cmd/ateapi/internal/functionaltest/main_test.go new file mode 100644 index 0000000000..5dcae4bec5 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/main_test.go @@ -0,0 +1,25 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "testing" + + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" +) + +func TestMain(m *testing.M) { + harness.Main(m) +} diff --git a/cmd/ateapi/internal/functionaltest/tags_test.go b/cmd/ateapi/internal/functionaltest/tags_test.go new file mode 100644 index 0000000000..0636339ea9 --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/tags_test.go @@ -0,0 +1,722 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "fmt" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" +) + +// Creates a tag from a suspended actor, sending output-only metadata and +// status, and verifies that the whole resource has the expected shape: +// ate-api ignores what was sent and assigns its own. Object storage holds a +// copy of the snapshot at the tag's URI, next to every object it held before. +func TestCreateTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + source := harness.ActorRef(h.SuspendedActor(as, tmpl)) + + in := &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + } + // The caller sends output-only fields, which ate-api ignores. + setOutputOnlyMetadata(in.Metadata) + in.Status = &ateapi.TagStatus{ActorTemplateUid: foreignUID} + objectsBefore := h.ObjectStore.Objects() + created, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: in}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + want := &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + Status: &ateapi.TagStatus{ + Snapshot: &ateapi.Snapshot{ + Generation: 1, + Owner: ateapi.SnapshotOwner_SNAPSHOT_OWNER_TAG, + Fidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + DurableSnapshot: &ateapi.SnapshotStorage{ + State: ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED, + Object: &ateapi.ObjectSnapshot{}, + }, + SandboxRuntime: harness.SandboxRuntime(), + }, + ActorTemplateUid: tmpl.GetMetadata().GetUid(), + }, + } + // The tag's snapshot is named by ate-api; it only has to hold the copy. + ignoreSnapshotName := cmp.Options{ + protocmp.IgnoreFields(&ateapi.Snapshot{}, "uuid"), + protocmp.IgnoreFields(&ateapi.ObjectSnapshot{}, "snapshot_uri"), + } + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata, ignoreSnapshotName); diff != "" { + t.Errorf("created tag (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) + uri := created.GetStatus().GetSnapshot().GetDurableSnapshot().GetObject().GetSnapshotUri() + wantObjects := append(objectsBefore, snapshotObjects(uri)...) + if diff := cmp.Diff(wantObjects, h.ObjectStore.Objects(), cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" { + t.Errorf("object storage after the tag (-want +got):\n%s", diff) + } +} + +// Creating a tag for an existing name fails with ALREADY_EXISTS and leaves +// the existing one unchanged. +func TestCreateTag_AlreadyExists(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + source := harness.ActorRef(h.SuspendedActor(as, h.NewTemplate(as, pool))) + tag := &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + } + created, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: tag}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + + _, err = h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: tag}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateTag of an existing name = %v, want AlreadyExists", err) + } + got, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: &ateapi.ObjectRef{Atespace: as, Name: "tag-a"}}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("tag after a refused create (-want +got):\n%s", diff) + } +} + +// Creating a tag with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestCreateTag_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "Not_A_Valid_Name"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}, + }}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateTag with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "tag.metadata.name: Invalid value") { + t.Errorf("CreateTag error %q does not start with %q", msg, "tag.metadata.name: Invalid value") + } +} + +// Creating a tag from a source actor that doesn't exist fails with +// FAILED_PRECONDITION, and no tag is created. +func TestCreateTag_SourceActorNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: &ateapi.ObjectRef{Atespace: as, Name: "actor-missing"}, + }}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("CreateTag from a missing source actor = %v, want FailedPrecondition", err) + } + listed, err := h.Control.ListTags(t.Context(), &ateapi.ListTagsRequest{Atespace: as}) + if err != nil { + t.Fatalf("ListTags: %v", err) + } + if diff := cmp.Diff(&ateapi.ListTagsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("tags after a refused create (-want +got):\n%s", diff) + } +} + +// Getting an existing tag returns exactly the resource CreateTag returned. +func TestGetTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + source := harness.ActorRef(h.SuspendedActor(as, h.NewTemplate(as, pool))) + created, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + + got, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: &ateapi.ObjectRef{Atespace: as, Name: "tag-a"}}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("GetTag (-created +got):\n%s", diff) + } +} + +// Getting a tag that doesn't exist fails with NOT_FOUND. +func TestGetTag_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: &ateapi.ObjectRef{Atespace: as, Name: "tag-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetTag of a missing tag = %v, want NotFound", err) + } +} + +// Getting a tag with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestGetTag_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("GetTag with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "tag.name: Invalid value") { + t.Errorf("GetTag error %q does not start with %q", msg, "tag.name: Invalid value") + } +} + +// Creates N tags in one atespace and one in another, then lists the first +// atespace with pages smaller than N. The pages together hold exactly its N +// tags. +func TestListTags(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + other := h.CreateAtespace("team-b") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + // The template's golden tag lives in the other atespace, so the listed + // one holds only the tags the test creates. + tmpl := h.NewTemplate(other, pool) + source := harness.ActorRef(h.SuspendedActor(as, tmpl)) + otherSource := harness.ActorRef(h.SuspendedActor(other, tmpl)) + const n, pageSize = 5, 2 + var created []*ateapi.Tag + for i := range n { + tag, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: fmt.Sprintf("tag-%d", i)}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + created = append(created, tag) + } + if _, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: other, Name: "tag-other"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: otherSource, + }}); err != nil { + t.Fatalf("CreateTag: %v", err) + } + + var listed []*ateapi.Tag + req := &ateapi.ListTagsRequest{Atespace: as, Options: &ateapi.ListOptions{PageSize: pageSize}} + for pages := 1; ; pages++ { + if pages > n { + t.Fatalf("listing took more than %d pages", n) + } + resp, err := h.Control.ListTags(t.Context(), req) + if err != nil { + t.Fatalf("ListTags page %d: %v", pages, err) + } + if got := len(resp.GetTags()); got > pageSize { + t.Errorf("page %d holds %d tags, want at most %d", pages, got, pageSize) + } + listed = append(listed, resp.GetTags()...) + if resp.GetNextPageToken() == "" { + break + } + req.Options.PageToken = resp.GetNextPageToken() + } + byName := cmpopts.SortSlices(func(a, b *ateapi.Tag) bool { return a.GetMetadata().GetName() < b.GetMetadata().GetName() }) + if diff := cmp.Diff(created, listed, protocmp.Transform(), byName); diff != "" { + t.Errorf("listed tags (-want +got):\n%s", diff) + } +} + +// Listing tags with a negative page size fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestListTags_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListTags(t.Context(), &ateapi.ListTagsRequest{Options: &ateapi.ListOptions{PageSize: -1}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListTags with a negative page size = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "options.page_size: Invalid value") { + t.Errorf("ListTags error %q does not start with %q", msg, "options.page_size: Invalid value") + } +} + +// Listing tags with a malformed page token fails with INVALID_ARGUMENT. +func TestListTags_InvalidPageToken(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListTags(t.Context(), &ateapi.ListTagsRequest{Options: &ateapi.ListOptions{PageToken: "not-a-real-token"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListTags with a malformed page token = %v, want InvalidArgument", err) + } +} + +// Listing tags in an atespace that doesn't exist succeeds with an empty +// list. +func TestListTags_AtespaceNotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + listed, err := h.Control.ListTags(t.Context(), &ateapi.ListTagsRequest{Atespace: "team-missing"}) + if err != nil { + t.Fatalf("ListTags in a missing atespace: %v", err) + } + if diff := cmp.Diff(&ateapi.ListTagsResponse{}, listed, protocmp.Transform()); diff != "" { + t.Errorf("ListTags in a missing atespace (-want +got):\n%s", diff) + } +} + +// Updates the scope of an existing tag, sending it as read with a changed +// status. The result, and a later Get, is the resource as read with the scope +// changed and a higher version: ate-api ignores the status. +func TestUpdateTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + source := harness.ActorRef(h.SuspendedActor(as, h.NewTemplate(as, pool))) + ref := &ateapi.ObjectRef{Atespace: as, Name: "tag-a"} + before, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + + toUpdate := mutated(before, func(tg *ateapi.Tag) { + tg.Scope = ateapi.TagScope_TAG_SCOPE_PUBLISHED + // The caller sends a changed status, which ate-api ignores. + tg.Status.ActorTemplateUid = foreignUID + }) + updated, err := h.Control.UpdateTag(t.Context(), &ateapi.UpdateTagRequest{Tag: toUpdate}) + if err != nil { + t.Fatalf("UpdateTag: %v", err) + } + want := mutated(before, func(tg *ateapi.Tag) { + tg.Scope = ateapi.TagScope_TAG_SCOPE_PUBLISHED + }) + if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("updated tag (-want +got):\n%s", diff) + } + if got, was := updated.GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("updated tag has version %d, want higher than %d", got, was) + } + got, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + if diff := cmp.Diff(updated, got, protocmp.Transform()); diff != "" { + t.Errorf("GetTag after update (-updated +got):\n%s", diff) + } +} + +// Updating a tag that doesn't exist fails with NOT_FOUND. +func TestUpdateTag_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.UpdateTag(t.Context(), &ateapi.UpdateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-missing", Uid: foreignUID, Version: 1}, + Scope: ateapi.TagScope_TAG_SCOPE_PUBLISHED, + SourceActor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}, + }}) + if status.Code(err) != codes.NotFound { + t.Errorf("UpdateTag of a missing tag = %v, want NotFound", err) + } +} + +// Updating a tag with the wrong UID fails with ABORTED, and with the right +// UID but the wrong version fails with ABORTED; both leave it unchanged. +// Updating it without a UID or a version fails with INVALID_ARGUMENT. +func TestUpdateTag_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + source := harness.ActorRef(h.SuspendedActor(as, h.NewTemplate(as, pool))) + ref := &ateapi.ObjectRef{Atespace: as, Name: "tag-a"} + before, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + update := func(uid string, version int64) error { + toUpdate := mutated(before, func(tg *ateapi.Tag) { + tg.Metadata.Uid, tg.Metadata.Version = uid, version + tg.Scope = ateapi.TagScope_TAG_SCOPE_PUBLISHED + }) + _, err := h.Control.UpdateTag(t.Context(), &ateapi.UpdateTagRequest{Tag: toUpdate}) + return err + } + + if err := update(foreignUID, before.GetMetadata().GetVersion()); status.Code(err) != codes.Aborted { + t.Errorf("UpdateTag with the wrong uid = %v, want Aborted", err) + } + if err := update(before.GetMetadata().GetUid(), before.GetMetadata().GetVersion()+1); status.Code(err) != codes.Aborted { + t.Errorf("UpdateTag with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + if diff := cmp.Diff(before, got, protocmp.Transform()); diff != "" { + t.Errorf("tag after refused updates (-want +got):\n%s", diff) + } + if err := update("", 0); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateTag without a uid or version = %v, want InvalidArgument", err) + } +} + +// Updating a tag with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestUpdateTag_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.UpdateTag(t.Context(), &ateapi.UpdateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "Not_A_Valid_Name", Uid: foreignUID, Version: 1}, + Scope: ateapi.TagScope_TAG_SCOPE_PUBLISHED, + SourceActor: &ateapi.ObjectRef{Atespace: as, Name: "actor-a"}, + }}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateTag with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "tag.metadata.name: Invalid value") { + t.Errorf("UpdateTag error %q does not start with %q", msg, "tag.metadata.name: Invalid value") + } +} + +// Deletes an existing tag. The response is the deleted resource, and a later +// Get fails with NOT_FOUND. Object storage no longer holds the tag's snapshot +// and still holds the source actor's. +func TestDeleteTag(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + source := harness.ActorRef(h.SuspendedActor(as, h.NewTemplate(as, pool))) + ref := &ateapi.ObjectRef{Atespace: as, Name: "tag-a"} + objectsBefore := h.ObjectStore.Objects() + created, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + + deleted, err := h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("DeleteTag: %v", err) + } + if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreDeleteTime); diff != "" { + t.Errorf("DeleteTag response (-created +deleted):\n%s", diff) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Error("DeleteTag response has no delete_time") + } + if _, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetTag after delete = %v, want NotFound", err) + } + if diff := cmp.Diff(objectsBefore, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after delete (-before tag +after delete):\n%s", diff) + } +} + +// Deleting the golden tag of a live template fails with FAILED_PRECONDITION +// and leaves the tag unchanged. +func TestDeleteTag_GoldenTagOfLiveTemplate(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + ref := h.NewTemplate(as, pool).GetStatus().GetGoldenSnapshotStatus().GetGoldenTag() + before, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + + if _, err := h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: ref}); status.Code(err) != codes.FailedPrecondition { + t.Errorf("DeleteTag of the golden tag = %v, want FailedPrecondition", err) + } + got, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag after a refused delete: %v", err) + } + if diff := cmp.Diff(before, got, protocmp.Transform()); diff != "" { + t.Errorf("tag after a refused delete (-want +got):\n%s", diff) + } +} + +// Deleting a tag that doesn't exist fails with NOT_FOUND. +func TestDeleteTag_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: &ateapi.ObjectRef{Atespace: as, Name: "tag-missing"}}) + if status.Code(err) != codes.NotFound { + t.Errorf("DeleteTag of a missing tag = %v, want NotFound", err) + } +} + +// Deleting a tag with the wrong UID, with only the wrong version, or with the +// right UID but the wrong version fails with ABORTED and leaves it unchanged. +// With the right UID and version the delete succeeds. +func TestDeleteTag_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + source := harness.ActorRef(h.SuspendedActor(as, h.NewTemplate(as, pool))) + ref := &ateapi.ObjectRef{Atespace: as, Name: "tag-a"} + created, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + uid, version := created.GetMetadata().GetUid(), created.GetMetadata().GetVersion() + + _, err = h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: ref, Options: &ateapi.DeleteOptions{Uid: foreignUID}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteTag with the wrong uid = %v, want Aborted", err) + } + _, err = h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: ref, Options: &ateapi.DeleteOptions{Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteTag with only the wrong version = %v, want Aborted", err) + } + _, err = h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteTag with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag after refused deletes: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("tag after refused deletes (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version}}); err != nil { + t.Errorf("DeleteTag with the right uid and version: %v", err) + } +} + +// Deleting a tag with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestDeleteTag_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + + _, err := h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: &ateapi.ObjectRef{Atespace: as, Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("DeleteTag with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "tag.name: Invalid value") { + t.Errorf("DeleteTag error %q does not start with %q", msg, "tag.name: Invalid value") + } +} + +// Creates a tag from an actor suspended asynchronously, whose latest snapshot +// is local to its node and not uploaded. The request succeeds (OK). The atelet +// received exactly one PromoteSnapshot and still holds the local snapshot. +// The source actor's snapshot is now uploaded and otherwise unchanged, and +// object storage holds both the actor's snapshot and the tag's copy. +func TestCreateTag_FromAsyncSuspendedActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + node := h.Node("a") + h.AddWorker(pool, node) + source := h.AsyncSuspendedActor(as, h.NewTemplate(as, pool)) + sourceRef := harness.ActorRef(source) + before := h.GetActor(sourceRef) + objectsBefore := h.ObjectStore.Objects() + rec := node.Atelet.RecordCalls() + + tag, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: sourceRef, + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + assertCalls(t, rec, harness.AteletPromoteSnapshot) + local := latestSnapshot(t, before) + if got := node.Atelet.LocalSnapshot(source.GetMetadata().GetUid()); got != local.GetUuid() { + t.Errorf("local snapshot on node a = %q, want %q", got, local.GetUuid()) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.Snapshots[len(a.Status.Snapshots)-1].DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED + }) + if diff := cmp.Diff(want, h.GetActor(sourceRef), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("source actor after the tag (-want +got):\n%s", diff) + } + var wantObjects []string + wantObjects = append(wantObjects, objectsBefore...) + for _, uri := range []string{local.GetDurableSnapshot().GetObject().GetSnapshotUri(), tag.GetStatus().GetSnapshot().GetDurableSnapshot().GetObject().GetSnapshotUri()} { + wantObjects = append(wantObjects, snapshotObjects(uri)...) + } + if diff := cmp.Diff(wantObjects, h.ObjectStore.Objects(), cmpopts.SortSlices(func(a, b string) bool { return a < b })); diff != "" { + t.Errorf("object storage after the tag (-want +got):\n%s", diff) + } +} + +// Creating a tag with the name of an existing tag, from a different source +// actor, fails with ALREADY_EXISTS. The existing tag and object storage are +// unchanged. +func TestCreateTag_AlreadyExistsFromAnotherActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + tmpl := h.NewTemplate(as, pool) + first := harness.ActorRef(h.SuspendedActor(as, tmpl)) + second := harness.ActorRef(h.SuspendedActor(as, tmpl)) + ref := &ateapi.ObjectRef{Atespace: as, Name: "tag-a"} + created, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: first, + }}) + if err != nil { + t.Fatalf("CreateTag: %v", err) + } + objectsBefore := h.ObjectStore.Objects() + + _, err = h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: second, + }}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateTag of an existing name from another actor = %v, want AlreadyExists", err) + } + got, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("tag after a refused create (-want +got):\n%s", diff) + } + if diff := cmp.Diff(objectsBefore, h.ObjectStore.Objects()); diff != "" { + t.Errorf("object storage after a refused create (-want +got):\n%s", diff) + } +} + +// Updating a tag whose delete failed partway, leaving it marked for deletion, +// fails with FAILED_PRECONDITION and leaves the tag unchanged. +func TestUpdateTag_Deleting(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + source := harness.ActorRef(h.SuspendedActor(as, h.NewTemplate(as, pool))) + ref := &ateapi.ObjectRef{Atespace: as, Name: "tag-a"} + if _, err := h.Control.CreateTag(t.Context(), &ateapi.CreateTagRequest{Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: as, Name: "tag-a"}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: source, + }}); err != nil { + t.Fatalf("CreateTag: %v", err) + } + h.ObjectStore.On(harness.ObjectStoreCleanupSnapshot).FailNext(harness.ErrStorageFailed) + if _, err := h.Control.DeleteTag(t.Context(), &ateapi.DeleteTagRequest{Tag: ref}); err == nil { + t.Fatal("DeleteTag succeeded despite failing object storage") + } + before, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag after a failed delete: %v", err) + } + + toUpdate := mutated(before, func(tg *ateapi.Tag) { + tg.Scope = ateapi.TagScope_TAG_SCOPE_PUBLISHED + }) + _, err = h.Control.UpdateTag(t.Context(), &ateapi.UpdateTagRequest{Tag: toUpdate}) + if status.Code(err) != codes.FailedPrecondition { + t.Errorf("UpdateTag of a deleting tag = %v, want FailedPrecondition", err) + } + got, err := h.Control.GetTag(t.Context(), &ateapi.GetTagRequest{Tag: ref}) + if err != nil { + t.Fatalf("GetTag: %v", err) + } + if diff := cmp.Diff(before, got, protocmp.Transform()); diff != "" { + t.Errorf("tag after a refused update (-want +got):\n%s", diff) + } +} diff --git a/cmd/ateapi/internal/functionaltest/workers_test.go b/cmd/ateapi/internal/functionaltest/workers_test.go new file mode 100644 index 0000000000..6d12a16c3e --- /dev/null +++ b/cmd/ateapi/internal/functionaltest/workers_test.go @@ -0,0 +1,713 @@ +// Copyright 2026 The Agent Substrate 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 functionaltest + +import ( + "fmt" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/testing/protocmp" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/functionaltest/harness" +) + +// workerSpec is a valid Worker named after the pod UID uid. +func workerSpec(uid string) *ateapi.Worker { + return &ateapi.Worker{ + Metadata: &ateapi.ResourceMetadata{Name: uid}, + WorkerNamespace: "workers", + WorkerPool: "pool1", + WorkerPod: "worker-" + uid[:8], + WorkerPodUid: uid, + NodeName: "node-a", + } +} + +const workerUID = "5f2c1a90-7b34-4e6d-8a11-0c3e9d5b7f42" + +// Creates a worker, sending output-only metadata and status, and verifies that +// the whole resource has the expected shape: ate-api ignores what was sent and +// assigns its own. +func TestCreateWorker(t *testing.T) { + t.Parallel() + h := harness.New(t) + + in := workerSpec(workerUID) + // The caller sends output-only fields, which ate-api ignores. + setOutputOnlyMetadata(in.Metadata) + in.Status = &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_ACTIVE} + created, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: in}) + if err != nil { + t.Fatalf("CreateWorker: %v", err) + } + want := &ateapi.Worker{ + Metadata: &ateapi.ResourceMetadata{Name: workerUID}, + WorkerNamespace: "workers", + WorkerPool: "pool1", + WorkerPod: "worker-5f2c1a90", + WorkerPodUid: workerUID, + NodeName: "node-a", + Status: &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_UNAVAILABLE}, + } + if diff := cmp.Diff(want, created, protocmp.Transform(), ignoreCreatedMetadata); diff != "" { + t.Errorf("created worker (-want +got):\n%s", diff) + } + assertAssignedMetadata(t, created.GetMetadata()) +} + +// Creating a worker for an existing name fails with ALREADY_EXISTS and +// leaves the existing one unchanged. +func TestCreateWorker_AlreadyExists(t *testing.T) { + t.Parallel() + h := harness.New(t) + created, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(workerUID)}) + if err != nil { + t.Fatalf("CreateWorker: %v", err) + } + + _, err = h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(workerUID)}) + if status.Code(err) != codes.AlreadyExists { + t.Errorf("CreateWorker of an existing name = %v, want AlreadyExists", err) + } + got, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: &ateapi.ObjectRef{Name: workerUID}}) + if err != nil { + t.Fatalf("GetWorker: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("worker after a refused create (-want +got):\n%s", diff) + } +} + +// Creating a worker with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestCreateWorker_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + worker := workerSpec(workerUID) + worker.Metadata.Name = "Not_A_Valid_Name" + + _, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: worker}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("CreateWorker with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "worker.metadata.name: Invalid value") { + t.Errorf("CreateWorker error %q does not start with %q", msg, "worker.metadata.name: Invalid value") + } +} + +// Getting an existing worker returns exactly the resource CreateWorker +// returned. +func TestGetWorker(t *testing.T) { + t.Parallel() + h := harness.New(t) + created, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(workerUID)}) + if err != nil { + t.Fatalf("CreateWorker: %v", err) + } + + got, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: &ateapi.ObjectRef{Name: workerUID}}) + if err != nil { + t.Fatalf("GetWorker: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("GetWorker (-created +got):\n%s", diff) + } +} + +// Getting a worker that doesn't exist fails with NOT_FOUND. +func TestGetWorker_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: &ateapi.ObjectRef{Name: workerUID}}) + if status.Code(err) != codes.NotFound { + t.Errorf("GetWorker of a missing worker = %v, want NotFound", err) + } +} + +// Getting a worker with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestGetWorker_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("GetWorker with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "worker.name: Invalid value") { + t.Errorf("GetWorker error %q does not start with %q", msg, "worker.name: Invalid value") + } +} + +// Creates N workers and lists them with pages smaller than N. The pages +// together hold exactly the N workers. +func TestListWorkers(t *testing.T) { + t.Parallel() + h := harness.New(t) + const n, pageSize = 5, 2 + var created []*ateapi.Worker + for i := range n { + worker, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(fmt.Sprintf("5f2c1a90-7b34-4e6d-8a11-0c3e9d5b7f4%d", i))}) + if err != nil { + t.Fatalf("CreateWorker: %v", err) + } + created = append(created, worker) + } + + var listed []*ateapi.Worker + req := &ateapi.ListWorkersRequest{Options: &ateapi.ListOptions{PageSize: pageSize}} + for pages := 1; ; pages++ { + if pages > n { + t.Fatalf("listing took more than %d pages", n) + } + resp, err := h.Control.ListWorkers(t.Context(), req) + if err != nil { + t.Fatalf("ListWorkers page %d: %v", pages, err) + } + if got := len(resp.GetWorkers()); got > pageSize { + t.Errorf("page %d holds %d workers, want at most %d", pages, got, pageSize) + } + listed = append(listed, resp.GetWorkers()...) + if resp.GetNextPageToken() == "" { + break + } + req.Options.PageToken = resp.GetNextPageToken() + } + byName := cmpopts.SortSlices(func(a, b *ateapi.Worker) bool { return a.GetMetadata().GetName() < b.GetMetadata().GetName() }) + if diff := cmp.Diff(created, listed, protocmp.Transform(), byName); diff != "" { + t.Errorf("listed workers (-want +got):\n%s", diff) + } +} + +// Listing workers with a negative page size fails with INVALID_ARGUMENT and +// the error names the invalid field. +func TestListWorkers_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListWorkers(t.Context(), &ateapi.ListWorkersRequest{Options: &ateapi.ListOptions{PageSize: -1}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListWorkers with a negative page size = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "options.page_size: Invalid value") { + t.Errorf("ListWorkers error %q does not start with %q", msg, "options.page_size: Invalid value") + } +} + +// Listing workers with a malformed page token fails with INVALID_ARGUMENT. +func TestListWorkers_InvalidPageToken(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListWorkers(t.Context(), &ateapi.ListWorkersRequest{Options: &ateapi.ListOptions{PageToken: "not-a-real-token"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListWorkers with a malformed page token = %v, want InvalidArgument", err) + } +} + +// Updates the labels of an existing worker, sending it as read with a changed +// status. The result, and a later Get, is the resource as read with the labels +// changed and a higher version: ate-api ignores the status. +func TestUpdateWorker(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: workerUID} + before, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(workerUID)}) + if err != nil { + t.Fatalf("CreateWorker: %v", err) + } + + toUpdate := mutated(before, func(wk *ateapi.Worker) { + wk.Labels = map[string]string{"tier": "1"} + // The caller sends a changed status, which ate-api ignores. + wk.Status.State = ateapi.WorkerState_WORKER_STATE_ACTIVE + }) + updated, err := h.Control.UpdateWorker(t.Context(), &ateapi.UpdateWorkerRequest{Worker: toUpdate}) + if err != nil { + t.Fatalf("UpdateWorker: %v", err) + } + want := mutated(before, func(wk *ateapi.Worker) { + wk.Labels = map[string]string{"tier": "1"} + }) + if diff := cmp.Diff(want, updated, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("updated worker (-want +got):\n%s", diff) + } + if got, was := updated.GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("updated worker has version %d, want higher than %d", got, was) + } + got, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: ref}) + if err != nil { + t.Fatalf("GetWorker: %v", err) + } + if diff := cmp.Diff(updated, got, protocmp.Transform()); diff != "" { + t.Errorf("GetWorker after update (-updated +got):\n%s", diff) + } +} + +// Updating a worker that doesn't exist fails with NOT_FOUND. +func TestUpdateWorker_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + worker := workerSpec(workerUID) + worker.Metadata.Uid, worker.Metadata.Version = foreignUID, 1 + + _, err := h.Control.UpdateWorker(t.Context(), &ateapi.UpdateWorkerRequest{Worker: worker}) + if status.Code(err) != codes.NotFound { + t.Errorf("UpdateWorker of a missing worker = %v, want NotFound", err) + } +} + +// Updating a worker with the wrong UID fails with ABORTED, and with the +// right UID but the wrong version fails with ABORTED; both leave it +// unchanged. Updating it without a UID or a version fails with +// INVALID_ARGUMENT. +func TestUpdateWorker_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: workerUID} + before, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(workerUID)}) + if err != nil { + t.Fatalf("CreateWorker: %v", err) + } + update := func(uid string, version int64) error { + toUpdate := mutated(before, func(wk *ateapi.Worker) { + wk.Metadata.Uid, wk.Metadata.Version = uid, version + wk.Labels = map[string]string{"tier": "1"} + }) + _, err := h.Control.UpdateWorker(t.Context(), &ateapi.UpdateWorkerRequest{Worker: toUpdate}) + return err + } + + if err := update(foreignUID, before.GetMetadata().GetVersion()); status.Code(err) != codes.Aborted { + t.Errorf("UpdateWorker with the wrong uid = %v, want Aborted", err) + } + if err := update(before.GetMetadata().GetUid(), before.GetMetadata().GetVersion()+1); status.Code(err) != codes.Aborted { + t.Errorf("UpdateWorker with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: ref}) + if err != nil { + t.Fatalf("GetWorker: %v", err) + } + if diff := cmp.Diff(before, got, protocmp.Transform()); diff != "" { + t.Errorf("worker after refused updates (-want +got):\n%s", diff) + } + if err := update("", 0); status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateWorker without a uid or version = %v, want InvalidArgument", err) + } +} + +// Updating a worker with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestUpdateWorker_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + worker := workerSpec(workerUID) + worker.Metadata.Name = "Not_A_Valid_Name" + worker.Metadata.Uid, worker.Metadata.Version = foreignUID, 1 + + _, err := h.Control.UpdateWorker(t.Context(), &ateapi.UpdateWorkerRequest{Worker: worker}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateWorker with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "worker.metadata.name: Invalid value") { + t.Errorf("UpdateWorker error %q does not start with %q", msg, "worker.metadata.name: Invalid value") + } +} + +// Updating a worker's node name, sending it as read with only that field +// changed, fails with INVALID_ARGUMENT and leaves the worker unchanged. +func TestUpdateWorker_ImmutableField(t *testing.T) { + t.Parallel() + h := harness.New(t) + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), h.Node("a")) + before := h.GetWorker(w) + + toUpdate := mutated(before, func(wk *ateapi.Worker) { + wk.NodeName = "another-node" + }) + _, err := h.Control.UpdateWorker(t.Context(), &ateapi.UpdateWorkerRequest{Worker: toUpdate}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("UpdateWorker changing the node name = %v, want InvalidArgument", err) + } + if diff := cmp.Diff(before, h.GetWorker(w), protocmp.Transform()); diff != "" { + t.Errorf("worker after a refused update (-want +got):\n%s", diff) + } +} + +// Deletes an existing worker. The response is the worker as read before the +// delete, marked DRAINING, and a later Get fails with NOT_FOUND. +func TestDeleteWorker(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: workerUID} + created, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(workerUID)}) + if err != nil { + t.Fatalf("CreateWorker: %v", err) + } + + deleted, err := h.Control.DeleteWorker(t.Context(), &ateapi.DeleteWorkerRequest{Worker: ref}) + if err != nil { + t.Fatalf("DeleteWorker: %v", err) + } + want := mutated(created, func(wk *ateapi.Worker) { + wk.Status.State = ateapi.WorkerState_WORKER_STATE_DRAINING + }) + if diff := cmp.Diff(want, deleted, protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreDeleteTime); diff != "" { + t.Errorf("DeleteWorker response (-want +got):\n%s", diff) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Error("DeleteWorker response has no delete_time") + } + if _, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: ref}); status.Code(err) != codes.NotFound { + t.Errorf("GetWorker after delete = %v, want NotFound", err) + } +} + +// Deleting a worker that doesn't exist fails with NOT_FOUND. +func TestDeleteWorker_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.DeleteWorker(t.Context(), &ateapi.DeleteWorkerRequest{Worker: &ateapi.ObjectRef{Name: workerUID}}) + if status.Code(err) != codes.NotFound { + t.Errorf("DeleteWorker of a missing worker = %v, want NotFound", err) + } +} + +// Deleting a worker with the wrong UID, with only the wrong version, or with +// the right UID but the wrong version fails with ABORTED and leaves it +// unchanged. With the right UID and version the delete succeeds. +func TestDeleteWorker_WithPreconditions(t *testing.T) { + t.Parallel() + h := harness.New(t) + ref := &ateapi.ObjectRef{Name: workerUID} + created, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(workerUID)}) + if err != nil { + t.Fatalf("CreateWorker: %v", err) + } + uid, version := created.GetMetadata().GetUid(), created.GetMetadata().GetVersion() + + _, err = h.Control.DeleteWorker(t.Context(), &ateapi.DeleteWorkerRequest{Worker: ref, Options: &ateapi.DeleteOptions{Uid: foreignUID}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteWorker with the wrong uid = %v, want Aborted", err) + } + _, err = h.Control.DeleteWorker(t.Context(), &ateapi.DeleteWorkerRequest{Worker: ref, Options: &ateapi.DeleteOptions{Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteWorker with only the wrong version = %v, want Aborted", err) + } + _, err = h.Control.DeleteWorker(t.Context(), &ateapi.DeleteWorkerRequest{Worker: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version + 1}}) + if status.Code(err) != codes.Aborted { + t.Errorf("DeleteWorker with the right uid and the wrong version = %v, want Aborted", err) + } + got, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: ref}) + if err != nil { + t.Fatalf("GetWorker after refused deletes: %v", err) + } + if diff := cmp.Diff(created, got, protocmp.Transform()); diff != "" { + t.Errorf("worker after refused deletes (-want +got):\n%s", diff) + } + + if _, err := h.Control.DeleteWorker(t.Context(), &ateapi.DeleteWorkerRequest{Worker: ref, Options: &ateapi.DeleteOptions{Uid: uid, Version: version}}); err != nil { + t.Errorf("DeleteWorker with the right uid and version: %v", err) + } +} + +// Deleting a worker with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestDeleteWorker_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.DeleteWorker(t.Context(), &ateapi.DeleteWorkerRequest{Worker: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("DeleteWorker with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "worker.name: Invalid value") { + t.Errorf("DeleteWorker error %q does not start with %q", msg, "worker.name: Invalid value") + } +} + +// Deleting a worker that hosts a running actor succeeds (OK), and a later +// Get of the worker fails with NOT_FOUND. The node's atelet receives one +// Terminate and holds no sandbox. The actor becomes CRASHED, with no worker +// assignment and a crash message saying the worker pod went away while +// hosting the actor. +func TestDeleteWorker_HostingActor(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + h.AddWorker(pool, h.Node("a")) + actor := h.RunningActor(as, h.NewTemplate(as, pool)) + ref := harness.ActorRef(actor) + host := h.WorkerOf(actor) + before := h.GetActor(ref) + + rec := host.Node.Atelet.RecordCalls() + if _, err := h.Control.DeleteWorker(t.Context(), &ateapi.DeleteWorkerRequest{Worker: host.Ref()}); err != nil { + t.Fatalf("DeleteWorker: %v", err) + } + if _, err := h.Control.GetWorker(t.Context(), &ateapi.GetWorkerRequest{Worker: host.Ref()}); status.Code(err) != codes.NotFound { + t.Errorf("GetWorker after delete = %v, want NotFound", err) + } + assertCalls(t, rec, harness.AteletTerminate) + if diff := cmp.Diff([]harness.Sandbox{}, host.Node.Atelet.Sandboxes()); diff != "" { + t.Errorf("sandboxes after the worker was deleted (-want +got):\n%s", diff) + } + want := mutated(before, func(a *ateapi.Actor) { + a.Status.State = ateapi.ActorState_ACTOR_STATE_CRASHED + a.Status.WorkerAssignment = nil + a.Status.Crash = &ateapi.ActorCrash{Message: "worker pod went away while hosting the actor"} + }) + ignoreCrashTime := protocmp.IgnoreFields(&ateapi.ActorCrash{}, "crash_time") + if diff := cmp.Diff(want, h.GetActor(ref), protocmp.Transform(), ignoreVersion, ignoreUpdateTime, ignoreCrashTime); diff != "" { + t.Errorf("actor after its worker was deleted (-want +got):\n%s", diff) + } +} + +// Draining an active worker marks it DRAINING. The result, and a later Get, +// is the worker as read with that state and a higher version. +func TestDrainWorker(t *testing.T) { + t.Parallel() + h := harness.New(t) + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), h.Node("a")) + before := h.GetWorker(w) + + resp, err := h.Control.DrainWorker(t.Context(), &ateapi.DrainWorkerRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("DrainWorker: %v", err) + } + drained := resp.GetWorker() + want := mutated(before, func(wk *ateapi.Worker) { + wk.Status.State = ateapi.WorkerState_WORKER_STATE_DRAINING + }) + if diff := cmp.Diff(want, drained, protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("drained worker (-want +got):\n%s", diff) + } + if got, was := drained.GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("drained worker has version %d, want higher than %d", got, was) + } + if diff := cmp.Diff(drained, h.GetWorker(w), protocmp.Transform()); diff != "" { + t.Errorf("GetWorker after drain (-drained +got):\n%s", diff) + } +} + +// Draining a worker that doesn't exist fails with NOT_FOUND. +func TestDrainWorker_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.DrainWorker(t.Context(), &ateapi.DrainWorkerRequest{Worker: &ateapi.ObjectRef{Name: workerUID}}) + if status.Code(err) != codes.NotFound { + t.Errorf("DrainWorker of a missing worker = %v, want NotFound", err) + } +} + +// Draining a worker with an invalid name fails with INVALID_ARGUMENT and the +// error names the invalid field. +func TestDrainWorker_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.DrainWorker(t.Context(), &ateapi.DrainWorkerRequest{Worker: &ateapi.ObjectRef{Name: "Not_A_Valid_Name"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("DrainWorker with an invalid name = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "worker.name: Invalid value") { + t.Errorf("DrainWorker error %q does not start with %q", msg, "worker.name: Invalid value") + } +} + +// Draining a worker that is already DRAINING succeeds (OK). The response, +// and a later Get, is the worker exactly as it was, its version included. +func TestDrainWorker_AlreadyDraining(t *testing.T) { + t.Parallel() + h := harness.New(t) + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), h.Node("a")) + w.Drain() + before := h.GetWorker(w) + + resp, err := h.Control.DrainWorker(t.Context(), &ateapi.DrainWorkerRequest{Worker: w.Ref()}) + if status.Code(err) != codes.OK { + t.Fatalf("DrainWorker of a draining worker = %v, want OK", err) + } + if diff := cmp.Diff(before, resp.GetWorker(), protocmp.Transform()); diff != "" { + t.Errorf("DrainWorker response (-want +got):\n%s", diff) + } + if diff := cmp.Diff(before, h.GetWorker(w), protocmp.Transform()); diff != "" { + t.Errorf("worker after draining it again (-want +got):\n%s", diff) + } +} + +// Lists the assignments of a worker hosting N running actors with pages +// smaller than N. The pages together hold exactly one assignment per actor. +func TestListWorkerActorAssignments(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + const n, pageSize = 3, 2 + w := h.AddWorker(pool, h.Node("a"), harness.WithActorCapacity(n)) + tmpl := h.NewTemplate(as, pool) + var want []*ateapi.ActorAssignment + for range n { + actor := h.RunningActor(as, tmpl) + want = append(want, &ateapi.ActorAssignment{ + Metadata: &ateapi.ResourceMetadata{Name: actor.GetMetadata().GetUid()}, + Actor: harness.ActorRef(actor), + ActorUid: actor.GetMetadata().GetUid(), + Resources: templateResources(), + }) + } + + var listed []*ateapi.ActorAssignment + req := &ateapi.ListWorkerActorAssignmentsRequest{Worker: w.Ref(), Options: &ateapi.ListOptions{PageSize: pageSize}} + for pages := 1; ; pages++ { + if pages > n { + t.Fatalf("listing took more than %d pages", n) + } + resp, err := h.Control.ListWorkerActorAssignments(t.Context(), req) + if err != nil { + t.Fatalf("ListWorkerActorAssignments page %d: %v", pages, err) + } + if got := len(resp.GetActorAssignments()); got > pageSize { + t.Errorf("page %d holds %d assignments, want at most %d", pages, got, pageSize) + } + listed = append(listed, resp.GetActorAssignments()...) + if resp.GetNextPageToken() == "" { + break + } + req.Options.PageToken = resp.GetNextPageToken() + } + byActor := cmpopts.SortSlices(func(a, b *ateapi.ActorAssignment) bool { return a.GetActorUid() < b.GetActorUid() }) + if diff := cmp.Diff(want, listed, protocmp.Transform(), ignoreCreatedMetadata, byActor); diff != "" { + t.Errorf("listed assignments (-want +got):\n%s", diff) + } +} + +// Listing the assignments of a worker that doesn't exist fails with +// NOT_FOUND. +func TestListWorkerActorAssignments_NotFound(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: &ateapi.ObjectRef{Name: workerUID}}) + if status.Code(err) != codes.NotFound { + t.Errorf("ListWorkerActorAssignments of a missing worker = %v, want NotFound", err) + } +} + +// Listing the assignments of a worker with a negative page size fails with +// INVALID_ARGUMENT and the error names the invalid field. +func TestListWorkerActorAssignments_ValidationError(t *testing.T) { + t.Parallel() + h := harness.New(t) + + _, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: &ateapi.ObjectRef{Name: workerUID}, Options: &ateapi.ListOptions{PageSize: -1}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListWorkerActorAssignments with a negative page size = %v, want InvalidArgument", err) + } + if msg := status.Convert(err).Message(); !strings.HasPrefix(msg, "options.page_size: Invalid value") { + t.Errorf("ListWorkerActorAssignments error %q does not start with %q", msg, "options.page_size: Invalid value") + } +} + +// Listing the assignments of a worker with a malformed page token fails with +// INVALID_ARGUMENT. +func TestListWorkerActorAssignments_InvalidPageToken(t *testing.T) { + t.Parallel() + h := harness.New(t) + if _, err := h.Control.CreateWorker(t.Context(), &ateapi.CreateWorkerRequest{Worker: workerSpec(workerUID)}); err != nil { + t.Fatalf("CreateWorker: %v", err) + } + + _, err := h.Control.ListWorkerActorAssignments(t.Context(), &ateapi.ListWorkerActorAssignmentsRequest{Worker: &ateapi.ObjectRef{Name: workerUID}, Options: &ateapi.ListOptions{PageToken: "not-a-real-token"}}) + if status.Code(err) != codes.InvalidArgument { + t.Errorf("ListWorkerActorAssignments with a malformed page token = %v, want InvalidArgument", err) + } +} + +// Marks an active worker unavailable. The response, and a later Get, is the +// worker as read with state UNAVAILABLE and a higher version. +func TestMarkWorkerUnavailable(t *testing.T) { + t.Parallel() + h := harness.New(t) + w := h.AddWorker(h.CreateWorkerPool("pool1", nil), h.Node("a")) + before := h.GetWorker(w) + + resp, err := h.Control.MarkWorkerUnavailable(t.Context(), &ateapi.MarkWorkerUnavailableRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("MarkWorkerUnavailable: %v", err) + } + want := mutated(before, func(wk *ateapi.Worker) { + wk.Status.State = ateapi.WorkerState_WORKER_STATE_UNAVAILABLE + }) + if diff := cmp.Diff(want, resp.GetWorker(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker marked unavailable (-want +got):\n%s", diff) + } + if got, was := resp.GetWorker().GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("worker marked unavailable has version %d, want higher than %d", got, was) + } + if diff := cmp.Diff(resp.GetWorker(), h.GetWorker(w), protocmp.Transform()); diff != "" { + t.Errorf("GetWorker after the mark (-marked +got):\n%s", diff) + } +} + +// Marks an unavailable worker available again. The response, and a later Get, +// is the worker as read with state ACTIVE and a higher version. Resuming an +// actor then succeeds (OK) on that worker, retrying while ate-api catches up. +func TestMarkWorkerAvailable(t *testing.T) { + t.Parallel() + h := harness.New(t) + as := h.CreateAtespace("team-a") + pool := h.CreateWorkerPool("pool1", nil) + w := h.AddWorker(pool, h.Node("a")) + actor := h.NewActor(as, h.NewTemplate(as, pool)) + if _, err := h.Control.MarkWorkerUnavailable(t.Context(), &ateapi.MarkWorkerUnavailableRequest{Worker: w.Ref()}); err != nil { + t.Fatalf("MarkWorkerUnavailable: %v", err) + } + before := h.GetWorker(w) + + resp, err := h.Control.MarkWorkerAvailable(t.Context(), &ateapi.MarkWorkerAvailableRequest{Worker: w.Ref()}) + if err != nil { + t.Fatalf("MarkWorkerAvailable: %v", err) + } + want := mutated(before, func(wk *ateapi.Worker) { + wk.Status.State = ateapi.WorkerState_WORKER_STATE_ACTIVE + }) + if diff := cmp.Diff(want, resp.GetWorker(), protocmp.Transform(), ignoreVersion, ignoreUpdateTime); diff != "" { + t.Errorf("worker marked available (-want +got):\n%s", diff) + } + if got, was := resp.GetWorker().GetMetadata().GetVersion(), before.GetMetadata().GetVersion(); got <= was { + t.Errorf("worker marked available has version %d, want higher than %d", got, was) + } + if diff := cmp.Diff(resp.GetWorker(), h.GetWorker(w), protocmp.Transform()); diff != "" { + t.Errorf("GetWorker after the mark (-marked +got):\n%s", diff) + } + placed, err := h.ResumeActorWithRetries(t.Context(), &ateapi.ResumeActorRequest{Actor: harness.ActorRef(actor)}) + if err != nil { + t.Fatalf("ResumeActor: %v", err) + } + if got := placed.GetActor().GetStatus().GetWorkerAssignment().GetWorker().GetName(); got != w.Name { + t.Errorf("actor runs on worker %q, want %q", got, w.Name) + } +} diff --git a/cmd/ateapi/internal/scheduling/scheduling.go b/cmd/ateapi/internal/scheduling/scheduling.go index 20d5659768..0a3997ab09 100644 --- a/cmd/ateapi/internal/scheduling/scheduling.go +++ b/cmd/ateapi/internal/scheduling/scheduling.go @@ -35,23 +35,23 @@ type Constraints struct { // SandboxClass, when set, is the sandbox class of the snapshot the actor // restores from, and the worker's must equal it. A snapshot's files, its // durable volumes included, are written by one class's worker and read - // back by the same, so unlike RequiredRuntime this holds for every - // fidelity and is never relaxed. Empty for an actor with no snapshot, - // which boots on whichever class its selectors pick. + // back by the same, so this holds for every fidelity and is never + // relaxed. Empty for an actor with no snapshot, which boots on whichever + // class its selectors pick. SandboxClass string - // RequiredRuntime, when it names a runtime, restricts placement to - // workers whose DefaultRuntime or RestorableRuntimes can restore a - // snapshot stamped with it. Prepared once per Schedule, since Applies - // asks it of every candidate. - RequiredRuntime hardware.Requirement - // SnapshotRuntime is the runtime of the snapshot the actor restores from, // or the zero Requirement when it starts on a worker's default runtime. - // Unlike RequiredRuntime it is never relaxed: it picks the worker runtime - // the actor runs under, and so the overhead it is booked with. + // Prepared once per Schedule, since BestRuntime asks it of every + // candidate. It picks the worker runtime the actor runs under, and so the + // overhead it is booked with. SnapshotRuntime hardware.Requirement + // MinFidelity is the lowest SnapshotFidelity a worker may restore + // SnapshotRuntime at to be eligible. Defaults to SNAPSHOT_FIDELITY_MEMORY + // when unset. + MinFidelity ateapi.SnapshotFidelity + // TemplateSelector and ActorSelector must both match the worker's labels. TemplateSelector labels.Selector ActorSelector labels.Selector @@ -66,19 +66,50 @@ type Constraints struct { Limits *ateapi.Resources } +// effectiveMinFidelity returns MinFidelity, or SNAPSHOT_FIDELITY_MEMORY when +// MinFidelity is unset. +func (c Constraints) effectiveMinFidelity() ateapi.SnapshotFidelity { + if c.MinFidelity == ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_UNSPECIFIED { + return ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY + } + return c.MinFidelity +} + // ErrNoCapacity is returned by Schedule when no worker that meets the // constraints has room. The cause can be full workers, or no worker that meets // the constraints at all. var ErrNoCapacity = errors.New("no worker that meets the constraints has room") +// ErrDoesNotFit wraps ErrNoCapacity. Schedule returns it when no worker has room +// and the actor exceeds the whole capacity of every worker that meets the +// constraints. See doesNotFit for which workers count. +var ErrDoesNotFit = fmt.Errorf("%w: the actor exceeds the capacity of every such worker", ErrNoCapacity) + +// Placement is a worker Schedule picked, the fidelity it picked it at, and +// what the actor books there. +type Placement struct { + Worker *ateapi.Worker + // Fidelity is the highest SnapshotFidelity Worker satisfies SnapshotRuntime + // at, or SNAPSHOT_FIDELITY_MEMORY when SnapshotRuntime is the zero + // Requirement (it measures runtime compatibility, not the snapshot's own + // fidelity). + Fidelity ateapi.SnapshotFidelity + // Booking is the actor's limits plus the overhead of the runtime it runs + // under on Worker. + Booking *ateapi.Resources +} + // Scheduler answers placement questions against the current worker fleet. type Scheduler interface { - // Schedule returns a worker that meets constraints and has room. - // Returns ErrNoCapacity when no worker that meets constraints has room. - Schedule(ctx context.Context, constraints Constraints) (*ateapi.Worker, error) - - // Applies reports whether worker satisfies non-capacity constraints. Capacity - // is excluded so an existing assignment does not make its Worker ineligible. + // Schedule returns a Placement on a worker that meets constraints and has + // room. Returns ErrNoCapacity when no worker that meets constraints has + // room, or ErrDoesNotFit when the actor exceeds the capacity of each of + // them. + Schedule(ctx context.Context, constraints Constraints) (Placement, error) + + // Applies reports whether worker is ACTIVE and satisfies non-capacity + // constraints. Capacity is excluded so an existing assignment does not make + // its Worker ineligible. Applies(worker *ateapi.Worker, constraints Constraints) bool // HasRoom reports whether worker's remaining capacity admits one more actor @@ -116,46 +147,102 @@ func New(source WorkerSource, opts ...Option) Scheduler { return s } -// Schedule filters the fleet for eligible candidates with room, samples two at -// random (power of two choices), and returns the less-loaded one, where load is -// the higher of actor-slot and compute-resource utilization. Spreading across -// the warm pool avoids hotspots until autoscaling reclaims idle workers. -func (s *scheduler) Schedule(ctx context.Context, constraints Constraints) (*ateapi.Worker, error) { +// Schedule filters the fleet in a single pass for the highest-fidelity +// candidates with room, samples two at random (power of two choices), and +// returns the less-loaded one, where load is the higher of actor-slot and +// compute-resource utilization. Spreading across the warm pool avoids hotspots +// until autoscaling reclaims idle workers. +func (s *scheduler) Schedule(ctx context.Context, constraints Constraints) (Placement, error) { workers, err := s.source.Workers() if err != nil { - return nil, fmt.Errorf("while listing workers: %w", err) + return Placement{}, fmt.Errorf("while listing workers: %w", err) } - var candidates []candidate + minFidelity := constraints.effectiveMinFidelity() + var ( + bestFidelity ateapi.SnapshotFidelity + candidates []candidate + ) for _, worker := range workers { - if !s.Applies(worker, constraints) { + if !matchesStatic(worker, constraints) { continue } - booking, ok := Booking(worker, constraints) + rt, fidelity := constraints.SnapshotRuntime.BestRuntime(worker.GetStatus()) + if fidelity < minFidelity || fidelity < bestFidelity { + continue + } + booking, ok := bookingFor(constraints.Limits, rt.GetActorOverhead()) if !ok { continue } - if cand, ok := checkRoom(worker, booking); ok { - candidates = append(candidates, cand) + cand, ok := checkRoom(worker, booking) + if !ok { + continue + } + if fidelity > bestFidelity { + bestFidelity = fidelity + candidates = candidates[:0] } + candidates = append(candidates, cand) } if len(candidates) == 0 { - return nil, ErrNoCapacity + if doesNotFit(workers, constraints) { + return Placement{}, ErrDoesNotFit + } + return Placement{}, ErrNoCapacity } + var picked *ateapi.Worker if len(candidates) == 1 { - return candidates[0].worker, nil + picked = candidates[0].worker + } else { + i := s.intn(len(candidates)) + j := s.intn(len(candidates) - 1) + if j >= i { + j++ + } + picked = candidates[i].worker + if lessLoaded(&candidates[j], &candidates[i]) { + picked = candidates[j].worker + } } + // Computing Booking once on the picked worker avoids storing it on every + // candidate in the loop. + booking, _ := Booking(picked, constraints) + return Placement{Worker: picked, Fidelity: bestFidelity, Booking: booking}, nil +} - i := s.intn(len(candidates)) - j := s.intn(len(candidates) - 1) - if j >= i { - j++ - } - if lessLoaded(&candidates[j], &candidates[i]) { - return candidates[j].worker, nil +// doesNotFit reports whether at least one registered worker meets constraints, +// and the actor exceeds the whole capacity of each of them, including UNAVAILABLE +// workers. +// +// TODO(#198): check WorkerPool sizes too. +func doesNotFit(workers []*ateapi.Worker, constraints Constraints) bool { + minFidelity := constraints.effectiveMinFidelity() + eligible := false + for _, worker := range workers { + // A DRAINING worker never takes actors again, so its size is + // irrelevant. + if worker.GetStatus().GetState() == ateapi.WorkerState_WORKER_STATE_DRAINING { + continue + } + // Skip a worker that is unregistered or fails the other constraints. + // Its state is ignored, so an UNAVAILABLE worker still counts. + if !matchesStaticAnyState(worker, constraints) { + continue + } + rt, fidelity := constraints.SnapshotRuntime.BestRuntime(worker.GetStatus()) + if fidelity < minFidelity { + continue + } + eligible = true + // The worker meets the constraints. If the actor fits its whole + // capacity, it may fit once the worker frees room or becomes ACTIVE. + if booking, ok := bookingFor(constraints.Limits, rt.GetActorOverhead()); ok && fitsEmpty(worker, booking) { + return false + } } - return candidates[i].worker, nil + return eligible } // candidate pairs an eligible worker with its cached compute utilization. @@ -232,7 +319,9 @@ func Registered(worker *ateapi.Worker) bool { return worker.GetStatus().GetRegisteredEpoch() != 0 && hardware.SandboxClass(worker.GetStatus()) != "" } -func (s *scheduler) Applies(worker *ateapi.Worker, constraints Constraints) bool { +// matchesStaticAnyState reports whether a registered worker satisfies the +// non-runtime, non-capacity constraints in any state. +func matchesStaticAnyState(worker *ateapi.Worker, constraints Constraints) bool { if !Registered(worker) { return false } @@ -240,19 +329,9 @@ func (s *scheduler) Applies(worker *ateapi.Worker, constraints Constraints) bool if constraints.SandboxClass != "" && workerClass != constraints.SandboxClass { return false } - - if worker.GetStatus().GetState() != ateapi.WorkerState_WORKER_STATE_ACTIVE { - return false - } - if len(constraints.RequiredNodes) > 0 && !slices.Contains(constraints.RequiredNodes, worker.GetNodeName()) { return false } - - if !constraints.RequiredRuntime.WorkerMatches(worker.GetStatus()) { - return false - } - set := labels.Set(worker.GetLabels()) if constraints.TemplateSelector != nil && !constraints.TemplateSelector.Matches(set) { return false @@ -260,6 +339,19 @@ func (s *scheduler) Applies(worker *ateapi.Worker, constraints Constraints) bool return constraints.ActorSelector == nil || constraints.ActorSelector.Matches(set) } +func matchesStatic(worker *ateapi.Worker, constraints Constraints) bool { + return worker.GetStatus().GetState() == ateapi.WorkerState_WORKER_STATE_ACTIVE && + matchesStaticAnyState(worker, constraints) +} + +func (s *scheduler) Applies(worker *ateapi.Worker, constraints Constraints) bool { + if !matchesStatic(worker, constraints) { + return false + } + _, fidelity := constraints.SnapshotRuntime.BestRuntime(worker.GetStatus()) + return fidelity >= constraints.effectiveMinFidelity() +} + // HasRoom reports whether what the worker has left admits one more actor of // this size. A dimension the worker does not report is unconstrained, so // placement is never blocked by missing data. @@ -277,10 +369,14 @@ func (s *scheduler) HasRoom(worker *ateapi.Worker, constraints Constraints) bool // false when that doesn't fit in an int64, and the actor doesn't fit on the worker. func Booking(worker *ateapi.Worker, constraints Constraints) (*ateapi.Resources, bool) { overhead := constraints.SnapshotRuntime.WorkerRuntimeFor(worker.GetStatus()).GetActorOverhead() + return bookingFor(constraints.Limits, overhead) +} + +func bookingFor(limits *ateapi.Resources, overhead *ateapi.RuntimeOverhead) (*ateapi.Resources, bool) { if overhead == nil { - return constraints.Limits, true + return limits, true } - limit := constraints.Limits.GetMemoryBytes() + limit := limits.GetMemoryBytes() scaled, ok := perGiB(limit, overhead.GetMemoryBytesPerGib()) if !ok { return nil, false @@ -289,7 +385,7 @@ func Booking(worker *ateapi.Worker, constraints Constraints) (*ateapi.Resources, if !ok { return nil, false } - return &ateapi.Resources{CpuMillicores: constraints.Limits.GetCpuMillicores(), MemoryBytes: memory}, true + return &ateapi.Resources{CpuMillicores: limits.GetCpuMillicores(), MemoryBytes: memory}, true } // perGiB scales rate bytes per GiB to n bytes, and reports false on overflow. @@ -318,6 +414,12 @@ func sum(vs ...int64) (int64, bool) { return total, true } +// fitsEmpty reports whether want fits the worker's whole capacity. It ignores +// the actor count, which limits how many actors fit and not how large one is. +func fitsEmpty(worker *ateapi.Worker, want *ateapi.Resources) bool { + return resources.Covers(resources.Free(worker.GetStatus().GetCapacity(), nil), want) +} + func checkRoom(worker *ateapi.Worker, want *ateapi.Resources) (candidate, bool) { capacity := worker.GetStatus().GetCapacity() used := worker.GetStatus().GetAllocated() diff --git a/cmd/ateapi/internal/scheduling/scheduling_bench_test.go b/cmd/ateapi/internal/scheduling/scheduling_bench_test.go new file mode 100644 index 0000000000..c55d446e28 --- /dev/null +++ b/cmd/ateapi/internal/scheduling/scheduling_bench_test.go @@ -0,0 +1,275 @@ +// Copyright 2026 The Agent Substrate 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 scheduling + +import ( + "context" + "fmt" + "testing" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/hardware" + "k8s.io/apimachinery/pkg/labels" + "k8s.io/utils/ptr" +) + +// The benchmark fleets are shaped like a production gVisor pool: every worker +// is registered and ACTIVE, reports the three attributes atelet writes for +// gVisor, carries a runtime overhead, and already hosts some actors, so the +// room check and lessLoaded do real work. Fleets are built from the worker +// index alone, so every run and every branch sees the same input. +const ( + benchGiB = int64(1) << 30 + benchMaxActors = int32(8) + benchWorkersPerNode = 4 + // benchCPUFeatures is a 64-digit mask, close to the width a current amd64 + // host reports, so parsing it costs what it costs in production. + benchCPUFeatures = "f7ffbfffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" +) + +var benchFleetSizes = []int{100, 1000, 10000} + +func benchCompat(bundleHash string) *ateapi.VersionedSandboxCompat { + return &ateapi.VersionedSandboxCompat{ + SchemaVersion: hardware.SchemaVersionV1, + Attributes: []*ateapi.AttributeEntry{ + {Key: hardware.AttrArchitecture, Value: "amd64"}, + {Key: hardware.AttrCPUFeatures, Value: benchCPUFeatures}, + {Key: hardware.AttrSandboxBundleHash, Value: bundleHash}, + }, + } +} + +func benchWorkerRuntime(bundleHash string) *ateapi.WorkerSandboxRuntime { + return &ateapi.WorkerSandboxRuntime{ + Version: benchCompat(bundleHash), + ActorOverhead: &ateapi.RuntimeOverhead{MemoryBytes: 64 << 20, MemoryBytesPerGib: 8 << 20}, + } +} + +func benchStamp(bundleHash string) *ateapi.ActorSandboxRuntime { + return &ateapi.ActorSandboxRuntime{SandboxClass: "gvisor", Version: benchCompat(bundleHash)} +} + +func benchNode(i int) string { return fmt.Sprintf("node-%d", i/benchWorkersPerNode) } + +// benchPinnedNode is the middle node a pinned scenario resumes on. +func benchPinnedNode(n int) string { return benchNode(n / 2) } + +type benchFleetOpts struct { + // oldEvery > 0 gives every oldEvery-th worker the "old" runtime as a + // RestorableRuntime; oldFull fills those workers to capacity. + oldEvery int + oldFull bool + // oldOnNode gives the workers of that node the "old" runtime. + oldOnNode string + // restorable lists extra restorable runtime bundle hashes carried by + // every worker ahead of "old", modeling a multi-version rollout. + restorable []string +} + +func benchFleet(n int, o benchFleetOpts) fleet { + newRT := benchWorkerRuntime("new") + oldRT := benchWorkerRuntime("old") + var extraRTs []*ateapi.WorkerSandboxRuntime + for _, h := range o.restorable { + extraRTs = append(extraRTs, benchWorkerRuntime(h)) + } + withOld := append(append([]*ateapi.WorkerSandboxRuntime(nil), extraRTs...), oldRT) + f := make(fleet, 0, n) + for i := range n { + node := benchNode(i) + class := &ateapi.WorkerSandboxClass{ + SandboxClass: "gvisor", + DefaultRuntime: newRT, + RestorableRuntimes: extraRTs, + } + used := int32(1 + i%6) + if (o.oldEvery > 0 && i%o.oldEvery == 0) || (o.oldOnNode != "" && node == o.oldOnNode) { + class.RestorableRuntimes = withOld + if o.oldFull { + used = benchMaxActors + } + } + f = append(f, &ateapi.Worker{ + Metadata: &ateapi.ResourceMetadata{Name: fmt.Sprintf("uid-%d", i)}, + WorkerPod: fmt.Sprintf("w-%d", i), + NodeName: node, + Labels: map[string]string{"workload": "sandbox", "pool": "p0"}, + Status: &ateapi.WorkerStatus{ + State: ateapi.WorkerState_WORKER_STATE_ACTIVE, + RegisteredEpoch: 1, + SandboxClasses: []*ateapi.WorkerSandboxClass{class}, + Capacity: &ateapi.WorkerResources{Actors: benchMaxActors, CpuMillicores: 4000, MemoryBytes: 16 * benchGiB}, + Allocated: &ateapi.WorkerResources{Actors: used, CpuMillicores: int64(used) * 500, MemoryBytes: int64(used) * benchGiB}, + }, + }) + } + return f +} + +type benchScenario struct { + name string + fleet func(n int) fleet + // snapshot is the bundle hash of the snapshot's runtime, "" for a cold + // boot. relaxable is what canRelaxRuntime reports for the actor. + snapshot string + relaxable bool + pinned bool + // wantOld reports whether the chosen worker must (true) or must not + // (false) carry the "old" runtime; nil accepts either. + wantOld *bool +} + +var benchScenarios = []benchScenario{ + { + name: "cold-boot", + fleet: func(n int) fleet { return benchFleet(n, benchFleetOpts{}) }, + }, + { + // Every worker's DefaultRuntime restores the snapshot. + name: "memory-hit", + fleet: func(n int) fleet { return benchFleet(n, benchFleetOpts{}) }, + snapshot: "new", + relaxable: true, + }, + { + // The workers that could restore the snapshot's memory are full, so + // placement falls back to a cold boot on a worker of the class. + name: "memory-fallback", + fleet: func(n int) fleet { return benchFleet(n, benchFleetOpts{oldEvery: 20, oldFull: true}) }, + snapshot: "old", + relaxable: true, + wantOld: ptr.To(false), + }, + { + // A tenth of the fleet still restores the snapshot's memory and has + // room, so placement stays at MEMORY. + name: "memory-mixed", + fleet: func(n int) fleet { return benchFleet(n, benchFleetOpts{oldEvery: 10}) }, + snapshot: "old", + relaxable: true, + wantOld: ptr.To(true), + }, + { + // Multi-version rollout: every worker carries two non-matching + // restorable runtimes, and a tenth also carry "old" last in the list. + name: "memory-rollout", + fleet: func(n int) fleet { + return benchFleet(n, benchFleetOpts{oldEvery: 10, restorable: []string{"prev-1", "prev-2"}}) + }, + snapshot: "old", + relaxable: true, + wantOld: ptr.To(true), + }, + { + // A pinned actor resumes on the node that holds its local snapshot. + // Pinned actors detach before relaxing, so the runtime is required. + name: "pinned", + fleet: func(n int) fleet { return benchFleet(n, benchFleetOpts{oldOnNode: benchPinnedNode(n)}) }, + snapshot: "old", + relaxable: false, + pinned: true, + wantOld: ptr.To(true), + }, +} + +// scheduleResume is how assignWorkerAttempt asks for a placement: a single +// Schedule, which falls back to ROOTFS only when MinFidelity allows it. +func scheduleResume(ctx context.Context, s Scheduler, c Constraints) (*ateapi.Worker, error) { + p, err := s.Schedule(ctx, c) + return p.Worker, err +} + +// benchConstraints is what schedulingConstraints would build for the +// scenario: the template's selector, the actor's empty selector, its limits, +// and for a resume the snapshot's class and runtime, with MinFidelity ROOTFS +// when the actor may fall back. +func benchConstraints(sc benchScenario, n int) Constraints { + c := Constraints{ + TemplateSelector: labels.SelectorFromSet(labels.Set{"workload": "sandbox"}), + ActorSelector: labels.SelectorFromSet(nil), + Limits: &ateapi.Resources{CpuMillicores: 500, MemoryBytes: benchGiB}, + } + if sc.snapshot != "" { + c.SandboxClass = "gvisor" + c.SnapshotRuntime = hardware.NewRequirement(benchStamp(sc.snapshot)) + if sc.relaxable { + c.MinFidelity = ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS + } + } + if sc.pinned { + c.RequiredNodes = []string{benchPinnedNode(n)} + } + return c +} + +func carriesOld(w *ateapi.Worker) bool { + for _, c := range w.GetStatus().GetSandboxClasses() { + for _, rt := range c.GetRestorableRuntimes() { + for _, a := range rt.GetVersion().GetAttributes() { + if a.GetKey() == hardware.AttrSandboxBundleHash && a.GetValue() == "old" { + return true + } + } + } + } + return false +} + +// TestBenchScenarios pins what each benchmark scenario measures: placement +// succeeds, and lands on the kind of worker the scenario is about. +func TestBenchScenarios(t *testing.T) { + const n = 100 + for _, sc := range benchScenarios { + t.Run(sc.name, func(t *testing.T) { + s := New(sc.fleet(n)) + c := benchConstraints(sc, n) + for range 20 { + got, err := scheduleResume(context.Background(), s, c) + if err != nil { + t.Fatalf("scheduleResume() error = %v", err) + } + if sc.wantOld != nil && carriesOld(got) != *sc.wantOld { + t.Fatalf("scheduleResume() = %s carrying old runtime %v, want %v", got.GetWorkerPod(), carriesOld(got), *sc.wantOld) + } + if sc.pinned && got.GetNodeName() != benchPinnedNode(n) { + t.Fatalf("scheduleResume() = %s on %s, want node %s", got.GetWorkerPod(), got.GetNodeName(), benchPinnedNode(n)) + } + } + }) + } +} + +// BenchmarkSchedule times one placement per scenario and fleet size, the way +// assignWorkerAttempt asks for it (see scheduleResume). The fleet is a plain +// slice, so the workercache copy is not included; BenchmarkWorkers in +// workercache measures that on its own. +func BenchmarkSchedule(b *testing.B) { + for _, n := range benchFleetSizes { + for _, sc := range benchScenarios { + s := New(sc.fleet(n)) + c := benchConstraints(sc, n) + b.Run(fmt.Sprintf("%s/n=%d", sc.name, n), func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + if _, err := scheduleResume(context.Background(), s, c); err != nil { + b.Fatal(err) + } + } + }) + } + } +} diff --git a/cmd/ateapi/internal/scheduling/scheduling_test.go b/cmd/ateapi/internal/scheduling/scheduling_test.go index e3cba527f9..9cdc6a5246 100644 --- a/cmd/ateapi/internal/scheduling/scheduling_test.go +++ b/cmd/ateapi/internal/scheduling/scheduling_test.go @@ -36,6 +36,11 @@ func TestSchedule(t *testing.T) { fleet fleet constraints Constraints wantPod string // "" means ErrNoCapacity expected + // wantFidelity is the fidelity Schedule picks wantPod at. Defaults to + // SNAPSHOT_FIDELITY_MEMORY when unset. + wantFidelity ateapi.SnapshotFidelity + // wantDoesNotFit, with no wantPod, expects ErrDoesNotFit. + wantDoesNotFit bool }{ { // Two full workers precede w-free so pair sampling cannot reach w-free @@ -150,12 +155,69 @@ func TestSchedule(t *testing.T) { wantPod: "w-big", }, { - name: "no worker with enough capacity yields ErrNoCapacity", + name: "an actor larger than every worker yields ErrDoesNotFit", fleet: fleet{ worker("w-small", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30)), }, + constraints: Constraints{Limits: resources.CPUMemory(2000, 0)}, + wantDoesNotFit: true, + }, + { + name: "a full worker the actor would fit when empty yields ErrNoCapacity", + fleet: fleet{ + worker("w-small", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30)), + worker("w-full", "gvisor", "node-a", tierTwo, withMaxActors(2), withCapacity(4000, 4<<30), + assignedFor("demo", "other", resources.CPUMemory(3000, 0))), + }, + constraints: Constraints{Limits: resources.CPUMemory(2000, 0)}, + }, + { + name: "a large worker that takes no actors yields ErrNoCapacity", + fleet: fleet{ + worker("w-none", "gvisor", "node-a", tierTwo, withMaxActors(0), withCapacity(4000, 4<<30)), + }, + constraints: Constraints{Limits: resources.CPUMemory(2000, 0)}, + }, + { + name: "a large worker the selectors exclude does not fit the actor", + fleet: fleet{ + worker("w-small", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30)), + worker("w-big", "gvisor", "node-a", tierOne, withCapacity(4000, 4<<30)), + }, + constraints: Constraints{ + TemplateSelector: labels.SelectorFromSet(tierTwo), + Limits: resources.CPUMemory(2000, 0), + }, + wantDoesNotFit: true, + }, + { + name: "an unavailable worker the actor would fit yields ErrNoCapacity", + fleet: fleet{ + worker("w-small", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30)), + worker("w-big", "gvisor", "node-a", tierTwo, withCapacity(4000, 4<<30), + withState(ateapi.WorkerState_WORKER_STATE_UNAVAILABLE)), + }, constraints: Constraints{Limits: resources.CPUMemory(2000, 0)}, }, + { + name: "a draining worker does not fit the actor", + fleet: fleet{ + worker("w-small", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30)), + worker("w-big", "gvisor", "node-a", tierTwo, withCapacity(4000, 4<<30), + withState(ateapi.WorkerState_WORKER_STATE_DRAINING)), + }, + constraints: Constraints{Limits: resources.CPUMemory(2000, 0)}, + wantDoesNotFit: true, + }, + { + name: "an unregistered worker does not fit the actor", + fleet: fleet{ + worker("w-small", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30)), + worker("w-new", "", "node-a", tierTwo, withState(ateapi.WorkerState_WORKER_STATE_UNAVAILABLE)), + }, + constraints: Constraints{Limits: resources.CPUMemory(2000, 0)}, + wantDoesNotFit: true, + }, { // A Worker reports everything it has, so one that has reported no // compute has none: an Actor that asks for some is not placed here. @@ -163,7 +225,8 @@ func TestSchedule(t *testing.T) { fleet: fleet{ worker("w-unknown", "gvisor", "node-a", tierTwo), }, - constraints: Constraints{Limits: resources.CPUMemory(2000, 2<<30)}, + constraints: Constraints{Limits: resources.CPUMemory(2000, 2<<30)}, + wantDoesNotFit: true, }, { // An Actor that declares nothing still fits: it asks for no @@ -320,29 +383,126 @@ func TestSchedule(t *testing.T) { wantPod: "w-busy-big", }, { - name: "required runtime matches worker default runtime", + name: "snapshot runtime matches worker default runtime", fleet: fleet{ worker("w-arm", "gvisor", "node-a", tierTwo, withRuntimes(sandboxRuntime("gvisor", "arm64"))), worker("w-amd", "gvisor", "node-b", tierTwo, withRuntimes(sandboxRuntime("gvisor", "amd64"))), }, - constraints: Constraints{RequiredRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64"))}, + constraints: Constraints{SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64"))}, wantPod: "w-amd", }, { - name: "required runtime matches worker restorable runtime", + name: "snapshot runtime matches worker restorable runtime", fleet: fleet{ worker("w-upgraded", "gvisor", "node-a", tierTwo, withRuntimes(sandboxRuntime("gvisor", "amd64", "new"), sandboxRuntime("gvisor", "amd64", "old"))), }, - constraints: Constraints{RequiredRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old"))}, + constraints: Constraints{SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old"))}, wantPod: "w-upgraded", }, { - name: "required runtime with no matching worker yields ErrNoCapacity", + name: "a restore books the overhead of the runtime it restores under", + fleet: fleet{ + worker("w-upgraded", "gvisor", "node-a", tierTwo, withCapacity(4000, 4<<30), + withRuntimes(sandboxRuntime("gvisor", "amd64", "new"), sandboxRuntime("gvisor", "amd64", "old")), + withOverhead(&ateapi.RuntimeOverhead{MemoryBytes: 4 << 20}, &ateapi.RuntimeOverhead{MemoryBytes: 16 << 20})), + }, + constraints: Constraints{ + SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old")), + Limits: resources.CPUMemory(500, 1<<30), + }, + wantPod: "w-upgraded", + }, + { + name: "snapshot runtime with no matching worker yields ErrNoCapacity when MinFidelity is MEMORY", fleet: fleet{ worker("w-arm", "gvisor", "node-a", tierTwo, withRuntimes(sandboxRuntime("gvisor", "arm64"))), }, - constraints: Constraints{RequiredRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64"))}, + constraints: Constraints{SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64"))}, + }, + { + name: "single pass upgrades from earlier ROOTFS worker to later MEMORY worker", + fleet: fleet{ + worker("w-rootfs", "gvisor", "node-a", tierTwo, withRuntimes(sandboxRuntime("gvisor", "amd64", "new"))), + worker("w-memory-full", "gvisor", "node-b", tierTwo, withRuntimes(sandboxRuntime("gvisor", "amd64", "old")), assigned("demo", "other")), + worker("w-memory-free", "gvisor", "node-c", tierTwo, withRuntimes(sandboxRuntime("gvisor", "amd64", "old"))), + }, + constraints: Constraints{ + SandboxClass: "gvisor", + SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old")), + MinFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + }, + wantPod: "w-memory-free", + }, + { + name: "single pass falls back to ROOTFS worker when all MEMORY workers are full", + fleet: fleet{ + worker("w-memory-full", "gvisor", "node-a", tierTwo, withRuntimes(sandboxRuntime("gvisor", "amd64", "old")), assigned("demo", "other")), + worker("w-rootfs-free", "gvisor", "node-b", tierTwo, withRuntimes(sandboxRuntime("gvisor", "amd64", "new"))), + }, + constraints: Constraints{ + SandboxClass: "gvisor", + SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old")), + MinFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + }, + wantPod: "w-rootfs-free", + wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + }, + { + name: "later ROOTFS worker does not displace earlier MEMORY candidate", + fleet: fleet{ + worker("w-memory", "gvisor", "node-a", tierTwo, withMaxActors(4), assigned("demo", "a"), + withRuntimes(sandboxRuntime("gvisor", "amd64", "old"))), + worker("w-rootfs-idle", "gvisor", "node-b", tierTwo, withMaxActors(4), + withRuntimes(sandboxRuntime("gvisor", "amd64", "new"))), + }, + constraints: Constraints{ + SandboxClass: "gvisor", + SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old")), + MinFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + }, + wantPod: "w-memory", + }, + { + name: "a small worker with an incompatible runtime yields ErrNoCapacity for a MEMORY restore", + fleet: fleet{ + worker("w-small-other", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30), + withRuntimes(sandboxRuntime("gvisor", "amd64", "new"))), + }, + constraints: Constraints{ + SandboxClass: "gvisor", + SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old")), + Limits: resources.CPUMemory(2000, 0), + }, + }, + { + name: "a large worker with an incompatible runtime does not fit a MEMORY restore", + fleet: fleet{ + worker("w-small-match", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30), + withRuntimes(sandboxRuntime("gvisor", "amd64", "old"))), + worker("w-big-other", "gvisor", "node-b", tierTwo, withCapacity(4000, 4<<30), + withRuntimes(sandboxRuntime("gvisor", "amd64", "new"))), + }, + constraints: Constraints{ + SandboxClass: "gvisor", + SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old")), + Limits: resources.CPUMemory(2000, 0), + }, + wantDoesNotFit: true, + }, + { + name: "a small worker with an incompatible runtime yields ErrDoesNotFit when ROOTFS is allowed", + fleet: fleet{ + worker("w-small-other", "gvisor", "node-a", tierTwo, withCapacity(1000, 1<<30), + withRuntimes(sandboxRuntime("gvisor", "amd64", "new"))), + }, + constraints: Constraints{ + SandboxClass: "gvisor", + SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old")), + MinFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + Limits: resources.CPUMemory(2000, 0), + }, + wantDoesNotFit: true, }, } @@ -355,8 +515,20 @@ func TestSchedule(t *testing.T) { if err != nil { t.Fatalf("Schedule() error = %v, want worker %q", err, tc.wantPod) } - if got.GetWorkerPod() != tc.wantPod { - t.Fatalf("Schedule() = %q, want %q", got.GetWorkerPod(), tc.wantPod) + if got.Worker.GetWorkerPod() != tc.wantPod { + t.Fatalf("Schedule() = %q, want %q", got.Worker.GetWorkerPod(), tc.wantPod) + } + wantFidelity := tc.wantFidelity + if wantFidelity == ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_UNSPECIFIED { + wantFidelity = ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY + } + if got.Fidelity != wantFidelity { + t.Errorf("Schedule() fidelity = %v, want %v", got.Fidelity, wantFidelity) + } + // admit compares the fresh row's Booking with this one, so they + // must agree on an unchanged worker. + if want, _ := Booking(got.Worker, tc.constraints); !proto.Equal(got.Booking, want) { + t.Errorf("Schedule() booking = %v, want %v", got.Booking, want) } return } @@ -364,6 +536,9 @@ func TestSchedule(t *testing.T) { if !errors.Is(err, ErrNoCapacity) { t.Fatalf("Schedule() error = %v, want ErrNoCapacity", err) } + if got := errors.Is(err, ErrDoesNotFit); got != tc.wantDoesNotFit { + t.Fatalf("Schedule() error = %v, ErrDoesNotFit = %t, want %t", err, got, tc.wantDoesNotFit) + } }) } } @@ -502,24 +677,34 @@ func TestApplies(t *testing.T) { want: false, }, { - name: "matches required runtime via default runtime", + name: "matches snapshot runtime via default runtime", worker: worker("w", "gvisor", "node-a", nil, withRuntimes(sandboxRuntime("gvisor", "amd64", "old"))), - constraints: Constraints{RequiredRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old"))}, + constraints: Constraints{SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old"))}, want: true, }, { - name: "matches required runtime via restorable runtimes", + name: "matches snapshot runtime via restorable runtimes", worker: worker("w", "gvisor", "node-a", nil, withRuntimes(sandboxRuntime("gvisor", "amd64", "new"), sandboxRuntime("gvisor", "amd64", "old"))), - constraints: Constraints{RequiredRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old"))}, + constraints: Constraints{SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old"))}, want: true, }, { - name: "skips worker when required runtime does not match", + name: "skips worker when snapshot runtime does not match and MinFidelity is MEMORY", worker: worker("w", "gvisor", "node-a", nil, withRuntimes(sandboxRuntime("gvisor", "arm64"))), - constraints: Constraints{RequiredRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64"))}, + constraints: Constraints{SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64"))}, want: false, }, + { + name: "accepts mismatched runtime of same class when MinFidelity is ROOTFS", + worker: worker("w", "gvisor", "node-a", nil, withRuntimes(sandboxRuntime("gvisor", "amd64", "new"))), + constraints: Constraints{ + SandboxClass: "gvisor", + SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("gvisor", "amd64", "old")), + MinFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + }, + want: true, + }, } for _, tc := range tests { @@ -680,8 +865,8 @@ func TestSchedulePowerOfTwoChoicesTieBreaking(t *testing.T) { if err != nil { t.Fatalf("Schedule() for index %d error = %v", wantIdx, err) } - if got.GetWorkerPod() != wantPod { - t.Fatalf("Schedule() for index %d = %q, want %q", wantIdx, got.GetWorkerPod(), wantPod) + if got.Worker.GetWorkerPod() != wantPod { + t.Fatalf("Schedule() for index %d = %q, want %q", wantIdx, got.Worker.GetWorkerPod(), wantPod) } } } @@ -710,8 +895,8 @@ func TestSchedulePowerOfTwoChoicesShiftedSecondSample(t *testing.T) { if err != nil { t.Fatalf("Schedule() error = %v", err) } - if got.GetWorkerPod() != "w-2" { - t.Fatalf("Schedule() = %q, want %q", got.GetWorkerPod(), "w-2") + if got.Worker.GetWorkerPod() != "w-2" { + t.Fatalf("Schedule() = %q, want %q", got.Worker.GetWorkerPod(), "w-2") } } @@ -742,16 +927,21 @@ func TestBooking(t *testing.T) { {name: "cold boot books the default runtime's", constraints: Constraints{Limits: limits}, want: gib/2 + 4<<20 + 4<<20}, { name: "a restore books the matching runtime's", - constraints: Constraints{Limits: limits, RequiredRuntime: hardware.NewRequirement(old), SnapshotRuntime: hardware.NewRequirement(old)}, + constraints: Constraints{Limits: limits, SnapshotRuntime: hardware.NewRequirement(old)}, want: gib/2 + 16<<20, }, { // relaxing what the worker must match doesn't change the runtime the // actor restores under, so it doesn't change the price name: "a relaxed restore still books the matching runtime's", - constraints: Constraints{Limits: limits, SnapshotRuntime: hardware.NewRequirement(old)}, + constraints: Constraints{Limits: limits, SnapshotRuntime: hardware.NewRequirement(old), MinFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS}, want: gib/2 + 16<<20, }, + { + name: "a relaxed restore nothing matches books the default runtime's", + constraints: Constraints{Limits: limits, SnapshotRuntime: hardware.NewRequirement(sandboxRuntime("microvm", "amd64", "gone")), MinFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS}, + want: gib/2 + 4<<20 + 4<<20, + }, } { t.Run(tc.name, func(t *testing.T) { got, ok := Booking(w, tc.constraints) diff --git a/cmd/ateapi/internal/server/cache_sync_test.go b/cmd/ateapi/internal/server/cache_sync_test.go new file mode 100644 index 0000000000..fd495e064d --- /dev/null +++ b/cmd/ateapi/internal/server/cache_sync_test.go @@ -0,0 +1,65 @@ +// Copyright 2026 The Agent Substrate 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 server + +import ( + "context" + "errors" + "testing" + "time" + + "go.ate.dev/substrate/cmd/ateapi/internal/controlapi" + "go.ate.dev/substrate/internal/cachesync" + atefake "go.ate.dev/substrate/pkg/client/clientset/versioned/fake" + "go.ate.dev/substrate/pkg/client/informers/externalversions" + apierrors "k8s.io/apimachinery/pkg/api/errors" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/informers" + kubefake "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" +) + +func TestRequiredKubernetesCachesWithoutSandboxConfigs(t *testing.T) { + kube := kubefake.NewClientset() + ate := atefake.NewSimpleClientset() + ate.PrependReactor("list", "sandboxconfigs", func(k8stesting.Action) (bool, runtime.Object, error) { + return true, nil, apierrors.NewForbidden(schema.GroupResource{Group: "ate.dev", Resource: "sandboxconfigs"}, "", errors.New("no SandboxConfig permission")) + }) + ateFactory := externalversions.NewSharedInformerFactoryWithOptions(ate, 0, externalversions.WithNamespace("workers")) + ateFactory.Ate().V1().WorkerPools().Lister() + ateFactory.Ate().V1().CSIDriverConfigs().Lister() + ateletFactory, ateletPods := controlapi.AteletInformer(kube, "ate-system") + scFactory := informers.NewSharedInformerFactory(kube, 0) + scFactory.Storage().V1().StorageClasses().Lister() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + t.Cleanup(func() { + cancel() + ateFactory.Shutdown() + ateletFactory.Shutdown() + scFactory.Shutdown() + }) + ateFactory.Start(ctx.Done()) + ateletFactory.Start(ctx.Done()) + scFactory.Start(ctx.Done()) + if err := cachesync.WaitForCacheSync(ctx, time.Second, requiredKubernetesCaches(ateletPods, ateFactory, scFactory)); err != nil { + t.Fatalf("required caches should sync without SandboxConfigs: %v", err) + } + for _, action := range ate.Actions() { + if action.GetResource().Resource == "sandboxconfigs" { + t.Fatalf("unexpected SandboxConfig request: %v", action) + } + } +} diff --git a/cmd/ateapi/internal/server/server.go b/cmd/ateapi/internal/server/server.go new file mode 100644 index 0000000000..24e163957d --- /dev/null +++ b/cmd/ateapi/internal/server/server.go @@ -0,0 +1,246 @@ +// Copyright 2026 The Agent Substrate 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 server builds ate-api's gRPC server and the background work it +// depends on. ate-api's main and the functional-test harness both build the +// server here, so the tests run what production runs. Only main calls +// controlapi.RegisterActorCrashes, because it sets a package global that the +// harness's parallel servers would race on. +package server + +import ( + "context" + "fmt" + "time" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/api/objectstore/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/apiauthn" + "go.ate.dev/substrate/cmd/ateapi/internal/authz" + "go.ate.dev/substrate/cmd/ateapi/internal/controlapi" + "go.ate.dev/substrate/cmd/ateapi/internal/store" + "go.ate.dev/substrate/cmd/ateapi/internal/workercache" + "go.ate.dev/substrate/cmd/ateapi/internal/workerservice" + "go.ate.dev/substrate/internal/ateinterceptors" + "go.ate.dev/substrate/internal/cachesync" + "go.ate.dev/substrate/internal/localca" + "go.ate.dev/substrate/internal/localjwtauthority" + "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/internal/volume" + "go.ate.dev/substrate/pkg/client/clientset/versioned" + "go.ate.dev/substrate/pkg/client/informers/externalversions" + "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" + "go.opentelemetry.io/otel/metric" + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/keepalive" + "google.golang.org/grpc/reflection" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/informers" + "k8s.io/client-go/kubernetes" + "k8s.io/client-go/tools/cache" +) + +// maxRPCDeadline is the max deadline for all RPC methods exposed by this server. +const maxRPCDeadline = 10 * time.Minute + +// cacheSyncTimeout bounds the startup wait for required Kubernetes caches. +const cacheSyncTimeout = time.Minute + +// Config is what the server takes from its environment. +type Config struct { + Store store.Interface + // KubeClient is the clientset for built-in Kubernetes resources, such as + // atelet pods and StorageClasses. + KubeClient kubernetes.Interface + // SubstrateCRDClient is the clientset for Agent Substrate's own CRDs, such + // as CSIDriverConfigs. + SubstrateCRDClient versioned.Interface + + // AteletNamespace is where the atelet pods run. + AteletNamespace string + // AteletSPIFFEID is the identity atelet presents, both on its serving + // certificate and on the client certificate it calls WorkerService with. + AteletSPIFFEID string + // AteletClientCredBundle and PodIdentityCACerts configure the mTLS ate-api + // dials atelet with. + AteletClientCredBundle string + PodIdentityCACerts string + // AteletDialerOptions customize how atelet is dialed. + AteletDialerOptions []controlapi.DialerOption + + ServerCreds credentials.TransportCredentials + Authn apiauthn.ServerConfig + Authorizer *authz.Authorizer + + ObjectStorePlugin objectstore.ControlProviderClient + SnapshotLocation string + + ActorJWTIssuer string + ActorJWTAuthorities localjwtauthority.Pool + ActorIDCAs localca.Pool + + DefaultEgressGatewayAddress string + // ActorWorkflowDeadline bounds each Resume/Suspend workflow end-to-end. + ActorWorkflowDeadline time.Duration + TemplateResyncInterval time.Duration + TemplateReconcilerWorkers int + IncludeErrorDebugInfo bool + PreviewGates *preview.Gates + + Meter metric.Meter +} + +// Server is ate-api's control plane server. +type Server struct { + GRPC *grpc.Server + + templateReconciler *controlapi.ActorTemplateReconciler + workerAssignmentReconciler *controlapi.WorkerAssignmentReconciler +} + +// New builds the server. It starts the worker cache and the informers, which +// run until ctx ends. startupCtx bounds how long startup may wait for sync. +// Caller must start the reconcilers with StartReconcilers and serve with GRPC. +func New(ctx, startupCtx context.Context, cfg Config) (*Server, error) { + if err := apiauthn.ValidateServerConfig(cfg.Authn); err != nil { + return nil, fmt.Errorf("invalid auth config: %w", err) + } + if cfg.PreviewGates == nil { + return nil, fmt.Errorf("PreviewGates must be set") + } + + workerCache := workercache.New(cfg.Store, 5*time.Minute) + if err := workerCache.Start(ctx); err != nil { + return nil, fmt.Errorf("seeding the worker cache: %w", err) + } + + ateFactory := externalversions.NewSharedInformerFactory(cfg.SubstrateCRDClient, 0) + csiDriverConfigLister := ateFactory.Ate().V1().CSIDriverConfigs().Lister() + + ateletPodInformerFactory, ateletPodInformer := controlapi.AteletInformer(cfg.KubeClient, cfg.AteletNamespace) + scInformerFactory := informers.NewSharedInformerFactory(cfg.KubeClient, 0) + storageClassLister := scInformerFactory.Storage().V1().StorageClasses().Lister() + + ateletPodInformerFactory.Start(ctx.Done()) + ateFactory.Start(ctx.Done()) + scInformerFactory.Start(ctx.Done()) + + if err := cachesync.WaitForCacheSync(startupCtx, cacheSyncTimeout, requiredKubernetesCaches(ateletPodInformer, ateFactory, scInformerFactory)); err != nil { + return nil, fmt.Errorf("syncing required Kubernetes caches: %w", err) + } + + if err := controlapi.RegisterWorkerCount(cfg.Meter, workerCache.Workers); err != nil { + return nil, fmt.Errorf("registering the worker-count metric: %w", err) + } + if err := controlapi.RegisterWorkerResources(cfg.Meter, workerCache.Workers); err != nil { + return nil, fmt.Errorf("registering the worker resource metrics: %w", err) + } + instruments, err := controlapi.NewInstruments(cfg.Meter) + if err != nil { + return nil, fmt.Errorf("creating metric instruments: %w", err) + } + + dialerOpts := append([]controlapi.DialerOption{ + controlapi.WithNodeGetter(func(ctx context.Context, nodeName string) error { + _, err := cfg.KubeClient.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{}) + return err + }), + }, cfg.AteletDialerOptions...) + ateletDialer := controlapi.NewAteletDialer(ateletPodInformer.GetIndexer(), cfg.AteletSPIFFEID, cfg.AteletClientCredBundle, cfg.PodIdentityCACerts, dialerOpts...) + + controlSrv, controlImpl := controlapi.NewRPCService( + cfg.Store, + workerCache, + csiDriverConfigLister, + storageClassLister, + ateletDialer, + instruments, + cfg.DefaultEgressGatewayAddress, + cfg.ActorWorkflowDeadline, + make(map[string]volume.VolumePluginControlPlane), + cfg.ObjectStorePlugin, + cfg.ActorJWTIssuer, + cfg.ActorJWTAuthorities, + cfg.SnapshotLocation, + cfg.PreviewGates, + ) + + methodGates, err := controlapi.PreviewMethodGates(ateapi.File_api_ateapi_v1_ateapi_proto.Services()) + if err != nil { + return nil, fmt.Errorf("invalid preview gate on a method: %w", err) + } + + unaryInterceptors := []grpc.UnaryServerInterceptor{ + apiauthn.UnaryServerInterceptor(cfg.Authn), + ateinterceptors.MaxDeadlineUnaryInterceptor(maxRPCDeadline), + ateinterceptors.NewServerUnaryInterceptor(cfg.IncludeErrorDebugInfo), + authz.UnaryServerInterceptor(cfg.Authorizer), + ateinterceptors.RejectUnknownFieldsUnaryInterceptor, + cfg.PreviewGates.UnaryServerInterceptor(methodGates), + } + + mux := grpc.NewServer( + grpc.Creds(cfg.ServerCreds), + grpc.StatsHandler(otelgrpc.NewServerHandler()), + // Close connections after an hour to allow for any + // client that doesn't use Kubernetes endpoint resolvers + // to eventually reobtain backend IPs. https://github.com/grpc/grpc/issues/12295 + grpc.KeepaliveParams(keepalive.ServerParameters{ + MaxConnectionAge: 1 * time.Hour, + MaxConnectionAgeGrace: maxRPCDeadline + time.Minute, + }), + // Clients ping every minute while an RPC waits. The default + // MinTime of 5 minutes would close their connections during long RPCs. + grpc.KeepaliveEnforcementPolicy(keepalive.EnforcementPolicy{ + MinTime: 30 * time.Second, + }), + grpc.ChainUnaryInterceptor(unaryInterceptors...), + grpc.ChainStreamInterceptor( + apiauthn.StreamServerInterceptor(cfg.Authn), + authz.StreamServerInterceptor(), + preview.StreamServerInterceptor, + ), + ) + reflection.Register(mux) + ateapi.RegisterControlServer(mux, controlSrv) + ateapi.RegisterWorkerServiceServer(mux, workerservice.New(cfg.Store, controlSrv, cfg.AteletSPIFFEID, cfg.ActorIDCAs, cfg.ActorJWTIssuer, cfg.ActorJWTAuthorities, cfg.PreviewGates)) + + // Drive stored ActorTemplates through the golden actor flow. + templateReconciler, err := controlapi.NewActorTemplateReconciler(controlImpl, controlSrv, cfg.TemplateResyncInterval, cfg.TemplateReconcilerWorkers) + if err != nil { + return nil, fmt.Errorf("creating actor template reconciler: %w", err) + } + + return &Server{ + GRPC: mux, + templateReconciler: templateReconciler, + // Crash the Actors lost when a Worker's worker restarts. + workerAssignmentReconciler: controlapi.NewWorkerAssignmentReconciler(cfg.Store, workerCache, cfg.PreviewGates), + }, nil +} + +// StartReconcilers starts the reconcilers, which run until ctx ends. +func (s *Server) StartReconcilers(ctx context.Context) { + s.templateReconciler.Start(ctx) + s.workerAssignmentReconciler.Start(ctx) +} + +func requiredKubernetesCaches(ateletPods cache.SharedIndexInformer, ateFactory externalversions.SharedInformerFactory, scFactory informers.SharedInformerFactory) map[string]cache.InformerSynced { + return map[string]cache.InformerSynced{ + "atelet Pods": ateletPods.HasSynced, + "CSIDriverConfigs": ateFactory.Ate().V1().CSIDriverConfigs().Informer().HasSynced, + "StorageClasses": scFactory.Storage().V1().StorageClasses().Informer().HasSynced, + } +} diff --git a/cmd/ateapi/internal/server/server_test.go b/cmd/ateapi/internal/server/server_test.go new file mode 100644 index 0000000000..4fea908db9 --- /dev/null +++ b/cmd/ateapi/internal/server/server_test.go @@ -0,0 +1,40 @@ +// Copyright 2026 The Agent Substrate 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 server + +import ( + "context" + "errors" + "strings" + "testing" + + "go.ate.dev/substrate/cmd/ateapi/internal/apiauthn" +) + +func TestNew_RequiresPreviewGates(t *testing.T) { + cfg := Config{ + Authn: apiauthn.ServerConfig{JWTProviders: []apiauthn.JWTProvider{{ + Name: "test", + Issuer: "https://issuer.test", + Verify: func(context.Context, string) (string, error) { + return "", errors.New("unused") + }, + }}}, + } + _, err := New(t.Context(), t.Context(), cfg) + if err == nil || !strings.Contains(err.Error(), "PreviewGates") { + t.Fatalf("New() error = %v, want error naming PreviewGates", err) + } +} diff --git a/cmd/ateapi/internal/store/atepg/AGENTS.md b/cmd/ateapi/internal/store/atepg/AGENTS.md new file mode 100644 index 0000000000..f5b75f1e6b --- /dev/null +++ b/cmd/ateapi/internal/store/atepg/AGENTS.md @@ -0,0 +1,11 @@ +# atepg + +This is the database layer. It stores and retrieves data from the database. It +should not have logic that is not related to this. + +- Never put API validation logic here. That belongs in the API layers. +- Always include tests, in particular for edge cases, consistency and + concurrency, error handling and performance. +- All type-specific code should go in the type's own file(s). For example, all + Actor related code goes in `actor.go` and all Actor related tests go in + `actor_test.go`. diff --git a/cmd/ateapi/internal/store/atepg/access_policy.go b/cmd/ateapi/internal/store/atepg/access_policy.go index 5d24f1f7b7..6d869c5dee 100644 --- a/cmd/ateapi/internal/store/atepg/access_policy.go +++ b/cmd/ateapi/internal/store/atepg/access_policy.go @@ -65,7 +65,7 @@ func (p *Persistence) GetGlobalAccessPolicy(ctx context.Context) (*ateapi.Access } func (p *Persistence) UpdateGlobalAccessPolicy(ctx context.Context, precondition store.Precondition, mutate func(*ateapi.AccessPolicy) error) (*ateapi.AccessPolicy, error) { - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } @@ -88,8 +88,7 @@ func (p *Persistence) UpdateGlobalAccessPolicy(ctx context.Context, precondition if err := mutate(dbPolicy); err != nil { return nil, err } - dbPolicy.Metadata = oldMeta - setUpdateMetadata(dbPolicy.Metadata, oldMeta) + dbPolicy.Metadata = setUpdateMetadata(oldMeta) protoBytes, err := proto.Marshal(dbPolicy) if err != nil { return nil, fmt.Errorf("marshaling updated global access policy: %w", err) @@ -151,7 +150,7 @@ func (p *Persistence) GetAtespaceAccessPolicy(ctx context.Context, name string) } func (p *Persistence) UpdateAtespaceAccessPolicy(ctx context.Context, name string, precondition store.Precondition, mutate func(*ateapi.AccessPolicy) error) (*ateapi.AccessPolicy, error) { - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } @@ -174,8 +173,7 @@ func (p *Persistence) UpdateAtespaceAccessPolicy(ctx context.Context, name strin if err := mutate(dbPolicy); err != nil { return nil, err } - dbPolicy.Metadata = oldMeta - setUpdateMetadata(dbPolicy.Metadata, oldMeta) + dbPolicy.Metadata = setUpdateMetadata(oldMeta) protoBytes, err := proto.Marshal(dbPolicy) if err != nil { return nil, fmt.Errorf("marshaling updated access policy: %w", err) @@ -195,7 +193,7 @@ func (p *Persistence) UpdateAtespaceAccessPolicy(ctx context.Context, name strin return dbPolicy, nil } -func (p *Persistence) DeleteAtespaceAccessPolicy(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.AccessPolicy, error) { +func (p *Persistence) DeleteAtespaceAccessPolicy(ctx context.Context, name string, precondition store.Precondition) (*ateapi.AccessPolicy, error) { tx, err := p.pool.Begin(ctx) if err != nil { return nil, fmt.Errorf("beginning access policy delete for %s: %w", name, err) diff --git a/cmd/ateapi/internal/store/atepg/access_policy_test.go b/cmd/ateapi/internal/store/atepg/access_policy_test.go index 4461178a30..7988bfb4e4 100644 --- a/cmd/ateapi/internal/store/atepg/access_policy_test.go +++ b/cmd/ateapi/internal/store/atepg/access_policy_test.go @@ -15,6 +15,7 @@ package atepg import ( + "context" "errors" "slices" "sync" @@ -112,6 +113,10 @@ func TestAtespaceAccessPolicy_LifecycleAndCascade(t *testing.T) { t.Fatalf("second CreateAtespaceAccessPolicy = %v, want ErrAlreadyExists", err) } + if _, err := p.UpdateAtespaceAccessPolicy(ctx, "team-a", store.Precondition{UID: created.GetMetadata().GetUid()}, func(*ateapi.AccessPolicy) error { return nil }); !errors.Is(err, store.ErrPreconditionRequired) { + t.Fatalf("UpdateAtespaceAccessPolicy without a version = %v, want ErrPreconditionRequired", err) + } + updated, err := p.UpdateAtespaceAccessPolicy(ctx, "team-a", store.PreconditionFrom(created), func(toUpdate *ateapi.AccessPolicy) error { toUpdate.Bindings = []*ateapi.Binding{ {Role: authz.RoleViewer, Members: []string{"user:dave"}}, @@ -122,14 +127,14 @@ func TestAtespaceAccessPolicy_LifecycleAndCascade(t *testing.T) { t.Fatalf("UpdateAtespaceAccessPolicy = %v, %v; want version 2", updated, err) } - if _, err := p.DeleteAtespaceAccessPolicy(ctx, "team-a", store.DeletePreconditions{Version: 99}); !errors.Is(err, store.ErrVersionConflict) { + if _, err := p.DeleteAtespaceAccessPolicy(ctx, "team-a", store.Precondition{Version: 99}); !errors.Is(err, store.ErrVersionConflict) { t.Fatalf("DeleteAtespaceAccessPolicy wrong version = %v, want ErrVersionConflict", err) } - if _, err := p.DeleteAtespaceAccessPolicy(ctx, "team-a", store.DeletePreconditions{UID: "wrong-uid"}); !errors.Is(err, store.ErrUIDConflict) { + if _, err := p.DeleteAtespaceAccessPolicy(ctx, "team-a", store.Precondition{UID: "wrong-uid"}); !errors.Is(err, store.ErrUIDConflict) { t.Fatalf("DeleteAtespaceAccessPolicy wrong uid = %v, want ErrUIDConflict", err) } - deleted, err := p.DeleteAtespaceAccessPolicy(ctx, "team-a", store.DeletePreconditions{ + deleted, err := p.DeleteAtespaceAccessPolicy(ctx, "team-a", store.Precondition{ UID: updated.GetMetadata().GetUid(), Version: updated.GetMetadata().GetVersion(), }) @@ -147,7 +152,7 @@ func TestAtespaceAccessPolicy_LifecycleAndCascade(t *testing.T) { if _, err := p.CreateAtespaceAccessPolicy(ctx, "team-a", policy); err != nil { t.Fatalf("re-creating access policy failed: %v", err) } - if _, err := p.DeleteAtespace(ctx, "team-a", store.DeletePreconditions{}); err != nil { + if _, err := p.DeleteAtespace(ctx, "team-a", store.Precondition{}); err != nil { t.Fatalf("DeleteAtespace failed: %v", err) } if _, err := p.GetAtespaceAccessPolicy(ctx, "team-a"); !errors.Is(err, store.ErrNotFound) { @@ -261,3 +266,43 @@ func TestGlobalAccessPolicy_UpdateIsAtomic(t *testing.T) { } }) } + +func TestUpdateGlobalAccessPolicy_DiscardsMetadataEdits(t *testing.T) { + testUpdateDiscardsMetadataEdits(t, + func(t *testing.T, s *Persistence) *ateapi.AccessPolicy { + created, err := s.CreateGlobalAccessPolicy(t.Context(), &ateapi.AccessPolicy{ + Metadata: &ateapi.ResourceMetadata{Name: "default"}, + Bindings: []*ateapi.Binding{{Role: authz.RoleOwner, Members: []string{"user:alice"}}}, + }) + if err != nil { + t.Fatalf("CreateGlobalAccessPolicy failed: %v", err) + } + return created + }, + func(ctx context.Context, s *Persistence, pc store.Precondition, mutate func(*ateapi.AccessPolicy) error) (*ateapi.AccessPolicy, error) { + return s.UpdateGlobalAccessPolicy(ctx, pc, mutate) + }, + func(ctx context.Context, s *Persistence) (*ateapi.AccessPolicy, error) { + return s.GetGlobalAccessPolicy(ctx) + }) +} + +func TestUpdateAtespaceAccessPolicy_DiscardsMetadataEdits(t *testing.T) { + testUpdateDiscardsMetadataEdits(t, + func(t *testing.T, s *Persistence) *ateapi.AccessPolicy { + created, err := s.CreateAtespaceAccessPolicy(t.Context(), "team-a", &ateapi.AccessPolicy{ + Metadata: &ateapi.ResourceMetadata{Name: "default"}, + Bindings: []*ateapi.Binding{{Role: authz.RoleEditor, Members: []string{"user:bob"}}}, + }) + if err != nil { + t.Fatalf("CreateAtespaceAccessPolicy failed: %v", err) + } + return created + }, + func(ctx context.Context, s *Persistence, pc store.Precondition, mutate func(*ateapi.AccessPolicy) error) (*ateapi.AccessPolicy, error) { + return s.UpdateAtespaceAccessPolicy(ctx, "team-a", pc, mutate) + }, + func(ctx context.Context, s *Persistence) (*ateapi.AccessPolicy, error) { + return s.GetAtespaceAccessPolicy(ctx, "team-a") + }) +} diff --git a/cmd/ateapi/internal/store/atepg/actor.go b/cmd/ateapi/internal/store/atepg/actor.go index 5ac0b4fe46..bfd14ae111 100644 --- a/cmd/ateapi/internal/store/atepg/actor.go +++ b/cmd/ateapi/internal/store/atepg/actor.go @@ -80,19 +80,19 @@ func (p *Persistence) GetActor(ctx context.Context, actorRef resources.ActorRef) } func (p *Persistence) UpdateActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } - return updateActor(ctx, p.pool, actorRef, store.DeletePreconditions(precondition), mutate, false) + return updateActor(ctx, p.pool, actorRef, precondition, mutate, false) } -func (p *Persistence) MarkActorForDeletion(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { +func (p *Persistence) MarkActorForDeletion(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { return updateActor(ctx, p.pool, actorRef, precondition, mutate, true) } // updateActor applies mutate to the stored actor through q, which is the pool // or a transaction the write must commit with. -func updateActor(ctx context.Context, q querier, actorRef resources.ActorRef, precondition store.DeletePreconditions, mutate func(*ateapi.Actor) error, markForDeletion bool) (*ateapi.Actor, error) { +func updateActor(ctx context.Context, q querier, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapi.Actor) error, markForDeletion bool) (*ateapi.Actor, error) { atespace, name := actorRef.Atespace, actorRef.Name var currentUID string var currentVersion int64 @@ -127,7 +127,7 @@ func updateActor(ctx context.Context, q querier, actorRef resources.ActorRef, pr } // Stored metadata is authoritative; discard any metadata edits made by the // closure and derive the next revision from the state this attempt read. - setUpdateMetadata(dbActor.Metadata, oldMeta) + dbActor.Metadata = setUpdateMetadata(oldMeta) if markForDeletion && dbActor.Metadata.DeleteTime == nil { dbActor.Metadata.DeleteTime = proto.CloneOf(dbActor.Metadata.UpdateTime) } @@ -153,7 +153,7 @@ func updateActor(ctx context.Context, q querier, actorRef resources.ActorRef, pr return dbActor, nil } -func (p *Persistence) DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions) (*ateapi.Actor, error) { +func (p *Persistence) DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (*ateapi.Actor, error) { atespace, name := actorRef.Atespace, actorRef.Name tx, err := p.pool.Begin(ctx) if err != nil { diff --git a/cmd/ateapi/internal/store/atepg/actor_template.go b/cmd/ateapi/internal/store/atepg/actor_template.go index aa0ee1dc8f..c0224de016 100644 --- a/cmd/ateapi/internal/store/atepg/actor_template.go +++ b/cmd/ateapi/internal/store/atepg/actor_template.go @@ -69,28 +69,18 @@ func (p *Persistence) GetActorTemplate(ctx context.Context, templateRef resource return out, nil } -func validateUpdateActorTemplateMutation(storedTemplate, mutatedTemplate *ateapi.ActorTemplate) error { - if stored, mutated := storedTemplate.GetMetadata().GetAtespace(), mutatedTemplate.GetMetadata().GetAtespace(); stored != mutated { - return fmt.Errorf("metadata.atespace is immutable: mutation changed it from %q to %q", stored, mutated) - } - if stored, mutated := storedTemplate.GetMetadata().GetName(), mutatedTemplate.GetMetadata().GetName(); stored != mutated { - return fmt.Errorf("metadata.name is immutable: mutation changed it from %q to %q", stored, mutated) - } - return nil -} - func (p *Persistence) UpdateActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition, mutate func(*ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) { - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } - return p.updateActorTemplate(ctx, templateRef, store.DeletePreconditions(precondition), mutate, false) + return p.updateActorTemplate(ctx, templateRef, precondition, mutate, false) } -func (p *Persistence) MarkActorTemplateForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions, mutate func(*ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) { +func (p *Persistence) MarkActorTemplateForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition, mutate func(*ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) { return p.updateActorTemplate(ctx, templateRef, precondition, mutate, true) } -func (p *Persistence) updateActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions, mutate func(*ateapi.ActorTemplate) error, markForDeletion bool) (*ateapi.ActorTemplate, error) { +func (p *Persistence) updateActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition, mutate func(*ateapi.ActorTemplate) error, markForDeletion bool) (*ateapi.ActorTemplate, error) { var currentUID string var currentVersion int64 var currentBytes []byte @@ -113,19 +103,13 @@ func (p *Persistence) updateActorTemplate(ctx context.Context, templateRef resou if err := precondition.Check(dbTemplate.GetMetadata()); err != nil { return nil, err } - templateBeforeMutation := proto.Clone(dbTemplate).(*ateapi.ActorTemplate) + oldMeta := proto.CloneOf(dbTemplate.Metadata) if mutate != nil { if err := mutate(dbTemplate); err != nil { return nil, err } } - if err := validateUpdateActorTemplateMutation(templateBeforeMutation, dbTemplate); err != nil { - return nil, err - } - if dbTemplate.Metadata == nil { - dbTemplate.Metadata = &ateapi.ResourceMetadata{} - } - setUpdateMetadata(dbTemplate.Metadata, templateBeforeMutation.GetMetadata()) + dbTemplate.Metadata = setUpdateMetadata(oldMeta) if markForDeletion && dbTemplate.Metadata.DeleteTime == nil { dbTemplate.Metadata.DeleteTime = proto.CloneOf(dbTemplate.Metadata.UpdateTime) } @@ -221,7 +205,7 @@ func (p *Persistence) ListActorTemplates(ctx context.Context, atespace string, o return store.ListResponse[*ateapi.ActorTemplate]{Items: result, NextPageToken: nextToken}, nil } -func (p *Persistence) DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.DeletePreconditions) (*ateapi.ActorTemplate, error) { +func (p *Persistence) DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition store.Precondition) (*ateapi.ActorTemplate, error) { var protoBytes []byte err := p.pool.QueryRow(ctx, ` DELETE FROM actor_templates AS t diff --git a/cmd/ateapi/internal/store/atepg/actor_template_test.go b/cmd/ateapi/internal/store/atepg/actor_template_test.go index 84d000175e..b1902d651e 100644 --- a/cmd/ateapi/internal/store/atepg/actor_template_test.go +++ b/cmd/ateapi/internal/store/atepg/actor_template_test.go @@ -116,3 +116,22 @@ func TestGetActorTemplate_BackfillsDefaults(t *testing.T) { t.Errorf("ListActorTemplates did not backfill snapshot_config defaults (-want +got):\n%s", diff) } } + +func TestUpdateActorTemplate_DiscardsMetadataEdits(t *testing.T) { + ref := resources.ActorTemplateRef{Atespace: "team-a", Name: "template-a"} + testUpdateDiscardsMetadataEdits(t, + func(t *testing.T, s *Persistence) *ateapi.ActorTemplate { + createTestActorTemplate(t, s, ref.Atespace, ref.Name) + tmpl, err := s.GetActorTemplate(t.Context(), ref) + if err != nil { + t.Fatalf("GetActorTemplate failed: %v", err) + } + return tmpl + }, + func(ctx context.Context, s *Persistence, pc store.Precondition, mutate func(*ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) { + return s.UpdateActorTemplate(ctx, ref, pc, mutate) + }, + func(ctx context.Context, s *Persistence) (*ateapi.ActorTemplate, error) { + return s.GetActorTemplate(ctx, ref) + }) +} diff --git a/cmd/ateapi/internal/store/atepg/actor_test.go b/cmd/ateapi/internal/store/atepg/actor_test.go index e2d66e1de9..4bd34f7e59 100644 --- a/cmd/ateapi/internal/store/atepg/actor_test.go +++ b/cmd/ateapi/internal/store/atepg/actor_test.go @@ -143,3 +143,24 @@ func TestListActors_CrossScopePageToken(t *testing.T) { } } } + +func TestUpdateActor_DiscardsMetadataEdits(t *testing.T) { + ref := resources.ActorRef{Atespace: "team-a", Name: "a"} + testUpdateDiscardsMetadataEdits(t, + func(t *testing.T, s *Persistence) *ateapi.Actor { + created, err := s.CreateActor(t.Context(), &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: ref.Atespace, Name: ref.Name}, + Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, + }) + if err != nil { + t.Fatalf("CreateActor failed: %v", err) + } + return created + }, + func(ctx context.Context, s *Persistence, pc store.Precondition, mutate func(*ateapi.Actor) error) (*ateapi.Actor, error) { + return s.UpdateActor(ctx, ref, pc, mutate) + }, + func(ctx context.Context, s *Persistence) (*ateapi.Actor, error) { + return s.GetActor(ctx, ref) + }) +} diff --git a/cmd/ateapi/internal/store/atepg/atepg.go b/cmd/ateapi/internal/store/atepg/atepg.go index 41d04dac2a..05320fa596 100644 --- a/cmd/ateapi/internal/store/atepg/atepg.go +++ b/cmd/ateapi/internal/store/atepg/atepg.go @@ -405,6 +405,8 @@ func unmarshalRow(b []byte, m proto.Message, kind string, id ...string) error { return nil } +// setCreateMetadata modifies the input metadata to be correct for a create +// operation. func setCreateMetadata(metadata *ateapi.ResourceMetadata) { metadata.Uid = uuid.NewString() metadata.Version = 1 @@ -439,15 +441,16 @@ func validateSnapshotURIs(resource string, snapshots ...*ateapi.Snapshot) error return nil } -func setUpdateMetadata(newMeta, oldMeta *ateapi.ResourceMetadata) { - newMeta.Uid = oldMeta.Uid - newMeta.Version = oldMeta.Version + 1 - newMeta.CreateTime = oldMeta.CreateTime - newMeta.UpdateTime = timestamppb.Now() - newMeta.DeleteTime = oldMeta.DeleteTime +// setUpdateMetadata modifies the input metadata for an update operation and +// returns it. There are no mutable metadata fields yet. If some are added in +// the future, (e.g. labels), this would take 2 params and merge them. +func setUpdateMetadata(metadata *ateapi.ResourceMetadata) *ateapi.ResourceMetadata { + metadata.Version++ + metadata.UpdateTime = timestamppb.Now() + return metadata } -func mapDeleteError(err error, uid string, version int64, precondition store.DeletePreconditions) error { +func mapDeleteError(err error, uid string, version int64, precondition store.Precondition) error { if errors.Is(err, pgx.ErrNoRows) { return store.ErrNotFound } diff --git a/cmd/ateapi/internal/store/atepg/atepg_test.go b/cmd/ateapi/internal/store/atepg/atepg_test.go index 0cdfe7c3eb..e12e775f8f 100644 --- a/cmd/ateapi/internal/store/atepg/atepg_test.go +++ b/cmd/ateapi/internal/store/atepg/atepg_test.go @@ -45,10 +45,16 @@ func TestList_NamesAnUndecodableRow(t *testing.T) { }); err != nil { t.Fatalf("CreateWorker failed: %v", err) } + if _, err := s.CreateExternalVolume(ctx, &ateapi.ExternalVolume{ + Metadata: &ateapi.ResourceMetadata{Name: "ev1", Atespace: "team-a"}, + Status: &ateapi.ExternalVolumeStatus{Csi: &ateapi.CsiVolumeStatus{VolumeId: "vol-1", DriverName: "nfs.csi.k8s.io"}}, + }); err != nil { + t.Fatalf("CreateExternalVolume failed: %v", err) + } // Not a valid encoding of any message. bad := []byte{0xff} - for _, table := range []string{"atespaces", "actors", "actor_templates", "tags", "workers"} { + for _, table := range []string{"atespaces", "actors", "actor_templates", "tags", "external_volumes", "workers"} { if _, err := s.pool.Exec(ctx, "UPDATE "+table+" SET proto = $1", bad); err != nil { t.Fatalf("corrupting %s: %v", table, err) } @@ -70,6 +76,8 @@ func TestList_NamesAnUndecodableRow(t *testing.T) { {"actor templates, all atespaces", func() error { _, err := s.ListActorTemplates(ctx, "", opts); return err }, "actor template team-a/t1"}, {"tags", func() error { _, err := s.ListTags(ctx, "team-a", opts); return err }, "tag team-a/v1"}, {"tags, all atespaces", func() error { _, err := s.ListTags(ctx, "", opts); return err }, "tag team-a/v1"}, + {"external volumes", func() error { _, err := s.ListExternalVolumes(ctx, "team-a", opts); return err }, "external volume team-a/ev1"}, + {"external volumes, all atespaces", func() error { _, err := s.ListExternalVolumes(ctx, "", opts); return err }, "external volume team-a/ev1"}, {"workers", func() error { _, err := s.ListWorkers(ctx, opts); return err }, "worker w1"}, {"worker assignments", func() error { _, err := s.ListWorkerAssignments(ctx, "w1", opts); return err }, "actor uid-1"}, } diff --git a/cmd/ateapi/internal/store/atepg/atespace.go b/cmd/ateapi/internal/store/atepg/atespace.go index 6d0f163e3b..d5a86aa84c 100644 --- a/cmd/ateapi/internal/store/atepg/atespace.go +++ b/cmd/ateapi/internal/store/atepg/atespace.go @@ -118,7 +118,7 @@ func (p *Persistence) ListAtespaces(ctx context.Context, opts store.ListOptions) return store.ListResponse[*ateapi.Atespace]{Items: result, NextPageToken: nextToken}, nil } -func (p *Persistence) DeleteAtespace(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.Atespace, error) { +func (p *Persistence) DeleteAtespace(ctx context.Context, name string, precondition store.Precondition) (*ateapi.Atespace, error) { tx, err := p.pool.Begin(ctx) if err != nil { return nil, fmt.Errorf("beginning atespace delete: %w", err) diff --git a/cmd/ateapi/internal/store/atepg/common_test.go b/cmd/ateapi/internal/store/atepg/common_test.go index 718317ee30..97c672d543 100644 --- a/cmd/ateapi/internal/store/atepg/common_test.go +++ b/cmd/ateapi/internal/store/atepg/common_test.go @@ -18,9 +18,14 @@ import ( "context" "testing" + "github.com/google/go-cmp/cmp" "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/authz" + "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/internal/installdefaults" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/testing/protocmp" + "google.golang.org/protobuf/types/known/timestamppb" ) // clearAll truncates every table so the next test starts from an empty store @@ -28,7 +33,7 @@ import ( // state, so the statement lives here rather than on Persistence. func clearAll(t *testing.T, p *Persistence) { t.Helper() - if _, err := p.pool.Exec(context.Background(), `TRUNCATE atespaces, global_access_policy, atespace_access_policies, actors, actor_egress_policies, actor_templates, tags, workers, worker_assignments, leases, worker_outbox, worker_outbox_trim, tuple, changelog`); err != nil { + if _, err := p.pool.Exec(context.Background(), `TRUNCATE atespaces, global_access_policy, atespace_access_policies, actors, actor_egress_policies, actor_templates, tags, external_volumes, external_volume_keys, workers, worker_assignments, leases, worker_outbox, worker_outbox_trim, csi_drivers, tuple, changelog`); err != nil { t.Fatalf("truncating tables: %v", err) } } @@ -58,7 +63,7 @@ func setTestPolicyManager(t *testing.T, p *Persistence) { _, policyManager, err := authz.New(t.Context(), p.pool, fgaServer, nil, authz.SystemPrincipals{ ControllerSPIFFEID: installdefaults.ControllerSPIFFEID(installdefaults.SystemNamespace), EgressGatewaySPIFFEIDs: []string{installdefaults.EgressSPIFFEID(installdefaults.SystemNamespace)}, - IngressRouterSPIFFEID: installdefaults.RouterSPIFFEID(installdefaults.SystemNamespace), + IngressRouterSPIFFEIDs: []string{installdefaults.RouterSPIFFEID(installdefaults.SystemNamespace)}, AteletSPIFFEID: installdefaults.AteletSPIFFEID(installdefaults.SystemNamespace), APIServerSidecarSPIFFEID: installdefaults.APIServerSPIFFEID(installdefaults.SystemNamespace), }) @@ -78,3 +83,60 @@ func createTestAtespace(t *testing.T, s *Persistence, name string) { t.Fatalf("CreateAtespace(%q) failed: %v", name, err) } } + +// metadataEdits are mutate closures that try to change metadata the store owns. +var metadataEdits = map[string]func(obj hasMetadata){ + "changed": func(obj hasMetadata) { + md := obj.GetMetadata() + md.Name = "other" + md.Atespace = "other" + md.Uid = "other-uid" + md.Version = 99 + md.CreateTime = nil + md.DeleteTime = timestamppb.Now() + }, + "cleared": func(obj hasMetadata) { + m := obj.ProtoReflect() + m.Clear(m.Descriptor().Fields().ByName("metadata")) + }, +} + +type hasMetadata interface { + proto.Message + GetMetadata() *ateapi.ResourceMetadata +} + +// testUpdateDiscardsMetadataEdits creates an object with create, updates it +// with each of metadataEdits, and checks that get returns the created metadata +// at version 2. Atespace team-a exists before create runs. +func testUpdateDiscardsMetadataEdits[T hasMetadata]( + t *testing.T, + create func(t *testing.T, s *Persistence) T, + update func(ctx context.Context, s *Persistence, precondition store.Precondition, mutate func(T) error) (T, error), + get func(ctx context.Context, s *Persistence) (T, error), +) { + t.Helper() + for name, edit := range metadataEdits { + t.Run(name, func(t *testing.T) { + s := setupPostgresPersistence(t) + ctx := t.Context() + createTestAtespace(t, s, "team-a") + created := create(t, s) + if _, err := update(ctx, s, store.PreconditionFrom(created), func(obj T) error { + edit(obj) + return nil + }); err != nil { + t.Fatalf("update failed: %v", err) + } + got, err := get(ctx, s) + if err != nil { + t.Fatalf("get failed: %v", err) + } + want := proto.CloneOf(created.GetMetadata()) + want.Version = 2 + if diff := cmp.Diff(want, got.GetMetadata(), protocmp.Transform(), protocmp.IgnoreFields(&ateapi.ResourceMetadata{}, "update_time")); diff != "" { + t.Errorf("stored metadata (-want +got):\n%s", diff) + } + }) + } +} diff --git a/cmd/ateapi/internal/store/atepg/csi_driver.go b/cmd/ateapi/internal/store/atepg/csi_driver.go new file mode 100644 index 0000000000..a45679b15c --- /dev/null +++ b/cmd/ateapi/internal/store/atepg/csi_driver.go @@ -0,0 +1,245 @@ +// Copyright 2026 The Agent Substrate 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 atepg + +import ( + "context" + "errors" + "fmt" + + "github.com/jackc/pgx/v5" + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/store" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func validateCSIDriverColumns(name string, driver *ateapi.CsiDriver, uid string, version int64, driverName string) error { + resource := fmt.Sprintf("csi driver %q", name) + if err := validateProtoMetadataMatchesColumns(resource, driver.GetMetadata(), uid, version); err != nil { + return err + } + if driver.GetMetadata().GetName() != name { + return fmt.Errorf("%s name projection %q does not match proto metadata name %q", resource, name, driver.GetMetadata().GetName()) + } + if driver.GetDriverName() != driverName { + return fmt.Errorf("%s driver_name projection %q does not match proto driver_name %q", resource, driverName, driver.GetDriverName()) + } + return nil +} + +func (p *Persistence) CreateCSIDriver(ctx context.Context, driver *ateapi.CsiDriver) (*ateapi.CsiDriver, error) { + dbDriver := proto.CloneOf(driver) + if dbDriver.Metadata == nil { + dbDriver.Metadata = &ateapi.ResourceMetadata{} + } + name := dbDriver.GetMetadata().GetName() + setCreateMetadata(dbDriver.Metadata) + protoBytes, err := proto.Marshal(dbDriver) + if err != nil { + return nil, fmt.Errorf("marshaling csi driver: %w", err) + } + _, err = p.pool.Exec(ctx, ` + INSERT INTO csi_drivers (name, uid, version, driver_name, proto) + VALUES ($1, $2, $3, $4, $5)`, + name, dbDriver.GetMetadata().GetUid(), dbDriver.GetMetadata().GetVersion(), dbDriver.GetDriverName(), protoBytes) + if err != nil { + if isUniqueViolation(err) { + if pgErrConstraint(err) == "csi_drivers_driver_name_key" { + return nil, fmt.Errorf("%w: %q", store.ErrDriverNameAlreadyExists, dbDriver.GetDriverName()) + } + return nil, fmt.Errorf("%w: csi driver %q already exists", store.ErrAlreadyExists, name) + } + return nil, fmt.Errorf("inserting csi driver %q: %w", name, err) + } + return dbDriver, nil +} + +func (p *Persistence) GetCSIDriver(ctx context.Context, name string) (*ateapi.CsiDriver, error) { + var rowName, uid, driverName string + var version int64 + var protoBytes []byte + if err := p.pool.QueryRow(ctx, `SELECT name, uid, version, driver_name, proto FROM csi_drivers WHERE name = $1`, name).Scan( + &rowName, &uid, &version, &driverName, &protoBytes); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, store.ErrNotFound + } + return nil, fmt.Errorf("getting csi driver %q: %w", name, err) + } + out := &ateapi.CsiDriver{} + if err := unmarshalStored(protoBytes, out); err != nil { + return nil, fmt.Errorf("unmarshaling csi driver: %w", err) + } + if err := validateCSIDriverColumns(rowName, out, uid, version, driverName); err != nil { + return nil, err + } + return out, nil +} + +func (p *Persistence) ListCSIDrivers(ctx context.Context, opts store.ListOptions) (store.ListResponse[*ateapi.CsiDriver], error) { + opts, err := store.NormalizeListOptions(opts) + if err != nil { + return store.ListResponse[*ateapi.CsiDriver]{}, err + } + pageSize := opts.PageSize + token, err := decodePageToken(opts.PageToken, kindCSIDriver, "", 1) + if err != nil { + return store.ListResponse[*ateapi.CsiDriver]{}, err + } + var last *string + if len(token.Last) > 0 { + last = &token.Last[0] + } + rows, err := p.pool.Query(ctx, ` + SELECT name, uid, version, driver_name, proto FROM csi_drivers + WHERE $1::text IS NULL OR name > $1 + ORDER BY name + LIMIT $2`, last, int64(pageSize)+1) + if err != nil { + return store.ListResponse[*ateapi.CsiDriver]{}, fmt.Errorf("listing csi drivers: %w", err) + } + defer rows.Close() + + var names []string + var result []*ateapi.CsiDriver + for rows.Next() { + var name, uid, driverName string + var version int64 + var protoBytes []byte + if err := rows.Scan(&name, &uid, &version, &driverName, &protoBytes); err != nil { + return store.ListResponse[*ateapi.CsiDriver]{}, fmt.Errorf("scanning csi driver row: %w", err) + } + driver := &ateapi.CsiDriver{} + if err := unmarshalRow(protoBytes, driver, "csi driver", name); err != nil { + return store.ListResponse[*ateapi.CsiDriver]{}, err + } + if err := validateCSIDriverColumns(name, driver, uid, version, driverName); err != nil { + return store.ListResponse[*ateapi.CsiDriver]{}, err + } + result = append(result, driver) + names = append(names, name) + } + if err := rows.Err(); err != nil { + return store.ListResponse[*ateapi.CsiDriver]{}, fmt.Errorf("listing csi drivers: %w", err) + } + var nextToken string + if len(result) > int(pageSize) { + result = result[:pageSize] + nextToken = encodePageToken(kindCSIDriver, "", []string{names[pageSize-1]}) + } + return store.ListResponse[*ateapi.CsiDriver]{Items: result, NextPageToken: nextToken}, nil +} + +func (p *Persistence) UpdateCSIDriver(ctx context.Context, name string, precondition store.Precondition, mutate func(toUpdate *ateapi.CsiDriver) error) (*ateapi.CsiDriver, error) { + if err := precondition.ValidateRequired(); err != nil { + return nil, err + } + var currentUID, currentDriverName string + var currentVersion int64 + var currentBytes []byte + err := p.pool.QueryRow(ctx, `SELECT uid, version, driver_name, proto FROM csi_drivers WHERE name = $1`, name).Scan( + ¤tUID, ¤tVersion, ¤tDriverName, ¤tBytes) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, store.ErrNotFound + } + return nil, fmt.Errorf("getting csi driver %q for update: %w", name, err) + } + dbDriver := &ateapi.CsiDriver{} + if err := unmarshalStored(currentBytes, dbDriver); err != nil { + return nil, fmt.Errorf("unmarshaling csi driver %q: %w", name, err) + } + if err := validateCSIDriverColumns(name, dbDriver, currentUID, currentVersion, currentDriverName); err != nil { + return nil, err + } + if err := precondition.Check(dbDriver.GetMetadata()); err != nil { + return nil, err + } + + // Snapshot the stored metadata before handing the driver to mutate. + // Immutable fields are enforced by declarative validation in the service layer. + oldMeta := proto.CloneOf(dbDriver.GetMetadata()) + if mutate != nil { + if err := mutate(dbDriver); err != nil { + return nil, err + } + } + dbDriver.Metadata = setUpdateMetadata(oldMeta) + if dbDriver.GetDriverName() != currentDriverName { + return nil, fmt.Errorf("updating csi driver %q: driver_name is immutable", name) + } + + updatedBytes, err := proto.Marshal(dbDriver) + if err != nil { + return nil, fmt.Errorf("marshaling csi driver: %w", err) + } + commandTag, err := p.pool.Exec(ctx, ` + UPDATE csi_drivers SET version = $1, proto = $2 + WHERE name = $3 AND uid = $4 AND version = $5`, + dbDriver.GetMetadata().GetVersion(), updatedBytes, name, currentUID, currentVersion) + if err != nil { + return nil, fmt.Errorf("updating csi driver %q: %w", name, err) + } + if commandTag.RowsAffected() == 0 { + return nil, store.ErrVersionConflict + } + if commandTag.RowsAffected() != 1 { + return nil, fmt.Errorf("updating csi driver %q affected %d rows, want 1", name, commandTag.RowsAffected()) + } + return dbDriver, nil +} + +func (p *Persistence) DeleteCSIDriver(ctx context.Context, name string, precondition store.Precondition) (*ateapi.CsiDriver, error) { + tx, err := p.pool.Begin(ctx) + if err != nil { + return nil, fmt.Errorf("beginning csi driver delete: %w", err) + } + defer tx.Rollback(ctx) //nolint:errcheck // no-op once committed + + var uid, driverName string + var version int64 + var protoBytes []byte + err = tx.QueryRow(ctx, `SELECT uid, version, driver_name, proto FROM csi_drivers WHERE name = $1 FOR UPDATE`, name).Scan( + &uid, &version, &driverName, &protoBytes) + if err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, store.ErrNotFound + } + return nil, fmt.Errorf("locking csi driver %q for delete: %w", name, err) + } + deleted := &ateapi.CsiDriver{} + if err := unmarshalStored(protoBytes, deleted); err != nil { + return nil, fmt.Errorf("unmarshaling csi driver %q: %w", name, err) + } + if err := validateCSIDriverColumns(name, deleted, uid, version, driverName); err != nil { + return nil, err + } + if err := precondition.Check(deleted.GetMetadata()); err != nil { + return nil, err + } + + commandTag, err := tx.Exec(ctx, `DELETE FROM csi_drivers WHERE name = $1`, name) + if err != nil { + return nil, fmt.Errorf("deleting csi driver %q: %w", name, err) + } + if commandTag.RowsAffected() != 1 { + return nil, fmt.Errorf("deleting csi driver %q affected %d rows, want 1", name, commandTag.RowsAffected()) + } + if err := tx.Commit(ctx); err != nil { + return nil, fmt.Errorf("committing csi driver delete %q: %w", name, err) + } + deleted.Metadata.DeleteTime = timestamppb.Now() + return deleted, nil +} diff --git a/cmd/ateapi/internal/store/atepg/csi_driver_test.go b/cmd/ateapi/internal/store/atepg/csi_driver_test.go new file mode 100644 index 0000000000..a7c0c70a40 --- /dev/null +++ b/cmd/ateapi/internal/store/atepg/csi_driver_test.go @@ -0,0 +1,119 @@ +// Copyright 2026 The Agent Substrate 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 atepg + +import ( + "context" + "errors" + "fmt" + "testing" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/store" +) + +func TestCreateCSIDriver_UniqueConstraintMessages(t *testing.T) { + s := setupPostgresPersistence(t) + ctx := context.Background() + if _, err := s.CreateCSIDriver(ctx, &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, DriverName: "nfs.csi.k8s.io", ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "10.0.0.1", Port: 12345}, + }); err != nil { + t.Fatalf("CreateCSIDriver failed: %v", err) + } + + _, err := s.CreateCSIDriver(ctx, &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, DriverName: "other.csi.k8s.io", ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "10.0.0.1", Port: 12345}, + }) + if !errors.Is(err, store.ErrAlreadyExists) || errors.Is(err, store.ErrDriverNameAlreadyExists) { + t.Errorf("duplicate name error = %v, want ErrAlreadyExists (not ErrDriverNameAlreadyExists)", err) + } + + _, err = s.CreateCSIDriver(ctx, &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs-2"}, DriverName: "nfs.csi.k8s.io", ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "10.0.0.1", Port: 12345}, + }) + if !errors.Is(err, store.ErrFailedPrecondition) || !errors.Is(err, store.ErrDriverNameAlreadyExists) { + t.Errorf("duplicate driver_name error = %v, want ErrDriverNameAlreadyExists (wrapping ErrFailedPrecondition)", err) + } +} + +func TestUpdateCSIDriver_ConcurrentWriteReturnsConflict(t *testing.T) { + s := setupPostgresPersistence(t) + ctx := context.Background() + created, err := s.CreateCSIDriver(ctx, &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, DriverName: "nfs.csi.k8s.io", ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "10.0.0.1", Port: 12345}, + }) + if err != nil { + t.Fatalf("CreateCSIDriver failed: %v", err) + } + _, err = s.UpdateCSIDriver(ctx, "csi-nfs", store.PreconditionFrom(created), func(toUpdate *ateapi.CsiDriver) error { + if _, err := s.UpdateCSIDriver(ctx, "csi-nfs", store.PreconditionFrom(created), func(d *ateapi.CsiDriver) error { + d.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "10.0.0.2", Port: 12345} + return nil + }); err != nil { + return fmt.Errorf("concurrent update: %w", err) + } + toUpdate.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "10.0.0.3", Port: 12345} + return nil + }) + if !errors.Is(err, store.ErrVersionConflict) { + t.Fatalf("UpdateCSIDriver error = %v, want ErrVersionConflict", err) + } + if stored, err := s.GetCSIDriver(ctx, "csi-nfs"); err != nil || stored.GetControllerEndpoint().GetHost() != "10.0.0.2" || stored.GetControllerEndpoint().GetPort() != 12345 { + t.Errorf("GetCSIDriver = (%v, %v), want winning endpoint", stored, err) + } +} + +func TestCSIDriver_CorruptAndColumnTamper(t *testing.T) { + cases := []struct { + name, tamperSQL string + tamperArg any + }{ + {"corrupt proto", `UPDATE csi_drivers SET proto = $1 WHERE name = 'csi-nfs'`, []byte{0xff}}, + {"uid mismatch", `UPDATE csi_drivers SET uid = $1 WHERE name = 'csi-nfs'`, "tampered-uid"}, + {"version mismatch", `UPDATE csi_drivers SET version = $1 WHERE name = 'csi-nfs'`, int64(99)}, + {"driver_name mismatch", `UPDATE csi_drivers SET driver_name = $1 WHERE name = 'csi-nfs'`, "tampered.csi.k8s.io"}, + } + for _, tc := range cases { + t.Run(tc.name, func(t *testing.T) { + s := setupPostgresPersistence(t) + ctx := context.Background() + created, err := s.CreateCSIDriver(ctx, &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, DriverName: "nfs.csi.k8s.io", ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "10.0.0.1", Port: 12345}, + }) + if err != nil { + t.Fatalf("CreateCSIDriver failed: %v", err) + } + if _, err := s.pool.Exec(ctx, tc.tamperSQL, tc.tamperArg); err != nil { + t.Fatalf("tampering csi_drivers row: %v", err) + } + for op, fn := range map[string]func() error{ + "GetCSIDriver": func() error { _, err := s.GetCSIDriver(ctx, "csi-nfs"); return err }, + "ListCSIDrivers": func() error { _, err := s.ListCSIDrivers(ctx, store.ListOptions{PageSize: 10}); return err }, + "UpdateCSIDriver": func() error { + _, err := s.UpdateCSIDriver(ctx, "csi-nfs", store.PreconditionFrom(created), func(*ateapi.CsiDriver) error { return nil }) + return err + }, + "DeleteCSIDriver": func() error { + _, err := s.DeleteCSIDriver(ctx, "csi-nfs", store.Precondition{}) + return err + }, + } { + if err := fn(); err == nil { + t.Errorf("%s succeeded on tampered row, want error", op) + } + } + }) + } +} diff --git a/cmd/ateapi/internal/store/atepg/egress_policy.go b/cmd/ateapi/internal/store/atepg/egress_policy.go index f3fdbf1c8a..86adb86ab3 100644 --- a/cmd/ateapi/internal/store/atepg/egress_policy.go +++ b/cmd/ateapi/internal/store/atepg/egress_policy.go @@ -56,7 +56,7 @@ func (p *Persistence) GetEgressPolicy(ctx context.Context, actorRef resources.Ac } func (p *Persistence) UpdateEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapi.EgressPolicy) error) (*ateapi.EgressPolicy, error) { - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } dbPolicy, err := getEgressPolicyRow(ctx, p.pool, ` @@ -74,8 +74,7 @@ func (p *Persistence) UpdateEgressPolicy(ctx context.Context, actorRef resources if err := mutate(dbPolicy); err != nil { return nil, err } - dbPolicy.Metadata = oldMeta - setUpdateMetadata(dbPolicy.Metadata, oldMeta) + dbPolicy.Metadata = setUpdateMetadata(oldMeta) protoBytes, err := proto.Marshal(dbPolicy) if err != nil { return nil, fmt.Errorf("marshaling updated egress policy: %w", err) @@ -96,7 +95,7 @@ func (p *Persistence) UpdateEgressPolicy(ctx context.Context, actorRef resources return dbPolicy, nil } -func (p *Persistence) DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.DeletePreconditions) (*ateapi.EgressPolicy, error) { +func (p *Persistence) DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition) (*ateapi.EgressPolicy, error) { var version int64 var uid string var protoBytes []byte diff --git a/cmd/ateapi/internal/store/atepg/egress_policy_test.go b/cmd/ateapi/internal/store/atepg/egress_policy_test.go new file mode 100644 index 0000000000..deb49a5687 --- /dev/null +++ b/cmd/ateapi/internal/store/atepg/egress_policy_test.go @@ -0,0 +1,50 @@ +// Copyright 2026 The Agent Substrate 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 atepg + +import ( + "context" + "testing" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/store" + "go.ate.dev/substrate/internal/resources" +) + +func TestUpdateEgressPolicy_DiscardsMetadataEdits(t *testing.T) { + ref := resources.ActorRef{Atespace: "team-a", Name: "a"} + testUpdateDiscardsMetadataEdits(t, + func(t *testing.T, s *Persistence) *ateapi.EgressPolicy { + if _, err := s.CreateActor(t.Context(), &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: ref.Atespace, Name: ref.Name}, + Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, + }); err != nil { + t.Fatalf("CreateActor failed: %v", err) + } + created, err := s.CreateEgressPolicy(t.Context(), ref, &ateapi.EgressPolicy{ + Metadata: &ateapi.ResourceMetadata{Atespace: ref.Atespace, Name: "default"}, + }) + if err != nil { + t.Fatalf("CreateEgressPolicy failed: %v", err) + } + return created + }, + func(ctx context.Context, s *Persistence, pc store.Precondition, mutate func(*ateapi.EgressPolicy) error) (*ateapi.EgressPolicy, error) { + return s.UpdateEgressPolicy(ctx, ref, pc, mutate) + }, + func(ctx context.Context, s *Persistence) (*ateapi.EgressPolicy, error) { + return s.GetEgressPolicy(ctx, ref) + }) +} diff --git a/cmd/ateapi/internal/store/atepg/external_volume.go b/cmd/ateapi/internal/store/atepg/external_volume.go new file mode 100644 index 0000000000..75a10b36ff --- /dev/null +++ b/cmd/ateapi/internal/store/atepg/external_volume.go @@ -0,0 +1,233 @@ +// Copyright 2026 The Agent Substrate 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 atepg + +import ( + "context" + "errors" + "fmt" + + "github.com/jackc/pgx/v5" + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/store" + "go.ate.dev/substrate/internal/resources" + "google.golang.org/protobuf/proto" +) + +func (p *Persistence) GetExternalVolume(ctx context.Context, volumeRef resources.ExternalVolumeRef) (*ateapi.ExternalVolume, error) { + atespace, name := volumeRef.Atespace, volumeRef.Name + var protoBytes []byte + if err := p.pool.QueryRow(ctx, ` + SELECT proto FROM external_volumes + WHERE atespace = $1 AND name = $2`, atespace, name).Scan(&protoBytes); err != nil { + if errors.Is(err, pgx.ErrNoRows) { + return nil, store.ErrNotFound + } + return nil, fmt.Errorf("getting external volume %s/%s: %w", atespace, name, err) + } + volume := &ateapi.ExternalVolume{} + if err := unmarshalStored(protoBytes, volume); err != nil { + return nil, fmt.Errorf("unmarshaling external volume: %w", err) + } + return volume, nil +} + +func (p *Persistence) ListExternalVolumes(ctx context.Context, atespace string, opts store.ListOptions) (store.ListResponse[*ateapi.ExternalVolume], error) { + opts, err := store.NormalizeListOptions(opts) + if err != nil { + return store.ListResponse[*ateapi.ExternalVolume]{}, err + } + var items []*ateapi.ExternalVolume + var nextToken string + if atespace != "" { + items, nextToken, err = p.listExternalVolumesScoped(ctx, atespace, opts.PageSize, opts.PageToken) + } else { + items, nextToken, err = p.listExternalVolumesGlobal(ctx, opts.PageSize, opts.PageToken) + } + if err != nil { + return store.ListResponse[*ateapi.ExternalVolume]{}, err + } + return store.ListResponse[*ateapi.ExternalVolume]{Items: items, NextPageToken: nextToken}, nil +} + +func (p *Persistence) listExternalVolumesScoped(ctx context.Context, atespace string, pageSize int32, pageTokenStr string) ([]*ateapi.ExternalVolume, string, error) { + token, err := decodePageToken(pageTokenStr, kindExternalVol, atespace, 1) + if err != nil { + return nil, "", err + } + var last *string + if len(token.Last) > 0 { + last = &token.Last[0] + } + rows, err := p.pool.Query(ctx, ` + SELECT name, proto FROM external_volumes + WHERE atespace = $1 AND ($2::text IS NULL OR name > $2) + ORDER BY name + LIMIT $3`, atespace, last, int64(pageSize)+1) + if err != nil { + return nil, "", fmt.Errorf("listing external volumes in %q: %w", atespace, err) + } + defer rows.Close() + + var names []string + var result []*ateapi.ExternalVolume + for rows.Next() { + var name string + var protoBytes []byte + if err := rows.Scan(&name, &protoBytes); err != nil { + return nil, "", fmt.Errorf("scanning external volume row: %w", err) + } + volume := &ateapi.ExternalVolume{} + if err := unmarshalRow(protoBytes, volume, "external volume", atespace, name); err != nil { + return nil, "", err + } + result = append(result, volume) + names = append(names, name) + } + if err := rows.Err(); err != nil { + return nil, "", fmt.Errorf("listing external volumes in %q: %w", atespace, err) + } + var nextToken string + if len(result) > int(pageSize) { + result = result[:pageSize] + nextToken = encodePageToken(kindExternalVol, atespace, []string{names[pageSize-1]}) + } + return result, nextToken, nil +} + +func (p *Persistence) listExternalVolumesGlobal(ctx context.Context, pageSize int32, pageTokenStr string) ([]*ateapi.ExternalVolume, string, error) { + token, err := decodePageToken(pageTokenStr, kindExternalVol, "", 2) + if err != nil { + return nil, "", err + } + var lastAtespace, lastName *string + if len(token.Last) == 2 { + lastAtespace, lastName = &token.Last[0], &token.Last[1] + } + rows, err := p.pool.Query(ctx, ` + SELECT atespace, name, proto FROM external_volumes + WHERE $1::text IS NULL OR (atespace, name) > ($1, $2) + ORDER BY atespace, name + LIMIT $3`, lastAtespace, lastName, int64(pageSize)+1) + if err != nil { + return nil, "", fmt.Errorf("listing external volumes: %w", err) + } + defer rows.Close() + + type key struct{ atespace, name string } + var keys []key + var result []*ateapi.ExternalVolume + for rows.Next() { + var k key + var protoBytes []byte + if err := rows.Scan(&k.atespace, &k.name, &protoBytes); err != nil { + return nil, "", fmt.Errorf("scanning external volume row: %w", err) + } + volume := &ateapi.ExternalVolume{} + if err := unmarshalRow(protoBytes, volume, "external volume", k.atespace, k.name); err != nil { + return nil, "", err + } + result = append(result, volume) + keys = append(keys, k) + } + if err := rows.Err(); err != nil { + return nil, "", fmt.Errorf("listing external volumes: %w", err) + } + var nextToken string + if len(result) > int(pageSize) { + result = result[:pageSize] + last := keys[pageSize-1] + nextToken = encodePageToken(kindExternalVol, "", []string{last.atespace, last.name}) + } + return result, nextToken, nil +} + +func (p *Persistence) CreateExternalVolume(ctx context.Context, volume *ateapi.ExternalVolume) (*ateapi.ExternalVolume, error) { + atespace := volume.GetMetadata().GetAtespace() + name := volume.GetMetadata().GetName() + dbVolume := proto.CloneOf(volume) + setCreateMetadata(dbVolume.Metadata) + protoBytes, err := proto.Marshal(dbVolume) + if err != nil { + return nil, fmt.Errorf("marshaling external volume: %w", err) + } + + tx, err := p.pool.Begin(ctx) + if err != nil { + return nil, fmt.Errorf("beginning external volume create: %w", err) + } + defer tx.Rollback(ctx) //nolint:errcheck // no-op once committed + + _, err = tx.Exec(ctx, ` + INSERT INTO external_volumes (atespace, name, uid, version, proto) + VALUES ($1, $2, $3, $4, $5)`, atespace, name, + dbVolume.GetMetadata().GetUid(), dbVolume.GetMetadata().GetVersion(), protoBytes) + if err != nil { + if isUniqueViolation(err) { + return nil, store.ErrAlreadyExists + } + if isForeignKeyViolation(err) { + switch pgErrConstraint(err) { + case "external_volumes_atespace_fk": + return nil, store.ErrFailedPrecondition + default: + return nil, fmt.Errorf("inserting external volume %s/%s violated unknown foreign key %q: %w", atespace, name, pgErrConstraint(err), err) + } + } + return nil, fmt.Errorf("inserting external volume %s/%s: %w", atespace, name, err) + } + // The key row holds the one-record-per-volume rule; it goes when the + // record does. A record with no CSI volume yet has no key. + if csi := dbVolume.GetStatus().GetCsi(); csi != nil { + _, err = tx.Exec(ctx, ` + INSERT INTO external_volume_keys (driver_name, volume_id, record_atespace, record_name) + VALUES ($1, $2, $3, $4)`, csi.GetDriverName(), csi.GetVolumeId(), atespace, name) + if err != nil { + if isUniqueViolation(err) { + return nil, store.ErrVolumeRegistered + } + return nil, fmt.Errorf("inserting external volume key for %s/%s: %w", atespace, name, err) + } + } + if err := tx.Commit(ctx); err != nil { + return nil, fmt.Errorf("committing external volume create %s/%s: %w", atespace, name, err) + } + return dbVolume, nil +} + +func (p *Persistence) DeleteExternalVolume(ctx context.Context, volumeRef resources.ExternalVolumeRef, precondition store.Precondition) (*ateapi.ExternalVolume, error) { + atespace, name := volumeRef.Atespace, volumeRef.Name + var protoBytes []byte + err := p.pool.QueryRow(ctx, ` + DELETE FROM external_volumes + WHERE atespace = $1 AND name = $2 + AND ($3::text = '' OR uid = $3::text) + AND ($4::bigint = 0 OR version = $4::bigint) + RETURNING proto`, atespace, name, precondition.UID, precondition.Version).Scan(&protoBytes) + if errors.Is(err, pgx.ErrNoRows) { + var uid string + var version int64 + err := p.pool.QueryRow(ctx, `SELECT uid, version FROM external_volumes WHERE atespace = $1 AND name = $2`, atespace, name).Scan(&uid, &version) + return nil, mapDeleteError(err, uid, version, precondition) + } + if err != nil { + return nil, fmt.Errorf("deleting external volume %s/%s: %w", atespace, name, err) + } + volume := &ateapi.ExternalVolume{} + if err := unmarshalStored(protoBytes, volume); err != nil { + return nil, fmt.Errorf("unmarshaling deleted external volume: %w", err) + } + return volume, nil +} diff --git a/cmd/ateapi/internal/store/atepg/migrations/000002_csi_drivers.sql b/cmd/ateapi/internal/store/atepg/migrations/000002_csi_drivers.sql new file mode 100644 index 0000000000..772476c1d4 --- /dev/null +++ b/cmd/ateapi/internal/store/atepg/migrations/000002_csi_drivers.sql @@ -0,0 +1,25 @@ +-- Copyright 2026 The Agent Substrate 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. + +-- +goose Up + +-- CsiDrivers are global-scoped, so name alone is the primary key. +-- driver_name is unique so at most one CsiDriver addresses each CSI driver. +CREATE TABLE csi_drivers ( + name text PRIMARY KEY, + uid text NOT NULL, + version bigint NOT NULL, + driver_name text NOT NULL CONSTRAINT csi_drivers_driver_name_key UNIQUE, + proto bytea NOT NULL +); diff --git a/cmd/ateapi/internal/store/atepg/migrations/000003_external_volumes.sql b/cmd/ateapi/internal/store/atepg/migrations/000003_external_volumes.sql new file mode 100644 index 0000000000..ddf7cd045d --- /dev/null +++ b/cmd/ateapi/internal/store/atepg/migrations/000003_external_volumes.sql @@ -0,0 +1,43 @@ +-- Copyright 2026 The Agent Substrate 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. + +-- +goose Up + +-- RESTRICT so that deleting an atespace cannot strand registered storage. +CREATE TABLE external_volumes ( + atespace text NOT NULL, + name text NOT NULL, + uid text NOT NULL, + version bigint NOT NULL, + proto bytea NOT NULL, + PRIMARY KEY (atespace, name), + CONSTRAINT external_volumes_atespace_fk + FOREIGN KEY (atespace) REFERENCES atespaces(name) ON DELETE RESTRICT +); + +-- One record per storage volume across all atespaces. A table of its own, +-- because a unique key without the atespace cannot live on external_volumes +-- once that is partitioned by atespace (TestActorsTablePartitionable). +CREATE TABLE external_volume_keys ( + driver_name text NOT NULL, + volume_id text NOT NULL, + record_atespace text NOT NULL, + record_name text NOT NULL, + PRIMARY KEY (driver_name, volume_id), + UNIQUE (record_atespace, record_name), + CHECK (driver_name <> '' AND volume_id <> ''), + CONSTRAINT external_volume_keys_record_fk + FOREIGN KEY (record_atespace, record_name) + REFERENCES external_volumes(atespace, name) ON DELETE CASCADE +); diff --git a/cmd/ateapi/internal/store/atepg/outbox_test.go b/cmd/ateapi/internal/store/atepg/outbox_test.go index 382ff3a187..d0eee5158f 100644 --- a/cmd/ateapi/internal/store/atepg/outbox_test.go +++ b/cmd/ateapi/internal/store/atepg/outbox_test.go @@ -376,7 +376,7 @@ func TestWorkerEvents_OneRowPerTransaction(t *testing.T) { t.Fatalf("UpdateWorker %d failed: %v", i, err) } } - if _, err := s.DeleteWorker(ctx, "one-row-worker", store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteWorker(ctx, "one-row-worker", store.Precondition{}); err != nil { t.Fatalf("DeleteWorker failed: %v", err) } @@ -1109,7 +1109,7 @@ func TestLocalPublishReachesWatchers(t *testing.T) { t.Error("locally published Worker aliases the caller's returned Worker; it must be a copy") } - if _, err := p.DeleteWorker(ctx, created.GetMetadata().GetName(), store.DeletePreconditions{}); err != nil { + if _, err := p.DeleteWorker(ctx, created.GetMetadata().GetName(), store.Precondition{}); err != nil { t.Fatalf("DeleteWorker failed: %v", err) } ev = nextEvent("delete", store.WorkerEventDeleted) @@ -1153,7 +1153,7 @@ func TestLocalPublishSurvivesWatchClose(t *testing.T) { if err != nil { t.Fatalf("CreateWorker failed: %v", err) } - if _, err := p.DeleteWorker(ctx, w.GetMetadata().GetName(), store.DeletePreconditions{}); err != nil { + if _, err := p.DeleteWorker(ctx, w.GetMetadata().GetName(), store.Precondition{}); err != nil { t.Fatalf("DeleteWorker failed: %v", err) } <-done diff --git a/cmd/ateapi/internal/store/atepg/pagetoken.go b/cmd/ateapi/internal/store/atepg/pagetoken.go index 5c8354c229..0b1c30d078 100644 --- a/cmd/ateapi/internal/store/atepg/pagetoken.go +++ b/cmd/ateapi/internal/store/atepg/pagetoken.go @@ -35,8 +35,10 @@ const ( kindActor resourceKind = "actor" kindActorTemplate resourceKind = "actor-template" kindTag resourceKind = "tag" + kindExternalVol resourceKind = "external-volume" kindWorker resourceKind = "worker" kindWorkerAssign resourceKind = "worker-assignment" + kindCSIDriver resourceKind = "csi-driver" ) // pageToken is PostgreSQL's opaque keyset page token. It carries no database diff --git a/cmd/ateapi/internal/store/atepg/partition_test.go b/cmd/ateapi/internal/store/atepg/partition_test.go index b5fc8ab742..766771b3e3 100644 --- a/cmd/ateapi/internal/store/atepg/partition_test.go +++ b/cmd/ateapi/internal/store/atepg/partition_test.go @@ -45,7 +45,7 @@ func TestActorsTablePartitionable(t *testing.T) { // by definition, under each partition key. spansPartitions := map[string][]string{ // A global list walks every atespace. - "atespace": {globalList("actors"), globalList("actor_templates"), globalList("tags")}, + "atespace": {globalList("actors"), globalList("actor_templates"), globalList("tags"), globalList("external_volumes")}, // A global list walks every name, and a list within one atespace // spans every name hash. "name": {globalList("actors"), scopedActorList}, diff --git a/cmd/ateapi/internal/store/atepg/tag.go b/cmd/ateapi/internal/store/atepg/tag.go index b8e66bdb00..31cf60ebba 100644 --- a/cmd/ateapi/internal/store/atepg/tag.go +++ b/cmd/ateapi/internal/store/atepg/tag.go @@ -188,50 +188,18 @@ func (p *Persistence) CreateTag(ctx context.Context, tag *ateapi.Tag) (*ateapi.T return dbTag, nil } -func isAllowedTagSnapshotTransition(stored, mutated *ateapi.Snapshot) bool { - if proto.Equal(stored, mutated) || stored == nil { - return true - } - if mutated == nil || stored.GetDurableSnapshot() == nil || mutated.GetDurableSnapshot() == nil { - return false - } - if stored.GetDurableSnapshot().GetState() != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_PENDING || - mutated.GetDurableSnapshot().GetState() != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED { - return false - } - expected := proto.CloneOf(stored) - expected.DurableSnapshot.State = ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED - return proto.Equal(expected, mutated) -} - -func validateUpdateTagMutation(storedTag, mutatedTag *ateapi.Tag) error { - if stored, mutated := storedTag.GetMetadata().GetAtespace(), mutatedTag.GetMetadata().GetAtespace(); stored != mutated { - return fmt.Errorf("metadata.atespace is immutable: mutation changed it from %q to %q", stored, mutated) - } - if stored, mutated := storedTag.GetMetadata().GetName(), mutatedTag.GetMetadata().GetName(); stored != mutated { - return fmt.Errorf("metadata.name is immutable: mutation changed it from %q to %q", stored, mutated) - } - if stored, mutated := storedTag.GetStatus().GetSnapshot(), mutatedTag.GetStatus().GetSnapshot(); !isAllowedTagSnapshotTransition(stored, mutated) { - return fmt.Errorf("status.snapshot is immutable once set: mutation changed it from %s to %s", stored, mutated) - } - if stored, mutated := storedTag.GetStatus().GetActorTemplateUid(), mutatedTag.GetStatus().GetActorTemplateUid(); stored != mutated { - return fmt.Errorf("status.actor_template_uid is immutable: mutation changed it from %q to %q", stored, mutated) - } - return nil -} - func (p *Persistence) UpdateTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(*ateapi.Tag) error) (*ateapi.Tag, error) { - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } - return p.updateTag(ctx, tagRef, store.DeletePreconditions(precondition), mutate, false) + return p.updateTag(ctx, tagRef, precondition, mutate, false) } -func (p *Persistence) MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions, mutate func(*ateapi.Tag) error) (*ateapi.Tag, error) { +func (p *Persistence) MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(*ateapi.Tag) error) (*ateapi.Tag, error) { return p.updateTag(ctx, tagRef, precondition, mutate, true) } -func (p *Persistence) updateTag(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions, mutate func(*ateapi.Tag) error, markForDeletion bool) (*ateapi.Tag, error) { +func (p *Persistence) updateTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition, mutate func(*ateapi.Tag) error, markForDeletion bool) (*ateapi.Tag, error) { atespace, name := tagRef.Atespace, tagRef.Name var currentUID string var currentVersion int64 @@ -255,23 +223,18 @@ func (p *Persistence) updateTag(ctx context.Context, tagRef resources.TagRef, pr if err := precondition.Check(dbTag.GetMetadata()); err != nil { return nil, err } - tagBeforeMutation := proto.Clone(dbTag).(*ateapi.Tag) oldMeta := proto.CloneOf(dbTag.Metadata) if mutate != nil { if err := mutate(dbTag); err != nil { return nil, err } } - // TODO: this should be done through DV and removed from here - if err := validateUpdateTagMutation(tagBeforeMutation, dbTag); err != nil { - return nil, fmt.Errorf("%w: %w", store.ErrImmutableField, err) - } if err := validateSnapshotURIs(fmt.Sprintf("tag %s/%s", atespace, name), dbTag.GetStatus().GetSnapshot()); err != nil { return nil, err } // Stored metadata is authoritative; discard any metadata edits made by the // closure and derive the next revision from the state this attempt read. - setUpdateMetadata(dbTag.Metadata, oldMeta) + dbTag.Metadata = setUpdateMetadata(oldMeta) if markForDeletion && dbTag.Metadata.DeleteTime == nil { dbTag.Metadata.DeleteTime = proto.CloneOf(dbTag.Metadata.UpdateTime) } @@ -297,7 +260,7 @@ func (p *Persistence) updateTag(ctx context.Context, tagRef resources.TagRef, pr return dbTag, nil } -func (p *Persistence) DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.DeletePreconditions) (*ateapi.Tag, error) { +func (p *Persistence) DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition store.Precondition) (*ateapi.Tag, error) { atespace, name := tagRef.Atespace, tagRef.Name var protoBytes []byte err := p.pool.QueryRow(ctx, ` diff --git a/cmd/ateapi/internal/store/atepg/tag_test.go b/cmd/ateapi/internal/store/atepg/tag_test.go index 5b0b37f8ac..6bdae654c7 100644 --- a/cmd/ateapi/internal/store/atepg/tag_test.go +++ b/cmd/ateapi/internal/store/atepg/tag_test.go @@ -62,7 +62,7 @@ func TestUpdateTag_CASPreventsDeleteRecreateABA(t *testing.T) { var recreated *ateapi.Tag _, err := s.UpdateTag(ctx, resources.TagRef{Atespace: "team-a", Name: "tag-a"}, store.PreconditionFrom(original), func(toUpdate *ateapi.Tag) error { mutations++ - if _, err := s.DeleteTag(ctx, resources.TagRef{Atespace: "team-a", Name: "tag-a"}, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteTag(ctx, resources.TagRef{Atespace: "team-a", Name: "tag-a"}, store.Precondition{}); err != nil { return fmt.Errorf("deleting original tag: %w", err) } recreated = createTestTag(t, s, "team-a", "tag-a") @@ -98,3 +98,17 @@ func TestCreateTag_TagForeignKeyErrors(t *testing.T) { t.Errorf("missing tag atespace error = %v, want ErrFailedPrecondition", err) } } + +func TestUpdateTag_DiscardsMetadataEdits(t *testing.T) { + ref := resources.TagRef{Atespace: "team-a", Name: "tag-a"} + testUpdateDiscardsMetadataEdits(t, + func(t *testing.T, s *Persistence) *ateapi.Tag { + return createTestTag(t, s, ref.Atespace, ref.Name) + }, + func(ctx context.Context, s *Persistence, pc store.Precondition, mutate func(*ateapi.Tag) error) (*ateapi.Tag, error) { + return s.UpdateTag(ctx, ref, pc, mutate) + }, + func(ctx context.Context, s *Persistence) (*ateapi.Tag, error) { + return s.GetTag(ctx, ref) + }) +} diff --git a/cmd/ateapi/internal/store/atepg/worker.go b/cmd/ateapi/internal/store/atepg/worker.go index 16d249f2cf..6a97d64bef 100644 --- a/cmd/ateapi/internal/store/atepg/worker.go +++ b/cmd/ateapi/internal/store/atepg/worker.go @@ -100,17 +100,17 @@ func getWorkerRowForUpdate(ctx context.Context, tx pgx.Tx, name string) (*ateapi // compare-and-set. The predicate cannot be pushed into SQL: the row stores an // opaque marshaled proto, so assignment is not addressable in a WHERE clause. func (p *Persistence) UpdateWorker(ctx context.Context, name string, precondition store.Precondition, mutate func(*ateapi.Worker) error) (*ateapi.Worker, error) { - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } - return p.updateWorker(ctx, name, store.DeletePreconditions(precondition), mutate, false) + return p.updateWorker(ctx, name, precondition, mutate, false) } -func (p *Persistence) MarkWorkerForDeletion(ctx context.Context, name string, precondition store.DeletePreconditions, mutate func(*ateapi.Worker) error) (*ateapi.Worker, error) { +func (p *Persistence) MarkWorkerForDeletion(ctx context.Context, name string, precondition store.Precondition, mutate func(*ateapi.Worker) error) (*ateapi.Worker, error) { return p.updateWorker(ctx, name, precondition, mutate, true) } -func (p *Persistence) updateWorker(ctx context.Context, name string, precondition store.DeletePreconditions, mutate func(*ateapi.Worker) error, markForDeletion bool) (*ateapi.Worker, error) { +func (p *Persistence) updateWorker(ctx context.Context, name string, precondition store.Precondition, mutate func(*ateapi.Worker) error, markForDeletion bool) (*ateapi.Worker, error) { return p.writeAndAppendEvent(ctx, store.WorkerEventUpdated, func(ctx context.Context, tx pgx.Tx) (*ateapi.Worker, error) { dbWorker, err := getWorkerRowForUpdate(ctx, tx, name) if err != nil { @@ -131,7 +131,7 @@ func (p *Persistence) updateWorker(ctx context.Context, name string, preconditio } // Stored metadata is authoritative; discard any metadata edits made by // the closure and derive the next revision from the row we locked. - setUpdateMetadata(dbWorker.Metadata, oldMeta) + dbWorker.Metadata = setUpdateMetadata(oldMeta) if markForDeletion && dbWorker.Metadata.DeleteTime == nil { dbWorker.Metadata.DeleteTime = proto.CloneOf(dbWorker.Metadata.UpdateTime) } @@ -156,7 +156,7 @@ func (p *Persistence) updateWorker(ctx context.Context, name string, preconditio }) } -func (p *Persistence) DeleteWorker(ctx context.Context, name string, precondition store.DeletePreconditions) (*ateapi.Worker, error) { +func (p *Persistence) DeleteWorker(ctx context.Context, name string, precondition store.Precondition) (*ateapi.Worker, error) { return p.writeAndAppendEvent(ctx, store.WorkerEventDeleted, func(ctx context.Context, tx pgx.Tx) (*ateapi.Worker, error) { // Locked rather than plainly read so the incarnation precondition was evaluated // against is the one the DELETE removes. diff --git a/cmd/ateapi/internal/store/atepg/worker_assignment.go b/cmd/ateapi/internal/store/atepg/worker_assignment.go index 0a0a4dc1da..6652ce1cc8 100644 --- a/cmd/ateapi/internal/store/atepg/worker_assignment.go +++ b/cmd/ateapi/internal/store/atepg/worker_assignment.go @@ -39,7 +39,7 @@ func getWorkerForUpdate(ctx context.Context, tx pgx.Tx, name string) (*ateapi.Wo return nil, fmt.Errorf("locking worker %s: %w", name, err) } worker := &ateapi.Worker{} - if err := proto.Unmarshal(protoBytes, worker); err != nil { + if err := unmarshalStored(protoBytes, worker); err != nil { return nil, fmt.Errorf("unmarshaling worker: %w", err) } return worker, nil @@ -48,20 +48,22 @@ func getWorkerForUpdate(ctx context.Context, tx pgx.Tx, name string) (*ateapi.Wo // saveWorker writes back a Worker whose allocation just moved, at the next // version. This assumes the caller holds the row lock getWorkerForUpdate took. func saveWorker(ctx context.Context, tx pgx.Tx, worker *ateapi.Worker) error { - read := proto.CloneOf(worker.GetMetadata()) - setUpdateMetadata(worker.GetMetadata(), worker.GetMetadata()) + currentUID := worker.GetMetadata().GetUid() + currentVersion := worker.GetMetadata().GetVersion() + worker.Metadata = setUpdateMetadata(worker.Metadata) protoBytes, err := proto.Marshal(worker) if err != nil { return fmt.Errorf("marshaling worker: %w", err) } - // Callers hold the row lock getWorkerForUpdate took, so this matches the + meta := worker.GetMetadata() + // Callers hold the row lock for this worker, so this matches the // row they read. It is stated anyway so a caller that skipped the lock // fails loudly instead of overwriting a newer Worker, and so a row that is // gone is an error rather than an update of nothing. tag, err := tx.Exec(ctx, `UPDATE workers SET version = $1, proto = $2 WHERE name = $3 AND uid = $4 AND version = $5`, - worker.GetMetadata().GetVersion(), protoBytes, read.GetName(), read.GetUid(), read.GetVersion()) + meta.GetVersion(), protoBytes, meta.GetName(), currentUID, currentVersion) if err != nil { - return fmt.Errorf("updating worker %s: %w", read.GetName(), err) + return fmt.Errorf("updating worker %s: %w", meta.GetName(), err) } if tag.RowsAffected() != 1 { return store.ErrVersionConflict @@ -74,7 +76,7 @@ func (p *Persistence) BindActorToWorker(ctx context.Context, workerName string, if actorUID == "" { return nil, fmt.Errorf("binding an assignment with no actor_uid to worker %s", workerName) } - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, err } if precondition.UID != actorUID { @@ -110,7 +112,7 @@ func (p *Persistence) BindActorToWorker(ctx context.Context, workerName string, } // The Actor's version check settles concurrent binds of it: every bind // updates the Actor, so all but the first fail it. - if updated, err = updateActor(ctx, tx, actorRef, store.DeletePreconditions(precondition), mutate, false); err != nil { + if updated, err = updateActor(ctx, tx, actorRef, precondition, mutate, false); err != nil { return nil, err } if _, err := tx.Exec(ctx, ` @@ -132,7 +134,7 @@ func (p *Persistence) BindActorToWorker(ctx context.Context, workerName string, } func (p *Persistence) UpdateActorAndRelease(ctx context.Context, actorRef resources.ActorRef, precondition store.Precondition, mutate func(*ateapi.Actor) error) (*ateapi.Actor, *ateapi.Worker, error) { - if err := precondition.Validate(); err != nil { + if err := precondition.ValidateRequired(); err != nil { return nil, nil, err } actorUID := precondition.UID @@ -144,7 +146,7 @@ func (p *Persistence) UpdateActorAndRelease(ctx context.Context, actorRef resour } // A row released since the caller read the Actor also moved the // Actor on, so its version check fails here. - if updated, err = updateActor(ctx, tx, actorRef, store.DeletePreconditions(precondition), mutate, false); err != nil { + if updated, err = updateActor(ctx, tx, actorRef, precondition, mutate, false); err != nil { return nil, err } return released, nil @@ -190,7 +192,7 @@ func releaseActor(ctx context.Context, tx pgx.Tx, actorUID string) (*ateapi.Work return nil, fmt.Errorf("releasing actor %s from worker %s: %w", actorUID, workerName, err) } assignment := &ateapi.ActorAssignment{} - if err := proto.Unmarshal(protoBytes, assignment); err != nil { + if err := unmarshalStored(protoBytes, assignment); err != nil { return nil, fmt.Errorf("unmarshaling released assignment: %w", err) } worker.Status.Allocated = resources.AddToAllocated(worker.Status.Allocated, assignment, -1) @@ -216,7 +218,7 @@ func getAssignmentRow(ctx context.Context, q querier, actorUID string) (*ateapi. return nil, "", fmt.Errorf("getting assignment for actor %s: %w", actorUID, err) } assignment := &ateapi.ActorAssignment{} - if err := proto.Unmarshal(protoBytes, assignment); err != nil { + if err := unmarshalStored(protoBytes, assignment); err != nil { return nil, "", fmt.Errorf("unmarshaling assignment: %w", err) } return assignment, workerName, nil @@ -269,7 +271,7 @@ func (p *Persistence) ListWorkerAssignments(ctx context.Context, workerName stri return store.ListResponse[*ateapi.ActorAssignment]{}, fmt.Errorf("scanning assignment of worker %s: %w", workerName, err) } assignment := &ateapi.ActorAssignment{} - if err := proto.Unmarshal(protoBytes, assignment); err != nil { + if err := unmarshalStored(protoBytes, assignment); err != nil { return store.ListResponse[*ateapi.ActorAssignment]{}, fmt.Errorf("unmarshaling assignment of actor %s: %w", actorUID, err) } result = append(result, assignment) diff --git a/cmd/ateapi/internal/store/atepg/worker_assignment_test.go b/cmd/ateapi/internal/store/atepg/worker_assignment_test.go index b94053d485..18381b4d3d 100644 --- a/cmd/ateapi/internal/store/atepg/worker_assignment_test.go +++ b/cmd/ateapi/internal/store/atepg/worker_assignment_test.go @@ -89,7 +89,7 @@ func TestSaveWorker_RejectsAVanishedWorker(t *testing.T) { if err != nil { t.Fatalf("CreateWorker failed: %v", err) } - if _, err := p.DeleteWorker(ctx, created.GetMetadata().GetName(), store.DeletePreconditions{}); err != nil { + if _, err := p.DeleteWorker(ctx, created.GetMetadata().GetName(), store.Precondition{}); err != nil { t.Fatalf("DeleteWorker failed: %v", err) } diff --git a/cmd/ateapi/internal/store/atepg/worker_test.go b/cmd/ateapi/internal/store/atepg/worker_test.go new file mode 100644 index 0000000000..b7a74d7ea1 --- /dev/null +++ b/cmd/ateapi/internal/store/atepg/worker_test.go @@ -0,0 +1,40 @@ +// Copyright 2026 The Agent Substrate 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 atepg + +import ( + "context" + "testing" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/store" +) + +func TestUpdateWorker_DiscardsMetadataEdits(t *testing.T) { + testUpdateDiscardsMetadataEdits(t, + func(t *testing.T, s *Persistence) *ateapi.Worker { + created, err := s.CreateWorker(t.Context(), &ateapi.Worker{Metadata: &ateapi.ResourceMetadata{Name: "w"}}) + if err != nil { + t.Fatalf("CreateWorker failed: %v", err) + } + return created + }, + func(ctx context.Context, s *Persistence, pc store.Precondition, mutate func(*ateapi.Worker) error) (*ateapi.Worker, error) { + return s.UpdateWorker(ctx, "w", pc, mutate) + }, + func(ctx context.Context, s *Persistence) (*ateapi.Worker, error) { + return s.GetWorker(ctx, "w") + }) +} diff --git a/cmd/ateapi/internal/store/store.go b/cmd/ateapi/internal/store/store.go index c91e83f9c9..bcb8d125ab 100644 --- a/cmd/ateapi/internal/store/store.go +++ b/cmd/ateapi/internal/store/store.go @@ -40,6 +40,10 @@ var ( // ErrFailedPrecondition indicates the object is not in the required state for the operation. ErrFailedPrecondition = errors.New("persistence: failed precondition") + // ErrDriverNameAlreadyExists indicates that a CSIDriver with the same + // driver_name is already registered. It wraps ErrFailedPrecondition. + ErrDriverNameAlreadyExists = fmt.Errorf("%w: driver_name already registered", ErrFailedPrecondition) + // ErrWorkerNotFound indicates BindActorToWorker found no Worker to bind // to. It is distinct from ErrNotFound, which the bind returns for a // missing Actor. @@ -64,9 +68,9 @@ var ( // missing either guard (uid or version). Blind writes are not accepted. ErrPreconditionRequired = errors.New("persistence: precondition required") - // ErrImmutableField indicates an update's mutation changed a field that is - // immutable for the lifetime of the stored object. - ErrImmutableField = errors.New("persistence: immutable field") + // ErrVolumeRegistered indicates another ExternalVolume, in any atespace, + // already names the same driver_name and volume_id. + ErrVolumeRegistered = errors.New("persistence: volume already registered") ) // Interface defines the contract for the persistence layer storing actor state. @@ -110,13 +114,15 @@ type Interface interface { // update the actor's status. Returns ErrNotFound if missing, // ErrUIDConflict/ErrVersionConflict if precondition fails or a concurrent // write wins, or mutate's error. - MarkActorForDeletion(ctx context.Context, actorRef resources.ActorRef, precondition DeletePreconditions, mutate func(toUpdate *ateapi.Actor) error) (*ateapi.Actor, error) + // Each precondition guard is optional: an unset one is not checked. + MarkActorForDeletion(ctx context.Context, actorRef resources.ActorRef, precondition Precondition, mutate func(toUpdate *ateapi.Actor) error) (*ateapi.Actor, error) // Removes an actor and returns the deleted resource. Returns ErrNotFound if // missing, ErrUIDConflict/ErrVersionConflict if precondition does not // describe the actor the caller observed, or ErrFailedPrecondition if the // actor's status.worker_assignment is set. - DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition DeletePreconditions) (*ateapi.Actor, error) + // Each precondition guard is optional: an unset one is not checked. + DeleteActor(ctx context.Context, actorRef resources.ActorRef, precondition Precondition) (*ateapi.Actor, error) // Creates the 1:1 policy subresource for an existing Actor. CreateEgressPolicy(ctx context.Context, actorRef resources.ActorRef, policy *ateapi.EgressPolicy) (*ateapi.EgressPolicy, error) @@ -124,11 +130,14 @@ type Interface interface { GetEgressPolicy(ctx context.Context, actorRef resources.ActorRef) (*ateapi.EgressPolicy, error) // Transactionally updates an Actor's policy when its current UID and version // match the precondition. + // Both precondition guards are required. Returns ErrPreconditionRequired if + // either is unset. UpdateEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition Precondition, mutate func(*ateapi.EgressPolicy) error) (*ateapi.EgressPolicy, error) // Deletes and returns an Actor's policy subresource. Returns ErrNotFound if // missing, or ErrUIDConflict/ErrVersionConflict if precondition does not // describe the policy the caller observed. - DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition DeletePreconditions) (*ateapi.EgressPolicy, error) + // Each precondition guard is optional: an unset one is not checked. + DeleteEgressPolicy(ctx context.Context, actorRef resources.ActorRef, precondition Precondition) (*ateapi.EgressPolicy, error) // CreateTag creates an immutable tag to an actor snapshot. // @@ -160,11 +169,8 @@ type Interface interface { // // Returns ErrPreconditionRequired if the precondition omits either guard, // ErrNotFound if missing, ErrUIDConflict or ErrVersionConflict if the - // precondition no longer holds, ErrVersionConflict if the retry budget is - // exhausted, ErrImmutableField if the mutated tag changed a field that is - // immutable for its lifetime, or the mutate's error verbatim otherwise. - // - // status.snapshot is immutable once set + // respective preconditions fail, ErrVersionConflict if the retry budget is + // exhausted, or mutate's own error otherwise. UpdateTag(ctx context.Context, tagRef resources.TagRef, precondition Precondition, mutate func(toUpdate *ateapi.Tag) error) (*ateapi.Tag, error) // MarkTagForDeletion initiates the deletion of a tag. It sets @@ -172,12 +178,33 @@ type Interface interface { // update the tag's status. Returns ErrNotFound if missing, // ErrUIDConflict/ErrVersionConflict if precondition fails or a concurrent // write wins, or mutate's error. - MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition DeletePreconditions, mutate func(toUpdate *ateapi.Tag) error) (*ateapi.Tag, error) + // Each precondition guard is optional: an unset one is not checked. + MarkTagForDeletion(ctx context.Context, tagRef resources.TagRef, precondition Precondition, mutate func(toUpdate *ateapi.Tag) error) (*ateapi.Tag, error) // Deletes and returns a tag. Returns ErrNotFound if missing, or // ErrUIDConflict/ErrVersionConflict if precondition does not describe the // tag the caller observed. - DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition DeletePreconditions) (*ateapi.Tag, error) + // Each precondition guard is optional: an unset one is not checked. + DeleteTag(ctx context.Context, tagRef resources.TagRef, precondition Precondition) (*ateapi.Tag, error) + + // Stores a new external volume and returns the stored resource with + // server-assigned metadata. The input is not mutated. Returns + // ErrAlreadyExists if the name is taken, ErrVolumeRegistered if another + // external volume already names the same status.csi driver_name and + // volume_id, or ErrFailedPrecondition if the atespace does not exist. + CreateExternalVolume(ctx context.Context, volume *ateapi.ExternalVolume) (*ateapi.ExternalVolume, error) + + // Fetches an external volume by reference. Returns ErrNotFound if missing. + GetExternalVolume(ctx context.Context, volumeRef resources.ExternalVolumeRef) (*ateapi.ExternalVolume, error) + + // Lists external volumes in one atespace, or in all atespaces when atespace + // is empty. + ListExternalVolumes(ctx context.Context, atespace string, opts ListOptions) (ListResponse[*ateapi.ExternalVolume], error) + + // Deletes an external volume record and returns it. Returns ErrNotFound if + // missing, and ErrUIDConflict or ErrVersionConflict when precondition does + // not match the stored record. The storage the record names is left alone. + DeleteExternalVolume(ctx context.Context, volumeRef resources.ExternalVolumeRef, precondition Precondition) (*ateapi.ExternalVolume, error) // Stores a new atespace and returns the stored resource with server-assigned // metadata (uid, version, timestamps). The input is not mutated. Returns @@ -195,7 +222,8 @@ type Interface interface { // does not describe the atespace the caller observed, or // ErrFailedPrecondition if the atespace is not empty (e.g. there are actors // in it). - DeleteAtespace(ctx context.Context, name string, precondition DeletePreconditions) (*ateapi.Atespace, error) + // Each precondition guard is optional: an unset one is not checked. + DeleteAtespace(ctx context.Context, name string, precondition Precondition) (*ateapi.Atespace, error) // Creates the deployment-wide global access policy singleton. CreateGlobalAccessPolicy(ctx context.Context, policy *ateapi.AccessPolicy) (*ateapi.AccessPolicy, error) @@ -203,6 +231,8 @@ type Interface interface { GetGlobalAccessPolicy(ctx context.Context) (*ateapi.AccessPolicy, error) // Transactionally updates the deployment-wide global access policy singleton // when its current UID and version match the precondition. + // Both precondition guards are required. Returns ErrPreconditionRequired if + // either is unset. UpdateGlobalAccessPolicy(ctx context.Context, precondition Precondition, mutate func(*ateapi.AccessPolicy) error) (*ateapi.AccessPolicy, error) // Creates the 1:1 access policy subresource for an existing Atespace. @@ -211,11 +241,33 @@ type Interface interface { GetAtespaceAccessPolicy(ctx context.Context, name string) (*ateapi.AccessPolicy, error) // Transactionally updates an Atespace's access policy when its current UID // and version match the precondition. + // Both precondition guards are required. Returns ErrPreconditionRequired if + // either is unset. UpdateAtespaceAccessPolicy(ctx context.Context, name string, precondition Precondition, mutate func(*ateapi.AccessPolicy) error) (*ateapi.AccessPolicy, error) // Deletes and returns an Atespace's access policy subresource. Returns // ErrNotFound if missing, or ErrUIDConflict/ErrVersionConflict if // precondition does not describe the policy the caller observed. - DeleteAtespaceAccessPolicy(ctx context.Context, name string, precondition DeletePreconditions) (*ateapi.AccessPolicy, error) + // Each precondition guard is optional: an unset one is not checked. + DeleteAtespaceAccessPolicy(ctx context.Context, name string, precondition Precondition) (*ateapi.AccessPolicy, error) + + // Stores a new CSIDriver and returns the stored resource with + // server-assigned metadata. Returns ErrAlreadyExists if metadata.name is + // taken, or ErrDriverNameAlreadyExists (which wraps ErrFailedPrecondition) + // if driver_name is taken. + CreateCSIDriver(ctx context.Context, driver *ateapi.CsiDriver) (*ateapi.CsiDriver, error) + + // Fetches a CSIDriver by metadata.name. Returns ErrNotFound if missing. + GetCSIDriver(ctx context.Context, name string) (*ateapi.CsiDriver, error) + + // Lists CSIDrivers ordered by metadata.name. + ListCSIDrivers(ctx context.Context, opts ListOptions) (ListResponse[*ateapi.CsiDriver], error) + + // UpdateCSIDriver updates a CSIDriver via guarded read-modify-write and + // returns the stored driver with advanced metadata. + UpdateCSIDriver(ctx context.Context, name string, precondition Precondition, mutate func(toUpdate *ateapi.CsiDriver) error) (*ateapi.CsiDriver, error) + + // Removes a CSIDriver and returns the deleted resource. + DeleteCSIDriver(ctx context.Context, name string, precondition Precondition) (*ateapi.CsiDriver, error) // Stores a new ActorTemplate and returns the stored resource with // server-assigned metadata (uid, version, timestamps). The input is not @@ -242,12 +294,14 @@ type Interface interface { // non-nil, so callers can update the template's status. Returns ErrNotFound // if missing, ErrUIDConflict/ErrVersionConflict if precondition fails or a // concurrent write wins, or mutate's error. - MarkActorTemplateForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition DeletePreconditions, mutate func(toUpdate *ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) + // Each precondition guard is optional: an unset one is not checked. + MarkActorTemplateForDeletion(ctx context.Context, templateRef resources.ActorTemplateRef, precondition Precondition, mutate func(toUpdate *ateapi.ActorTemplate) error) (*ateapi.ActorTemplate, error) // Removes an ActorTemplate and returns the deleted resource. Returns // ErrNotFound if missing, or ErrUIDConflict/ErrVersionConflict if // precondition does not describe the template the caller observed. - DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition DeletePreconditions) (*ateapi.ActorTemplate, error) + // Each precondition guard is optional: an unset one is not checked. + DeleteActorTemplate(ctx context.Context, templateRef resources.ActorTemplateRef, precondition Precondition) (*ateapi.ActorTemplate, error) // Registers a new idle worker and returns the stored resource with // server-assigned metadata (uid, version, timestamps). The input is not @@ -278,13 +332,15 @@ type Interface interface { // update the worker's status. Returns ErrNotFound if missing, // ErrUIDConflict/ErrVersionConflict if precondition fails or a concurrent // write wins, or mutate's error. - MarkWorkerForDeletion(ctx context.Context, name string, precondition DeletePreconditions, mutate func(toUpdate *ateapi.Worker) error) (*ateapi.Worker, error) + // Each precondition guard is optional: an unset one is not checked. + MarkWorkerForDeletion(ctx context.Context, name string, precondition Precondition, mutate func(toUpdate *ateapi.Worker) error) (*ateapi.Worker, error) // Removes a worker by name and returns the deleted resource. Returns // ErrNotFound if missing, ErrUIDConflict/ErrVersionConflict if // precondition does not describe the worker the caller observed, or // ErrFailedPrecondition if the worker still holds an assignment. - DeleteWorker(ctx context.Context, name string, precondition DeletePreconditions) (*ateapi.Worker, error) + // Each precondition guard is optional: an unset one is not checked. + DeleteWorker(ctx context.Context, name string, precondition Precondition) (*ateapi.Worker, error) // An assignment is written only together with its Actor, and Worker // allocation moves with it, so an Actor names a Worker in @@ -295,13 +351,15 @@ type Interface interface { // BindActorToWorker assigns an Actor, updates the Worker's allocation, and // applies mutate to the Actor as UpdateActor does, all in one transaction. // It returns the updated Actor. precondition must name the assignment's - // Actor, and mutate should point the Actor at the Worker. + // Actor with both guards set, and mutate should point the Actor at the + // Worker. // // admit decides whether the Worker will take the Actor, and runs against the // Worker as it stands with its row locked, so the answer cannot go stale // between the check and the bind. Returning an error from it refuses the // bind and is returned unchanged. // + // ErrPreconditionRequired if precondition omits either guard, // ErrWorkerNotFound if the Worker is gone, ErrNotFound if the Actor is, and // ErrUIDConflict/ErrVersionConflict if precondition fails. Binding an Actor // that is already bound is an error. Any error leaves both unchanged. @@ -313,6 +371,9 @@ type Interface interface { // clear the Actor's worker assignment. It returns the updated Actor and // released Worker after commit, or nil Worker if none was bound. Any error // leaves both unchanged. + // + // Both precondition guards are required. Returns ErrPreconditionRequired if + // either is unset. UpdateActorAndRelease(ctx context.Context, actorRef resources.ActorRef, precondition Precondition, mutate func(toUpdate *ateapi.Actor) error) (*ateapi.Actor, *ateapi.Worker, error) // GetWorkerAssignment returns a Worker's assignment for actorUID, or @@ -335,45 +396,18 @@ type Interface interface { AcquireLease(ctx context.Context, key string) (*Lease, error) } -// Precondition guards an update with the uid and version the caller observed: -// the write lands only if the stored object still matches both. Both fields are -// required. +// Precondition holds validation checks that allow callers to enforce that +// a mutated resource has a given UID and/or version. Useful for implementing +// optimistic locking. type Precondition struct { - // UID is the incarnation the write is for. - UID string - // Version is the revision the write is against. - Version int64 -} - -// DeletePreconditions pins the object incarnation a delete may act on. Unlike -// Precondition, whose guards an update requires, each guard here is -// independently waivable: the zero value pins nothing, which is what an -// unguarded delete wants. -type DeletePreconditions struct { - // UID accepts only the object carrying it; empty accepts whichever object - // holds the name at delete time. + // A precondition that validates the mutated resource still has this + // UID. If not set, no validation is performed. UID string - // Version accepts only that revision; zero accepts whatever revision the - // store is at. + // A precondition that validates the mutated resource still is at this + // version. If not set, no validation is performed. Version int64 } -// Check reports whether md still describes the object the caller observed. -// A waived guard is not checked. The uid is reported first: a new incarnation -// makes the version meaningless. -// -// Returns ErrUIDConflict or ErrVersionConflict, which the delete surfaces -// verbatim. -func (p DeletePreconditions) Check(md *ateapi.ResourceMetadata) error { - if p.UID != "" && p.UID != md.GetUid() { - return ErrUIDConflict - } - if p.Version != 0 && p.Version != md.GetVersion() { - return ErrVersionConflict - } - return nil -} - // hasResourceMetadata is an object the store addresses by atespace and name, // and whose identity a caller can guard with a Precondition. type hasResourceMetadata interface { @@ -387,10 +421,10 @@ func PreconditionFrom(observed hasResourceMetadata) Precondition { return Precondition{UID: md.GetUid(), Version: md.GetVersion()} } -// Validate reports whether the precondition carries both required guards (uid and version) +// ValidateRequired reports whether the precondition carries both guards. // -// Returns ErrPreconditionRequired, which the update surfaces verbatim. -func (p Precondition) Validate() error { +// Returns an error matching ErrPreconditionRequired. +func (p Precondition) ValidateRequired() error { if p.UID == "" { return fmt.Errorf("%w: uid", ErrPreconditionRequired) } @@ -400,13 +434,17 @@ func (p Precondition) Validate() error { return nil } -// Check reports whether md still matches the guards p carries. The uid is reported -// first: a new incarnation makes the version meaningless. +// Checks whether a given resource passes a given set of preconditions. +// An unset guard is not checked. +// The uid check is reported first: a new incarnation makes the version +// meaningless. +// +// Returns ErrUIDConflict or ErrVersionConflict. func (p Precondition) Check(md *ateapi.ResourceMetadata) error { - if p.UID != md.GetUid() { + if p.UID != "" && p.UID != md.GetUid() { return ErrUIDConflict } - if p.Version != md.GetVersion() { + if p.Version != 0 && p.Version != md.GetVersion() { return ErrVersionConflict } return nil diff --git a/cmd/ateapi/internal/store/store_test.go b/cmd/ateapi/internal/store/store_test.go index cd4b276745..61dfe18ea2 100644 --- a/cmd/ateapi/internal/store/store_test.go +++ b/cmd/ateapi/internal/store/store_test.go @@ -46,7 +46,6 @@ func TestPreconditionCheck(t *testing.T) { { name: "the guarded object is still the stored one", precondition: Precondition{UID: storedUID, Version: storedVer}, - wantErr: nil, }, { name: "the name now addresses a different incarnation", @@ -65,6 +64,27 @@ func TestPreconditionCheck(t *testing.T) { precondition: Precondition{UID: staleUID, Version: staleVer}, wantErr: ErrUIDConflict, }, + { + name: "no guards", + }, + { + name: "uid only", + precondition: Precondition{UID: storedUID}, + }, + { + name: "stale uid only", + precondition: Precondition{UID: staleUID}, + wantErr: ErrUIDConflict, + }, + { + name: "version only", + precondition: Precondition{Version: storedVer}, + }, + { + name: "stale version only", + precondition: Precondition{Version: staleVer}, + wantErr: ErrVersionConflict, + }, } for _, tt := range tests { @@ -76,7 +96,7 @@ func TestPreconditionCheck(t *testing.T) { } } -func TestPreconditionValidate(t *testing.T) { +func TestPreconditionValidateRequired(t *testing.T) { tests := []struct { name string precondition Precondition @@ -106,8 +126,8 @@ func TestPreconditionValidate(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - if err := tt.precondition.Validate(); !errors.Is(err, tt.wantErr) { - t.Errorf("Validate() = %v, want one matching %v", err, tt.wantErr) + if err := tt.precondition.ValidateRequired(); !errors.Is(err, tt.wantErr) { + t.Errorf("ValidateRequired() = %v, want one matching %v", err, tt.wantErr) } }) } @@ -152,8 +172,8 @@ func TestPreconditionFrom(t *testing.T) { if got != tt.want { t.Errorf("PreconditionFrom(observed) = %+v, want %+v", got, tt.want) } - if err := got.Validate(); !errors.Is(err, tt.wantValidateErr) { - t.Errorf("PreconditionFrom(observed).Validate() = %v, want one matching %v", err, tt.wantValidateErr) + if err := got.ValidateRequired(); !errors.Is(err, tt.wantValidateErr) { + t.Errorf("PreconditionFrom(observed).ValidateRequired() = %v, want one matching %v", err, tt.wantValidateErr) } }) } diff --git a/cmd/ateapi/internal/store/storecontract/contract.go b/cmd/ateapi/internal/store/storecontract/contract.go index 301b24988b..9215294f39 100644 --- a/cmd/ateapi/internal/store/storecontract/contract.go +++ b/cmd/ateapi/internal/store/storecontract/contract.go @@ -215,7 +215,7 @@ type markForDeletionCase[R any, T resourceMessage] struct { create func(context.Context, T) (T, error) get func(context.Context, R) (T, error) update func(context.Context, R, store.Precondition, func(T) error) (T, error) - mark func(context.Context, R, store.DeletePreconditions, func(T) error) (T, error) + mark func(context.Context, R, store.Precondition, func(T) error) (T, error) // mutate, if set, is passed to the first mark, and mutated reports whether // it landed in the same write. mutate func(T) error @@ -249,16 +249,16 @@ func testMarkForDeletion[R any, T resourceMessage](t *testing.T, c markForDeleti t.Errorf("a plain update set delete_time to %v, want it ignored", smuggled.GetMetadata().GetDeleteTime()) } - if _, err := c.mark(ctx, c.ref, store.DeletePreconditions{UID: "other-uid"}, nil); !errors.Is(err, store.ErrUIDConflict) { + if _, err := c.mark(ctx, c.ref, store.Precondition{UID: "other-uid"}, nil); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("mark with a foreign uid = %v, want ErrUIDConflict", err) } - if _, err := c.mark(ctx, c.ref, store.DeletePreconditions{Version: created.GetMetadata().GetVersion()}, nil); !errors.Is(err, store.ErrVersionConflict) { + if _, err := c.mark(ctx, c.ref, store.Precondition{Version: created.GetMetadata().GetVersion()}, nil); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("mark with a stale version = %v, want ErrVersionConflict", err) } // mutate's refusal writes nothing, so nothing is stamped. refused := errors.New("refused") - if _, err := c.mark(ctx, c.ref, store.DeletePreconditions{}, func(T) error { return refused }); !errors.Is(err, refused) { + if _, err := c.mark(ctx, c.ref, store.Precondition{}, func(T) error { return refused }); !errors.Is(err, refused) { t.Errorf("mark with a refusing mutate = %v, want it verbatim", err) } unmarked, err := c.get(ctx, c.ref) @@ -270,7 +270,7 @@ func testMarkForDeletion[R any, T resourceMessage](t *testing.T, c markForDeleti } // Unguarded, so the version having moved since created was read is fine. - marked, err := c.mark(ctx, c.ref, store.DeletePreconditions{}, c.mutate) + marked, err := c.mark(ctx, c.ref, store.Precondition{}, c.mutate) if err != nil { t.Fatalf("mark failed: %v", err) } @@ -307,12 +307,12 @@ func testMarkForDeletion[R any, T resourceMessage](t *testing.T, c markForDeleti } // The guards still bite after the mark: a version from before it is stale. - if _, err := c.mark(ctx, c.ref, store.DeletePreconditions{Version: smuggled.GetMetadata().GetVersion()}, nil); !errors.Is(err, store.ErrVersionConflict) { + if _, err := c.mark(ctx, c.ref, store.Precondition{Version: smuggled.GetMetadata().GetVersion()}, nil); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("mark after the first with a stale version = %v, want ErrVersionConflict", err) } // A second mark writes but keeps the first stamp. - again, err := c.mark(ctx, c.ref, store.DeletePreconditions{UID: cleared.GetMetadata().GetUid()}, nil) + again, err := c.mark(ctx, c.ref, store.Precondition{UID: cleared.GetMetadata().GetUid()}, nil) if err != nil { t.Fatalf("second mark failed: %v", err) } @@ -336,8 +336,10 @@ func RunContractTests(t *testing.T, setup func(t *testing.T) store.Interface) { runWorkerContractTests(t, setup) runWorkerAssignmentContractTests(t, setup) runAtespaceContractTests(t, setup) + runCSIDriverContractTests(t, setup) runActorTemplateContractTests(t, setup) runTagContractTests(t, setup) + runExternalVolumeContractTests(t, setup) runLeaseContractTests(t, setup) runListOptionsContractTests(t, setup) runUnknownFieldContractTests(t, setup) @@ -397,7 +399,7 @@ func runEgressPolicyContractTests(t *testing.T, setup func(t *testing.T) store.I if err != nil || updated.GetMetadata().GetAtespace() != testAtespace || updated.GetMetadata().GetName() != "default" || updated.GetMetadata().GetVersion() != 2 || updated.GetMetadata().GetUid() != created.GetMetadata().GetUid() { t.Fatalf("UpdateEgressPolicy = %v, %v; want version 2", updated, err) } - deleted, err := s.DeleteEgressPolicy(ctx, actorRef, store.DeletePreconditions{}) + deleted, err := s.DeleteEgressPolicy(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("DeleteEgressPolicy failed: %v", err) } @@ -429,42 +431,42 @@ func runEgressPolicyContractTests(t *testing.T, setup func(t *testing.T) store.I } return created } - del := func(precondition store.DeletePreconditions) error { + del := func(precondition store.Precondition) error { _, err := s.DeleteEgressPolicy(ctx, actorRef, precondition) return err } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { + if err := del(store.Precondition{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { t.Errorf("guarded delete of a missing policy = %v, want ErrNotFound", err) } policy := create() uid, version := policy.GetMetadata().GetUid(), policy.GetMetadata().GetVersion() - if err := del(store.DeletePreconditions{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("stale version alone = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("matching uid, stale version = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid alone = %v, want ErrUIDConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid, matching version = %v, want ErrUIDConflict", err) } if _, err := s.GetEgressPolicy(ctx, actorRef); err != nil { t.Fatalf("a refused delete removed the policy: %v", err) } - if err := del(store.DeletePreconditions{Version: version}); err != nil { + if err := del(store.Precondition{Version: version}); err != nil { t.Fatalf("matching version alone = %v, want nil", err) } policy = create() - if err := del(store.DeletePreconditions{UID: policy.GetMetadata().GetUid()}); err != nil { + if err := del(store.Precondition{UID: policy.GetMetadata().GetUid()}); err != nil { t.Fatalf("matching uid alone = %v, want nil", err) } policy = create() - if err := del(store.DeletePreconditions{UID: policy.GetMetadata().GetUid(), Version: policy.GetMetadata().GetVersion()}); err != nil { + if err := del(store.Precondition{UID: policy.GetMetadata().GetUid(), Version: policy.GetMetadata().GetVersion()}); err != nil { t.Fatalf("matching uid and version = %v, want nil", err) } if _, err := s.GetEgressPolicy(ctx, actorRef); !errors.Is(err, store.ErrNotFound) { @@ -493,7 +495,7 @@ func runEgressPolicyContractTests(t *testing.T, setup func(t *testing.T) store.I if _, err := s.CreateEgressPolicy(ctx, actorRef, policy); err != nil { t.Fatal(err) } - if _, err := s.DeleteActor(ctx, actorRef, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatal(err) } if _, err := s.GetEgressPolicy(ctx, actorRef); !errors.Is(err, store.ErrNotFound) { @@ -529,7 +531,9 @@ func runListOptionsContractTests(t *testing.T, setup func(t *testing.T) store.In {"actors", func(opts store.ListOptions) error { _, err := s.ListActors(ctx, "", opts); return err }}, {"actor templates", func(opts store.ListOptions) error { _, err := s.ListActorTemplates(ctx, "", opts); return err }}, {"tags", func(opts store.ListOptions) error { _, err := s.ListTags(ctx, "", opts); return err }}, + {"external volumes", func(opts store.ListOptions) error { _, err := s.ListExternalVolumes(ctx, "", opts); return err }}, {"workers", func(opts store.ListOptions) error { _, err := s.ListWorkers(ctx, opts); return err }}, + {"csi drivers", func(opts store.ListOptions) error { _, err := s.ListCSIDrivers(ctx, opts); return err }}, } for _, call := range calls { t.Run(call.name, func(t *testing.T) { @@ -554,7 +558,9 @@ func runListOptionsContractTests(t *testing.T, setup func(t *testing.T) store.In {"actors", func(opts store.ListOptions) error { _, err := s.ListActors(ctx, "", opts); return err }}, {"actor templates", func(opts store.ListOptions) error { _, err := s.ListActorTemplates(ctx, "", opts); return err }}, {"tags", func(opts store.ListOptions) error { _, err := s.ListTags(ctx, "", opts); return err }}, + {"external volumes", func(opts store.ListOptions) error { _, err := s.ListExternalVolumes(ctx, "", opts); return err }}, {"workers", func(opts store.ListOptions) error { _, err := s.ListWorkers(ctx, opts); return err }}, + {"csi drivers", func(opts store.ListOptions) error { _, err := s.ListCSIDrivers(ctx, opts); return err }}, } for _, call := range calls { t.Run(call.name, func(t *testing.T) { @@ -789,7 +795,7 @@ func runActorContractTests(t *testing.T, setup func(t *testing.T) store.Interfac }); err != nil { t.Fatalf("marking actor deleting failed: %v", err) } - if _, err := s.DeleteActor(ctx, actorRef, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatalf("DeleteActor failed: %v", err) } recreated, err := s.CreateActor(ctx, newActor()) @@ -943,7 +949,7 @@ func runActorContractTests(t *testing.T, setup func(t *testing.T) store.Interfac t.Fatalf("CreateActor failed: %v", err) } - deleted, err := s.DeleteActor(ctx, actorRef, store.DeletePreconditions{}) + deleted, err := s.DeleteActor(ctx, actorRef, store.Precondition{}) if err != nil { t.Fatalf("DeleteActor failed: %v", err) } @@ -961,7 +967,7 @@ func runActorContractTests(t *testing.T, setup func(t *testing.T) store.Interfac s := setup(t) ctx := context.Background() - if _, err := s.DeleteActor(ctx, resources.ActorRef{Atespace: testAtespace, Name: "non-existent"}, store.DeletePreconditions{}); !errors.Is(err, store.ErrNotFound) { + if _, err := s.DeleteActor(ctx, resources.ActorRef{Atespace: testAtespace, Name: "non-existent"}, store.Precondition{}); !errors.Is(err, store.ErrNotFound) { t.Errorf("expected ErrNotFound deleting non-existent actor, got %v", err) } }) @@ -978,42 +984,42 @@ func runActorContractTests(t *testing.T, setup func(t *testing.T) store.Interfac } return created } - del := func(precondition store.DeletePreconditions) error { + del := func(precondition store.Precondition) error { _, err := s.DeleteActor(ctx, actorRef, precondition) return err } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { + if err := del(store.Precondition{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { t.Errorf("guarded delete of a missing actor = %v, want ErrNotFound", err) } actor := create() uid, version := actor.GetMetadata().GetUid(), actor.GetMetadata().GetVersion() - if err := del(store.DeletePreconditions{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("stale version alone = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("matching uid, stale version = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid alone = %v, want ErrUIDConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid, matching version = %v, want ErrUIDConflict", err) } if _, err := s.GetActor(ctx, actorRef); err != nil { t.Fatalf("a refused delete removed the actor: %v", err) } - if err := del(store.DeletePreconditions{Version: version}); err != nil { + if err := del(store.Precondition{Version: version}); err != nil { t.Fatalf("matching version alone = %v, want nil", err) } actor = create() - if err := del(store.DeletePreconditions{UID: actor.GetMetadata().GetUid()}); err != nil { + if err := del(store.Precondition{UID: actor.GetMetadata().GetUid()}); err != nil { t.Fatalf("matching uid alone = %v, want nil", err) } actor = create() - if err := del(store.DeletePreconditions{UID: actor.GetMetadata().GetUid(), Version: actor.GetMetadata().GetVersion()}); err != nil { + if err := del(store.Precondition{UID: actor.GetMetadata().GetUid(), Version: actor.GetMetadata().GetVersion()}); err != nil { t.Fatalf("matching uid and version = %v, want nil", err) } if _, err := s.GetActor(ctx, actorRef); !errors.Is(err, store.ErrNotFound) { @@ -1218,7 +1224,7 @@ func runActorTemplateContractTests(t *testing.T, setup func(t *testing.T) store. t.Errorf("stored template mismatch (-created +got):\n%s", diff) } - if _, err := s.DeleteActorTemplate(ctx, templateRef, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteActorTemplate(ctx, templateRef, store.Precondition{}); err != nil { t.Fatalf("DeleteActorTemplate failed: %v", err) } }) @@ -1235,42 +1241,42 @@ func runActorTemplateContractTests(t *testing.T, setup func(t *testing.T) store. } return created } - del := func(precondition store.DeletePreconditions) error { + del := func(precondition store.Precondition) error { _, err := s.DeleteActorTemplate(ctx, ref, precondition) return err } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { + if err := del(store.Precondition{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { t.Errorf("guarded delete of a missing template = %v, want ErrNotFound", err) } template := create() uid, version := template.GetMetadata().GetUid(), template.GetMetadata().GetVersion() - if err := del(store.DeletePreconditions{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("stale version alone = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("matching uid, stale version = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid alone = %v, want ErrUIDConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid, matching version = %v, want ErrUIDConflict", err) } if _, err := s.GetActorTemplate(ctx, ref); err != nil { t.Fatalf("a refused delete removed the template: %v", err) } - if err := del(store.DeletePreconditions{Version: version}); err != nil { + if err := del(store.Precondition{Version: version}); err != nil { t.Fatalf("matching version alone = %v, want nil", err) } template = create() - if err := del(store.DeletePreconditions{UID: template.GetMetadata().GetUid()}); err != nil { + if err := del(store.Precondition{UID: template.GetMetadata().GetUid()}); err != nil { t.Fatalf("matching uid alone = %v, want nil", err) } template = create() - if err := del(store.DeletePreconditions{UID: template.GetMetadata().GetUid(), Version: template.GetMetadata().GetVersion()}); err != nil { + if err := del(store.Precondition{UID: template.GetMetadata().GetUid(), Version: template.GetMetadata().GetVersion()}); err != nil { t.Fatalf("matching uid and version = %v, want nil", err) } if _, err := s.GetActorTemplate(ctx, ref); !errors.Is(err, store.ErrNotFound) { @@ -1340,7 +1346,7 @@ func runActorTemplateContractTests(t *testing.T, setup func(t *testing.T) store. if _, err := s.CreateActorTemplate(ctx, newTestActorTemplate("team-a", "tmpl-a")); err != nil { t.Fatalf("CreateActorTemplate failed: %v", err) } - if _, err := s.DeleteAtespace(ctx, "team-a", store.DeletePreconditions{}); !errors.Is(err, store.ErrFailedPrecondition) { + if _, err := s.DeleteAtespace(ctx, "team-a", store.Precondition{}); !errors.Is(err, store.ErrFailedPrecondition) { t.Errorf("DeleteAtespace with template = %v, want ErrFailedPrecondition", err) } }) @@ -1473,11 +1479,11 @@ func runTagContractTests(t *testing.T, setup func(t *testing.T) store.Interface) }); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("stale UpdateTag = %v, want ErrVersionConflict", err) } - if _, err := s.DeleteAtespace(ctx, "team-a", store.DeletePreconditions{}); !errors.Is(err, store.ErrFailedPrecondition) { + if _, err := s.DeleteAtespace(ctx, "team-a", store.Precondition{}); !errors.Is(err, store.ErrFailedPrecondition) { t.Errorf("DeleteAtespace with tag = %v, want ErrFailedPrecondition", err) } - deleted, err := s.DeleteTag(ctx, resources.TagRef{Atespace: "team-a", Name: "production"}, store.DeletePreconditions{}) + deleted, err := s.DeleteTag(ctx, resources.TagRef{Atespace: "team-a", Name: "production"}, store.Precondition{}) if err != nil || !proto.Equal(deleted, updated) { t.Errorf("DeleteTag = (%v, %v), want updated tag", deleted, err) } @@ -1502,42 +1508,42 @@ func runTagContractTests(t *testing.T, setup func(t *testing.T) store.Interface) } return created } - del := func(precondition store.DeletePreconditions) error { + del := func(precondition store.Precondition) error { _, err := s.DeleteTag(ctx, tagRef, precondition) return err } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { + if err := del(store.Precondition{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { t.Errorf("guarded delete of a missing tag = %v, want ErrNotFound", err) } tag := create() uid, version := tag.GetMetadata().GetUid(), tag.GetMetadata().GetVersion() - if err := del(store.DeletePreconditions{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("stale version alone = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("matching uid, stale version = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid alone = %v, want ErrUIDConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid, matching version = %v, want ErrUIDConflict", err) } if _, err := s.GetTag(ctx, tagRef); err != nil { t.Fatalf("a refused delete removed the tag: %v", err) } - if err := del(store.DeletePreconditions{Version: version}); err != nil { + if err := del(store.Precondition{Version: version}); err != nil { t.Fatalf("matching version alone = %v, want nil", err) } tag = create() - if err := del(store.DeletePreconditions{UID: tag.GetMetadata().GetUid()}); err != nil { + if err := del(store.Precondition{UID: tag.GetMetadata().GetUid()}); err != nil { t.Fatalf("matching uid alone = %v, want nil", err) } tag = create() - if err := del(store.DeletePreconditions{UID: tag.GetMetadata().GetUid(), Version: tag.GetMetadata().GetVersion()}); err != nil { + if err := del(store.Precondition{UID: tag.GetMetadata().GetUid(), Version: tag.GetMetadata().GetVersion()}); err != nil { t.Fatalf("matching uid and version = %v, want nil", err) } if _, err := s.GetTag(ctx, tagRef); !errors.Is(err, store.ErrNotFound) { @@ -1545,53 +1551,6 @@ func runTagContractTests(t *testing.T, setup func(t *testing.T) store.Interface) } }) - t.Run("Tag_ImmutableFields", func(t *testing.T) { - s := setup(t) - ctx := context.Background() - actor := seedSuspendedActor(t, s, "team-a", "actor-1") - tag := storeTag(t, s, newTestInProgressTag("production", actor)) - - tests := []struct { - name string - mutate func(*ateapi.Tag) - }{ - { - name: "snapshot uri", - mutate: func(toUpdate *ateapi.Tag) { - toUpdate.Status.Snapshot.DurableSnapshot.Object.SnapshotUri = "gs://private/elsewhere" - }, - }, - { - name: "snapshot content scope", - mutate: func(toUpdate *ateapi.Tag) { - toUpdate.Status.Snapshot.Fidelity = ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES - }, - }, - { - name: "clearing the snapshot", - mutate: func(toUpdate *ateapi.Tag) { - toUpdate.Status.Snapshot = nil - }, - }, - { - name: "actor template uid", - mutate: func(toUpdate *ateapi.Tag) { toUpdate.Status.ActorTemplateUid = "other-template-uid" }, - }, - } - - for _, tt := range tests { - t.Run(tt.name, func(t *testing.T) { - _, err := s.UpdateTag(ctx, resources.TagRef{Atespace: "team-a", Name: "production"}, store.PreconditionFrom(tag), func(toUpdate *ateapi.Tag) error { - tt.mutate(toUpdate) - return nil - }) - if !errors.Is(err, store.ErrImmutableField) { - t.Errorf("UpdateTag error = %v, want one matching store.ErrImmutableField", err) - } - }) - } - }) - t.Run("Tag_RecordSnapshotAfterReserve", func(t *testing.T) { s := setup(t) ctx := context.Background() @@ -1617,14 +1576,6 @@ func runTagContractTests(t *testing.T, setup func(t *testing.T) store.Interface) if diff := cmp.Diff(pending, recorded.GetStatus().GetSnapshot(), protocmp.Transform()); diff != "" { t.Errorf("recorded snapshot mismatch (-want +got):\n%s", diff) } - - // Once recorded, the snapshot is fixed like any other. - if _, err := s.UpdateTag(ctx, tagRef, store.PreconditionFrom(recorded), func(toUpdate *ateapi.Tag) error { - toUpdate.Status.Snapshot.DurableSnapshot.Object.SnapshotUri = "gs://private/elsewhere" - return nil - }); !errors.Is(err, store.ErrImmutableField) { - t.Errorf("rewriting a recorded snapshot = %v, want one matching store.ErrImmutableField", err) - } }) t.Run("CreateTag_ReusedTagName", func(t *testing.T) { @@ -1808,6 +1759,212 @@ func storeTag(t *testing.T, s store.Interface, tag *ateapi.Tag) *ateapi.Tag { return stored } +func newTestExternalVolume(atespace, name string) *ateapi.ExternalVolume { + return &ateapi.ExternalVolume{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: name}, + Status: &ateapi.ExternalVolumeStatus{Csi: &ateapi.CsiVolumeStatus{ + VolumeId: "filestore-" + atespace + "-" + name, + DriverName: "filestore.csi.storage.gke.io", + VolumeContext: map[string]string{"ip": "10.0.0.2"}, + }}, + } +} + +func storeExternalVolume(t *testing.T, s store.Interface, volume *ateapi.ExternalVolume) *ateapi.ExternalVolume { + t.Helper() + stored, err := s.CreateExternalVolume(context.Background(), volume) + if err != nil { + t.Fatalf("CreateExternalVolume(%q) failed: %v", volume.GetMetadata().GetName(), err) + } + return stored +} + +func runExternalVolumeContractTests(t *testing.T, setup func(t *testing.T) store.Interface) { + t.Helper() + + t.Run("ExternalVolume_Lifecycle", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + mustCreateAtespace(t, s, "team-a") + + input := newTestExternalVolume("team-a", "scratch") + created, err := s.CreateExternalVolume(ctx, input) + if err != nil { + t.Fatalf("CreateExternalVolume failed: %v", err) + } + if created.GetMetadata().GetVersion() != 1 || created.GetMetadata().GetUid() == "" { + t.Errorf("created volume metadata = %v, want server-owned uid and version 1", created.GetMetadata()) + } + if input.GetMetadata().GetUid() != "" || input.GetMetadata().GetVersion() != 0 { + t.Errorf("CreateExternalVolume mutated its input metadata: %v", input.GetMetadata()) + } + + volumeRef := resources.ExternalVolumeRef{Atespace: "team-a", Name: "scratch"} + volume, err := s.GetExternalVolume(ctx, volumeRef) + if err != nil { + t.Fatalf("GetExternalVolume failed: %v", err) + } + if diff := cmp.Diff(input, volume, protocmp.Transform(), ignoreUID, ignoreVersion, ignoreTimestamps); diff != "" { + t.Errorf("stored external volume mismatch (-want +got):\n%s", diff) + } + if _, err := s.GetExternalVolume(ctx, resources.ExternalVolumeRef{Atespace: "team-a", Name: "missing"}); !errors.Is(err, store.ErrNotFound) { + t.Errorf("missing GetExternalVolume = %v, want ErrNotFound", err) + } + if _, err := s.DeleteAtespace(ctx, "team-a", store.Precondition{}); !errors.Is(err, store.ErrFailedPrecondition) { + t.Errorf("DeleteAtespace with an external volume = %v, want ErrFailedPrecondition", err) + } + + if _, err := s.DeleteExternalVolume(ctx, volumeRef, store.Precondition{Version: volume.GetMetadata().GetVersion() + 1}); !errors.Is(err, store.ErrVersionConflict) { + t.Errorf("stale DeleteExternalVolume = %v, want ErrVersionConflict", err) + } + if _, err := s.DeleteExternalVolume(ctx, volumeRef, store.Precondition{UID: "another-lifecycle"}); !errors.Is(err, store.ErrUIDConflict) { + t.Errorf("DeleteExternalVolume with another uid = %v, want ErrUIDConflict", err) + } + deleted, err := s.DeleteExternalVolume(ctx, volumeRef, store.Precondition{UID: volume.GetMetadata().GetUid(), Version: volume.GetMetadata().GetVersion()}) + if err != nil || !proto.Equal(deleted, volume) { + t.Errorf("DeleteExternalVolume = (%v, %v), want the stored volume", deleted, err) + } + if _, err := s.GetExternalVolume(ctx, volumeRef); !errors.Is(err, store.ErrNotFound) { + t.Errorf("deleted GetExternalVolume = %v, want ErrNotFound", err) + } + if _, err := s.DeleteExternalVolume(ctx, volumeRef, store.Precondition{}); !errors.Is(err, store.ErrNotFound) { + t.Errorf("DeleteExternalVolume on a missing volume = %v, want ErrNotFound", err) + } + }) + + t.Run("CreateExternalVolume_ReusedName", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + mustCreateAtespace(t, s, "team-a") + input := newTestExternalVolume("team-a", "scratch") + if _, err := s.CreateExternalVolume(ctx, input); err != nil { + t.Fatalf("CreateExternalVolume failed: %v", err) + } + if _, err := s.CreateExternalVolume(ctx, input); !errors.Is(err, store.ErrAlreadyExists) { + t.Errorf("duplicate CreateExternalVolume = %v, want ErrAlreadyExists", err) + } + + stored, err := s.GetExternalVolume(ctx, resources.ExternalVolumeRef{Atespace: "team-a", Name: "scratch"}) + if err != nil { + t.Fatalf("GetExternalVolume failed: %v", err) + } + if stored.GetMetadata().GetVersion() != 1 { + t.Errorf("volume version after rejected create = %d, want 1", stored.GetMetadata().GetVersion()) + } + }) + + t.Run("CreateExternalVolume_ReusedVolume", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + mustCreateAtespace(t, s, "team-a") + mustCreateAtespace(t, s, "team-b") + first := storeExternalVolume(t, s, newTestExternalVolume("team-a", "scratch")) + + firstCSI := first.GetStatus().GetCsi() + same := newTestExternalVolume("team-b", "other") + same.Status.Csi.DriverName, same.Status.Csi.VolumeId = firstCSI.GetDriverName(), firstCSI.GetVolumeId() + if _, err := s.CreateExternalVolume(ctx, same); !errors.Is(err, store.ErrVolumeRegistered) { + t.Errorf("CreateExternalVolume naming a registered volume = %v, want ErrVolumeRegistered", err) + } + if _, err := s.GetExternalVolume(ctx, resources.ExternalVolumeRef{Atespace: "team-b", Name: "other"}); !errors.Is(err, store.ErrNotFound) { + t.Errorf("GetExternalVolume after the rejected create = %v, want ErrNotFound", err) + } + + // The key is the pair, so sharing one half is fine. + sameDriver := newTestExternalVolume("team-b", "same-driver") + sameDriver.Status.Csi.DriverName = firstCSI.GetDriverName() + storeExternalVolume(t, s, sameDriver) + sameID := newTestExternalVolume("team-b", "same-id") + sameID.Status.Csi.DriverName, sameID.Status.Csi.VolumeId = "other.csi.example.com", firstCSI.GetVolumeId() + storeExternalVolume(t, s, sameID) + + // Records with no CSI volume yet do not collide with each other. + for _, name := range []string{"unbound-1", "unbound-2"} { + unbound := newTestExternalVolume("team-b", name) + unbound.Status = nil + storeExternalVolume(t, s, unbound) + } + + // Deleting the record frees the volume for another record. + if _, err := s.DeleteExternalVolume(ctx, resources.ExternalVolumeRef{Atespace: "team-a", Name: "scratch"}, store.Precondition{}); err != nil { + t.Fatalf("DeleteExternalVolume failed: %v", err) + } + storeExternalVolume(t, s, same) + }) + + t.Run("CreateExternalVolume_EmptyCSIVolume", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + mustCreateAtespace(t, s, "team-a") + + empty := newTestExternalVolume("team-a", "scratch") + empty.Status.Csi = &ateapi.CsiVolumeStatus{} + if _, err := s.CreateExternalVolume(ctx, empty); err == nil { + t.Error("CreateExternalVolume with an empty CSI volume succeeded, want an error") + } + if _, err := s.GetExternalVolume(ctx, resources.ExternalVolumeRef{Atespace: "team-a", Name: "scratch"}); !errors.Is(err, store.ErrNotFound) { + t.Errorf("GetExternalVolume after the rejected create = %v, want ErrNotFound", err) + } + }) + + t.Run("CreateExternalVolume_UnknownAtespace", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + + if _, err := s.CreateExternalVolume(ctx, newTestExternalVolume("team-missing", "scratch")); !errors.Is(err, store.ErrFailedPrecondition) { + t.Errorf("CreateExternalVolume in an unknown atespace = %v, want ErrFailedPrecondition", err) + } + }) + + t.Run("ListExternalVolumes_PaginationAndScope", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + for _, atespace := range []string{"team-a", "team-b"} { + mustCreateAtespace(t, s, atespace) + for i := 0; i < 3; i++ { + storeExternalVolume(t, s, newTestExternalVolume(atespace, fmt.Sprintf("volume-%d", i))) + } + } + + var scoped []*ateapi.ExternalVolume + for token := ""; ; { + page, err := s.ListExternalVolumes(ctx, "team-a", store.ListOptions{PageSize: 2, PageToken: token}) + if err != nil { + t.Fatalf("scoped ListExternalVolumes failed: %v", err) + } + scoped = append(scoped, page.Items...) + if page.NextPageToken == "" { + break + } + token = page.NextPageToken + } + if len(scoped) != 3 { + t.Errorf("scoped ListExternalVolumes returned %d volumes, want 3", len(scoped)) + } + for _, volume := range scoped { + if volume.GetMetadata().GetAtespace() != "team-a" { + t.Errorf("scoped ListExternalVolumes returned %s/%s", volume.GetMetadata().GetAtespace(), volume.GetMetadata().GetName()) + } + } + + var global []*ateapi.ExternalVolume + for token := ""; ; { + page, err := s.ListExternalVolumes(ctx, "", store.ListOptions{PageSize: 2, PageToken: token}) + if err != nil { + t.Fatalf("global ListExternalVolumes failed: %v", err) + } + global = append(global, page.Items...) + if page.NextPageToken == "" { + break + } + token = page.NextPageToken + } + if len(global) != 6 { + t.Errorf("global ListExternalVolumes returned %d volumes, want 6", len(global)) + } + }) +} + func runWorkerContractTests(t *testing.T, setup func(t *testing.T) store.Interface) { t.Helper() @@ -2015,7 +2172,7 @@ func runWorkerContractTests(t *testing.T, setup func(t *testing.T) store.Interfa } defer watch.Close() - marked, err := s.MarkWorkerForDeletion(ctx, testWorkerName, store.DeletePreconditions{}, nil) + marked, err := s.MarkWorkerForDeletion(ctx, testWorkerName, store.Precondition{}, nil) if err != nil { t.Fatalf("mark failed: %v", err) } @@ -2039,7 +2196,7 @@ func runWorkerContractTests(t *testing.T, setup func(t *testing.T) store.Interfa if err != nil { t.Fatalf("CreateWorker failed: %v", err) } - if _, err := s.DeleteWorker(ctx, testWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteWorker(ctx, testWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker failed: %v", err) } recreated, err := s.CreateWorker(ctx, newTestWorker(testWorkerName, "pod-1")) @@ -2214,7 +2371,7 @@ func runWorkerContractTests(t *testing.T, setup func(t *testing.T) store.Interfa } defer watch.Close() - deleted, err := s.DeleteWorker(ctx, testWorkerName, store.DeletePreconditions{}) + deleted, err := s.DeleteWorker(ctx, testWorkerName, store.Precondition{}) if err != nil { t.Fatalf("DeleteWorker failed: %v", err) } @@ -2241,7 +2398,7 @@ func runWorkerContractTests(t *testing.T, setup func(t *testing.T) store.Interfa s := setup(t) ctx := context.Background() - if _, err := s.DeleteWorker(ctx, testWorkerName, store.DeletePreconditions{}); !errors.Is(err, store.ErrNotFound) { + if _, err := s.DeleteWorker(ctx, testWorkerName, store.Precondition{}); !errors.Is(err, store.ErrNotFound) { t.Errorf("expected ErrNotFound deleting a missing worker, got %v", err) } }) @@ -2256,42 +2413,42 @@ func runWorkerContractTests(t *testing.T, setup func(t *testing.T) store.Interfa } return created } - del := func(precondition store.DeletePreconditions) error { + del := func(precondition store.Precondition) error { _, err := s.DeleteWorker(ctx, testWorkerName, precondition) return err } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { + if err := del(store.Precondition{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { t.Errorf("guarded delete of a missing worker = %v, want ErrNotFound", err) } worker := create() uid, version := worker.GetMetadata().GetUid(), worker.GetMetadata().GetVersion() - if err := del(store.DeletePreconditions{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("stale version alone = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("matching uid, stale version = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid alone = %v, want ErrUIDConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid, matching version = %v, want ErrUIDConflict", err) } if _, err := s.GetWorker(ctx, testWorkerName); err != nil { t.Fatalf("a refused delete removed the worker: %v", err) } - if err := del(store.DeletePreconditions{Version: version}); err != nil { + if err := del(store.Precondition{Version: version}); err != nil { t.Fatalf("matching version alone = %v, want nil", err) } worker = create() - if err := del(store.DeletePreconditions{UID: worker.GetMetadata().GetUid()}); err != nil { + if err := del(store.Precondition{UID: worker.GetMetadata().GetUid()}); err != nil { t.Fatalf("matching uid alone = %v, want nil", err) } worker = create() - if err := del(store.DeletePreconditions{UID: worker.GetMetadata().GetUid(), Version: worker.GetMetadata().GetVersion()}); err != nil { + if err := del(store.Precondition{UID: worker.GetMetadata().GetUid(), Version: worker.GetMetadata().GetVersion()}); err != nil { t.Fatalf("matching uid and version = %v, want nil", err) } if _, err := s.GetWorker(ctx, testWorkerName); !errors.Is(err, store.ErrNotFound) { @@ -2767,7 +2924,7 @@ func runWorkerAssignmentContractTests(t *testing.T, setup func(t *testing.T) sto if err != nil { t.Fatalf("GetActor failed: %v", err) } - if _, err := s.DeleteActor(ctx, ref, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteActor(ctx, ref, store.Precondition{}); err != nil { t.Fatalf("DeleteActor failed: %v", err) } @@ -2780,6 +2937,79 @@ func runWorkerAssignmentContractTests(t *testing.T, setup func(t *testing.T) sto } }) + t.Run("BindActorToWorker_MissingPrecondition", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + + if _, err := s.CreateWorker(ctx, newTestWorker(testWorkerName, "pod-1")); err != nil { + t.Fatalf("CreateWorker failed: %v", err) + } + assignment := newTestAssignment(t, s, "1", 0, 0) + ref := resources.ActorRefFromObjectRef(assignment.GetActor()) + actor, err := s.GetActor(ctx, ref) + if err != nil { + t.Fatalf("GetActor failed: %v", err) + } + for _, tt := range []struct { + name string + precondition store.Precondition + }{ + {"no precondition", store.Precondition{}}, + {"guarding on only a uid", store.Precondition{UID: actor.GetMetadata().GetUid()}}, + {"guarding on only a version", store.Precondition{Version: actor.GetMetadata().GetVersion()}}, + } { + t.Run(tt.name, func(t *testing.T) { + _, err := s.BindActorToWorker(ctx, testWorkerName, assignment, nil, ref, tt.precondition, func(*ateapi.Actor) error { + t.Error("mutate ran for a blind write") + return nil + }) + if !errors.Is(err, store.ErrPreconditionRequired) { + t.Errorf("BindActorToWorker error = %v, want one matching store.ErrPreconditionRequired", err) + } + }) + } + if _, err := s.GetWorkerAssignment(ctx, testWorkerName, assignment.GetActorUid()); !errors.Is(err, store.ErrNotFound) { + t.Errorf("GetWorkerAssignment after the refused binds = %v, want ErrNotFound", err) + } + }) + + t.Run("UpdateActorAndRelease_MissingPrecondition", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + + if _, err := s.CreateWorker(ctx, newTestWorker(testWorkerName, "pod-1")); err != nil { + t.Fatalf("CreateWorker failed: %v", err) + } + assignment := newTestAssignment(t, s, "1", 0, 0) + bind(t, s, testWorkerName, assignment) + ref := resources.ActorRefFromObjectRef(assignment.GetActor()) + actor, err := s.GetActor(ctx, ref) + if err != nil { + t.Fatalf("GetActor failed: %v", err) + } + for _, tt := range []struct { + name string + precondition store.Precondition + }{ + {"no precondition", store.Precondition{}}, + {"guarding on only a uid", store.Precondition{UID: actor.GetMetadata().GetUid()}}, + {"guarding on only a version", store.Precondition{Version: actor.GetMetadata().GetVersion()}}, + } { + t.Run(tt.name, func(t *testing.T) { + _, _, err := s.UpdateActorAndRelease(ctx, ref, tt.precondition, func(*ateapi.Actor) error { + t.Error("mutate ran for a blind write") + return nil + }) + if !errors.Is(err, store.ErrPreconditionRequired) { + t.Errorf("UpdateActorAndRelease error = %v, want one matching store.ErrPreconditionRequired", err) + } + }) + } + if _, err := s.GetWorkerAssignment(ctx, testWorkerName, assignment.GetActorUid()); err != nil { + t.Errorf("GetWorkerAssignment after the refused releases = %v, want the assignment kept", err) + } + }) + t.Run("UpdateActorAndRelease_LeavesOtherAssignments", func(t *testing.T) { s := setup(t) ctx := context.Background() @@ -3112,7 +3342,7 @@ func runWorkerAssignmentContractTests(t *testing.T, setup func(t *testing.T) sto } assignment := newTestAssignment(t, s, "1", 0, 0) bind(t, s, testWorkerName, assignment) - if _, err := s.DeleteWorker(ctx, testWorkerName, store.DeletePreconditions{}); !errors.Is(err, store.ErrFailedPrecondition) { + if _, err := s.DeleteWorker(ctx, testWorkerName, store.Precondition{}); !errors.Is(err, store.ErrFailedPrecondition) { t.Fatalf("DeleteWorker of an assigned worker = %v, want ErrFailedPrecondition", err) } if _, err := s.GetWorkerAssignment(ctx, testWorkerName, assignment.GetActorUid()); err != nil { @@ -3120,7 +3350,7 @@ func runWorkerAssignmentContractTests(t *testing.T, setup func(t *testing.T) sto } release(t, s, assignment) - if _, err := s.DeleteWorker(ctx, testWorkerName, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteWorker(ctx, testWorkerName, store.Precondition{}); err != nil { t.Fatalf("DeleteWorker after release failed: %v", err) } }) @@ -3146,7 +3376,7 @@ func runWorkerAssignmentContractTests(t *testing.T, setup func(t *testing.T) sto if err != nil { t.Fatalf("BindActorToWorker failed: %v", err) } - if _, err := s.DeleteActor(ctx, ref, store.DeletePreconditions{}); !errors.Is(err, store.ErrFailedPrecondition) { + if _, err := s.DeleteActor(ctx, ref, store.Precondition{}); !errors.Is(err, store.ErrFailedPrecondition) { t.Fatalf("DeleteActor of an assigned actor = %v, want ErrFailedPrecondition", err) } if _, err := s.GetActor(ctx, ref); err != nil { @@ -3159,7 +3389,7 @@ func runWorkerAssignmentContractTests(t *testing.T, setup func(t *testing.T) sto }); err != nil { t.Fatalf("UpdateActorAndRelease failed: %v", err) } - if _, err := s.DeleteActor(ctx, ref, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteActor(ctx, ref, store.Precondition{}); err != nil { t.Fatalf("DeleteActor after release failed: %v", err) } }) @@ -3366,7 +3596,7 @@ func runAtespaceContractTests(t *testing.T, setup func(t *testing.T) store.Inter if _, err := s.CreateAtespace(ctx, newTestAtespace("team-a")); err != nil { t.Fatalf("CreateAtespace failed: %v", err) } - deleted, err := s.DeleteAtespace(ctx, "team-a", store.DeletePreconditions{}) + deleted, err := s.DeleteAtespace(ctx, "team-a", store.Precondition{}) if err != nil { t.Fatalf("DeleteAtespace failed: %v", err) } @@ -3385,7 +3615,7 @@ func runAtespaceContractTests(t *testing.T, setup func(t *testing.T) store.Inter s := setup(t) ctx := context.Background() - if _, err := s.DeleteAtespace(ctx, "nope", store.DeletePreconditions{}); !errors.Is(err, store.ErrNotFound) { + if _, err := s.DeleteAtespace(ctx, "nope", store.Precondition{}); !errors.Is(err, store.ErrNotFound) { t.Errorf("expected ErrNotFound, got %v", err) } }) @@ -3400,27 +3630,27 @@ func runAtespaceContractTests(t *testing.T, setup func(t *testing.T) store.Inter } return created } - del := func(precondition store.DeletePreconditions) error { + del := func(precondition store.Precondition) error { _, err := s.DeleteAtespace(ctx, "team-a", precondition) return err } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { + if err := del(store.Precondition{UID: foreignUID, Version: 1}); !errors.Is(err, store.ErrNotFound) { t.Errorf("guarded delete of a missing atespace = %v, want ErrNotFound", err) } atespace := create() uid, version := atespace.GetMetadata().GetUid(), atespace.GetMetadata().GetVersion() - if err := del(store.DeletePreconditions{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("stale version alone = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + if err := del(store.Precondition{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { t.Errorf("matching uid, stale version = %v, want ErrVersionConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid alone = %v, want ErrUIDConflict", err) } - if err := del(store.DeletePreconditions{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { + if err := del(store.Precondition{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { t.Errorf("foreign uid, matching version = %v, want ErrUIDConflict", err) } if _, err := s.GetAtespace(ctx, "team-a"); err != nil { @@ -3432,25 +3662,25 @@ func runAtespaceContractTests(t *testing.T, setup func(t *testing.T) store.Inter if _, err := s.CreateActor(ctx, newTestSuspendedActor(actorRef.Atespace, actorRef.Name)); err != nil { t.Fatalf("CreateActor failed: %v", err) } - if err := del(store.DeletePreconditions{UID: uid, Version: version}); !errors.Is(err, store.ErrFailedPrecondition) { + if err := del(store.Precondition{UID: uid, Version: version}); !errors.Is(err, store.ErrFailedPrecondition) { t.Errorf("matching guards on a non-empty atespace = %v, want ErrFailedPrecondition", err) } if _, err := s.GetAtespace(ctx, "team-a"); err != nil { t.Fatalf("a refused delete removed the atespace: %v", err) } - if _, err := s.DeleteActor(ctx, actorRef, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteActor(ctx, actorRef, store.Precondition{}); err != nil { t.Fatalf("DeleteActor failed: %v", err) } - if err := del(store.DeletePreconditions{Version: version}); err != nil { + if err := del(store.Precondition{Version: version}); err != nil { t.Fatalf("matching version alone = %v, want nil", err) } atespace = create() - if err := del(store.DeletePreconditions{UID: atespace.GetMetadata().GetUid()}); err != nil { + if err := del(store.Precondition{UID: atespace.GetMetadata().GetUid()}); err != nil { t.Fatalf("matching uid alone = %v, want nil", err) } atespace = create() - if err := del(store.DeletePreconditions{UID: atespace.GetMetadata().GetUid(), Version: atespace.GetMetadata().GetVersion()}); err != nil { + if err := del(store.Precondition{UID: atespace.GetMetadata().GetUid(), Version: atespace.GetMetadata().GetVersion()}); err != nil { t.Fatalf("matching uid and version = %v, want nil", err) } if _, err := s.GetAtespace(ctx, "team-a"); !errors.Is(err, store.ErrNotFound) { @@ -3468,7 +3698,7 @@ func runAtespaceContractTests(t *testing.T, setup func(t *testing.T) store.Inter if _, err := s.CreateActor(ctx, &ateapi.Actor{Metadata: &ateapi.ResourceMetadata{Name: "id1", Atespace: "team-a"}, Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_DELETING}}); err != nil { t.Fatalf("CreateActor failed: %v", err) } - if _, err := s.DeleteAtespace(ctx, "team-a", store.DeletePreconditions{}); !errors.Is(err, store.ErrFailedPrecondition) { + if _, err := s.DeleteAtespace(ctx, "team-a", store.Precondition{}); !errors.Is(err, store.ErrFailedPrecondition) { t.Errorf("DeleteAtespace on non-empty = %v, want ErrFailedPrecondition", err) } if _, err := s.GetAtespace(ctx, "team-a"); err != nil { @@ -3486,13 +3716,13 @@ func runAtespaceContractTests(t *testing.T, setup func(t *testing.T) store.Inter if _, err := s.CreateActor(ctx, &ateapi.Actor{Metadata: &ateapi.ResourceMetadata{Name: "id1", Atespace: "team-a"}, Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_DELETING}}); err != nil { t.Fatalf("CreateActor failed: %v", err) } - if _, err := s.DeleteAtespace(ctx, "team-a", store.DeletePreconditions{}); !errors.Is(err, store.ErrFailedPrecondition) { + if _, err := s.DeleteAtespace(ctx, "team-a", store.Precondition{}); !errors.Is(err, store.ErrFailedPrecondition) { t.Fatalf("expected rejection while non-empty, got %v", err) } - if _, err := s.DeleteActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteActor(ctx, resources.ActorRef{Atespace: "team-a", Name: "id1"}, store.Precondition{}); err != nil { t.Fatalf("DeleteActor failed: %v", err) } - if _, err := s.DeleteAtespace(ctx, "team-a", store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteAtespace(ctx, "team-a", store.Precondition{}); err != nil { t.Errorf("DeleteAtespace after actor removed = %v, want nil", err) } }) @@ -3511,18 +3741,216 @@ func runAtespaceContractTests(t *testing.T, setup func(t *testing.T) store.Inter t.Fatalf("CreateActor failed: %v", err) } - if _, err := s.DeleteAtespace(ctx, "team-a", store.DeletePreconditions{}); err != nil { + if _, err := s.DeleteAtespace(ctx, "team-a", store.Precondition{}); err != nil { t.Errorf("DeleteAtespace(team-a, empty) = %v, want nil (must not be blocked by team-b's actor)", err) } if _, err := s.GetAtespace(ctx, "team-a"); !errors.Is(err, store.ErrNotFound) { t.Errorf("after delete, GetAtespace(team-a) = %v, want ErrNotFound", err) } - if _, err := s.DeleteAtespace(ctx, "team-b", store.DeletePreconditions{}); !errors.Is(err, store.ErrFailedPrecondition) { + if _, err := s.DeleteAtespace(ctx, "team-b", store.Precondition{}); !errors.Is(err, store.ErrFailedPrecondition) { t.Errorf("DeleteAtespace(team-b, non-empty) = %v, want ErrFailedPrecondition", err) } }) } +func newTestCSIDriver(name, driverName string) *ateapi.CsiDriver { + return &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: name}, + DriverName: driverName, + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "csi-nfs-controller.csi-nfs.svc", Port: 12345}, + Tls: &ateapi.CsiDriverTlsConfig{ServerName: "csi-nfs-controller.csi-nfs.svc"}, + } +} + +func runCSIDriverContractTests(t *testing.T, setup func(t *testing.T) store.Interface) { + t.Helper() + + t.Run("CreateAndGetCSIDriver", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + + input := newTestCSIDriver("csi-nfs", "nfs.csi.k8s.io") + input.Metadata = &ateapi.ResourceMetadata{ + Name: "csi-nfs", Uid: "caller-uid", Version: 99, + CreateTime: timestamppb.New(time.Unix(1, 0)), UpdateTime: timestamppb.New(time.Unix(2, 0)), DeleteTime: timestamppb.New(time.Unix(3, 0)), + } + before := proto.CloneOf(input) + created, err := s.CreateCSIDriver(ctx, input) + if err != nil { + t.Fatalf("CreateCSIDriver failed: %v", err) + } + if diff := cmp.Diff(before, input, protocmp.Transform()); diff != "" { + t.Errorf("CreateCSIDriver mutated caller input (-before +after):\n%s", diff) + } + if md := created.GetMetadata(); md.GetUid() == "" || md.GetUid() == "caller-uid" || md.GetVersion() != 1 || + md.GetCreateTime() == nil || md.GetCreateTime().AsTime().Unix() == 1 || + md.GetUpdateTime() == nil || md.GetUpdateTime().AsTime().Unix() == 2 || md.GetDeleteTime() != nil { + t.Errorf("created metadata = %v; want fresh server-assigned metadata at version 1", md) + } + if diff := cmp.Diff(newTestCSIDriver("csi-nfs", "nfs.csi.k8s.io"), created, protocmp.Transform(), ignoreUID, ignoreTimestamps, ignoreVersion); diff != "" { + t.Errorf("CreateCSIDriver mismatch (-want +got):\n%s", diff) + } + + got, err := s.GetCSIDriver(ctx, "csi-nfs") + if err != nil || !proto.Equal(created, got) { + t.Fatalf("GetCSIDriver = (%v, %v), want %v", got, err, created) + } + if _, err := s.GetCSIDriver(ctx, "nope"); !errors.Is(err, store.ErrNotFound) { + t.Errorf("GetCSIDriver(missing) = %v, want ErrNotFound", err) + } + if _, err := s.CreateCSIDriver(ctx, newTestCSIDriver("csi-nfs", "other.csi.k8s.io")); !errors.Is(err, store.ErrAlreadyExists) { + t.Errorf("duplicate name = %v, want ErrAlreadyExists", err) + } + if _, err := s.CreateCSIDriver(ctx, newTestCSIDriver("csi-nfs-2", "nfs.csi.k8s.io")); !errors.Is(err, store.ErrDriverNameAlreadyExists) || !errors.Is(err, store.ErrFailedPrecondition) { + t.Errorf("duplicate driver_name = %v, want ErrDriverNameAlreadyExists (wrapping ErrFailedPrecondition)", err) + } + }) + + t.Run("ListCSIDrivers_PaginationAndTokens", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + + if empty, err := s.ListCSIDrivers(ctx, store.ListOptions{PageSize: 1000}); err != nil || len(empty.Items) != 0 || empty.NextPageToken != "" { + t.Fatalf("empty ListCSIDrivers = (%v, %q, %v); want empty", empty.Items, empty.NextPageToken, err) + } + for _, idx := range []int{3, 1, 4, 0, 2} { + if _, err := s.CreateCSIDriver(ctx, newTestCSIDriver(fmt.Sprintf("drv-%d", idx), fmt.Sprintf("d%d.csi.k8s.io", idx))); err != nil { + t.Fatalf("CreateCSIDriver(drv-%d) failed: %v", idx, err) + } + } + + var got []string + for pageToken := ""; ; { + page, err := s.ListCSIDrivers(ctx, store.ListOptions{PageSize: 2, PageToken: pageToken}) + if err != nil { + t.Fatalf("ListCSIDrivers failed: %v", err) + } + for _, driver := range page.Items { + got = append(got, driver.GetMetadata().GetName()) + } + if page.NextPageToken == "" { + break + } + pageToken = page.NextPageToken + } + if diff := cmp.Diff([]string{"drv-0", "drv-1", "drv-2", "drv-3", "drv-4"}, got); diff != "" { + t.Errorf("paged driver names mismatch (-want +got):\n%s", diff) + } + + mustCreateAtespace(t, s, "team-a") + mustCreateAtespace(t, s, "team-b") + atespacePage, err := s.ListAtespaces(ctx, store.ListOptions{PageSize: 1}) + if err != nil || atespacePage.NextPageToken == "" { + t.Fatalf("ListAtespaces page 1 = (%q, %v); want next page token", atespacePage.NextPageToken, err) + } + if _, err := s.ListCSIDrivers(ctx, store.ListOptions{PageSize: 1, PageToken: atespacePage.NextPageToken}); !errors.Is(err, store.ErrInvalidPageToken) { + t.Errorf("cross-resource page token = %v, want ErrInvalidPageToken", err) + } + }) + + t.Run("UpdateCSIDriver", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + noop := func(*ateapi.CsiDriver) error { return nil } + + if _, err := s.UpdateCSIDriver(ctx, "nope", store.Precondition{UID: foreignUID, Version: 1}, noop); !errors.Is(err, store.ErrNotFound) { + t.Errorf("UpdateCSIDriver(missing) = %v, want ErrNotFound", err) + } + created, err := s.CreateCSIDriver(ctx, newTestCSIDriver("csi-nfs", "nfs.csi.k8s.io")) + if err != nil { + t.Fatalf("CreateCSIDriver failed: %v", err) + } + + for _, pre := range []store.Precondition{{}, {UID: created.GetMetadata().GetUid()}, {Version: created.GetMetadata().GetVersion()}} { + if _, err := s.UpdateCSIDriver(ctx, "csi-nfs", pre, noop); !errors.Is(err, store.ErrPreconditionRequired) { + t.Errorf("UpdateCSIDriver(%+v) = %v, want ErrPreconditionRequired", pre, err) + } + } + if _, err := s.UpdateCSIDriver(ctx, "csi-nfs", store.Precondition{UID: foreignUID, Version: 1}, noop); !errors.Is(err, store.ErrUIDConflict) { + t.Errorf("wrong uid = %v, want ErrUIDConflict", err) + } + if _, err := s.UpdateCSIDriver(ctx, "csi-nfs", store.Precondition{UID: created.GetMetadata().GetUid(), Version: 99}, noop); !errors.Is(err, store.ErrVersionConflict) { + t.Errorf("wrong version = %v, want ErrVersionConflict", err) + } + + abortErr := errors.New("abort") + if _, err := s.UpdateCSIDriver(ctx, "csi-nfs", store.PreconditionFrom(created), func(driver *ateapi.CsiDriver) error { + driver.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "10.0.0.9", Port: 9999} + return abortErr + }); !errors.Is(err, abortErr) { + t.Errorf("mutate error = %v, want %v", err, abortErr) + } + + updated, err := s.UpdateCSIDriver(ctx, "csi-nfs", store.PreconditionFrom(created), func(driver *ateapi.CsiDriver) error { + driver.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "10.0.0.2", Port: 9000} + driver.Tls = nil + driver.Metadata.Name = "other" + driver.Metadata.Atespace = "team-a" + driver.Metadata.UpdateTime = timestamppb.New(time.Unix(1, 0)) + return nil + }) + if err != nil { + t.Fatalf("UpdateCSIDriver failed: %v", err) + } + if updated.GetMetadata().GetName() != "csi-nfs" || updated.GetMetadata().GetAtespace() != "" || + updated.GetMetadata().GetVersion() != 2 || updated.GetMetadata().GetUid() != created.GetMetadata().GetUid() || + !updated.GetMetadata().GetCreateTime().AsTime().Equal(created.GetMetadata().GetCreateTime().AsTime()) || + updated.GetMetadata().GetUpdateTime().AsTime().Before(created.GetMetadata().GetUpdateTime().AsTime()) { + t.Errorf("updated metadata = %v, created = %v", updated.GetMetadata(), created.GetMetadata()) + } + got, err := s.GetCSIDriver(ctx, "csi-nfs") + if err != nil { + t.Fatalf("GetCSIDriver after update failed: %v", err) + } + if diff := cmp.Diff(updated, got, protocmp.Transform()); diff != "" { + t.Errorf("stored driver after update mismatch (-updated +got):\n%s", diff) + } + if got.GetControllerEndpoint().GetHost() != "10.0.0.2" || got.GetControllerEndpoint().GetPort() != 9000 || got.GetTls() != nil { + t.Errorf("updated fields did not persist: %v", got) + } + }) + + t.Run("DeleteCSIDriver_Preconditions", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + + for _, pre := range []store.Precondition{{}, {UID: foreignUID, Version: 1}} { + if _, err := s.DeleteCSIDriver(ctx, "csi-nfs", pre); !errors.Is(err, store.ErrNotFound) { + t.Errorf("DeleteCSIDriver(missing, %+v) = %v, want ErrNotFound", pre, err) + } + } + + created, err := s.CreateCSIDriver(ctx, newTestCSIDriver("csi-nfs", "nfs.csi.k8s.io")) + if err != nil { + t.Fatalf("CreateCSIDriver failed: %v", err) + } + uid, version := created.GetMetadata().GetUid(), created.GetMetadata().GetVersion() + if _, err := s.DeleteCSIDriver(ctx, "csi-nfs", store.Precondition{UID: uid, Version: version + 1}); !errors.Is(err, store.ErrVersionConflict) { + t.Errorf("stale version = %v, want ErrVersionConflict", err) + } + if _, err := s.DeleteCSIDriver(ctx, "csi-nfs", store.Precondition{UID: foreignUID, Version: version}); !errors.Is(err, store.ErrUIDConflict) { + t.Errorf("foreign uid = %v, want ErrUIDConflict", err) + } + + deleted, err := s.DeleteCSIDriver(ctx, "csi-nfs", store.Precondition{UID: uid, Version: version}) + if err != nil { + t.Fatalf("DeleteCSIDriver failed: %v", err) + } + if deleted.GetMetadata().GetDeleteTime() == nil { + t.Error("deleted driver carries no delete_time") + } + if diff := cmp.Diff(created, deleted, protocmp.Transform(), ignoreTimestamps); diff != "" { + t.Errorf("DeleteCSIDriver mismatch (-created +deleted):\n%s", diff) + } + if _, err := s.GetCSIDriver(ctx, "csi-nfs"); !errors.Is(err, store.ErrNotFound) { + t.Errorf("GetCSIDriver after delete = %v, want ErrNotFound", err) + } + if _, err := s.CreateCSIDriver(ctx, newTestCSIDriver("csi-nfs-2", "nfs.csi.k8s.io")); err != nil { + t.Errorf("reusing driver_name after delete failed: %v", err) + } + }) +} + func runLeaseContractTests(t *testing.T, setup func(t *testing.T) store.Interface) { t.Helper() @@ -3644,7 +4072,7 @@ func runUnknownFieldContractTests(t *testing.T, setup func(t *testing.T) store.I } assertPruned(t, "UpdateActor", created, updated) - deleted, err := s.DeleteActor(ctx, ref, store.DeletePreconditions{}) + deleted, err := s.DeleteActor(ctx, ref, store.Precondition{}) if err != nil { t.Fatalf("DeleteActor failed: %v", err) } @@ -3688,7 +4116,7 @@ func runUnknownFieldContractTests(t *testing.T, setup func(t *testing.T) store.I } assertPruned(t, "UpdateEgressPolicy", created, updated) - deleted, err := s.DeleteEgressPolicy(ctx, ref, store.DeletePreconditions{}) + deleted, err := s.DeleteEgressPolicy(ctx, ref, store.Precondition{}) if err != nil { t.Fatalf("DeleteEgressPolicy failed: %v", err) } @@ -3734,13 +4162,45 @@ func runUnknownFieldContractTests(t *testing.T, setup func(t *testing.T) store.I } assertPruned(t, "UpdateTag", created, updated) - deleted, err := s.DeleteTag(ctx, tagRef, store.DeletePreconditions{}) + deleted, err := s.DeleteTag(ctx, tagRef, store.Precondition{}) if err != nil { t.Fatalf("DeleteTag failed: %v", err) } assertPruned(t, "DeleteTag", created, deleted) }) + t.Run("UnknownFields_ExternalVolume", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + mustCreateAtespace(t, s, testAtespace) + + volumeRef := resources.ExternalVolumeRef{Atespace: testAtespace, Name: "vol-1"} + volume := withUnknownField(newTestExternalVolume(testAtespace, volumeRef.Name)) + withUnknownField(volume.Metadata) + created, err := s.CreateExternalVolume(ctx, volume) + if err != nil { + t.Fatalf("CreateExternalVolume failed: %v", err) + } + + got, err := s.GetExternalVolume(ctx, volumeRef) + if err != nil { + t.Fatalf("GetExternalVolume failed: %v", err) + } + assertPruned(t, "GetExternalVolume", created, got) + + list, err := s.ListExternalVolumes(ctx, testAtespace, store.ListOptions{}) + if err != nil || len(list.Items) != 1 { + t.Fatalf("ListExternalVolumes = %d items, %v; want 1", len(list.Items), err) + } + assertPruned(t, "ListExternalVolumes", created, list.Items[0]) + + deleted, err := s.DeleteExternalVolume(ctx, volumeRef, store.Precondition{}) + if err != nil { + t.Fatalf("DeleteExternalVolume failed: %v", err) + } + assertPruned(t, "DeleteExternalVolume", created, deleted) + }) + t.Run("UnknownFields_Atespace", func(t *testing.T) { s := setup(t) ctx := context.Background() @@ -3763,13 +4223,49 @@ func runUnknownFieldContractTests(t *testing.T, setup func(t *testing.T) store.I } assertPruned(t, "ListAtespaces", created, list.Items[0]) - deleted, err := s.DeleteAtespace(ctx, testAtespace, store.DeletePreconditions{}) + deleted, err := s.DeleteAtespace(ctx, testAtespace, store.Precondition{}) if err != nil { t.Fatalf("DeleteAtespace failed: %v", err) } assertPruned(t, "DeleteAtespace", created, deleted) }) + t.Run("UnknownFields_CSIDriver", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + driver := withUnknownField(newTestCSIDriver("csi-nfs", "nfs.csi.k8s.io")) + withUnknownField(driver.Metadata) + withUnknownField(driver.ControllerEndpoint) + withUnknownField(driver.Tls) + created, err := s.CreateCSIDriver(ctx, driver) + if err != nil { + t.Fatalf("CreateCSIDriver failed: %v", err) + } + got, err := s.GetCSIDriver(ctx, "csi-nfs") + if err != nil { + t.Fatalf("GetCSIDriver failed: %v", err) + } + assertPruned(t, "GetCSIDriver", created, got) + list, err := s.ListCSIDrivers(ctx, store.ListOptions{}) + if err != nil || len(list.Items) != 1 { + t.Fatalf("ListCSIDrivers = %d items, %v; want 1", len(list.Items), err) + } + assertPruned(t, "ListCSIDrivers", created, list.Items[0]) + updated, err := s.UpdateCSIDriver(ctx, "csi-nfs", store.PreconditionFrom(got), func(toUpdate *ateapi.CsiDriver) error { + requireNoUnknownFields(t, "UpdateCSIDriver mutation input", toUpdate) + return nil + }) + if err != nil { + t.Fatalf("UpdateCSIDriver failed: %v", err) + } + assertPruned(t, "UpdateCSIDriver", created, updated) + deleted, err := s.DeleteCSIDriver(ctx, "csi-nfs", store.Precondition{}) + if err != nil { + t.Fatalf("DeleteCSIDriver failed: %v", err) + } + assertPruned(t, "DeleteCSIDriver", created, deleted) + }) + t.Run("UnknownFields_ActorTemplate", func(t *testing.T) { s := setup(t) ctx := context.Background() @@ -3804,7 +4300,7 @@ func runUnknownFieldContractTests(t *testing.T, setup func(t *testing.T) store.I } assertPruned(t, "UpdateActorTemplate", created, updated) - deleted, err := s.DeleteActorTemplate(ctx, ref, store.DeletePreconditions{}) + deleted, err := s.DeleteActorTemplate(ctx, ref, store.Precondition{}) if err != nil { t.Fatalf("DeleteActorTemplate failed: %v", err) } @@ -3855,12 +4351,53 @@ func runUnknownFieldContractTests(t *testing.T, setup func(t *testing.T) store.I } assertPruned(t, "UpdateWorker", created, updated) - deleted, err := s.DeleteWorker(ctx, testWorkerName, store.DeletePreconditions{}) + deleted, err := s.DeleteWorker(ctx, testWorkerName, store.Precondition{}) if err != nil { t.Fatalf("DeleteWorker failed: %v", err) } assertPruned(t, "DeleteWorker", created, deleted) }) + + t.Run("UnknownFields_WorkerAssignment", func(t *testing.T) { + s := setup(t) + ctx := context.Background() + mustCreateAtespace(t, s, testAtespace) + worker := withUnknownField(newTestWorker(testWorkerName, "pod-1")) + withUnknownField(worker.Metadata) + if _, err := s.CreateWorker(ctx, worker); err != nil { + t.Fatalf("CreateWorker failed: %v", err) + } + actor, err := s.CreateActor(ctx, newTestSuspendedActor(testAtespace, "actor-1")) + if err != nil { + t.Fatalf("CreateActor failed: %v", err) + } + ref := resources.ActorRefFromActor(actor) + + assignment := withUnknownField(&ateapi.ActorAssignment{ + Actor: withUnknownField(&ateapi.ObjectRef{Atespace: ref.Atespace, Name: ref.Name}), + ActorUid: actor.GetMetadata().GetUid(), + Resources: withUnknownField(resources.CPUMemory(500, 1<<20)), + }) + admit := func(toAdmit *ateapi.Worker) error { + requireNoUnknownFields(t, "BindActorToWorker admit input", toAdmit) + return nil + } + if _, err := s.BindActorToWorker(ctx, testWorkerName, assignment, admit, ref, store.PreconditionFrom(actor), nil); err != nil { + t.Fatalf("BindActorToWorker failed: %v", err) + } + + got, err := s.GetWorkerAssignment(ctx, testWorkerName, assignment.GetActorUid()) + if err != nil { + t.Fatalf("GetWorkerAssignment failed: %v", err) + } + assertPruned(t, "GetWorkerAssignment", assignment, got) + + list, err := s.ListWorkerAssignments(ctx, testWorkerName, store.ListOptions{}) + if err != nil || len(list.Items) != 1 { + t.Fatalf("ListWorkerAssignments = %d items, %v; want 1", len(list.Items), err) + } + assertPruned(t, "ListWorkerAssignments", assignment, list.Items[0]) + }) } // sameAllocation compares two allocation totals by what they hold, so an diff --git a/cmd/ateapi/internal/store/storetest/storetest.go b/cmd/ateapi/internal/store/storetest/storetest.go index 362652e5cc..8e6f2289c3 100644 --- a/cmd/ateapi/internal/store/storetest/storetest.go +++ b/cmd/ateapi/internal/store/storetest/storetest.go @@ -31,6 +31,7 @@ import ( "github.com/google/uuid" "github.com/jackc/pgx/v5/pgxpool" + "github.com/testcontainers/testcontainers-go" "github.com/testcontainers/testcontainers-go/modules/postgres" "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/authz" @@ -64,6 +65,29 @@ func SetupTestStore(t *testing.T) (store.Interface, func()) { // SetupPostgresPersistence returns an isolated atepg persistence instance. func SetupPostgresPersistence(t *testing.T) *atepg.Persistence { + t.Helper() + persistence := SetupPostgresPersistenceWithoutAuthz(t) + pool := persistence.Pool() + // The server always wires a PolicyManager, so test stores do too. + fgaServer, err := authz.NewOpenFGAServer(pool) + if err != nil { + t.Fatalf("creating OpenFGA server: %v", err) + } + t.Cleanup(fgaServer.Close) + _, policyManager, err := authz.New(context.Background(), pool, fgaServer, nil, DefaultSystemPrincipals()) + if err != nil { + t.Fatalf("initializing OpenFGA authz: %v", err) + } + persistence.SetPolicyManager(policyManager) + return persistence +} + +// SetupPostgresPersistenceWithoutAuthz returns an isolated atepg persistence +// instance with no PolicyManager. The caller must set one, as ate-api's main +// does, before the store deletes an atespace or writes an access policy. +// +// TODO(#4041): Remove once atepg takes the PolicyManager in its constructor. +func SetupPostgresPersistenceWithoutAuthz(t *testing.T) *atepg.Persistence { t.Helper() ctx := context.Background() admin := requireAdminPool(t) @@ -74,6 +98,9 @@ func SetupPostgresPersistence(t *testing.T) *atepg.Persistence { config := admin.Config().Copy() config.ConnConfig.Database = databaseName + // pgxpool defaults to max(4, NumCPU) connections. Cap each test at 4 so + // parallel tests stay under the container's max_connections. + config.MaxConns = 4 pool, err := pgxpool.NewWithConfig(ctx, config) if err != nil { t.Fatalf("connecting to PostgreSQL test database: %v", err) @@ -85,23 +112,13 @@ func SetupPostgresPersistence(t *testing.T) *atepg.Persistence { } pools.Store(persistence, pool) t.Cleanup(func() { + persistence.Close() pools.Delete(persistence) pool.Close() if _, err := admin.Exec(context.Background(), "DROP DATABASE "+databaseName); err != nil { t.Errorf("dropping PostgreSQL test database: %v", err) } }) - // The server always wires a PolicyManager, so test stores do too. - fgaServer, err := authz.NewOpenFGAServer(pool) - if err != nil { - t.Fatalf("creating OpenFGA server: %v", err) - } - t.Cleanup(fgaServer.Close) - _, policyManager, err := authz.New(ctx, pool, fgaServer, nil, DefaultSystemPrincipals()) - if err != nil { - t.Fatalf("initializing OpenFGA authz: %v", err) - } - persistence.SetPolicyManager(policyManager) return persistence } @@ -111,7 +128,7 @@ func DefaultSystemPrincipals() authz.SystemPrincipals { return authz.SystemPrincipals{ ControllerSPIFFEID: installdefaults.ControllerSPIFFEID(installdefaults.SystemNamespace), EgressGatewaySPIFFEIDs: []string{installdefaults.EgressSPIFFEID(installdefaults.SystemNamespace)}, - IngressRouterSPIFFEID: installdefaults.RouterSPIFFEID(installdefaults.SystemNamespace), + IngressRouterSPIFFEIDs: []string{installdefaults.RouterSPIFFEID(installdefaults.SystemNamespace)}, AteletSPIFFEID: installdefaults.AteletSPIFFEID(installdefaults.SystemNamespace), APIServerSidecarSPIFFEID: installdefaults.APIServerSPIFFEID(installdefaults.SystemNamespace), } @@ -260,6 +277,9 @@ func requireAdminPool(t *testing.T) *pgxpool.Pool { postgres.WithDatabase("postgres"), postgres.WithUsername("postgres"), postgres.WithPassword("postgres"), + // Allow a large number of connections so that parallel tests + // can accommodate their connections. + testcontainers.WithCmdArgs("-c", "max_connections=1000"), ) if containerErr != nil { return diff --git a/cmd/ateapi/internal/workercache/workercache.go b/cmd/ateapi/internal/workercache/workercache.go index b09d674bfe..13958aab3f 100644 --- a/cmd/ateapi/internal/workercache/workercache.go +++ b/cmd/ateapi/internal/workercache/workercache.go @@ -31,8 +31,15 @@ import ( "k8s.io/apimachinery/pkg/util/wait" ) -// relistPageSize is the page size used for the relist. -const relistPageSize = 1000 +const ( + // relistPageSize is the page size used for the relist. + relistPageSize = 1000 + + // relistJitterFactor spreads periodic relists across [1.0, 1.0+factor] of + // relistInterval so multiple ate-api-server replicas started together do not + // stampede PostgreSQL with synchronized full-table ListWorkers scans. + relistJitterFactor = 0.2 +) // Cache maintains an in-memory snapshot of all workers. // @@ -76,10 +83,14 @@ func notify(handlers []func(*ateapi.Worker), workers ...*ateapi.Worker) { } } -// New creates a Cache backed by a given store. relistInterval controls how -// often the cache performs a full ListWorkers to recover from state drifts -// caused by missing WorkerWatch events. +// New creates a Cache backed by a given store. relistInterval must be positive +// and controls how often the cache performs a full ListWorkers to recover from +// state drifts caused by missing WorkerWatch events (jittered up to +20% to +// avoid synchronized relists across replicas). func New(store workerListWatcher, relistInterval time.Duration) *Cache { + if relistInterval <= 0 { + panic(fmt.Sprintf("workercache: relistInterval must be positive, got %v", relistInterval)) + } return &Cache{ store: store, relistInterval: relistInterval, @@ -200,9 +211,13 @@ func (c *Cache) relist(ctx context.Context) error { return nil } +func (c *Cache) nextRelistDelay() time.Duration { + return wait.Jitter(c.relistInterval, relistJitterFactor) +} + func (c *Cache) watchEvents(ctx context.Context, watch *store.WorkerWatch) { - ticker := time.NewTicker(c.relistInterval) - defer ticker.Stop() + timer := time.NewTimer(c.nextRelistDelay()) + defer timer.Stop() for { select { case event, ok := <-watch.Events: @@ -218,13 +233,17 @@ func (c *Cache) watchEvents(ctx context.Context, watch *store.WorkerWatch) { return // context cancelled } c.ready.Store(true) + // resync just completed a full relist; push the next periodic + // relist out by a fresh jittered interval. + timer.Reset(c.nextRelistDelay()) } else { c.applyEvent(event) } - case <-ticker.C: + case <-timer.C: if err := c.relist(ctx); err != nil { slog.WarnContext(ctx, "worker cache: periodic relist failed", slog.Any("err", err)) } + timer.Reset(c.nextRelistDelay()) case <-ctx.Done(): c.ready.Store(false) watch.Close() diff --git a/cmd/ateapi/internal/workercache/workercache_bench_test.go b/cmd/ateapi/internal/workercache/workercache_bench_test.go new file mode 100644 index 0000000000..20f4265e12 --- /dev/null +++ b/cmd/ateapi/internal/workercache/workercache_bench_test.go @@ -0,0 +1,52 @@ +// Copyright 2026 The Agent Substrate 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 workercache_test + +import ( + "context" + "fmt" + "testing" + "time" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/ateapi/internal/workercache" +) + +// BenchmarkWorkers times the copy Workers() hands to every Schedule call, on +// its own, so the scheduling benchmarks can be read as filter cost and this +// one as cache cost. +func BenchmarkWorkers(b *testing.B) { + for _, n := range []int{100, 1000, 10000} { + workers := make([]*ateapi.Worker, 0, n) + for i := range n { + workers = append(workers, makeWorker("ns", fmt.Sprintf("w-%d", i), 1)) + } + c := workercache.New(newFakeStore(workers...), time.Hour) + ctx, cancel := context.WithCancel(context.Background()) + if err := c.Start(ctx); err != nil { + cancel() + b.Fatal(err) + } + b.Run(fmt.Sprintf("n=%d", n), func(b *testing.B) { + b.ReportAllocs() + for b.Loop() { + if _, err := c.Workers(); err != nil { + b.Fatal(err) + } + } + }) + cancel() + } +} diff --git a/cmd/ateapi/internal/workercache/workercache_test.go b/cmd/ateapi/internal/workercache/workercache_test.go index 1269e91e23..8912f9890b 100644 --- a/cmd/ateapi/internal/workercache/workercache_test.go +++ b/cmd/ateapi/internal/workercache/workercache_test.go @@ -19,6 +19,7 @@ import ( "errors" "sync" "testing" + "testing/synctest" "time" "github.com/google/go-cmp/cmp" @@ -377,11 +378,12 @@ func TestCache_Relist_FailureIsNonFatal(t *testing.T) { type fakeStore struct { store.Interface - mu sync.Mutex - workers []*ateapi.Worker - watchCh chan store.WorkerEvent - listErr error // if set, ListWorkers returns it - closes int // number of times a returned watch was Closed + mu sync.Mutex + workers []*ateapi.Worker + watchCh chan store.WorkerEvent + listErr error // if set, ListWorkers returns it + closes int // number of times a returned watch was Closed + listTimes []time.Time // timestamps of ListWorkers calls } func newFakeStore(workers ...*ateapi.Worker) *fakeStore { @@ -404,6 +406,7 @@ func (f *fakeStore) WatchWorkers(_ context.Context) (*store.WorkerWatch, error) func (f *fakeStore) ListWorkers(_ context.Context, _ store.ListOptions) (store.ListResponse[*ateapi.Worker], error) { f.mu.Lock() defer f.mu.Unlock() + f.listTimes = append(f.listTimes, time.Now()) if f.listErr != nil { return store.ListResponse[*ateapi.Worker]{}, f.listErr } @@ -412,6 +415,14 @@ func (f *fakeStore) ListWorkers(_ context.Context, _ store.ListOptions) (store.L return store.ListResponse[*ateapi.Worker]{Items: out}, nil } +func (f *fakeStore) recordedListTimes() []time.Time { + f.mu.Lock() + defer f.mu.Unlock() + out := make([]time.Time, len(f.listTimes)) + copy(out, f.listTimes) + return out +} + func (f *fakeStore) send(event store.WorkerEvent) { f.mu.Lock() ch := f.watchCh @@ -608,3 +619,138 @@ func TestCache_AddHandler_SeesRelistChanges(t *testing.T) { t.Errorf("pod3 versions (-want +got):\n%s", diff) } } + +func TestNew_PanicsOnNonPositiveRelistInterval(t *testing.T) { + for _, interval := range []time.Duration{0, -time.Second} { + t.Run(interval.String(), func(t *testing.T) { + defer func() { + if r := recover(); r == nil { + t.Fatalf("New(store, %v) did not panic, want panic", interval) + } + }() + workercache.New(newFakeStore(), interval) + }) + } +} + +func TestCache_Relist_JitteredInterval(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + const ( + interval = 5 * time.Minute + maxInterval = interval + interval/5 + ) + fs := newFakeStore(makeWorker("ns", "pod1", 1)) + c := workercache.New(fs, interval) + ctx, cancel := context.WithCancel(t.Context()) + defer func() { + cancel() + synctest.Wait() + }() + + if err := c.Start(ctx); err != nil { + t.Fatalf("Start: %v", err) + } + + // No periodic relist should fire before the base interval elapses. + time.Sleep(interval - time.Nanosecond) + synctest.Wait() + if got := len(fs.recordedListTimes()); got != 1 { + t.Fatalf("ListWorkers calls before base interval = %d, want 1 (initial sync only)", got) + } + + // Advance across enough virtual time for at least 20 periodic relists. + time.Sleep(20 * maxInterval) + synctest.Wait() + + times := fs.recordedListTimes() + if len(times) < 21 { + t.Fatalf("ListWorkers calls = %d, want at least 21", len(times)) + } + seen := make(map[time.Duration]struct{}) + for i := 1; i < len(times); i++ { + d := times[i].Sub(times[i-1]) + if d < interval || d > maxInterval { + t.Fatalf("relist #%d interval = %v, want in [%v, %v]", i, d, interval, maxInterval) + } + seen[d] = struct{}{} + } + if len(seen) < 2 { + t.Fatalf("expected jittered relist intervals to vary, got only %d distinct value(s)", len(seen)) + } + }) +} + +func TestCache_Relist_ResetsTimerAfterDisconnectResync(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + const ( + interval = 5 * time.Minute + maxInterval = interval + interval/5 + ) + w1 := makeWorker("ns", "pod1", 1) + fs := newFakeStore(w1) + c := workercache.New(fs, interval) + ctx, cancel := context.WithCancel(t.Context()) + defer func() { + cancel() + synctest.Wait() + }() + + if err := c.Start(ctx); err != nil { + t.Fatalf("Start: %v", err) + } + + // Disconnect near the end of the first interval; resync runs a full + // relist and must push the next periodic relist out by a fresh interval. + time.Sleep(4 * time.Minute) + fs.disconnect() + synctest.Wait() + + fs.mu.Lock() + closes := fs.closes + fs.mu.Unlock() + if closes != 1 { + t.Fatalf("watch closes after disconnect = %d, want 1", closes) + } + if got := len(fs.recordedListTimes()); got != 2 { + t.Fatalf("ListWorkers calls after resync = %d, want 2", got) + } + + // Add w2 silently and advance 4 more minutes (to t0+8m, well past the + // original t0+6m upper bound). No periodic relist should fire yet. + w2 := makeWorker("ns", "pod2", 1) + fs.setWorkers(w1, w2) + time.Sleep(4 * time.Minute) + synctest.Wait() + + if got := len(fs.recordedListTimes()); got != 2 { + t.Fatalf("ListWorkers calls 4m after resync = %d, want 2 (timer should have reset on resync)", got) + } + got, err := c.Workers() + if err != nil { + t.Fatalf("Workers: %v", err) + } + if diff := cmp.Diff([]*ateapi.Worker{w1}, got, protocmp.Transform(), workerSortOpt); diff != "" { + t.Errorf("workers before reset relist (-want +got):\n%s", diff) + } + + // Advance past resync + maxInterval (4m + 6m = 10m from t0); the + // periodic relist must fire and pick up w2. + time.Sleep(2 * time.Minute) + synctest.Wait() + + times := fs.recordedListTimes() + if len(times) != 3 { + t.Fatalf("ListWorkers calls after reset interval = %d, want 3", len(times)) + } + if d := times[2].Sub(times[1]); d < interval || d > maxInterval { + t.Fatalf("periodic relist delay after resync = %v, want in [%v, %v]", d, interval, maxInterval) + } + got, err = c.Workers() + if err != nil { + t.Fatalf("Workers: %v", err) + } + if diff := cmp.Diff([]*ateapi.Worker{w1, w2}, got, protocmp.Transform(), workerSortOpt); diff != "" { + t.Errorf("workers after periodic relist (-want +got):\n%s", diff) + } + }) +} diff --git a/cmd/ateapi/internal/workerservice/certificate.go b/cmd/ateapi/internal/workerservice/certificate.go index 6cbe28a8f7..0ff0009be8 100644 --- a/cmd/ateapi/internal/workerservice/certificate.go +++ b/cmd/ateapi/internal/workerservice/certificate.go @@ -36,7 +36,7 @@ import ( // MintWorkerActorCertificate mints a Substrate-issued SPIFFE certificate that asserts // a worker acting on behalf of a particular actor. func (s *Server) MintWorkerActorCertificate(ctx context.Context, req *ateapi.MintWorkerActorCertificateRequest) (*ateapi.MintWorkerActorCertificateResponse, error) { - if errs := apivalidation.ValidateMintWorkerActorCertificateRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateMintWorkerActorCertificateRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -51,7 +51,7 @@ func (s *Server) MintWorkerActorCertificate(ctx context.Context, req *ateapi.Min dbActor, err := s.store.GetActor(ctx, resources.ActorRefFromObjectRef(req.GetActor())) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("actor not found") + return nil, apierror.NotFound("actor not found").WithCause(err) } else if err != nil { return nil, fmt.Errorf("while retrieving actor: %w", err) } diff --git a/cmd/ateapi/internal/workerservice/certificate_test.go b/cmd/ateapi/internal/workerservice/certificate_test.go index 901a9cfbc6..7e00760076 100644 --- a/cmd/ateapi/internal/workerservice/certificate_test.go +++ b/cmd/ateapi/internal/workerservice/certificate_test.go @@ -29,6 +29,7 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/localca" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "go.ate.dev/substrate/internal/substratex509" "google.golang.org/grpc/codes" @@ -111,7 +112,7 @@ func newTestCAPool(t *testing.T) *localca.ConcretePool { func TestMintWorkerActorCertificate(t *testing.T) { st, actor := newFakeStoreWithActor("team-a", "my-actor", "3b9f1e77-2c4d-4a80-91be-6d5c8f0a7e21") caPool := newTestCAPool(t) - s := New(st, &fakeControl{}, testAteletSPIFFEID, caPool, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, caPool, "", nil, preview.NewForTest(t)) csr, key := generateTestCSR(t) @@ -164,7 +165,7 @@ func TestMintWorkerActorCertificate(t *testing.T) { func TestMintWorkerActorCertificate_Errors(t *testing.T) { st, actor := newFakeStoreWithActor("team-a", "my-actor", "3b9f1e77-2c4d-4a80-91be-6d5c8f0a7e21") caPool := newTestCAPool(t) - s := New(st, &fakeControl{}, testAteletSPIFFEID, caPool, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, caPool, "", nil, preview.NewForTest(t)) csr, _ := generateTestCSR(t) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, "node-1")) diff --git a/cmd/ateapi/internal/workerservice/crash.go b/cmd/ateapi/internal/workerservice/crash.go index cdd064b038..f09f5eed94 100644 --- a/cmd/ateapi/internal/workerservice/crash.go +++ b/cmd/ateapi/internal/workerservice/crash.go @@ -32,13 +32,13 @@ func (s *Server) ReportActorCrashed(ctx context.Context, req *ateapi.ReportActor if err != nil { return nil, err } - if errs := apivalidation.ValidateReportActorCrashedRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateReportActorCrashedRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } workerName := req.GetWorker().GetName() actorRef := resources.ActorRefFromObjectRef(req.GetActor()) - if err := s.authorizeHostedActor(ctx, caller, workerName, actorRef, req.GetActorUid()); err != nil { + if _, err := s.authorizeHostedActor(ctx, caller, workerName, actorRef, req.GetActorUid()); err != nil { return nil, err } actor, err := s.control.CrashActorReportedByWorker(ctx, actorRef, req.GetActorUid(), workerName, req.GetMessage()) diff --git a/cmd/ateapi/internal/workerservice/crash_test.go b/cmd/ateapi/internal/workerservice/crash_test.go index 09db8cc251..0234fdafe9 100644 --- a/cmd/ateapi/internal/workerservice/crash_test.go +++ b/cmd/ateapi/internal/workerservice/crash_test.go @@ -26,15 +26,17 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/ateletauth/ateletauthtest" "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" ) func crashRequest(actorUID string) *ateapi.ReportActorCrashedRequest { return &ateapi.ReportActorCrashedRequest{ - Worker: &ateapi.ObjectRef{Name: testWorkerName}, - Actor: &ateapi.ObjectRef{Atespace: suspendAtespace, Name: suspendActor}, - ActorUid: actorUID, - Message: "cloud-hypervisor exited: signal: killed", + Worker: &ateapi.ObjectRef{Name: testWorkerName}, + Actor: &ateapi.ObjectRef{Atespace: suspendAtespace, Name: suspendActor}, + ActorUid: actorUID, + Message: "cloud-hypervisor exited: signal: killed", + ActivationUid: "f91585ad-2435-4c49-bc02-1096554b774c", } } @@ -45,7 +47,7 @@ func TestReportActorCrashed(t *testing.T) { actor := seedHostedActor(t, st, testWorkerName) uid := actor.GetMetadata().GetUid() control := &fakeControl{crashResp: actor} - s := New(st, control, testAteletSPIFFEID, nil, "", nil) + s := New(st, control, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) if _, err := s.ReportActorCrashed(ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)), crashRequest(uid)); err != nil { t.Fatalf("ReportActorCrashed() failed: %v", err) @@ -73,6 +75,8 @@ func TestReportActorCrashed_Refused(t *testing.T) { noMessage.Message = "" longMessage := crashRequest(uid) longMessage.Message = strings.Repeat("x", 4097) + invalidActivation := crashRequest(uid) + invalidActivation.ActivationUid = "invalid" tests := []struct { name string @@ -85,11 +89,12 @@ func TestReportActorCrashed_Refused(t *testing.T) { {"stale actor incarnation", authed, crashRequest("3b9f1e77-2c4d-4a80-91be-6d5c8f0a7e21"), codes.NotFound}, {"no message", authed, noMessage, codes.InvalidArgument}, {"message too long", authed, longMessage, codes.InvalidArgument}, + {"invalid activation UID", authed, invalidActivation, codes.InvalidArgument}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { control := &fakeControl{} - s := New(st, control, testAteletSPIFFEID, nil, "", nil) + s := New(st, control, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) _, err := s.ReportActorCrashed(tc.ctx, tc.req) if got := apierror.Code(err); got != tc.want { t.Fatalf("code = %v (err %v), want %v", got, err, tc.want) diff --git a/cmd/ateapi/internal/workerservice/jwt.go b/cmd/ateapi/internal/workerservice/jwt.go index d91275c0eb..cff2ba3308 100644 --- a/cmd/ateapi/internal/workerservice/jwt.go +++ b/cmd/ateapi/internal/workerservice/jwt.go @@ -39,7 +39,7 @@ import ( const workerActorJWTLifetime = time.Hour func (s *Server) MintWorkerActorJwt(ctx context.Context, req *ateapi.MintWorkerActorJwtRequest) (*ateapi.MintWorkerActorJwtResponse, error) { - if errs := apivalidation.ValidateMintWorkerActorJwtRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateMintWorkerActorJwtRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } @@ -52,7 +52,7 @@ func (s *Server) MintWorkerActorJwt(ctx context.Context, req *ateapi.MintWorkerA // snapshot before resume and to upload a checkpoint during or after suspend. dbActor, err := s.store.GetActor(ctx, resources.ActorRefFromObjectRef(req.GetActor())) if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("actor not found") + return nil, apierror.NotFound("actor not found").WithCause(err) } else if err != nil { return nil, fmt.Errorf("while retrieving actor: %w", err) } diff --git a/cmd/ateapi/internal/workerservice/jwt_test.go b/cmd/ateapi/internal/workerservice/jwt_test.go index 4974b9aa1e..25033a1ccd 100644 --- a/cmd/ateapi/internal/workerservice/jwt_test.go +++ b/cmd/ateapi/internal/workerservice/jwt_test.go @@ -29,6 +29,7 @@ import ( "go.ate.dev/substrate/internal/actoridjwt" "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/localjwtauthority" + "go.ate.dev/substrate/internal/preview" "google.golang.org/grpc/codes" ) @@ -64,7 +65,7 @@ func decodeJWTClaims(t *testing.T, token string) actoridjwt.WireClaims { func TestMintWorkerActorJwt(t *testing.T) { st, actor := newFakeStoreWithActor("team-a", "my-actor", "3b9f1e77-2c4d-4a80-91be-6d5c8f0a7e21") - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, testActorJWTIssuer, newTestJWTPool(t)) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, testActorJWTIssuer, newTestJWTPool(t), preview.NewForTest(t)) ctx := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, "node-1")) before := time.Now().Truncate(time.Second) @@ -139,7 +140,7 @@ func uploadPendingStatus(node string) *ateapi.ActorStatus { func TestMintWorkerActorJwt_Errors(t *testing.T) { st, actor := newFakeStoreWithActor("team-a", "my-actor", "3b9f1e77-2c4d-4a80-91be-6d5c8f0a7e21") - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, testActorJWTIssuer, newTestJWTPool(t)) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, testActorJWTIssuer, newTestJWTPool(t), preview.NewForTest(t)) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, "node-1")) valid := func() *ateapi.MintWorkerActorJwtRequest { @@ -343,7 +344,7 @@ func TestNodeRefusalLogNamesCredential(t *testing.T) { st, actor := newFakeStoreWithActor("team-a", "my-actor", "3b9f1e77-2c4d-4a80-91be-6d5c8f0a7e21") csr, _ := generateTestCSR(t) - s := New(st, &fakeControl{}, testAteletSPIFFEID, newTestCAPool(t), testActorJWTIssuer, newTestJWTPool(t)) + s := New(st, &fakeControl{}, testAteletSPIFFEID, newTestCAPool(t), testActorJWTIssuer, newTestJWTPool(t), preview.NewForTest(t)) // The actor's worker runs on node-1. otherNode := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, "node-2")) actorRef := &ateapi.ObjectRef{Atespace: "team-a", Name: "my-actor"} diff --git a/cmd/ateapi/internal/workerservice/register.go b/cmd/ateapi/internal/workerservice/register.go index 3a9ee8b6e8..f167e6bf55 100644 --- a/cmd/ateapi/internal/workerservice/register.go +++ b/cmd/ateapi/internal/workerservice/register.go @@ -39,7 +39,7 @@ func (s *Server) AcquireWorkerEpoch(ctx context.Context, req *ateapi.AcquireWork if err != nil { return nil, err } - if errs := apivalidation.ValidateAcquireWorkerEpochRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateAcquireWorkerEpochRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } name := req.GetWorker().GetName() @@ -72,7 +72,7 @@ func (s *Server) RegisterWorker(ctx context.Context, req *ateapi.RegisterWorkerR if err != nil { return nil, err } - if errs := apivalidation.ValidateRegisterWorkerRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateRegisterWorkerRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } name := req.GetWorker().GetName() @@ -131,7 +131,7 @@ func (s *Server) SetWorkerSandboxRuntimes(ctx context.Context, req *ateapi.SetWo if err != nil { return nil, err } - if errs := apivalidation.ValidateSetWorkerSandboxRuntimesRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateSetWorkerSandboxRuntimesRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } classes := req.GetSandboxClasses() @@ -179,7 +179,7 @@ func (s *Server) workerOnCallerNode(ctx context.Context, name string, caller *at worker, err := s.store.GetWorker(ctx, name) if err != nil { if errors.Is(err, store.ErrNotFound) { - return nil, apierror.NotFound("Worker %s not found", name) + return nil, apierror.NotFound("Worker %s not found", name).WithCause(err) } return nil, fmt.Errorf("while fetching worker %s: %w", name, err) } @@ -204,9 +204,9 @@ func (s *Server) workerOnCallerNode(ctx context.Context, name string, caller *at func workerWriteError(name, doing string, err error) error { switch { case errors.Is(err, store.ErrNotFound): - return apierror.NotFound("Worker %s not found", name) + return apierror.NotFound("Worker %s not found", name).WithCause(err) case errors.Is(err, store.ErrUIDConflict), errors.Is(err, store.ErrVersionConflict): - return apierror.Aborted("concurrent update conflict, please retry") + return apierror.Aborted("concurrent update conflict, please retry").WithCause(err) default: return fmt.Errorf("while %s for worker %s: %w", doing, name, err) } diff --git a/cmd/ateapi/internal/workerservice/register_test.go b/cmd/ateapi/internal/workerservice/register_test.go index 77a3f85bfe..4655fc6693 100644 --- a/cmd/ateapi/internal/workerservice/register_test.go +++ b/cmd/ateapi/internal/workerservice/register_test.go @@ -26,6 +26,7 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/ateletauth/ateletauthtest" "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/preview" "google.golang.org/grpc/codes" ) @@ -84,7 +85,7 @@ func mustGetWorker(t *testing.T, s *Server, name string) *ateapi.Worker { func TestAcquireWorkerEpoch(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) @@ -109,7 +110,7 @@ func TestAcquireWorkerEpoch(t *testing.T) { func TestAcquireWorkerEpoch_NewWorker(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seedWorker(t, st, testWorkerName, testNode, &ateapi.WorkerStatus{State: ateapi.WorkerState_WORKER_STATE_UNAVAILABLE}) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) @@ -125,7 +126,7 @@ func TestAcquireWorkerEpoch_NewWorker(t *testing.T) { func TestAcquireWorkerEpoch_Errors(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) ref := &ateapi.ObjectRef{Name: testWorkerName} @@ -160,7 +161,7 @@ func TestAcquireWorkerEpoch_Errors(t *testing.T) { func TestRegisterWorker(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1, CpuMillicores: 2000, MemoryBytes: 0}) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) @@ -205,7 +206,7 @@ func TestRegisterWorker(t *testing.T) { func TestRegisterWorker_Epochs(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) seeded := func() *ateapi.WorkerStatus { return &ateapi.WorkerStatus{ @@ -308,7 +309,7 @@ func TestRegisterWorker_Epochs(t *testing.T) { func TestRegisterWorker_OtherNodeIsNotFound(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) _, err := s.RegisterWorker(ateletauthtest.ContextWith(ateletauthtest.CertOn(t, "some-other-node")), registerRequest(testEpoch, 4094)) @@ -329,7 +330,7 @@ func TestRegisterWorker_OtherNodeIsNotFound(t *testing.T) { func TestRegisterWorker_Errors(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) without := func(mutate func(*ateapi.RegisterWorkerRequest)) *ateapi.RegisterWorkerRequest { @@ -369,7 +370,7 @@ func TestRegisterWorker_Errors(t *testing.T) { func TestRegisterWorker_RejectsNonsense(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seeded := seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 4094}) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) @@ -406,7 +407,7 @@ func TestRegisterWorker_RejectsNonsense(t *testing.T) { func TestSetWorkerSandboxRuntimes(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) amd64, arm64 := testCompat("amd64"), testCompat("arm64") @@ -541,7 +542,7 @@ func TestSetWorkerSandboxRuntimes(t *testing.T) { func TestSetWorkerSandboxRuntimes_SortsAttributes(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) @@ -578,7 +579,7 @@ func TestSetWorkerSandboxRuntimes_SortsAttributes(t *testing.T) { func TestSetWorkerSandboxRuntimes_Errors(t *testing.T) { st, cleanup := storetest.SetupTestStore(t) defer cleanup() - s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil) + s := New(st, &fakeControl{}, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) without := func(mutate func(*ateapi.SetWorkerSandboxRuntimesRequest)) *ateapi.SetWorkerSandboxRuntimesRequest { diff --git a/cmd/ateapi/internal/workerservice/report.go b/cmd/ateapi/internal/workerservice/report.go index 2d2128702d..572b432fd0 100644 --- a/cmd/ateapi/internal/workerservice/report.go +++ b/cmd/ateapi/internal/workerservice/report.go @@ -32,7 +32,7 @@ func (s *Server) ReportActorSnapshotState(ctx context.Context, req *ateapi.Repor if err != nil { return nil, err } - if errs := apivalidation.ValidateReportActorSnapshotStateRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateReportActorSnapshotStateRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } actorRef := resources.ActorRefFromObjectRef(req.GetActor()) diff --git a/cmd/ateapi/internal/workerservice/report_test.go b/cmd/ateapi/internal/workerservice/report_test.go index e6d994c62e..b8ac920456 100644 --- a/cmd/ateapi/internal/workerservice/report_test.go +++ b/cmd/ateapi/internal/workerservice/report_test.go @@ -25,6 +25,7 @@ import ( "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/ateletauth/ateletauthtest" "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" ) @@ -49,7 +50,7 @@ func reportRequest() *ateapi.ReportActorSnapshotStateRequest { // certificate. The handler reads nothing from the store. func TestReportActorSnapshotState(t *testing.T) { control := &fakeControl{} - s := New(nil, control, testAteletSPIFFEID, nil, "", nil) + s := New(nil, control, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) req := reportRequest() if _, err := s.ReportActorSnapshotState(ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)), req); err != nil { @@ -93,7 +94,7 @@ func TestReportActorSnapshotState_Refused(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { control := &fakeControl{reportErr: tt.controlErr} - s := New(nil, control, testAteletSPIFFEID, nil, "", nil) + s := New(nil, control, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) _, err := s.ReportActorSnapshotState(tt.ctx, tt.req) if got := apierror.Code(err); got != tt.want { t.Fatalf("ReportActorSnapshotState() error = %v, want code %v", err, tt.want) diff --git a/cmd/ateapi/internal/workerservice/service.go b/cmd/ateapi/internal/workerservice/service.go index 0ed2617440..adbdb394c1 100644 --- a/cmd/ateapi/internal/workerservice/service.go +++ b/cmd/ateapi/internal/workerservice/service.go @@ -23,6 +23,7 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/internal/localca" "go.ate.dev/substrate/internal/localjwtauthority" + "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" ) @@ -49,6 +50,8 @@ type Server struct { // Control.MintActorJwt uses. actorJWTIssuer string actorIDJWTPool localjwtauthority.Pool + + gates *preview.Gates } // actorControl is the in-process slice of the Control service this package @@ -61,7 +64,7 @@ type actorControl interface { var _ ateapi.WorkerServiceServer = (*Server)(nil) -func New(store store.Interface, control actorControl, ateletSPIFFEID string, actorIDCAPool localca.Pool, actorJWTIssuer string, actorIDJWTPool localjwtauthority.Pool) *Server { +func New(store store.Interface, control actorControl, ateletSPIFFEID string, actorIDCAPool localca.Pool, actorJWTIssuer string, actorIDJWTPool localjwtauthority.Pool, gates *preview.Gates) *Server { return &Server{ store: store, control: control, @@ -69,5 +72,6 @@ func New(store store.Interface, control actorControl, ateletSPIFFEID string, act actorIDCAPool: actorIDCAPool, actorJWTIssuer: actorJWTIssuer, actorIDJWTPool: actorIDJWTPool, + gates: gates, } } diff --git a/cmd/ateapi/internal/workerservice/service_test.go b/cmd/ateapi/internal/workerservice/service_test.go index 01e21f0622..7abd9b1f10 100644 --- a/cmd/ateapi/internal/workerservice/service_test.go +++ b/cmd/ateapi/internal/workerservice/service_test.go @@ -42,6 +42,9 @@ type fakeControl struct { calls []*ateapi.SuspendActorRequest resp *ateapi.SuspendActorResponse err error + // onSuspend, if set, runs before SuspendActor returns, as a write that + // races the suspend would. + onSuspend func() reports []appliedReport reportErr error @@ -51,6 +54,9 @@ type fakeControl struct { func (f *fakeControl) SuspendActor(_ context.Context, req *ateapi.SuspendActorRequest) (*ateapi.SuspendActorResponse, error) { f.calls = append(f.calls, req) + if f.onSuspend != nil { + f.onSuspend() + } return f.resp, f.err } diff --git a/cmd/ateapi/internal/workerservice/suspend.go b/cmd/ateapi/internal/workerservice/suspend.go index 1205fe4e60..c4dca04152 100644 --- a/cmd/ateapi/internal/workerservice/suspend.go +++ b/cmd/ateapi/internal/workerservice/suspend.go @@ -20,6 +20,8 @@ import ( "fmt" "log/slog" + "google.golang.org/grpc/codes" + "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/cmd/ateapi/internal/apivalidation" "go.ate.dev/substrate/cmd/ateapi/internal/ateletauth" @@ -35,13 +37,14 @@ func (s *Server) RequestActorSuspend(ctx context.Context, req *ateapi.RequestAct if err != nil { return nil, err } - if errs := apivalidation.ValidateRequestActorSuspendRequest(ctx, req); len(errs) > 0 { + if errs := apivalidation.ValidateRequestActorSuspendRequest(ctx, s.gates, req); len(errs) > 0 { return nil, resources.ToAPIError(errs) } workerName := req.GetWorker().GetName() actorRef := resources.ActorRefFromObjectRef(req.GetActor()) - if err := s.authorizeHostedActor(ctx, caller, workerName, actorRef, req.GetActorUid()); err != nil { + actor, err := s.authorizeHostedActor(ctx, caller, workerName, actorRef, req.GetActorUid()) + if err != nil { return nil, err } @@ -50,12 +53,25 @@ func (s *Server) RequestActorSuspend(ctx context.Context, req *ateapi.RequestAct // suspendable, and a proposal that races a resume, suspend, or delete loses // to whichever holds the Actor's lease. // - // TODO: the checks above run outside the Actor's lease, so there is a small - // race with the suspend that follows: within the one round trip it takes - // the workflow to acquire the lease, the Actor can be resumed onto another - // Worker, or deleted and recreated under the same name, and the workflow - // suspends whatever the reference resolves to by then. See #1773. - resp, err := s.control.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: req.GetActor()}) + // The checks above run outside the Actor's lease. The uid and version + // preconditions make the workflow refuse the Actor if anything wrote it + // since, such as a resume onto another Worker or a delete and recreate. + resp, err := s.control.SuspendActor(ctx, &ateapi.SuspendActorRequest{ + Actor: req.GetActor(), + Options: &ateapi.SuspendOptions{ + Uid: actor.GetMetadata().GetUid(), + Version: actor.GetMetadata().GetVersion(), + }, + }) + if apierror.Code(err) == codes.Aborted { + // The workflow also refuses with ABORTED when a precondition fails. + // Check again so an Actor the caller no longer hosts is NotFound, as + // above. If the caller still hosts it, the ABORTED stands, and the + // worker retries against the Actor's new version. + if _, authErr := s.authorizeHostedActor(ctx, caller, workerName, actorRef, req.GetActorUid()); apierror.Code(authErr) == codes.NotFound { + return nil, authErr + } + } if err != nil { return nil, err } @@ -69,15 +85,16 @@ func (s *Server) RequestActorSuspend(ctx context.Context, req *ateapi.RequestAct // authorizeHostedActor checks that the calling atelet may speak for actorRef: // workerName must be on the caller's node, and the actor must be assigned to it. -func (s *Server) authorizeHostedActor(ctx context.Context, caller *ateletauth.Caller, workerName string, actorRef resources.ActorRef, actorUID string) error { +// It returns the actor it checked. +func (s *Server) authorizeHostedActor(ctx context.Context, caller *ateletauth.Caller, workerName string, actorRef resources.ActorRef, actorUID string) (*ateapi.Actor, error) { // Use authoritative state to authorize the request, never the request // itself: the caller proves which node it is on, and nothing else. worker, err := s.store.GetWorker(ctx, workerName) if err != nil { if errors.Is(err, store.ErrNotFound) { - return apierror.NotFound("Worker %s not found", workerName) + return nil, apierror.NotFound("Worker %s not found", workerName).WithCause(err) } - return fmt.Errorf("while fetching worker %s: %w", workerName, err) + return nil, fmt.Errorf("while fetching worker %s: %w", workerName, err) } if worker.GetNodeName() != caller.NodeName { // Do not disclose Workers on other nodes. @@ -86,17 +103,20 @@ func (s *Server) authorizeHostedActor(ctx context.Context, caller *ateletauth.Ca slog.String("worker_node", worker.GetNodeName()), slog.String("caller_node", caller.NodeName), slog.String("caller_pod", caller.PodName)) - return apierror.NotFound("Worker %s not found", workerName) + return nil, apierror.NotFound("Worker %s not found", workerName) } actor, err := s.store.GetActor(ctx, actorRef) if err != nil { if errors.Is(err, store.ErrNotFound) { - return apierror.NotFound("Actor %s not found", actorRef) + return nil, apierror.NotFound("Actor %s not found", actorRef).WithCause(err) } - return fmt.Errorf("while fetching actor %s: %w", actorRef, err) + return nil, fmt.Errorf("while fetching actor %s: %w", actorRef, err) + } + if err := checkActorHostedBy(ctx, actor, workerName, actorUID); err != nil { + return nil, err } - return checkActorHostedBy(ctx, actor, workerName, actorUID) + return actor, nil } // checkActorHostedBy reports whether the Worker may speak for this Actor: the diff --git a/cmd/ateapi/internal/workerservice/suspend_test.go b/cmd/ateapi/internal/workerservice/suspend_test.go index 1681461c28..3c589044a8 100644 --- a/cmd/ateapi/internal/workerservice/suspend_test.go +++ b/cmd/ateapi/internal/workerservice/suspend_test.go @@ -27,6 +27,8 @@ import ( "go.ate.dev/substrate/cmd/ateapi/internal/store" "go.ate.dev/substrate/cmd/ateapi/internal/store/storetest" "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/internal/resources" ) const ( @@ -78,7 +80,7 @@ func TestRequestActorSuspend(t *testing.T) { Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED}, } control := &fakeControl{resp: &ateapi.SuspendActorResponse{Actor: suspended}} - s := New(st, control, testAteletSPIFFEID, nil, "", nil) + s := New(st, control, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) got, err := s.RequestActorSuspend( ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)), @@ -87,7 +89,8 @@ func TestRequestActorSuspend(t *testing.T) { t.Fatalf("RequestActorSuspend() failed: %v", err) } want := []*ateapi.SuspendActorRequest{{ - Actor: &ateapi.ObjectRef{Atespace: suspendAtespace, Name: suspendActor}, + Actor: &ateapi.ObjectRef{Atespace: suspendAtespace, Name: suspendActor}, + Options: &ateapi.SuspendOptions{Uid: actor.GetMetadata().GetUid(), Version: actor.GetMetadata().GetVersion()}, }} if diff := cmp.Diff(want, control.calls, protocmp.Transform()); diff != "" { t.Errorf("suspend calls mismatch (-want +got):\n%s", diff) @@ -126,7 +129,7 @@ func TestRequestActorSuspend_OnlyForHostedActors(t *testing.T) { seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) actor := seedHostedActor(t, st, tc.assignedWorker) control := &fakeControl{} - s := New(st, control, testAteletSPIFFEID, nil, "", nil) + s := New(st, control, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) uid := tc.requestedUID if uid == "" { @@ -152,7 +155,7 @@ func TestRequestActorSuspend_Errors(t *testing.T) { actor := seedHostedActor(t, st, testWorkerName) uid := actor.GetMetadata().GetUid() control := &fakeControl{} - s := New(st, control, testAteletSPIFFEID, nil, "", nil) + s := New(st, control, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) authed := ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)) tests := []struct { @@ -210,19 +213,51 @@ func TestRequestActorSuspend_Errors(t *testing.T) { // The suspend is a proposal, and the control plane's refusal is the answer: a // request that loses a race to a resume, suspend, or delete comes back as what -// the workflow said, not as something the worker has to interpret. +// the workflow said, not as something the worker has to interpret. The +// exception is an Actor the caller no longer hosts, which is NotFound as +// before the suspend. func TestRequestActorSuspend_PassesThroughTheWorkflowsRefusal(t *testing.T) { - st, cleanup := storetest.SetupTestStore(t) - defer cleanup() - seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) - actor := seedHostedActor(t, st, testWorkerName) - control := &fakeControl{err: apierror.FailedPrecondition("Actor is RESUMING")} - s := New(st, control, testAteletSPIFFEID, nil, "", nil) + tests := []struct { + name string + controlErr error + recreate bool + want codes.Code + }{ + {name: "refused", controlErr: apierror.FailedPrecondition("Actor is RESUMING"), want: codes.FailedPrecondition}, + {name: "lease contention", controlErr: apierror.Aborted("concurrent update conflict, please retry"), want: codes.Aborted}, + {name: "actor recreated", controlErr: apierror.Aborted("Actor does not have uid"), recreate: true, want: codes.NotFound}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + ctx := context.Background() + st, cleanup := storetest.SetupTestStore(t) + defer cleanup() + seedReportedWorker(t, st, testNode, &ateapi.WorkerResources{Actors: 1}) + actor := seedHostedActor(t, st, testWorkerName) + control := &fakeControl{err: tc.controlErr} + if tc.recreate { + control.onSuspend = func() { + // The store deletes only an Actor with no assignment. + if _, err := st.UpdateActor(ctx, resources.ActorRefFromActor(actor), store.PreconditionFrom(actor), func(a *ateapi.Actor) error { + a.Status = &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_SUSPENDED} + return nil + }); err != nil { + t.Fatalf("UpdateActor() failed: %v", err) + } + if _, err := st.DeleteActor(ctx, resources.ActorRefFromActor(actor), store.Precondition{}); err != nil { + t.Fatalf("DeleteActor() failed: %v", err) + } + seedHostedActor(t, st, testWorkerName) + } + } + s := New(st, control, testAteletSPIFFEID, nil, "", nil, preview.NewForTest(t)) - _, err := s.RequestActorSuspend( - ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)), - suspendRequest(actor.GetMetadata().GetUid())) - if got := apierror.Code(err); got != codes.FailedPrecondition { - t.Fatalf("code = %v (err %v), want FailedPrecondition", got, err) + _, err := s.RequestActorSuspend( + ateletauthtest.ContextWith(ateletauthtest.CertOn(t, testNode)), + suspendRequest(actor.GetMetadata().GetUid())) + if got := apierror.Code(err); got != tc.want { + t.Fatalf("code = %v (err %v), want %v", got, err, tc.want) + } + }) } } diff --git a/cmd/ateapi/main.go b/cmd/ateapi/main.go index 803fbd3be6..298e60b0de 100644 --- a/cmd/ateapi/main.go +++ b/cmd/ateapi/main.go @@ -31,16 +31,13 @@ import ( "github.com/jackc/pgx/v5/pgconn" "github.com/spf13/pflag" - "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/api/objectstore/v1" "go.ate.dev/substrate/cmd/ateapi/internal/apiauthn" "go.ate.dev/substrate/cmd/ateapi/internal/authz" "go.ate.dev/substrate/cmd/ateapi/internal/controlapi" + "go.ate.dev/substrate/cmd/ateapi/internal/server" "go.ate.dev/substrate/cmd/ateapi/internal/store/atepg" - "go.ate.dev/substrate/cmd/ateapi/internal/workercache" - "go.ate.dev/substrate/cmd/ateapi/internal/workerservice" "go.ate.dev/substrate/internal/apiconfig" - "go.ate.dev/substrate/internal/ateinterceptors" "go.ate.dev/substrate/internal/credbundle" "go.ate.dev/substrate/internal/installdefaults" "go.ate.dev/substrate/internal/localca" @@ -50,26 +47,17 @@ import ( "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/resources" "go.ate.dev/substrate/internal/serverboot" + "go.ate.dev/substrate/internal/serverboot/pprofserver" "go.ate.dev/substrate/internal/version" - "go.ate.dev/substrate/internal/volume" "go.ate.dev/substrate/pkg/client/clientset/versioned" - "go.ate.dev/substrate/pkg/client/informers/externalversions" - "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "go.opentelemetry.io/otel" "google.golang.org/grpc" "google.golang.org/grpc/credentials" - "google.golang.org/grpc/keepalive" - "google.golang.org/grpc/reflection" - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/util/validation/field" - "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" ) -// maxRPCDeadline is the max deadline for all RPC methods exposed by this server. -const maxRPCDeadline = 10 * time.Minute - const minResyncInterval = 250 * time.Millisecond var ( @@ -78,6 +66,7 @@ var ( listenAddr = pflag.String("grpc-listen-addr", ":443", "Address and port the gRPC server should listen on.") metricsListenAddr = pflag.String("metrics-listen-addr", ":9090", "Address and port the prometheus metrics server should listen on.") healthListenAddr = pflag.String("health-listen-addr", ":9091", "Address and port the /readyz and /healthz probe server should listen on.") + pprofCfg = pprofserver.RegisterFlags(pflag.CommandLine) grpcServerCredBundle = pflag.String("grpc-server-cred-bundle", "", "File with the server TLS credential bundle.") authenticationConfigFile = pflag.String("authentication-config", "", "YAML file configuring trusted JWT providers.") @@ -94,8 +83,8 @@ var ( // These SPIFFE IDs hold the matching system component role when they call // over mTLS. controllerSPIFFEID = pflag.String("controller-spiffe-id", installdefaults.ControllerSPIFFEID(installdefaults.NamespaceFromPodEnv()), "mTLS SPIFFE ID of ate-controller. Holds the controller authz role, which manages workers.") - egressGatewaySPIFFEIDs = pflag.StringArray("egress-gateway-spiffe-id", []string{installdefaults.EgressSPIFFEID(installdefaults.NamespaceFromPodEnv())}, "mTLS SPIFFE IDs of atenet-egress and any other client that holds the egress_gateway authz role, which reads and lists actors and reads their egress policies. Repeat the flag for each ID.") - ingressRouterSPIFFEID = pflag.String("ingress-router-spiffe-id", installdefaults.RouterSPIFFEID(installdefaults.NamespaceFromPodEnv()), "mTLS SPIFFE ID of atenet-router. Holds the ingress_router authz role, which resumes and lists actors.") + egressGatewaySPIFFEIDs = pflag.StringSlice("egress-gateway-spiffe-id", []string{installdefaults.EgressSPIFFEID(installdefaults.NamespaceFromPodEnv())}, "mTLS SPIFFE IDs of atenet-egress and any other client that holds the egress_gateway authz role, which reads and lists actors and reads their egress policies. Repeat the flag for each ID.") + ingressRouterSPIFFEIDs = pflag.StringSlice("ingress-router-spiffe-id", []string{installdefaults.RouterSPIFFEID(installdefaults.NamespaceFromPodEnv())}, "mTLS SPIFFE IDs of atenet-router and any other client that holds the ingress_router authz role, which resumes and lists actors. Repeat the flag for each ID.") apiServerSidecarSPIFFEID = pflag.String("api-server-sidecar-spiffe-id", installdefaults.APIServerSPIFFEID(installdefaults.NamespaceFromPodEnv()), "mTLS SPIFFE ID of the ate-api-server pod, which its sidecars share. Holds the api_server_sidecar role, which reads actors so the objectstore control plugin can scope their storage credentials.") actorIDJWTPoolFile = pflag.String("actor-id-jwt-pool", "", "The file that contains the serialized JWT authority pool for signing actor JWTs") @@ -112,10 +101,11 @@ var ( drainTimeout = pflag.Duration("drain-timeout", 15*time.Second, "Deadline for the graceful gRPC drain on shutdown. In-flight RPCs still running past it are forcefully cancelled.") objectStorePluginSocket = pflag.String("objectstore-plugin-socket", "/run/objectstore-plugin/control.sock", "Unix socket of the control object-store plugin that external snapshots are deleted and copied through.") - snapshotLocation = pflag.String("snapshot-location", "", "Base object-storage URI (for example gs://BUCKET/PREFIX/) that actor snapshots are stored under. Required unless the PerTemplateSnapshotLocation preview gate is enabled; with the gate, an actor template's snapshotConfig.storageLocation overrides it.") + snapshotLocation = pflag.String("snapshot-location", "", "Base object-storage URI (for example gs://BUCKET/PREFIX/) that actor snapshots are stored under. For gs://, keep BUCKET and PREFIX within 338 characters together, or actors under it may each get a token from STS instead of a locally minted one. Required unless the PerTemplateSnapshotLocation preview gate is enabled; with the gate, an actor template's snapshotConfig.storageLocation overrides it.") - templateResyncInterval = pflag.Duration("template-resync-interval", 20*time.Second, fmt.Sprintf("Interval between actor template resyncs. Must be at least %s.", minResyncInterval)) - actorWorkflowDeadline = pflag.Duration("actor-workflow-deadline", 5*time.Minute, "Maximum wall-clock duration of a single Resume/Suspend workflow; raise it for slow image registries.") + templateResyncInterval = pflag.Duration("template-resync-interval", 20*time.Second, fmt.Sprintf("Interval between actor template resyncs. Must be at least %s.", minResyncInterval)) + templateReconcilerWorkers = pflag.Int("template-reconciler-workers", controlapi.DefaultTemplateReconcilerWorkers, "Number of concurrent workers per replica reconciling actor templates. Must be at least 1.") + actorWorkflowDeadline = pflag.Duration("actor-workflow-deadline", 5*time.Minute, "Maximum wall-clock duration of a single Resume/Suspend workflow; raise it for slow image registries.") showVersion = pflag.Bool("version", false, "Print version and exit.") previewFlags = pflag.StringSlice("preview", nil, "Preview gates to enable.") @@ -151,9 +141,13 @@ func main() { serverboot.Fatal(ctx, "Invalid PostgreSQL configuration", err) } - if err := preview.Init(*previewFlags...); err != nil { + previewGates, err := preview.New(*previewFlags...) + if err != nil { serverboot.Fatal(ctx, "Invalid --preview", err) } + if err := pprofCfg.Validate(); err != nil { + serverboot.Fatal(ctx, "Invalid pprof configuration", err) + } if err := rejectStorageEnv(); err != nil { serverboot.Fatal(ctx, "Storage settings moved to the objectstore-plugin sidecar", err) @@ -163,6 +157,9 @@ func main() { if *templateResyncInterval < minResyncInterval { serverboot.Fatal(ctx, "Invalid --template-resync-interval", fmt.Errorf("must be at least %s", minResyncInterval)) } + if *templateReconcilerWorkers < 1 { + serverboot.Fatal(ctx, "Invalid --template-reconciler-workers", errors.New("must be at least 1")) + } if err := validateActorJWTIssuer(*actorJWTIssuer); err != nil { serverboot.Fatal(ctx, "Invalid --actor-jwt-issuer", err) } @@ -175,7 +172,10 @@ func main() { if err := resources.ValidateSnapshotLocation(*snapshotLocation); err != nil { serverboot.Fatal(ctx, "Invalid --snapshot-location", err) } - } else if !preview.IsEnabled(preview.GatePerTemplateSnapshotLocation) { + if err := resources.ValidateGCSLocationLength(*snapshotLocation); err != nil { + slog.WarnContext(ctx, "--snapshot-location is too long for locally minted GCS tokens. Actors whose prefix doesn't fit each get a token from STS, which counts against the STS quota", slog.Any("err", err)) + } + } else if !previewGates.IsEnabled(preview.GatePerTemplateSnapshotLocation) { serverboot.Fatal(ctx, "Missing --snapshot-location", fmt.Errorf("required unless the %s preview gate is enabled", preview.GatePerTemplateSnapshotLocation)) } @@ -202,6 +202,7 @@ func main() { // The probes have their own server, so /metrics starts here and serves // during the store connect and the schema migrations. go serverboot.StartMetricsServer(ctx, *metricsListenAddr) + go pprofserver.Start(ctx, pprofCfg) lp, err := serverboot.InitLogging(ctx, serverboot.LoggingOptions{ ServiceName: "ateapi", @@ -257,10 +258,16 @@ func main() { serverboot.Fatal(ctx, "Failed to create OpenFGA server", err) } defer fgaServer.Close() + if len(*egressGatewaySPIFFEIDs) == 0 { + slog.InfoContext(ctx, "No client holds the gateway role", slog.String("role", authz.RoleEgressGateway)) + } + if len(*ingressRouterSPIFFEIDs) == 0 { + slog.InfoContext(ctx, "No client holds the gateway role", slog.String("role", authz.RoleIngressRouter)) + } authorizer, policyManager, err := authz.New(shutdownCtx, pool, fgaServer, *authzBootstrapOwners, authz.SystemPrincipals{ ControllerSPIFFEID: *controllerSPIFFEID, EgressGatewaySPIFFEIDs: *egressGatewaySPIFFEIDs, - IngressRouterSPIFFEID: *ingressRouterSPIFFEID, + IngressRouterSPIFFEIDs: *ingressRouterSPIFFEIDs, AteletSPIFFEID: ateletSPIFFEID, APIServerSidecarSPIFFEID: *apiServerSidecarSPIFFEID, }) @@ -279,41 +286,10 @@ func main() { serverboot.Fatal(ctx, "Failed to build server credentials", err) } - workerCache := workercache.New(persistence, 5*time.Minute) - if err := workerCache.Start(ctx); err != nil { - serverboot.Fatal(ctx, "Failed to seed worker cache", err) - } - - ateFactory := externalversions.NewSharedInformerFactory(ateClient, 0) - workerPoolLister := ateFactory.Ate().V1().WorkerPools().Lister() - csiDriverConfigLister := ateFactory.Ate().V1().CSIDriverConfigs().Lister() - - ateletPodInformerFactory, ateletPodInformer := controlapi.AteletInformer(clientset, ateletNamespace) - scInformerFactory := informers.NewSharedInformerFactory(clientset, 0) - storageClassLister := scInformerFactory.Storage().V1().StorageClasses().Lister() - - stopCh := make(chan struct{}) - defer close(stopCh) - ateletPodInformerFactory.Start(stopCh) - ateFactory.Start(stopCh) - scInformerFactory.Start(stopCh) - - ateletPodInformerFactory.WaitForCacheSync(stopCh) - ateFactory.WaitForCacheSync(stopCh) - scInformerFactory.WaitForCacheSync(stopCh) - - if err := controlapi.RegisterWorkerCount(otel.Meter("ateapi"), workerCache.Workers, workerPoolLister.List); err != nil { - serverboot.Fatal(ctx, "Failed to register worker-count metric", err) - } if err := controlapi.RegisterActorCrashes(otel.Meter("ateapi")); err != nil { serverboot.Fatal(ctx, "Failed to register actor-crashes metric", err) } - instruments, err := controlapi.NewInstruments(otel.Meter("ateapi")) - if err != nil { - serverboot.Fatal(ctx, "Failed to create metric instruments", err) - } - objectStorePluginConn, err := pluginsocket.Dial(*objectStorePluginSocket, pluginsocket.ReadyWait) if err != nil { serverboot.Fatal(ctx, "Failed to set up the object-store plugin client", err) @@ -328,17 +304,10 @@ func main() { serverboot.Fatal(ctx, "Object-store plugin is not serving", err) } - volPlugins := make(map[string]volume.VolumePluginControlPlane) - dialerOpts := []controlapi.DialerOption{ - controlapi.WithNodeGetter(func(ctx context.Context, nodeName string) error { - _, err := clientset.CoreV1().Nodes().Get(ctx, nodeName, metav1.GetOptions{}) - return err - }), - } + var ateletDialerOpts []controlapi.DialerOption if *ateletInsecure { - dialerOpts = append(dialerOpts, controlapi.WithInsecureCredentials()) + ateletDialerOpts = append(ateletDialerOpts, controlapi.WithInsecureCredentials()) } - ateletDialer := controlapi.NewAteletDialer(ateletPodInformer.GetIndexer(), ateletSPIFFEID, *ateletClientCredBundle, *podIdentityCACerts, dialerOpts...) actorIDCAPool, err := localca.NewRefreshingPool(*actorIDCAPoolFile) if err != nil { @@ -350,29 +319,38 @@ func main() { serverboot.Fatal(ctx, "while loading the Actor ID JWT authority pool", err) } - controlSrv := controlapi.NewRPCService( - persistence, - workerCache, - csiDriverConfigLister, - storageClassLister, - ateletDialer, - instruments, - *defaultEgressGatewayAddress, - *actorWorkflowDeadline, - volPlugins, - objectstore.NewControlProviderClient(objectStorePluginConn), - *actorJWTIssuer, - actorIDJWTAuthorityPool, - *snapshotLocation, - ) - - // Drive stored ActorTemplates through the golden actor flow. - templateReconciler := controlapi.NewActorTemplateReconciler(persistence, controlSrv, *templateResyncInterval) - templateReconciler.Start(shutdownCtx) - - // Crash the Actors lost when a Worker's worker restarts. - workerAssignmentReconciler := controlapi.NewWorkerAssignmentReconciler(persistence, workerCache) - workerAssignmentReconciler.Start(shutdownCtx) + cacheCtx, stopCaches := context.WithCancel(ctx) + defer stopCaches() + srv, err := server.New(cacheCtx, shutdownCtx, server.Config{ + Store: persistence, + KubeClient: clientset, + SubstrateCRDClient: ateClient, + AteletNamespace: ateletNamespace, + AteletSPIFFEID: ateletSPIFFEID, + AteletClientCredBundle: *ateletClientCredBundle, + PodIdentityCACerts: *podIdentityCACerts, + AteletDialerOptions: ateletDialerOpts, + ServerCreds: serverCreds, + Authn: authCfg, + Authorizer: authorizer, + ObjectStorePlugin: objectstore.NewControlProviderClient(objectStorePluginConn), + SnapshotLocation: *snapshotLocation, + ActorJWTIssuer: *actorJWTIssuer, + ActorJWTAuthorities: actorIDJWTAuthorityPool, + ActorIDCAs: actorIDCAPool, + DefaultEgressGatewayAddress: *defaultEgressGatewayAddress, + ActorWorkflowDeadline: *actorWorkflowDeadline, + TemplateResyncInterval: *templateResyncInterval, + TemplateReconcilerWorkers: *templateReconcilerWorkers, + IncludeErrorDebugInfo: config.GetIncludeErrorDebugInfo(), + PreviewGates: previewGates, + Meter: otel.Meter("ateapi"), + }) + if err != nil { + serverboot.Fatal(ctx, "Failed to build the server", err) + } + srv.StartReconcilers(shutdownCtx) + mux := srv.GRPC lisCfg := &net.ListenConfig{} lis, err := lisCfg.Listen(ctx, "tcp", *listenAddr) @@ -380,40 +358,6 @@ func main() { serverboot.Fatal(ctx, "Failed to start listener", err) } - if err := apiauthn.ValidateServerConfig(authCfg); err != nil { - serverboot.Fatal(ctx, "Invalid auth config", err) - } - - unaryInterceptors := []grpc.UnaryServerInterceptor{ - apiauthn.UnaryServerInterceptor(authCfg), - ateinterceptors.MaxDeadlineUnaryInterceptor(maxRPCDeadline), - ateinterceptors.ServerUnaryInterceptor, - authz.UnaryServerInterceptor(authorizer), - ateinterceptors.RejectUnknownFieldsUnaryInterceptor, - preview.UnaryServerInterceptor, - } - - mux := grpc.NewServer( - grpc.Creds(serverCreds), - grpc.StatsHandler(otelgrpc.NewServerHandler()), - // Close connections after an hour to allow for any - // client that doesn't use Kubernetes endpoint resolvers - // to eventually reobtain backend IPs. https://github.com/grpc/grpc/issues/12295 - grpc.KeepaliveParams(keepalive.ServerParameters{ - MaxConnectionAge: 1 * time.Hour, - MaxConnectionAgeGrace: maxRPCDeadline + time.Minute, - }), - grpc.ChainUnaryInterceptor(unaryInterceptors...), - grpc.ChainStreamInterceptor( - apiauthn.StreamServerInterceptor(authCfg), - authz.StreamServerInterceptor(), - preview.StreamServerInterceptor, - ), - ) - reflection.Register(mux) - ateapi.RegisterControlServer(mux, controlSrv) - ateapi.RegisterWorkerServiceServer(mux, workerservice.New(persistence, controlSrv, ateletSPIFFEID, actorIDCAPool, *actorJWTIssuer, actorIDJWTAuthorityPool)) - // Every RPC needs the store, so a replica that cannot reach it leaves the // Service until it can. Liveness stays green: the pool reconnects on its own. // The check pings over its own connection, so a busy request pool does not diff --git a/cmd/atecontroller/internal/controllers/cache.go b/cmd/atecontroller/internal/controllers/cache.go new file mode 100644 index 0000000000..3b32e43886 --- /dev/null +++ b/cmd/atecontroller/internal/controllers/cache.go @@ -0,0 +1,44 @@ +// Copyright 2026 The Agent Substrate 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 controllers + +import ( + corev1 "k8s.io/api/core/v1" + "k8s.io/apimachinery/pkg/fields" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// CacheOptions scopes workload resources to watchNamespace. An empty namespace +// watches all workloads. The CA pool stays in the system namespace, and +// cluster-scoped resources such as ClusterTrustBundles remain cluster-scoped. +func CacheOptions(watchNamespace, systemNamespace string) cache.Options { + pool := EgressMITMCAPoolRef(systemNamespace) + opts := cache.Options{ + ByObject: map[client.Object]cache.ByObject{ + &corev1.Secret{}: { + Namespaces: map[string]cache.Config{ + pool.Namespace: { + FieldSelector: fields.OneTermEqualSelector("metadata.name", pool.Name), + }, + }, + }, + }, + } + if watchNamespace != "" { + opts.DefaultNamespaces = map[string]cache.Config{watchNamespace: {}} + } + return opts +} diff --git a/cmd/atecontroller/internal/controllers/cache_test.go b/cmd/atecontroller/internal/controllers/cache_test.go new file mode 100644 index 0000000000..eebd153b8c --- /dev/null +++ b/cmd/atecontroller/internal/controllers/cache_test.go @@ -0,0 +1,239 @@ +// Copyright 2026 The Agent Substrate 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 controllers + +import ( + "context" + "testing" + "time" + + atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" + "go.ate.dev/substrate/cmd/atecontroller/internal/workersync" + "go.ate.dev/substrate/pkg/client/clientset/versioned" + "go.ate.dev/substrate/pkg/client/informers/externalversions" + appsv1 "k8s.io/api/apps/v1" + certsv1beta1 "k8s.io/api/certificates/v1beta1" + corev1 "k8s.io/api/core/v1" + networkingv1 "k8s.io/api/networking/v1" + rbacv1 "k8s.io/api/rbac/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/types" + "k8s.io/apimachinery/pkg/util/wait" + "k8s.io/client-go/kubernetes" + clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/rest" + "sigs.k8s.io/controller-runtime/pkg/cache" + "sigs.k8s.io/controller-runtime/pkg/client" +) + +// The real API server rejects cluster-wide requests for namespaced resources. +// Workload caches must still sync, while the system Secret and cluster-scoped +// configuration keep their independent scopes. +func TestNamespaceScopedCachesWithRBAC(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second) + defer cancel() + create := func(obj client.Object) { + t.Helper() + if err := k8sClient.Create(ctx, obj); err != nil { + t.Fatal(err) + } + deleteOnCleanup(t, obj) + } + newNamespace := func(prefix string) string { + t.Helper() + namespace := &corev1.Namespace{ObjectMeta: metav1.ObjectMeta{GenerateName: prefix}} + create(namespace) + return namespace.Name + } + workloadNamespace := newNamespace("scoped-workloads-") + systemNamespace := newNamespace("scoped-system-") + otherNamespace := newNamespace("scoped-other-") + username := workloadNamespace + "-reader" + create(&rbacv1.Role{ + ObjectMeta: metav1.ObjectMeta{Name: "workloads", Namespace: workloadNamespace}, + Rules: []rbacv1.PolicyRule{ + {APIGroups: []string{""}, Resources: []string{"pods"}, Verbs: []string{"get", "list", "watch"}}, + {APIGroups: []string{"apps"}, Resources: []string{"deployments"}, Verbs: []string{"get", "list", "watch"}}, + {APIGroups: []string{"networking.k8s.io"}, Resources: []string{"networkpolicies"}, Verbs: []string{"get", "list", "watch"}}, + {APIGroups: []string{"ate.dev"}, Resources: []string{"workerpools"}, Verbs: []string{"get", "list", "watch"}}, + }, + }) + pool := EgressMITMCAPoolRef(systemNamespace) + create(&rbacv1.Role{ + ObjectMeta: metav1.ObjectMeta{Name: "ca-pool", Namespace: systemNamespace}, + Rules: []rbacv1.PolicyRule{{APIGroups: []string{""}, Resources: []string{"secrets"}, ResourceNames: []string{pool.Name}, Verbs: []string{"get", "list", "watch"}}}, + }) + for namespace, role := range map[string]string{workloadNamespace: "workloads", systemNamespace: "ca-pool"} { + create(&rbacv1.RoleBinding{ + ObjectMeta: metav1.ObjectMeta{Name: role, Namespace: namespace}, + Subjects: []rbacv1.Subject{{Kind: "User", Name: username, APIGroup: rbacv1.GroupName}}, + RoleRef: rbacv1.RoleRef{Kind: "Role", Name: role, APIGroup: rbacv1.GroupName}, + }) + } + create(&rbacv1.ClusterRole{ + ObjectMeta: metav1.ObjectMeta{Name: username}, + Rules: []rbacv1.PolicyRule{ + {APIGroups: []string{"ate.dev"}, Resources: []string{"sandboxconfigs", "csidriverconfigs"}, Verbs: []string{"get", "list", "watch"}}, + {APIGroups: []string{"certificates.k8s.io"}, Resources: []string{"clustertrustbundles"}, Verbs: []string{"get", "list", "watch"}}, + }, + }) + create(&rbacv1.ClusterRoleBinding{ + ObjectMeta: metav1.ObjectMeta{Name: username}, + Subjects: []rbacv1.Subject{{Kind: "User", Name: username, APIGroup: rbacv1.GroupName}}, + RoleRef: rbacv1.RoleRef{Kind: "ClusterRole", Name: username, APIGroup: rbacv1.GroupName}, + }) + create(&corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: pool.Name, Namespace: systemNamespace}}) + _, roots := caPoolSecret(t, "scoped-root") + bundle := &certsv1beta1.ClusterTrustBundle{ + ObjectMeta: metav1.ObjectMeta{Name: username}, + Spec: certsv1beta1.ClusterTrustBundleSpec{TrustBundle: rootPEM(t, roots)}, + } + create(bundle) + for _, namespace := range []string{workloadNamespace, otherNamespace} { + create(&corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: "worker", Namespace: namespace, Labels: map[string]string{"ate.dev/worker-pool": "pool"}}, + Spec: corev1.PodSpec{Containers: []corev1.Container{{Name: "main", Image: "test.invalid/worker"}}}, + }) + } + restricted := rest.CopyConfig(cfg) + restricted.Impersonate = rest.ImpersonationConfig{UserName: username, Groups: []string{"system:authenticated"}} + kc := kubernetes.NewForConfigOrDie(restricted) + if err := wait.PollUntilContextCancel(ctx, 20*time.Millisecond, true, func(ctx context.Context) (bool, error) { + _, err := kc.CoreV1().Pods(workloadNamespace).List(ctx, metav1.ListOptions{}) + if apierrors.IsForbidden(err) { + return false, nil + } + return err == nil, err + }); err != nil { + t.Fatalf("waiting for RoleBinding: %v", err) + } + if _, err := kc.CoreV1().Pods("").List(ctx, metav1.ListOptions{}); !apierrors.IsForbidden(err) { + t.Fatalf("cluster-wide Pod list = %v, want Forbidden", err) + } + ac := versioned.NewForConfigOrDie(restricted) + if _, err := ac.AteV1().WorkerPools("").List(ctx, metav1.ListOptions{}); !apierrors.IsForbidden(err) { + t.Fatalf("cluster-wide WorkerPool list = %v, want Forbidden", err) + } + + workerFactory, workerInformer := workersync.WorkerPodInformer(kc, workloadNamespace) + ateFactory := externalversions.NewSharedInformerFactoryWithOptions(ac, 0, externalversions.WithNamespace(workloadNamespace)) + ateFactory.Ate().V1().WorkerPools().Informer() + ateFactory.Ate().V1().SandboxConfigs().Informer() + ateFactory.Ate().V1().CSIDriverConfigs().Informer() + workerFactory.Start(ctx.Done()) + ateFactory.Start(ctx.Done()) + t.Cleanup(func() { + cancel() + workerFactory.Shutdown() + ateFactory.Shutdown() + }) + for _, synced := range workerFactory.WaitForCacheSync(ctx.Done()) { + if !synced { + t.Fatal("Worker Pod cache did not sync with namespace Role") + } + } + for kind, synced := range ateFactory.WaitForCacheSync(ctx.Done()) { + if !synced { + t.Fatalf("%v cache did not sync", kind) + } + } + if got := workerInformer.GetStore().List(); len(got) != 1 || got[0].(*corev1.Pod).Namespace != workloadNamespace { + t.Fatalf("worker cache = %v, want only the watched namespace", got) + } + // Exercise the watch after the initial list has synced. + var updated corev1.Pod + key := types.NamespacedName{Namespace: workloadNamespace, Name: "worker"} + if err := k8sClient.Get(ctx, key, &updated); err != nil { + t.Fatal(err) + } + updated.Labels["watch-observed"] = "updated" + if err := k8sClient.Update(ctx, &updated); err != nil { + t.Fatal(err) + } + if err := wait.PollUntilContextCancel(ctx, 20*time.Millisecond, true, func(context.Context) (bool, error) { + obj, exists, err := workerInformer.GetIndexer().GetByKey(key.String()) + return exists && obj.(*corev1.Pod).Labels["watch-observed"] == "updated", err + }); err != nil { + t.Fatalf("namespace-scoped watch did not deliver Pod update: %v", err) + } + + for _, namespace := range []string{workloadNamespace, ""} { + t.Run("manager-namespace="+namespace, func(t *testing.T) { + config := restricted + if namespace == "" { + config = cfg + } + opts := CacheOptions(namespace, systemNamespace) + opts.Scheme = runtime.NewScheme() + if err := clientgoscheme.AddToScheme(opts.Scheme); err != nil { + t.Fatal(err) + } + if err := atev1.AddToScheme(opts.Scheme); err != nil { + t.Fatal(err) + } + c, err := cache.New(config, opts) + if err != nil { + t.Fatal(err) + } + for _, obj := range []client.Object{&corev1.Pod{}, &atev1.WorkerPool{}, &appsv1.Deployment{}, &networkingv1.NetworkPolicy{}, &corev1.Secret{}, &certsv1beta1.ClusterTrustBundle{}} { + if _, err := c.GetInformer(ctx, obj, cache.BlockUntilSynced(false)); err != nil { + t.Fatal(err) + } + } + cacheCtx, stop := context.WithCancel(ctx) + done := make(chan error, 1) + go func() { done <- c.Start(cacheCtx) }() + t.Cleanup(func() { + stop() + if err := <-done; err != nil { + t.Errorf("cache stopped: %v", err) + } + }) + if !c.WaitForCacheSync(ctx) { + t.Fatal("manager cache did not sync") + } + var secret corev1.Secret + if err := c.Get(ctx, pool, &secret); err != nil { + t.Fatalf("system CA pool: %v", err) + } + var cachedBundle certsv1beta1.ClusterTrustBundle + if err := c.Get(ctx, types.NamespacedName{Name: bundle.Name}, &cachedBundle); err != nil { + t.Fatalf("cluster trust bundle: %v", err) + } + if cachedBundle.Spec.TrustBundle != bundle.Spec.TrustBundle { + t.Fatal("cluster trust bundle cache did not contain the expected certificate") + } + var pods corev1.PodList + if err := c.List(ctx, &pods, client.MatchingLabels{"ate.dev/worker-pool": "pool"}); err != nil { + t.Fatal(err) + } + want := 1 + if namespace == "" { + want = 2 + } + if len(pods.Items) != want { + t.Fatalf("cached %d Pods, want %d", len(pods.Items), want) + } + if namespace != "" { + var pod corev1.Pod + if err := c.Get(ctx, types.NamespacedName{Namespace: otherNamespace, Name: "worker"}, &pod); err == nil { + t.Fatal("manager cache exposed a Pod outside the watched namespace") + } + } + }) + } +} diff --git a/cmd/atecontroller/internal/controllers/sandboxconfig_protection_controller.go b/cmd/atecontroller/internal/controllers/sandboxconfig_protection_controller.go index e6edd4f7be..d632f62922 100644 --- a/cmd/atecontroller/internal/controllers/sandboxconfig_protection_controller.go +++ b/cmd/atecontroller/internal/controllers/sandboxconfig_protection_controller.go @@ -41,6 +41,12 @@ type SandboxConfigProtectionReconciler struct { // can lag behind a pool that just started using a config, so a finalizer // is only removed after a live list finds no user. APIReader client.Reader + // WatchNamespace scopes the live list, which bypasses the (already + // scoped) manager cache and would otherwise reach for every namespace. + // A scoped deployment's RBAC cannot list beyond it, and pools outside + // the scope are another deployment's responsibility. Empty means all + // namespaces. + WatchNamespace string } //+kubebuilder:rbac:groups=ate.dev,resources=sandboxconfigs,verbs=get;list;watch;patch @@ -91,7 +97,7 @@ func (r *SandboxConfigProtectionReconciler) usedByWorkerPool(ctx context.Context return true, nil } var pools atev1.WorkerPoolList - if err := r.APIReader.List(ctx, &pools); err != nil { + if err := r.APIReader.List(ctx, &pools, client.InNamespace(r.WatchNamespace)); err != nil { return false, fmt.Errorf("failed to list WorkerPools: %w", err) } for i := range pools.Items { diff --git a/cmd/atecontroller/internal/controllers/sandboxconfig_protection_controller_test.go b/cmd/atecontroller/internal/controllers/sandboxconfig_protection_controller_test.go index 4d85385990..a93641e96c 100644 --- a/cmd/atecontroller/internal/controllers/sandboxconfig_protection_controller_test.go +++ b/cmd/atecontroller/internal/controllers/sandboxconfig_protection_controller_test.go @@ -390,3 +390,103 @@ func TestRemoveProtectionFinalizer(t *testing.T) { }, }) } + +// namespaceRecorder records the namespace a live list was scoped to. +type namespaceRecorder struct { + client.Reader + namespace string +} + +func (r *namespaceRecorder) List(ctx context.Context, list client.ObjectList, opts ...client.ListOption) error { + for _, opt := range opts { + if ns, ok := opt.(client.InNamespace); ok { + r.namespace = string(ns) + } + } + return r.Reader.List(ctx, list, opts...) +} + +// A scoped watch reaches only its own namespace, so the live list that guards +// finalizer removal must carry the watch namespace, and only a user inside it +// holds the finalizer on. An empty watch namespace keeps listing every +// namespace. +func TestSandboxConfigLiveListScopesToWatchNamespace(t *testing.T) { + t.Parallel() + scheme := runtime.NewScheme() + if err := atev1.AddToScheme(scheme); err != nil { + t.Fatalf("add scheme: %v", err) + } + now := metav1.Now() + + sc := makeSandboxConfig("sc", atev1.SandboxClassGvisor, true) + controllerutil.AddFinalizer(sc, atev1.SandboxConfigWorkerPoolProtectionFinalizer) + controllerutil.AddFinalizer(sc, testHoldFinalizer) + sc.DeletionTimestamp = &now + + user := func(ns string) *atev1.WorkerPool { + wp := makeWorkerPool("pool", ns, 1, "worker:v1") + wp.Status.SandboxClasses = []atev1.WorkerPoolSandboxClassStatus{{ + Name: atev1.SandboxClassGvisor, + ConfigRef: &atev1.SandboxConfigReference{Name: "sc"}, + }} + return wp + } + + tests := []struct { + name string + watchNamespace string + live []client.Object + want bool + wantNamespace string + }{ + { + name: "user outside the watched namespace does not hold the finalizer", + watchNamespace: "watched", + live: []client.Object{user("elsewhere")}, + want: false, + wantNamespace: "watched", + }, + { + name: "user inside the watched namespace holds the finalizer", + watchNamespace: "watched", + live: []client.Object{user("watched")}, + want: true, + wantNamespace: "watched", + }, + { + name: "empty watch namespace lists every namespace", + watchNamespace: "", + live: []client.Object{user("elsewhere")}, + want: true, + wantNamespace: "", + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + cached := fake.NewClientBuilder().WithScheme(scheme).WithObjects(sc.DeepCopy()). + WithIndex(&atev1.WorkerPool{}, workerPoolSandboxConfigIndex, func(obj client.Object) []string { + return sandboxConfigsInUse(obj.(*atev1.WorkerPool)) + }).Build() + reader := &namespaceRecorder{Reader: fake.NewClientBuilder().WithScheme(scheme).WithObjects(tc.live...).Build()} + r := &SandboxConfigProtectionReconciler{Client: cached, APIReader: reader, WatchNamespace: tc.watchNamespace} + + if _, err := r.Reconcile(t.Context(), ctrl.Request{NamespacedName: types.NamespacedName{Name: sc.Name}}); err != nil { + t.Fatalf("Reconcile error = %v", err) + } + if reader.namespace != tc.wantNamespace { + t.Errorf("live list namespace = %q, want %q", reader.namespace, tc.wantNamespace) + } + got := &atev1.SandboxConfig{} + if err := cached.Get(t.Context(), types.NamespacedName{Name: sc.Name}, got); err != nil { + t.Fatalf("get SandboxConfig: %v", err) + } + if has := controllerutil.ContainsFinalizer(got, atev1.SandboxConfigWorkerPoolProtectionFinalizer); has != tc.want { + t.Errorf("has protection finalizer = %v, want %v", has, tc.want) + } + if !controllerutil.ContainsFinalizer(got, testHoldFinalizer) { + t.Errorf("lost %s", testHoldFinalizer) + } + }) + } +} diff --git a/cmd/atecontroller/internal/controllers/workerpool_apply.go b/cmd/atecontroller/internal/controllers/workerpool_apply.go index 1244d6498a..ed45ef9889 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_apply.go +++ b/cmd/atecontroller/internal/controllers/workerpool_apply.go @@ -16,6 +16,7 @@ package controllers import ( "slices" + "strconv" "strings" appsv1 "k8s.io/api/apps/v1" @@ -30,7 +31,6 @@ import ( "go.ate.dev/substrate/internal/deviceplugin" "go.ate.dev/substrate/internal/installdefaults" "go.ate.dev/substrate/internal/nodepath" - "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/workercapacity" ) @@ -93,9 +93,19 @@ type workerOTelSettings struct { MetricsExporter string } +// WorkerPprofSettings is the pprof configuration propagated to worker pods. +// Zero value disables worker pprof. +type WorkerPprofSettings struct { + Enabled bool + MutexFraction int + BlockRate int +} + // workerPoolLabel names the WorkerPool on each of its worker pods. const workerPoolLabel = "ate.dev/worker-pool" +const workerPprofPort = 6060 + const ( atunnelIdentityVolume = "atunnel-identity" atunnelIdentityMountPath = "/run/podidentity.podcert.ate.dev" @@ -106,9 +116,9 @@ const ( // buildDeploymentApplyConfig constructs the SSA apply configuration for the // Deployment managed by a WorkerPool. Only fields owned by this controller -// are declared here. otel is propagated to the worker container (see -// workerContainerEnv). -func buildDeploymentApplyConfig(wp *atev1.WorkerPool, otel workerOTelSettings, systemNamespace, ateletServiceAccount, routerServiceAccount, dnsEgressPolicy string) *appsv1ac.DeploymentApplyConfiguration { +// are declared here. otel and pprof are propagated to the worker container +// (see workerContainerEnv). +func buildDeploymentApplyConfig(wp *atev1.WorkerPool, otel workerOTelSettings, pprof WorkerPprofSettings, systemNamespace, ateletServiceAccount, routerServiceAccount, dnsEgressPolicy string, previewGates []string) *appsv1ac.DeploymentApplyConfiguration { labels := map[string]string{} annotations := map[string]string{} if wp.Spec.Template != nil { @@ -153,20 +163,9 @@ func buildDeploymentApplyConfig(wp *atev1.WorkerPool, otel workerOTelSettings, s "--dns-egress-policy="+dnsEgressPolicy, ) - // worker gets preview features when the controller has them. - enabledGates := func() []string { - ret := []string{} - for k, v := range preview.AsMap() { - if v { - ret = append(ret, k) - } - } - // Map order is random; a stable arg avoids needless rollouts. - slices.Sort(ret) - return ret - } - previewArg := "--preview=" + strings.Join(enabledGates(), ",") - args = append(args, previewArg) + // worker gets preview features when the controller has them. Sort the + // gates so the arg is stable and avoids needless rollouts. + args = append(args, "--preview="+strings.Join(slices.Sorted(slices.Values(previewGates)), ",")) containerAC := corev1ac.Container(). WithName("worker"). @@ -189,7 +188,7 @@ func buildDeploymentApplyConfig(wp *atev1.WorkerPool, otel workerOTelSettings, s WithPath("/readyz"). WithPort(intstr.FromString("readyz")))). WithSecurityContext(workerSecurityContext(wp.Spec.DefaultSandboxClass())). - WithEnv(workerContainerEnv(otel)...). + WithEnv(workerContainerEnv(otel, pprof)...). WithVolumeMounts( corev1ac.VolumeMount(). WithName(workerCapacityVolume). @@ -208,6 +207,12 @@ func buildDeploymentApplyConfig(wp *atev1.WorkerPool, otel workerOTelSettings, s WithMountPath(atunnelEgressTrustMountPath). WithReadOnly(true), ) + if pprof.Enabled { + containerAC.WithPorts(corev1ac.ContainerPort(). + WithName("pprof"). + WithContainerPort(workerPprofPort). + WithProtocol(corev1.ProtocolTCP)) + } podSpecAC := corev1ac.PodSpec(). WithSecurityContext(corev1ac.PodSecurityContext(). @@ -293,7 +298,7 @@ func buildDeploymentApplyConfig(wp *atev1.WorkerPool, otel workerOTelSettings, s // exports through atelet's relay whenever atelet has a collector, and adds the // OTLP endpoint only when one is configured. Every ref precedes // OTEL_RESOURCE_ATTRIBUTES so its $(...) substitutions resolve. -func workerContainerEnv(otel workerOTelSettings) []*corev1ac.EnvVarApplyConfiguration { +func workerContainerEnv(otel workerOTelSettings, pprof WorkerPprofSettings) []*corev1ac.EnvVarApplyConfiguration { // The pool pair also labels every usage record. A worker pod runs in its // WorkerPool's namespace. envs := []*corev1ac.EnvVarApplyConfiguration{ @@ -345,6 +350,26 @@ func workerContainerEnv(otel workerOTelSettings) []*corev1ac.EnvVarApplyConfigur WithName("OTEL_METRICS_EXPORTER"). WithValue(otel.MetricsExporter)) } + if pprof.Enabled { + envs = append(envs, + corev1ac.EnvVar(). + WithName("ATE_PPROF_LISTEN_ADDR"). + WithValue(":"+strconv.Itoa(workerPprofPort)), + corev1ac.EnvVar(). + WithName("GRPC_GO_SERVER_GOROUTINE_LABELS"). + WithValue("grpc.method=true"), + ) + if pprof.MutexFraction > 0 { + envs = append(envs, corev1ac.EnvVar(). + WithName("ATE_PPROF_MUTEX_FRACTION"). + WithValue(strconv.Itoa(pprof.MutexFraction))) + } + if pprof.BlockRate > 0 { + envs = append(envs, corev1ac.EnvVar(). + WithName("ATE_PPROF_BLOCK_RATE"). + WithValue(strconv.Itoa(pprof.BlockRate))) + } + } return envs } @@ -383,6 +408,12 @@ func fieldRefEnv(name, fieldPath string) *corev1ac.EnvVarApplyConfiguration { // needs NET_ADMIN/NET_RAW, and rootfs ownership and modes need // DAC_OVERRIDE/FOWNER/CHOWN. // +// IPC_LOCK lets runsc create each sandbox's pin ring, a *disabled* io_uring +// used to parallelize kernel FD release operations with gVisor's own teardown +// process, making sandbox teardown faster. +// Without the capability the kernel charges each ring to uid 0, which fails +// with ENOMEM when that is over RLIMIT_MEMLOCK. +// // The sandbox's user namespace supplies its own SYS_CHROOT (gofer) and // SYS_PTRACE (systrap); the outer worker needs neither, nor SETPCAP. That user // namespace comes from runsc's modifySpecForDirectfs, which creates an @@ -394,7 +425,7 @@ func fieldRefEnv(name, fieldPath string) *corev1ac.EnvVarApplyConfiguration { // does not require MKNOD. var workerGvisorCapabilities = []corev1.Capability{ "NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", - "FOWNER", "CHOWN", "NET_RAW", "SETFCAP", + "FOWNER", "CHOWN", "NET_RAW", "SETFCAP", "IPC_LOCK", } // workerMicroVMCapabilities retains virtiofsd's eight default child @@ -588,6 +619,9 @@ func applyWorkerPoolPodTemplate( podSpecAC.Tolerations = []corev1ac.TolerationApplyConfiguration{} podSpecAC.WithPriorityClassName("") podSpecAC.WithServiceAccountName(installdefaults.WorkerServiceAccount) + // Workers never call the Kubernetes API. Set here, not only on the + // ServiceAccount, so a template serviceAccountName can't bring the token back. + podSpecAC.WithAutomountServiceAccountToken(false) podSpecAC.WithAffinity(corev1ac.Affinity()) resourcesAC := corev1ac.ResourceRequirements() containerAC.WithResources(resourcesAC) diff --git a/cmd/atecontroller/internal/controllers/workerpool_apply_test.go b/cmd/atecontroller/internal/controllers/workerpool_apply_test.go index 2ae55a2584..448f8fc67a 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_apply_test.go +++ b/cmd/atecontroller/internal/controllers/workerpool_apply_test.go @@ -224,7 +224,7 @@ func TestBuildDeploymentApplyConfig(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - got := buildDeploymentApplyConfig(tt.wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel) + got := buildDeploymentApplyConfig(tt.wp, workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil) if diff := cmp.Diff(tt.want, got); diff != "" { t.Fatalf("buildDeploymentApplyConfig() mismatch (-want +got):\n%s", diff) } @@ -244,7 +244,7 @@ func TestBuildDeploymentApplyConfigMetadata(t *testing.T) { }, }) - got := buildDeploymentApplyConfig(wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel) + got := buildDeploymentApplyConfig(wp, workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil) wantLabels := map[string]string{ "project": "agent-substrate", "team": "compute", @@ -302,7 +302,7 @@ func TestSandboxClassToleration(t *testing.T) { }}, }) wp.Spec.SandboxClasses = []atev1.WorkerPoolSandboxClass{{Name: tt.class}} - ps := buildDeploymentApplyConfig(wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel).Spec.Template.Spec + ps := buildDeploymentApplyConfig(wp, workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil).Spec.Template.Spec var classValues []string hasTemplateToleration := false @@ -350,7 +350,7 @@ func TestMicroVMPodShape(t *testing.T) { t.Run(tt.name, func(t *testing.T) { wp := testWorkerPoolApplyConfig(nil) wp.Spec.SandboxClasses = []atev1.WorkerPoolSandboxClass{{Name: tt.class}} - ps := buildDeploymentApplyConfig(wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel).Spec.Template.Spec + ps := buildDeploymentApplyConfig(wp, workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil).Spec.Template.Spec // /dev/kvm must come from the device plugin, never a hostPath: a // hostPath mount carries no cgroup device allow rule, and the @@ -437,7 +437,7 @@ func TestMicroVMDeviceRequestsPreserveTemplateResources(t *testing.T) { }, }) wp.Spec.SandboxClasses = []atev1.WorkerPoolSandboxClass{{Name: atev1.SandboxClassMicroVM}} - c := buildDeploymentApplyConfig(wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel).Spec.Template.Spec.Containers[0] + c := buildDeploymentApplyConfig(wp, workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil).Spec.Template.Spec.Containers[0] if got, ok := deviceLimit(c, string(corev1.ResourceMemory)); !ok || got != "2Gi" { t.Errorf("memory limit = %q (present=%v), want 2Gi", got, ok) @@ -460,8 +460,8 @@ func TestWorkerSecurityContextByClass(t *testing.T) { // virtiofsd's sandbox pivot_root(), which the default profile denies. wantSeccompUnconfined bool }{ - {"gvisor default", "", []corev1.Capability{"NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER", "CHOWN", "NET_RAW", "SETFCAP"}, true}, - {"gvisor explicit", atev1.SandboxClassGvisor, []corev1.Capability{"NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER", "CHOWN", "NET_RAW", "SETFCAP"}, true}, + {"gvisor default", "", []corev1.Capability{"NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER", "CHOWN", "NET_RAW", "SETFCAP", "IPC_LOCK"}, true}, + {"gvisor explicit", atev1.SandboxClassGvisor, []corev1.Capability{"NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER", "CHOWN", "NET_RAW", "SETFCAP", "IPC_LOCK"}, true}, {"microvm", atev1.SandboxClassMicroVM, []corev1.Capability{"NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER", "CHOWN", "MKNOD", "SETFCAP", "FSETID", "SETPCAP"}, true}, } for _, tt := range tests { @@ -470,7 +470,7 @@ func TestWorkerSecurityContextByClass(t *testing.T) { if tt.class != "" { wp.Spec.SandboxClasses = []atev1.WorkerPoolSandboxClass{{Name: tt.class}} } - sc := buildDeploymentApplyConfig(wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel).Spec.Template.Spec.Containers[0].SecurityContext + sc := buildDeploymentApplyConfig(wp, workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil).Spec.Template.Spec.Containers[0].SecurityContext if sc.AllowPrivilegeEscalation == nil || *sc.AllowPrivilegeEscalation { t.Errorf("AllowPrivilegeEscalation = %v, want false for every class", sc.AllowPrivilegeEscalation) } @@ -509,7 +509,7 @@ func TestWorkerSecurityContextByClass(t *testing.T) { // TestTerminationGracePeriodSeconds asserts the pod's grace period is hardcoded to 3600s. func TestTerminationGracePeriodSeconds(t *testing.T) { wp := testWorkerPoolApplyConfig(nil) - ps := buildDeploymentApplyConfig(wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel).Spec.Template.Spec + ps := buildDeploymentApplyConfig(wp, workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil).Spec.Template.Spec if ps.TerminationGracePeriodSeconds == nil { t.Fatalf("TerminationGracePeriodSeconds not set") } @@ -523,7 +523,7 @@ func TestTerminationGracePeriodSeconds(t *testing.T) { // actors' drain window. func TestRolloutStrategy(t *testing.T) { wp := testWorkerPoolApplyConfig(nil) - spec := buildDeploymentApplyConfig(wp, workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel).Spec + spec := buildDeploymentApplyConfig(wp, workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil).Spec if spec.Strategy == nil || spec.Strategy.RollingUpdate == nil { t.Fatalf("Strategy.RollingUpdate not set") } @@ -558,7 +558,7 @@ func TestBuildDeploymentApplyConfigOTelEndpoint(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{Endpoint: tt.endpoint}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{Endpoint: tt.endpoint}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] env := envByName(c.Env) @@ -597,6 +597,89 @@ func TestBuildDeploymentApplyConfigOTelEndpoint(t *testing.T) { } } +// TestBuildDeploymentApplyConfigWorkerPprof asserts worker pprof env vars and +// port 6060 are added only when enabled, and contention rates only when positive. +func TestBuildDeploymentApplyConfigWorkerPprof(t *testing.T) { + pprofEnvKeys := []string{ + "ATE_PPROF_LISTEN_ADDR", + "GRPC_GO_SERVER_GOROUTINE_LABELS", + "ATE_PPROF_MUTEX_FRACTION", + "ATE_PPROF_BLOCK_RATE", + } + tests := []struct { + name string + pprof WorkerPprofSettings + wantEnv map[string]string + wantPort bool + }{ + { + name: "off leaves worker template unchanged", + pprof: WorkerPprofSettings{Enabled: false, MutexFraction: 10, BlockRate: 1000000}, + }, + { + name: "on without positive rates", + pprof: WorkerPprofSettings{Enabled: true, MutexFraction: 0, BlockRate: -1}, + wantEnv: map[string]string{ + "ATE_PPROF_LISTEN_ADDR": ":6060", + "GRPC_GO_SERVER_GOROUTINE_LABELS": "grpc.method=true", + }, + wantPort: true, + }, + { + name: "on with positive rates", + pprof: WorkerPprofSettings{Enabled: true, MutexFraction: 10, BlockRate: 1000000}, + wantEnv: map[string]string{ + "ATE_PPROF_LISTEN_ADDR": ":6060", + "GRPC_GO_SERVER_GOROUTINE_LABELS": "grpc.method=true", + "ATE_PPROF_MUTEX_FRACTION": "10", + "ATE_PPROF_BLOCK_RATE": "1000000", + }, + wantPort: true, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + d := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, tt.pprof, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil) + c := d.Spec.Template.Spec.Containers[0] + env := envByName(c.Env) + for _, k := range pprofEnvKeys { + got, ok := env[k] + want, wantSet := tt.wantEnv[k] + if ok != wantSet || (ok && got.value != want) { + t.Errorf("%s = %q (present %v), want %q (present %v)", k, got.value, ok, want, wantSet) + } + } + + if !tt.wantPort { + if diff := cmp.Diff(expectedDeploymentApplyConfig(nil), d); diff != "" { + t.Errorf("disabled worker pprof changed deployment (-want +got):\n%s", diff) + } + return + } + + var portNames []string + var pprofPorts []corev1ac.ContainerPortApplyConfiguration + for _, p := range c.Ports { + if p.Name != nil { + portNames = append(portNames, *p.Name) + if *p.Name == "pprof" { + pprofPorts = append(pprofPorts, p) + } + } + } + wantPorts := []string{"https", "connect", "readyz", "pprof"} + if diff := cmp.Diff(wantPorts, portNames); diff != "" { + t.Errorf("container port names mismatch (-want +got):\n%s", diff) + } + if len(pprofPorts) != 1 || pprofPorts[0].ContainerPort == nil || *pprofPorts[0].ContainerPort != 6060 || + pprofPorts[0].Protocol == nil || *pprofPorts[0].Protocol != corev1.ProtocolTCP { + t.Errorf("pprof port = %+v, want 6060/TCP", pprofPorts) + } + }) + } +} + // TestBuildDeploymentApplyConfigMetricExportTuning asserts the export interval and // per-export timeout reach the worker container only when each is set, with or // without an endpoint, since the worker also exports through atelet's relay. The @@ -639,7 +722,7 @@ func TestBuildDeploymentApplyConfigMetricExportTuning(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] env := envByName(c.Env) for _, k := range []string{"OTEL_METRIC_EXPORT_INTERVAL", "OTEL_METRIC_EXPORT_TIMEOUT"} { @@ -696,7 +779,7 @@ func TestBuildDeploymentApplyConfigTracesSamplerPropagation(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] env := envByName(c.Env) for _, k := range []string{"OTEL_TRACES_SAMPLER", "OTEL_TRACES_SAMPLER_ARG"} { @@ -731,7 +814,7 @@ func TestBuildDeploymentApplyConfigTracesExporterPropagation(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] got, ok := envByName(c.Env)["OTEL_TRACES_EXPORTER"] if ok != tt.wantSet || got.value != tt.want { @@ -758,7 +841,7 @@ func TestBuildDeploymentApplyConfigMetricsExporterPropagation(t *testing.T) { } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] got, ok := envByName(c.Env)["OTEL_METRICS_EXPORTER"] if ok != tt.wantSet || got.value != tt.want { @@ -981,6 +1064,7 @@ func expectedDeploymentApplyConfig(mutatePodSpec func(*corev1ac.PodSpecApplyConf } podSpecAC.WithPriorityClassName("") podSpecAC.WithServiceAccountName("ateworker") + podSpecAC.WithAutomountServiceAccountToken(false) podSpecAC.WithAffinity(corev1ac.Affinity()) podSpecAC.WithTerminationGracePeriodSeconds(workerTerminationGracePeriodSeconds) if mutatePodSpec != nil { @@ -1020,7 +1104,7 @@ func expectedDeploymentApplyConfig(mutatePodSpec func(*corev1ac.PodSpecApplyConf func TestBuildDeploymentAtunnelIdentitiesRelocatedNamespace(t *testing.T) { const relocated = "substrate-test" - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, relocated, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, WorkerPprofSettings{}, relocated, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] want := map[string]string{ @@ -1055,7 +1139,7 @@ func TestBuildDeploymentAtunnelIdentitiesPrefixedServiceAccounts(t *testing.T) { router = "kagent-atenet-router" ) - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, namespace, atelet, router, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, WorkerPprofSettings{}, namespace, atelet, router, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] want := map[string]string{ @@ -1080,8 +1164,8 @@ func TestBuildDeploymentAtunnelIdentitiesPrefixedServiceAccounts(t *testing.T) { // --atunnel-broker-identity existed, which exits on the unrecognized flag, so // passing it would crashloop that pool's workers. func TestBuildDeploymentOmitsBrokerIdentityForCanonicalInstall(t *testing.T) { - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, - installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, WorkerPprofSettings{}, + installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] for _, arg := range c.Args { @@ -1107,7 +1191,7 @@ func TestBuildDeploymentOmitsBrokerIdentityForCanonicalInstall(t *testing.T) { // pool from the label the controller puts on the pod, so the usage records // name the pool the pod belongs to. func TestBuildDeploymentApplyConfigWorkerPoolEnv(t *testing.T) { - d := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel) + d := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil) c := d.Spec.Template.Spec.Containers[0] var path string for _, e := range c.Env { @@ -1138,7 +1222,7 @@ func TestBuildDeploymentApplyConfigLogsExporter(t *testing.T) { {"set without endpoint", workerOTelSettings{LogsExporter: "otlp"}, "otlp"}, } { t.Run(tt.name, func(t *testing.T) { - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), tt.otel, WorkerPprofSettings{}, installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, nil). Spec.Template.Spec.Containers[0] got, ok := envByName(c.Env)["OTEL_LOGS_EXPORTER"] if ok != (tt.want != "") || (ok && got.value != tt.want) { @@ -1150,6 +1234,22 @@ func TestBuildDeploymentApplyConfigLogsExporter(t *testing.T) { // worker gets preview features when the controller has them. func TestBuildDeploymentPreview(t *testing.T) { + check := func(t *testing.T, gates, want []string) { + t.Helper() + c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, WorkerPprofSettings{}, + installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel, gates). + Spec.Template.Spec.Containers[0] + var got []string + for _, arg := range c.Args { + if strings.HasPrefix(arg, "--preview") { + got = append(got, arg) + } + } + if diff := cmp.Diff(want, got); diff != "" { + t.Errorf("--preview args mismatch (-want +got):\n%s", diff) + } + } + for _, tc := range []struct { name string gates []string @@ -1160,19 +1260,16 @@ func TestBuildDeploymentPreview(t *testing.T) { {name: "ALL", gates: []string{"ALL"}, want: []string{"--preview=Fake,Phony"}}, } { t.Run(tc.name, func(t *testing.T) { - preview.InitForTestFake(t, []preview.Gate{"Fake", "Phony"}, tc.gates...) - c := buildDeploymentApplyConfig(testWorkerPoolApplyConfig(nil), workerOTelSettings{}, - installdefaults.SystemNamespace, installdefaults.AteletServiceAccount, installdefaults.RouterServiceAccount, egresspolicy.DNSEgressPolicyEnforceInAtunnel). - Spec.Template.Spec.Containers[0] - var got []string - for _, arg := range c.Args { - if strings.HasPrefix(arg, "--preview") { - got = append(got, arg) - } - } - if diff := cmp.Diff(tc.want, got); diff != "" { - t.Errorf("--preview args mismatch (-want +got):\n%s", diff) - } + gates := preview.NewForTestFake(t, []preview.Gate{"Fake", "Phony"}, tc.gates...) + check(t, gates.Enabled(), tc.want) }) } + + t.Run("unsorted", func(t *testing.T) { + in := []string{"Phony", "Fake"} + check(t, in, []string{"--preview=Fake,Phony"}) + if diff := cmp.Diff([]string{"Phony", "Fake"}, in); diff != "" { + t.Errorf("input slice mutated (-want +got):\n%s", diff) + } + }) } diff --git a/cmd/atecontroller/internal/controllers/workerpool_controller.go b/cmd/atecontroller/internal/controllers/workerpool_controller.go index 23b1906a4f..71f7ce4e8f 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_controller.go +++ b/cmd/atecontroller/internal/controllers/workerpool_controller.go @@ -78,6 +78,8 @@ type WorkerPoolReconciler struct { // OTelMetricsExporter is the OTEL_METRICS_EXPORTER propagated to worker pods. // Empty keeps the ateworker binary's default. OTelMetricsExporter string + // WorkerPprof is the pprof configuration propagated to worker pods. + WorkerPprof WorkerPprofSettings // SystemNamespace is the namespace substrate's control plane runs in, and // AteletServiceAccount / RouterServiceAccount are the ServiceAccounts those // components run as. Together they name the SPIFFE identities that atunnel @@ -89,6 +91,9 @@ type WorkerPoolReconciler struct { RouterServiceAccount string // DNSEgressPolicy is the --dns-egress-policy mode propagated to worker pods. DNSEgressPolicy string + // PreviewGates are the names of the controller's enabled preview gates, + // propagated to worker pods. + PreviewGates []string // Recorder emits a Normal event each time a pool's SandboxConfig // changes, and a Warning event when a class stops resolving. Recorder events.EventRecorder @@ -340,7 +345,7 @@ func (r *WorkerPoolReconciler) applyDeployment(ctx context.Context, wp *atev1.Wo LogsExporter: r.OTelLogsExporter, TracesExporter: r.OTelTracesExporter, MetricsExporter: r.OTelMetricsExporter, - }, r.SystemNamespace, r.AteletServiceAccount, r.RouterServiceAccount, r.DNSEgressPolicy) + }, r.WorkerPprof, r.SystemNamespace, r.AteletServiceAccount, r.RouterServiceAccount, r.DNSEgressPolicy, r.PreviewGates) if err := r.Apply(ctx, depAC, client.FieldOwner(workerPoolFieldOwner), client.ForceOwnership); err != nil { return fmt.Errorf("failed to apply Deployment: %w", err) } @@ -350,7 +355,8 @@ func (r *WorkerPoolReconciler) applyDeployment(ctx context.Context, wp *atev1.Wo // applyWorkerServiceAccount creates the default ServiceAccount worker pods run // as. The pools in a namespace share it, so none of them owns it. func (r *WorkerPoolReconciler) applyWorkerServiceAccount(ctx context.Context, namespace string) error { - saAC := corev1ac.ServiceAccount(installdefaults.WorkerServiceAccount, namespace) + saAC := corev1ac.ServiceAccount(installdefaults.WorkerServiceAccount, namespace). + WithAutomountServiceAccountToken(false) if err := r.Apply(ctx, saAC, client.FieldOwner(workerPoolFieldOwner), client.ForceOwnership); err != nil { return fmt.Errorf("failed to apply worker ServiceAccount: %w", err) } diff --git a/cmd/atecontroller/internal/controllers/workerpool_controller_test.go b/cmd/atecontroller/internal/controllers/workerpool_controller_test.go index 3b6d3502ba..f254ab29a3 100644 --- a/cmd/atecontroller/internal/controllers/workerpool_controller_test.go +++ b/cmd/atecontroller/internal/controllers/workerpool_controller_test.go @@ -17,12 +17,14 @@ package controllers import ( "context" "fmt" + "log/slog" "os" "reflect" "slices" "testing" "time" + "github.com/go-logr/logr" "go.opentelemetry.io/otel/attribute" sdkmetric "go.opentelemetry.io/otel/sdk/metric" "go.opentelemetry.io/otel/sdk/metric/metricdata" @@ -38,6 +40,7 @@ import ( clientgoscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" "k8s.io/client-go/util/retry" + "k8s.io/klog/v2" "k8s.io/utils/ptr" ctrl "sigs.k8s.io/controller-runtime" "sigs.k8s.io/controller-runtime/pkg/client" @@ -56,6 +59,9 @@ var ( ) func TestMain(m *testing.M) { + // m.Run redirects os.Stderr in JSON mode while background controllers log. + klog.SetLogger(logr.FromSlogHandler(slog.NewTextHandler(os.Stdout, nil))) + var stopEnv func() cfg, stopEnv = testenv.Start() @@ -420,6 +426,9 @@ func TestWorkerPoolRunsWorkersAsWorkerServiceAccount(t *testing.T) { if len(sa.OwnerReferences) != 0 { t.Errorf("worker ServiceAccount has owners %v, want none", sa.OwnerReferences) } + if sa.AutomountServiceAccountToken == nil || *sa.AutomountServiceAccountToken { + t.Errorf("worker ServiceAccount automountServiceAccountToken = %v, want false", sa.AutomountServiceAccountToken) + } } // TestWorkerPoolWithServiceAccountSkipsDefault checks that a pool naming its own diff --git a/cmd/atecontroller/internal/workersync/fakecontrol_test.go b/cmd/atecontroller/internal/workersync/fakecontrol_test.go index 0f1eb32c14..d0f37c55b8 100644 --- a/cmd/atecontroller/internal/workersync/fakecontrol_test.go +++ b/cmd/atecontroller/internal/workersync/fakecontrol_test.go @@ -52,7 +52,7 @@ type fakeControl struct { // createHook, when set, decides CreateWorker's outcome: a non-nil error is // returned and nothing is registered. - createHook func(*ateapi.Worker) error + createHook func(context.Context, *ateapi.Worker) error // listHook, when set, runs before each ListWorkers and can fail the call. listHook func(*ateapi.ListWorkersRequest) error // updateHook, when set, runs once before an UpdateWorker applies, so a test @@ -113,7 +113,7 @@ func (f *fakeControl) storeLocked(w *ateapi.Worker) { f.workers[w.GetMetadata().GetName()] = w } -func (f *fakeControl) setCreateHook(hook func(*ateapi.Worker) error) { +func (f *fakeControl) setCreateHook(hook func(context.Context, *ateapi.Worker) error) { f.mu.Lock() defer f.mu.Unlock() f.createHook = hook @@ -150,12 +150,12 @@ func (f *fakeControl) GetWorker(_ context.Context, in *ateapi.GetWorkerRequest, return nil, status.Errorf(codes.NotFound, "Worker %s not found", name) } -func (f *fakeControl) CreateWorker(_ context.Context, in *ateapi.CreateWorkerRequest, _ ...grpc.CallOption) (*ateapi.Worker, error) { +func (f *fakeControl) CreateWorker(ctx context.Context, in *ateapi.CreateWorkerRequest, _ ...grpc.CallOption) (*ateapi.Worker, error) { f.mu.Lock() defer f.mu.Unlock() if f.createHook != nil { - if err := f.createHook(in.GetWorker()); err != nil { + if err := f.createHook(ctx, in.GetWorker()); err != nil { return nil, err } } diff --git a/cmd/atecontroller/internal/workersync/informer.go b/cmd/atecontroller/internal/workersync/informer.go index 387531a1e6..84b3464ff6 100644 --- a/cmd/atecontroller/internal/workersync/informer.go +++ b/cmd/atecontroller/internal/workersync/informer.go @@ -25,11 +25,13 @@ import ( ) // WorkerPodInformer creates a SharedInformerFactory and SharedIndexInformer for -// worker pods. The resync period re-delivers every cached pod as an update, so +// worker pods in namespace, or all namespaces when empty. The resync period +// re-delivers every cached pod as an update, so // a registry record that drifted without a corresponding pod event is repaired // on the next sweep. -func WorkerPodInformer(kc kubernetes.Interface) (informers.SharedInformerFactory, cache.SharedIndexInformer) { +func WorkerPodInformer(kc kubernetes.Interface, namespace string) (informers.SharedInformerFactory, cache.SharedIndexInformer) { factory := informers.NewSharedInformerFactoryWithOptions(kc, 5*time.Minute, + informers.WithNamespace(namespace), informers.WithTweakListOptions(func(options *metav1.ListOptions) { options.LabelSelector = workerPodLabel }), diff --git a/cmd/atecontroller/internal/workersync/informer_test.go b/cmd/atecontroller/internal/workersync/informer_test.go new file mode 100644 index 0000000000..1c0d327012 --- /dev/null +++ b/cmd/atecontroller/internal/workersync/informer_test.go @@ -0,0 +1,70 @@ +// Copyright 2026 The Agent Substrate 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 workersync + +import ( + "context" + "testing" + "time" + + "k8s.io/apimachinery/pkg/runtime" + "k8s.io/apimachinery/pkg/watch" + "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" +) + +func TestWorkerPodInformerNamespace(t *testing.T) { + for _, namespace := range []string{"agent-workloads", ""} { + t.Run("namespace="+namespace, func(t *testing.T) { + client := fake.NewClientset() + actions := make(chan k8stesting.Action, 10) + client.PrependReactor("list", "pods", func(action k8stesting.Action) (bool, runtime.Object, error) { + actions <- action + return false, nil, nil + }) + client.PrependWatchReactor("pods", func(action k8stesting.Action) (bool, watch.Interface, error) { + actions <- action + return false, nil, nil + }) + factory, _ := WorkerPodInformer(client, namespace) + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + t.Cleanup(func() { + cancel() + factory.Shutdown() + }) + factory.Start(ctx.Done()) + for _, verb := range []string{"list", "watch"} { + select { + case action := <-actions: + if action.GetVerb() != verb || action.GetNamespace() != namespace { + t.Fatalf("requested %s pods in namespace %q, want %s in %q", action.GetVerb(), action.GetNamespace(), verb, namespace) + } + var selector string + switch action := action.(type) { + case k8stesting.ListAction: + selector = action.GetListRestrictions().Labels.String() + case k8stesting.WatchAction: + selector = action.GetWatchRestrictions().Labels.String() + } + if selector != workerPodLabel { + t.Fatalf("%s selector = %q, want %q", verb, selector, workerPodLabel) + } + case <-ctx.Done(): + t.Fatalf("waiting for %s: %v", verb, ctx.Err()) + } + } + }) + } +} diff --git a/cmd/atecontroller/internal/workersync/syncer.go b/cmd/atecontroller/internal/workersync/syncer.go index 429b134bd4..fc629cdd6e 100644 --- a/cmd/atecontroller/internal/workersync/syncer.go +++ b/cmd/atecontroller/internal/workersync/syncer.go @@ -47,6 +47,12 @@ const workerPodLabel = "ate.dev/worker-pool" // as members of that pool. const workerPoolIndex = "worker-pool" +// reconcileTimeout bounds one reconcile, and one attempt of the startup +// ListWorkers scan, so a call to ate-api-server that hangs fails instead of +// holding one of the syncer's goroutines. It leaves room for DeleteWorker, +// which can wait 30s on atelet. +const reconcileTimeout = time.Minute + // workerKey identifies the pod incarnation a queued event concerns. namespace // and name locate the pod in the informer, which is indexed by namespace/name // rather than by UID. @@ -101,6 +107,7 @@ type WorkerPoolSyncer struct { apps appsv1client.AppsV1Interface workerInformer cache.SharedIndexInformer workerPoolInformer cache.SharedIndexInformer + watchNamespace string queue workqueue.TypedRateLimitingInterface[workerKey] workerCount int @@ -114,13 +121,16 @@ type WorkerPoolSyncer struct { // NewWorkerPoolSyncer creates a new WorkerPoolSyncer. pods is used to delete // worker pods that have reached a terminal phase or outlived their pool, and // apps to tell the latter from pods the garbage collector is still removing. -func NewWorkerPoolSyncer(client ateapi.ControlClient, pods corev1client.PodsGetter, apps appsv1client.AppsV1Interface, workerInformer, workerPoolInformer cache.SharedIndexInformer, workerCount int) *WorkerPoolSyncer { +// watchNamespace must match the informers' namespace; empty watches all +// namespaces. +func NewWorkerPoolSyncer(client ateapi.ControlClient, pods corev1client.PodsGetter, apps appsv1client.AppsV1Interface, workerInformer, workerPoolInformer cache.SharedIndexInformer, watchNamespace string, workerCount int) *WorkerPoolSyncer { return &WorkerPoolSyncer{ client: client, pods: pods, apps: apps, workerInformer: workerInformer, workerPoolInformer: workerPoolInformer, + watchNamespace: watchNamespace, queue: workqueue.NewTypedRateLimitingQueue(workqueue.DefaultTypedControllerRateLimiter[workerKey]()), workerCount: workerCount, listBackoff: defaultListBackoff, @@ -234,7 +244,9 @@ func (s *WorkerPoolSyncer) processNextWorkItem(ctx context.Context) bool { } defer s.queue.Done(key) - if err := s.reconcile(ctx, key); err != nil { + reconcileCtx, cancel := context.WithTimeout(ctx, reconcileTimeout) + defer cancel() + if err := s.reconcile(reconcileCtx, key); err != nil { // The syncer builds its requests from pod and pool state, so a request // the API rejects as invalid would be resent verbatim on every retry. // INVALID_ARGUMENT is therefore terminal: the key is dropped and a @@ -258,6 +270,15 @@ func (s *WorkerPoolSyncer) processNextWorkItem(ctx context.Context) bool { // reconcile converges the registry record for key with the current pod state in // the informer cache. Returning an error requeues the key with backoff. func (s *WorkerPoolSyncer) reconcile(ctx context.Context, key workerKey) error { + // The pod informer only delivers keys in the watched namespace and the + // startup scan filters its keys the same way, so a key outside it means + // one of those invariants broke. Error, and drop the key: silence would + // hide the regression, and requeueing would retry it forever. + if s.watchNamespace != "" && key.namespace != s.watchNamespace { + slog.ErrorContext(ctx, "Syncer: reconcile key outside watch namespace; this should not happen", + append(key.logAttrs(), slog.String("watch-namespace", s.watchNamespace))...) + return nil + } obj, exists, err := s.workerInformer.GetIndexer().GetByKey(key.namespace + "/" + key.name) if err != nil { return err @@ -549,7 +570,8 @@ const ( ) // enqueueRegisteredWorkers enqueues a key for every worker record in the -// registry. Records whose pods are live and unchanged reconcile to a no-op; +// watched namespace, or all namespaces when unset. Records whose pods are live +// and unchanged reconcile to a no-op; // orphaned records (pod gone, or its name reused by a new pod UID) get cleaned // up. // @@ -560,6 +582,12 @@ const ( // enqueued as they are read, so the whole worker set is never held in memory at // once and a late failure does not re-scan the pages already enqueued. func (s *WorkerPoolSyncer) enqueueRegisteredWorkers(ctx context.Context) { + var skipped int + defer func() { + if skipped > 0 { + slog.WarnContext(ctx, "Syncer: skipped registered workers outside the watched namespace; drain these workers before narrowing the watch scope", "count", skipped, "watch-namespace", s.watchNamespace) + } + }() var pageToken string for { page, err := s.listWorkersPageWithRetry(ctx, pageToken) @@ -571,6 +599,11 @@ func (s *WorkerPoolSyncer) enqueueRegisteredWorkers(ctx context.Context) { return } for _, w := range page.GetWorkers() { + // Workers outside our Pod cache are not evidence of deleted Pods. + if s.watchNamespace != "" && w.GetWorkerNamespace() != s.watchNamespace { + skipped++ + continue + } // The key is a pod identity, so it is rebuilt from the recorded pod // fields rather than from the Worker's name. s.queue.Add(workerKey{ @@ -586,6 +619,13 @@ func (s *WorkerPoolSyncer) enqueueRegisteredWorkers(ctx context.Context) { } } +// listWorkersPage reads one page of workers, bounded by reconcileTimeout. +func (s *WorkerPoolSyncer) listWorkersPage(ctx context.Context, pageToken string) (*ateapi.ListWorkersResponse, error) { + ctx, cancel := context.WithTimeout(ctx, reconcileTimeout) + defer cancel() + return s.client.ListWorkers(ctx, &ateapi.ListWorkersRequest{Options: &ateapi.ListOptions{PageSize: 1000, PageToken: pageToken}}) +} + // listWorkersPageWithRetry reads one page of workers, retrying the call with // capped exponential backoff until it succeeds or ctx is cancelled. The page // token is a stateless cursor, so retrying the failed call with the same token @@ -605,7 +645,7 @@ func (s *WorkerPoolSyncer) listWorkersPageWithRetry(ctx context.Context, pageTok Cap: s.listCap, } for { - page, err := s.client.ListWorkers(ctx, &ateapi.ListWorkersRequest{Options: &ateapi.ListOptions{PageSize: 1000, PageToken: pageToken}}) + page, err := s.listWorkersPage(ctx, pageToken) if err == nil { return page, nil } diff --git a/cmd/atecontroller/internal/workersync/syncer_test.go b/cmd/atecontroller/internal/workersync/syncer_test.go index 4c4c2286a5..00bb0ae72f 100644 --- a/cmd/atecontroller/internal/workersync/syncer_test.go +++ b/cmd/atecontroller/internal/workersync/syncer_test.go @@ -15,11 +15,16 @@ package workersync import ( + "bytes" "context" "errors" "fmt" + "log/slog" "maps" + "slices" + "strings" "testing" + "testing/synctest" "time" "go.ate.dev/substrate/api/ateapi/v1" @@ -125,12 +130,12 @@ func setupSyncerTest(t *testing.T, ctx context.Context, api *fakeControl, initPo //nolint:staticcheck // NewSimpleClientset is what the informer machinery takes. fakeK8s := fake.NewSimpleClientset() - workerFactory, workerInformer := WorkerPodInformer(fakeK8s) + workerFactory, workerInformer := WorkerPodInformer(fakeK8s, "") poolClient, poolFactory, workerPoolInformer := newWorkerPoolInformer(initPools...) // Start before the factories: the informer's initial list is what seeds the // queue with the pods that already exist. - NewWorkerPoolSyncer(api, fakeK8s.CoreV1(), fakeK8s.AppsV1(), workerInformer, workerPoolInformer, 2).Start(ctx) + NewWorkerPoolSyncer(api, fakeK8s.CoreV1(), fakeK8s.AppsV1(), workerInformer, workerPoolInformer, "", 2).Start(ctx) workerFactory.Start(ctx.Done()) poolFactory.Start(ctx.Done()) workerFactory.WaitForCacheSync(ctx.Done()) @@ -149,7 +154,7 @@ func setupReconcileTest(t *testing.T, api *fakeControl, initPools ...*atev1.Work //nolint:staticcheck // NewSimpleClientset is what the informer machinery takes. fakeK8s := fake.NewSimpleClientset() - _, workerInformer := WorkerPodInformer(fakeK8s) + _, workerInformer := WorkerPodInformer(fakeK8s, "") _, _, workerPoolInformer := newWorkerPoolInformer() poolIndexer := workerPoolInformer.GetIndexer() for _, pool := range initPools { @@ -158,7 +163,83 @@ func setupReconcileTest(t *testing.T, api *fakeControl, initPools ...*atev1.Work } } - return NewWorkerPoolSyncer(api, fakeK8s.CoreV1(), fakeK8s.AppsV1(), workerInformer, workerPoolInformer, 2), workerInformer.GetIndexer(), poolIndexer + return NewWorkerPoolSyncer(api, fakeK8s.CoreV1(), fakeK8s.AppsV1(), workerInformer, workerPoolInformer, "", 2), workerInformer.GetIndexer(), poolIndexer +} + +func TestStartupScanRespectsNamespace(t *testing.T) { + for _, namespace := range []string{"agent-workloads", ""} { + t.Run("namespace="+namespace, func(t *testing.T) { + var logs bytes.Buffer + oldLogger := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) + t.Cleanup(func() { slog.SetDefault(oldLogger) }) + api := newFakeControl() + // Put the out-of-scope worker on the first page, so skipping it + // must still advance to the in-scope worker on the next page. + api.listPageSize = 1 + api.put(registeredWorker("other", "pool", "live", testPodUID)) + api.put(registeredWorker("agent-workloads", "pool", "deleted", otherPodUID)) + const thirdPodUID = "33333333-3333-3333-3333-333333333333" + api.put(registeredWorker("other", "pool", "also-live", thirdPodUID)) + kc := fake.NewClientset() + _, pods := WorkerPodInformer(kc, namespace) + _, _, pools := newWorkerPoolInformer() + s := NewWorkerPoolSyncer(api, kc.CoreV1(), kc.AppsV1(), pods, pools, namespace, 2) + defer s.queue.ShutDown() + s.enqueueRegisteredWorkers(t.Context()) + for s.queue.Len() > 0 { + key, _ := s.queue.Get() + if err := s.reconcile(t.Context(), key); err != nil { + t.Fatal(err) + } + s.queue.Done(key) + } + var want []string + if namespace != "" { + want = []string{testPodUID, thirdPodUID} + for _, fragment := range []string{`"level":"WARN"`, `"count":2`, `"watch-namespace":"agent-workloads"`} { + if !strings.Contains(logs.String(), fragment) { + t.Errorf("skipped-worker warning lacks %q: %s", fragment, logs.String()) + } + } + if count := strings.Count(logs.String(), "skipped registered workers"); count != 1 { + t.Errorf("got %d skipped-worker warnings across pages, want one", count) + } + } else if strings.Contains(logs.String(), "skipped registered workers") { + t.Errorf("unexpected skipped-worker warning for all namespaces: %s", logs.String()) + } + if got := api.names(); !slices.Equal(got, want) { + t.Fatalf("workers after startup scan = %v, want %v", got, want) + } + }) + } +} + +func TestReconcileIgnoresWorkerOutsideNamespace(t *testing.T) { + var logs bytes.Buffer + oldLogger := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(&logs, nil))) + t.Cleanup(func() { slog.SetDefault(oldLogger) }) + api := newFakeControl() + api.put(registeredWorker("other", "pool", "live", testPodUID)) + s, _, _ := setupReconcileTest(t, api) + defer s.queue.ShutDown() + s.watchNamespace = "agent-workloads" + // An unexpected queue source must not turn absence from our scoped Pod + // cache into deletion of a Worker that belongs to another namespace. + if err := s.reconcile(t.Context(), workerKey{namespace: "other", name: "live", uid: testPodUID}); err != nil { + t.Fatal(err) + } + if got := api.names(); !slices.Equal(got, []string{testPodUID}) { + t.Fatalf("out-of-scope Worker was deregistered: %v", got) + } + // The skip is a should-never-happen path: it must be visible in the logs, + // not silent. + for _, fragment := range []string{`"level":"ERROR"`, "should not happen", `"pod":"other/live"`, `"watch-namespace":"agent-workloads"`} { + if !strings.Contains(logs.String(), fragment) { + t.Errorf("out-of-scope key diagnostic lacks %q: %s", fragment, logs.String()) + } + } } // seedPod puts a pod in the syncer's cache as though the informer had delivered @@ -935,10 +1016,10 @@ func TestSyncer_StartWaitsForWorkerPoolCache(t *testing.T) { //nolint:staticcheck // NewSimpleClientset is what the informer machinery takes. fakeK8s := fake.NewSimpleClientset(workerPod(ns, podName, poolName, testPodUID, "10.0.0.8")) - workerFactory, workerInformer := WorkerPodInformer(fakeK8s) + workerFactory, workerInformer := WorkerPodInformer(fakeK8s, "") _, poolFactory, workerPoolInformer := newWorkerPoolInformer(workerPool(ns, poolName, poolLabels)) - NewWorkerPoolSyncer(api, fakeK8s.CoreV1(), fakeK8s.AppsV1(), workerInformer, workerPoolInformer, 2).Start(ctx) + NewWorkerPoolSyncer(api, fakeK8s.CoreV1(), fakeK8s.AppsV1(), workerInformer, workerPoolInformer, "", 2).Start(ctx) workerFactory.Start(ctx.Done()) workerFactory.WaitForCacheSync(ctx.Done()) @@ -1354,7 +1435,8 @@ func TestSyncer_ReadinessFlapDoesNotDeregister(t *testing.T) { // The syncer builds its requests from pod and pool state, so a request the API // rejects as invalid would be resent verbatim on every retry. INVALID_ARGUMENT // is therefore dropped, while every other code — including the UNAVAILABLE a -// transport failure surfaces as — requeues. +// transport failure surfaces as — requeues. A call that hangs times out and +// requeues too. func TestSyncer_ReconcileErrorsAreClassified(t *testing.T) { ctx := context.Background() ns, podName, poolName := "ns-syncer-classify", "worker-classify-1", "pool1" @@ -1362,30 +1444,44 @@ func TestSyncer_ReconcileErrorsAreClassified(t *testing.T) { tests := []struct { name string code codes.Code + hang bool wantRequeues int }{ {name: "invalid argument is dropped", code: codes.InvalidArgument, wantRequeues: 0}, {name: "unavailable requeues", code: codes.Unavailable, wantRequeues: 1}, + {name: "hung call times out and requeues", hang: true, wantRequeues: 1}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - api := newFakeControl() - api.setCreateHook(func(*ateapi.Worker) error { - return status.Error(tc.code, "rejected") + synctest.Test(t, func(t *testing.T) { + api := newFakeControl() + api.setCreateHook(func(ctx context.Context, _ *ateapi.Worker) error { + if !tc.hang { + return status.Error(tc.code, "rejected") + } + select { + case <-ctx.Done(): + return status.FromContextError(ctx.Err()).Err() + case <-time.After(time.Hour): + t.Error("CreateWorker was not canceled within an hour") + return status.Error(codes.Unavailable, "gave up") + } + }) + s, pods, _ := setupReconcileTest(t, api, workerPool(ns, poolName, nil)) + defer s.queue.ShutDown() + key := seedPod(t, pods, workerPod(ns, podName, poolName, testPodUID, "10.0.0.9")) + + s.queue.Add(key) + if !s.processNextWorkItem(ctx) { + t.Fatal("processNextWorkItem reported the queue was shut down") + } + if got := s.queue.NumRequeues(key); got != tc.wantRequeues { + t.Errorf("queue requeues = %d, want %d", got, tc.wantRequeues) + } + if got := api.names(); len(got) != 0 { + t.Errorf("registry holds %v, want nothing written for a rejected create", got) + } }) - s, pods, _ := setupReconcileTest(t, api, workerPool(ns, poolName, nil)) - key := seedPod(t, pods, workerPod(ns, podName, poolName, testPodUID, "10.0.0.9")) - - s.queue.Add(key) - if !s.processNextWorkItem(ctx) { - t.Fatal("processNextWorkItem reported the queue was shut down") - } - if got := s.queue.NumRequeues(key); got != tc.wantRequeues { - t.Errorf("queue requeues = %d, want %d", got, tc.wantRequeues) - } - if got := api.names(); len(got) != 0 { - t.Errorf("registry holds %v, want nothing written for a rejected create", got) - } }) } } diff --git a/cmd/atecontroller/main.go b/cmd/atecontroller/main.go index d99fb97c81..e493c0ffa5 100644 --- a/cmd/atecontroller/main.go +++ b/cmd/atecontroller/main.go @@ -18,6 +18,7 @@ import ( "fmt" "log/slog" "os" + "time" "github.com/go-logr/logr" "github.com/spf13/pflag" @@ -26,26 +27,24 @@ import ( "go.ate.dev/substrate/cmd/atecontroller/internal/controllers" "go.ate.dev/substrate/cmd/atecontroller/internal/workersync" "go.ate.dev/substrate/internal/ateapiauth" + "go.ate.dev/substrate/internal/cachesync" "go.ate.dev/substrate/internal/egresspolicy" "go.ate.dev/substrate/internal/installdefaults" "go.ate.dev/substrate/internal/k8sresolver" "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/serverboot" + "go.ate.dev/substrate/internal/serverboot/pprofserver" "go.ate.dev/substrate/internal/version" "go.ate.dev/substrate/pkg/client/clientset/versioned" "go.ate.dev/substrate/pkg/client/informers/externalversions" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "google.golang.org/grpc" - corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/fields" "k8s.io/apimachinery/pkg/runtime" - "k8s.io/apimachinery/pkg/types" utilruntime "k8s.io/apimachinery/pkg/util/runtime" "k8s.io/client-go/kubernetes" clientgoscheme "k8s.io/client-go/kubernetes/scheme" + "k8s.io/client-go/tools/cache" ctrl "sigs.k8s.io/controller-runtime" - "sigs.k8s.io/controller-runtime/pkg/cache" - "sigs.k8s.io/controller-runtime/pkg/client" "sigs.k8s.io/controller-runtime/pkg/healthz" ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" @@ -60,9 +59,12 @@ var ( ateAPIConnSpec = pflag.String("ateapi-conn-spec", "k8s:///api.ate-system.svc:443", "") + watchNamespace = pflag.String("watch-namespace", "", "Namespace containing the WorkerPools to manage. Empty watches all namespaces. Does not change the system namespace or cluster-scoped resources.") + showVersion = pflag.Bool("version", false, "Print version and exit.") logLevelFlag = pflag.String("log-level", "info", "Minimum log level: debug, info, warn, or error.") previewFlags = pflag.StringSlice("preview", nil, "Preview gates to enable.") + pprofCfg = pprofserver.RegisterFlags(pflag.CommandLine) otelEndpoint = pflag.String("otel-exporter-otlp-endpoint", os.Getenv("OTEL_EXPORTER_OTLP_ENDPOINT"), "OTLP endpoint set on worker pods, which export to it directly when their node's atelet serves no OTLP relay. Defaults to the controller's own OTEL_EXPORTER_OTLP_ENDPOINT.") @@ -98,6 +100,15 @@ var ( workerSyncConcurrency = pflag.Int("worker-sync-concurrency", 2, "Number of concurrent worker goroutines reconciling worker pods into the Worker registry. Defaults to 2.") dnsEgressPolicy = pflag.String("dns-egress-policy", "", "DNS egress policy enforcement mode propagated to worker pods (must be "+egresspolicy.DNSEgressPolicyEnforceInAtunnel+").") + + workerPprof = pflag.Bool("worker-pprof", false, + "Enable net/http/pprof on :6060 and gRPC method goroutine labels on worker pods. Defaults to ATE_WORKER_PPROF. Never enable pprof on a cluster that serves real actors.") + + workerPprofMutexFraction = pflag.Int("worker-pprof-mutex-fraction", 0, + "Mutex contention sampling rate (ATE_PPROF_MUTEX_FRACTION) set on worker pods when --worker-pprof is enabled. Defaults to ATE_WORKER_PPROF_MUTEX_FRACTION.") + + workerPprofBlockRate = pflag.Int("worker-pprof-block-rate", 0, + "Blocking profile rate in nanoseconds (ATE_PPROF_BLOCK_RATE) set on worker pods when --worker-pprof is enabled. Defaults to ATE_WORKER_PPROF_BLOCK_RATE.") ) func init() { @@ -112,6 +123,9 @@ const ( // turns it off. metricsPullAddr = ":8080" metricsOffAddr = "0" + + // cacheSyncTimeout bounds the startup wait for the worker-sync caches. + cacheSyncTimeout = time.Minute ) // logr verbosity V(n) maps to slog level -n, so V(1) stays below Info until @@ -130,21 +144,11 @@ func metricsBindAddr(servePull bool) string { } // managerOptions configures the controller-runtime manager. -func managerOptions(egressMITMCAPool types.NamespacedName, servePull bool) ctrl.Options { +func managerOptions(watchNamespace, systemNamespace string, servePull bool) ctrl.Options { return ctrl.Options{ Scheme: scheme, Metrics: metricsserver.Options{BindAddress: metricsBindAddr(servePull)}, - Cache: cache.Options{ - ByObject: map[client.Object]cache.ByObject{ - &corev1.Secret{}: { - Namespaces: map[string]cache.Config{ - egressMITMCAPool.Namespace: { - FieldSelector: fields.OneTermEqualSelector("metadata.name", egressMITMCAPool.Name), - }, - }, - }, - }, - }, + Cache: controllers.CacheOptions(watchNamespace, systemNamespace), } } @@ -159,9 +163,20 @@ func main() { if err := serverboot.SetLogLevel(*logLevelFlag); err != nil { serverboot.Fatal(ctx, "Invalid --log-level", err) } - if err := preview.Init(*previewFlags...); err != nil { + previewGates, err := preview.New(*previewFlags...) + if err != nil { serverboot.Fatal(ctx, "Invalid --preview", err) } + if err := serverboot.ValidateWatchNamespace(*watchNamespace); err != nil { + serverboot.Fatal(ctx, "Invalid --watch-namespace", err) + } + slog.InfoContext(ctx, "Resolved workload watch scope", "watch-namespace", *watchNamespace, "all-namespaces", *watchNamespace == "") + if err := pprofCfg.Validate(); err != nil { + serverboot.Fatal(ctx, "Invalid pprof configuration", err) + } + if err := loadFlagsFromEnv(); err != nil { + serverboot.Fatal(ctx, "Invalid worker pprof configuration", err) + } slog.InfoContext(ctx, "atecontroller starting", slog.String("version", version.Version)) ctrl.SetLogger(newControllerRuntimeLogger(slog.Default().Handler())) @@ -196,6 +211,7 @@ func main() { } defer serverboot.ShutdownProvider("MeterProvider", mp.Shutdown) slog.InfoContext(ctx, "Metrics listener", slog.Bool("enabled", servePull), slog.String("addr", metricsBindAddr(servePull))) + go pprofserver.Start(ctx, pprofCfg) k8sConfig := ctrl.GetConfigOrDie() k8sClient, err := kubernetes.NewForConfig(k8sConfig) @@ -242,10 +258,8 @@ func main() { } } - // EgressMITMTrustReconciler watches the Secret `egress-mitm-ca-pool`. systemNamespace := installdefaults.NamespaceFromPodEnv() - egressMITMCAPool := controllers.EgressMITMCAPoolRef(systemNamespace) - mgr, err := ctrl.NewManager(k8sConfig, managerOptions(egressMITMCAPool, servePull)) + mgr, err := ctrl.NewManager(k8sConfig, managerOptions(*watchNamespace, systemNamespace, servePull)) if err != nil { setupLog.Error(err, "unable to start manager") os.Exit(1) @@ -262,20 +276,27 @@ func main() { OTelLogsExporter: *otelLogsExporter, OTelTracesExporter: *otelTracesExporter, OTelMetricsExporter: *otelMetricsExporter, - SystemNamespace: systemNamespace, - AteletServiceAccount: *ateletServiceAccount, - RouterServiceAccount: *routerServiceAccount, - DNSEgressPolicy: *dnsEgressPolicy, - Recorder: mgr.GetEventRecorder("workerpool-controller"), - APIReader: mgr.GetAPIReader(), + WorkerPprof: controllers.WorkerPprofSettings{ + Enabled: *workerPprof, + MutexFraction: *workerPprofMutexFraction, + BlockRate: *workerPprofBlockRate, + }, + SystemNamespace: systemNamespace, + AteletServiceAccount: *ateletServiceAccount, + RouterServiceAccount: *routerServiceAccount, + DNSEgressPolicy: *dnsEgressPolicy, + PreviewGates: previewGates.Enabled(), + Recorder: mgr.GetEventRecorder("workerpool-controller"), + APIReader: mgr.GetAPIReader(), }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "WorkerPool") os.Exit(1) } if err = (&controllers.SandboxConfigProtectionReconciler{ - Client: mgr.GetClient(), - APIReader: mgr.GetAPIReader(), + Client: mgr.GetClient(), + APIReader: mgr.GetAPIReader(), + WatchNamespace: *watchNamespace, }).SetupWithManager(mgr); err != nil { setupLog.Error(err, "unable to create controller", "controller", "SandboxConfigProtection") os.Exit(1) @@ -317,19 +338,27 @@ func main() { // without a pod event, and an informer's resync period is a property of the // informer, so asking the shared cache for one would impose it on every other // controller here too. - ateFactory := externalversions.NewSharedInformerFactory(ateClient, 0) + ateFactory := externalversions.NewSharedInformerFactoryWithOptions(ateClient, 0, externalversions.WithNamespace(*watchNamespace)) workerPoolInformer := ateFactory.Ate().V1().WorkerPools() - workerPodInformerFactory, workerPodInformer := workersync.WorkerPodInformer(k8sClient) + workerPodInformerFactory, workerPodInformer := workersync.WorkerPodInformer(k8sClient, *watchNamespace) // Start registers the informer event handlers, so it has to run before the // factory does: the initial list then synthesizes an Add for every pod that // already exists, and no explicit startup re-list is needed. - workersync.NewWorkerPoolSyncer(ateapiClient, k8sClient.CoreV1(), k8sClient.AppsV1(), workerPodInformer, workerPoolInformer.Informer(), *workerSyncConcurrency).Start(runCtx) + workersync.NewWorkerPoolSyncer(ateapiClient, k8sClient.CoreV1(), k8sClient.AppsV1(), workerPodInformer, workerPoolInformer.Informer(), *watchNamespace, *workerSyncConcurrency).Start(runCtx) workerPodInformerFactory.Start(runCtx.Done()) ateFactory.Start(runCtx.Done()) - workerPodInformerFactory.WaitForCacheSync(runCtx.Done()) - ateFactory.WaitForCacheSync(runCtx.Done()) + // Fatal, like the manager's own caches: controller-runtime fails the + // process a cache misses its CacheSyncTimeout in, and a controller blind + // to workers has nothing to run half-alive for. + if err := cachesync.WaitForCacheSync(runCtx, cacheSyncTimeout, map[string]cache.InformerSynced{ + "worker Pods": workerPodInformer.HasSynced, + "WorkerPools": workerPoolInformer.Informer().HasSynced, + }); err != nil { + setupLog.Error(err, "worker-sync caches not synced") + os.Exit(1) + } setupLog.Info("starting manager") if err := mgr.Start(runCtx); err != nil { @@ -337,3 +366,20 @@ func main() { os.Exit(1) } } + +func loadFlagsFromEnv() error { + if err := serverboot.ApplyEnvFlags(pflag.CommandLine, []serverboot.EnvFlag{ + {Flag: "worker-pprof", Env: "ATE_WORKER_PPROF"}, + {Flag: "worker-pprof-mutex-fraction", Env: "ATE_WORKER_PPROF_MUTEX_FRACTION"}, + {Flag: "worker-pprof-block-rate", Env: "ATE_WORKER_PPROF_BLOCK_RATE"}, + }); err != nil { + return err + } + if *workerPprofMutexFraction < 0 { + return fmt.Errorf("--worker-pprof-mutex-fraction (ATE_WORKER_PPROF_MUTEX_FRACTION) must not be negative, got %d", *workerPprofMutexFraction) + } + if *workerPprofBlockRate < 0 { + return fmt.Errorf("--worker-pprof-block-rate (ATE_WORKER_PPROF_BLOCK_RATE) must not be negative, got %d", *workerPprofBlockRate) + } + return nil +} diff --git a/cmd/atecontroller/main_test.go b/cmd/atecontroller/main_test.go index 0795aaf1c1..569af6f769 100644 --- a/cmd/atecontroller/main_test.go +++ b/cmd/atecontroller/main_test.go @@ -23,7 +23,6 @@ import ( "github.com/spf13/pflag" prombridge "go.opentelemetry.io/contrib/bridges/prometheus" corev1 "k8s.io/api/core/v1" - "k8s.io/apimachinery/pkg/types" "sigs.k8s.io/controller-runtime/pkg/cache" ctrlmetrics "sigs.k8s.io/controller-runtime/pkg/metrics" metricsserver "sigs.k8s.io/controller-runtime/pkg/metrics/server" @@ -40,6 +39,103 @@ func TestDNSEgressPolicyFlagDefault(t *testing.T) { } } +func TestLoadFlagsFromEnvWorkerPprof(t *testing.T) { + tests := []struct { + name string + env map[string]string + setFlag map[string]string + wantPprof bool + wantMut int + wantBlk int + wantErr string + }{ + { + name: "unset leaves defaults", + }, + { + name: "all three env bindings populate flags", + env: map[string]string{ + "ATE_WORKER_PPROF": "true", + "ATE_WORKER_PPROF_MUTEX_FRACTION": "10", + "ATE_WORKER_PPROF_BLOCK_RATE": "1000000", + }, + wantPprof: true, + wantMut: 10, + wantBlk: 1000000, + }, + { + name: "negative mutex fraction flag fails startup", + setFlag: map[string]string{ + "worker-pprof-mutex-fraction": "-1", + }, + wantErr: "--worker-pprof-mutex-fraction (ATE_WORKER_PPROF_MUTEX_FRACTION) must not be negative", + }, + { + name: "negative mutex fraction env fails startup", + env: map[string]string{ + "ATE_WORKER_PPROF_MUTEX_FRACTION": "-1", + }, + wantErr: "--worker-pprof-mutex-fraction (ATE_WORKER_PPROF_MUTEX_FRACTION) must not be negative", + }, + { + name: "negative block rate flag fails startup", + setFlag: map[string]string{ + "worker-pprof-block-rate": "-1", + }, + wantErr: "--worker-pprof-block-rate (ATE_WORKER_PPROF_BLOCK_RATE) must not be negative", + }, + { + name: "negative block rate env fails startup", + env: map[string]string{ + "ATE_WORKER_PPROF_BLOCK_RATE": "-1", + }, + wantErr: "--worker-pprof-block-rate (ATE_WORKER_PPROF_BLOCK_RATE) must not be negative", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + oldPprof, oldMut, oldBlk := *workerPprof, *workerPprofMutexFraction, *workerPprofBlockRate + t.Cleanup(func() { + *workerPprof, *workerPprofMutexFraction, *workerPprofBlockRate = oldPprof, oldMut, oldBlk + }) + *workerPprof, *workerPprofMutexFraction, *workerPprofBlockRate = false, 0, 0 + + for _, name := range []string{"worker-pprof", "worker-pprof-mutex-fraction", "worker-pprof-block-rate"} { + f := pflag.CommandLine.Lookup(name) + oldChanged := f.Changed + t.Cleanup(func() { f.Changed = oldChanged }) + f.Changed = false + } + for name, val := range tt.setFlag { + if err := pflag.CommandLine.Set(name, val); err != nil { + t.Fatalf("Set(%q, %q): %v", name, val, err) + } + } + + for _, k := range []string{"ATE_WORKER_PPROF", "ATE_WORKER_PPROF_MUTEX_FRACTION", "ATE_WORKER_PPROF_BLOCK_RATE"} { + t.Setenv(k, tt.env[k]) + } + + err := loadFlagsFromEnv() + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("loadFlagsFromEnv() error = %v, want substring %q", err, tt.wantErr) + } + return + } + if err != nil { + t.Fatalf("loadFlagsFromEnv() unexpected error: %v", err) + } + if *workerPprof != tt.wantPprof || *workerPprofMutexFraction != tt.wantMut || *workerPprofBlockRate != tt.wantBlk { + t.Errorf("got (%v, %d, %d), want (%v, %d, %d)", + *workerPprof, *workerPprofMutexFraction, *workerPprofBlockRate, + tt.wantPprof, tt.wantMut, tt.wantBlk) + } + }) + } +} + func TestNewControllerRuntimeLoggerVerbosity(t *testing.T) { const probe = "verbosity-probe" @@ -112,7 +208,7 @@ func TestManagerOptionsMetricsListener(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() - opts := managerOptions(types.NamespacedName{Namespace: "ate-system", Name: "pool"}, tt.servePull) + opts := managerOptions("", "ate-system", tt.servePull) if opts.Metrics.BindAddress != tt.wantAddr { t.Errorf("metrics address = %q, want %q", opts.Metrics.BindAddress, tt.wantAddr) @@ -131,8 +227,7 @@ func TestManagerOptionsMetricsListener(t *testing.T) { func TestManagerOptionsScopeSecretCache(t *testing.T) { t.Parallel() - ref := types.NamespacedName{Namespace: "ate-system", Name: "pool"} - opts := managerOptions(ref, true) + opts := managerOptions("", "ate-system", true) var byObject cache.ByObject found := false @@ -144,11 +239,11 @@ func TestManagerOptionsScopeSecretCache(t *testing.T) { if !found { t.Fatal("no cache scope for Secrets") } - cfg, ok := byObject.Namespaces[ref.Namespace] + cfg, ok := byObject.Namespaces["ate-system"] if !ok || len(byObject.Namespaces) != 1 { - t.Fatalf("Secret cache namespaces = %v, want only %q", byObject.Namespaces, ref.Namespace) + t.Fatalf("Secret cache namespaces = %v, want only %q", byObject.Namespaces, "ate-system") } - if got := cfg.FieldSelector.String(); got != "metadata.name="+ref.Name { - t.Errorf("Secret field selector = %q, want %q", got, "metadata.name="+ref.Name) + if got := cfg.FieldSelector.String(); got != "metadata.name=egress-mitm-ca-pool" { + t.Errorf("Secret field selector = %q, want %q", got, "metadata.name=egress-mitm-ca-pool") } } diff --git a/cmd/atelet/internal/apivalidation/AGENTS.md b/cmd/atelet/internal/apivalidation/AGENTS.md index e2178c16f3..91d3c5b945 100644 --- a/cmd/atelet/internal/apivalidation/AGENTS.md +++ b/cmd/atelet/internal/apivalidation/AGENTS.md @@ -5,6 +5,6 @@ See `docs/api-validation.md` for how declarative validation (DV) works in Substr - Validates atelet RPC requests. The input types and their DV tags live in `internal/proto/ateletpb`. - `zz_generated.validation.go` is generated by `hack/update/codegen.sh`. Never edit it by hand. - Every `ateletpb` message whose name ends in `Request` gets generated validation from its DV tags. -- `validate.go` holds the thin exported shims that RPC handlers call, plus custom validators. +- `validate.go` holds the thin exported shims that RPC handlers call, plus custom validators. `workloadspec.go` holds the custom validators for the `WorkloadSpec` tree. - Tests cover exported functions only, with one table-driven test per exported function that covers all of its cases. - Run `go test -cover` (or `-coverprofile`) to check that every path is covered, both valid and invalid inputs. diff --git a/cmd/atelet/internal/apivalidation/validation_test.go b/cmd/atelet/internal/apivalidation/validation_test.go index 03f47b3acf..1cac21cb63 100644 --- a/cmd/atelet/internal/apivalidation/validation_test.go +++ b/cmd/atelet/internal/apivalidation/validation_test.go @@ -250,6 +250,13 @@ func TestValidateRunRequest(t *testing.T) { }{{ name: "valid", obj: valid(), + }, { + name: "valid activation_uid", + obj: valid(func(r *ateletpb.RunRequest) { r.ActivationUid = "754f3dc4-2996-41c4-8e5a-a1b79e6678d5" }), + }, { + name: "invalid activation_uid", + obj: valid(func(r *ateletpb.RunRequest) { r.ActivationUid = "invalid" }), + want: field.ErrorList{field.Invalid(field.NewPath("activation_uid"), nil, "").WithOrigin("format=k8s-uuid")}, }, { name: "missing worker_pod_uid", obj: valid(func(r *ateletpb.RunRequest) { r.WorkerPodUid = "" }), @@ -591,6 +598,11 @@ func TestValidateRestoreRequest(t *testing.T) { } return r } + withVolumeType := func(volumeType string) func(*ateletpb.RestoreRequest) { + return func(r *ateletpb.RestoreRequest) { + r.Spec = &ateletpb.WorkloadSpec{Volumes: []*ateletpb.Volume{{Name: "data", External: &ateletpb.ExternalVolumeSource{StorageVolumeId: "vol-1", VolumeType: volumeType}}}} + } + } tests := []struct { name string @@ -599,6 +611,13 @@ func TestValidateRestoreRequest(t *testing.T) { }{{ name: "valid", obj: valid(), + }, { + name: "valid activation_uid", + obj: valid(func(r *ateletpb.RestoreRequest) { r.ActivationUid = "754f3dc4-2996-41c4-8e5a-a1b79e6678d5" }), + }, { + name: "invalid activation_uid", + obj: valid(func(r *ateletpb.RestoreRequest) { r.ActivationUid = "invalid" }), + want: field.ErrorList{field.Invalid(field.NewPath("activation_uid"), nil, "").WithOrigin("format=k8s-uuid")}, }, { name: "missing object storage", obj: valid(func(r *ateletpb.RestoreRequest) { r.Snapshot.Object = nil }), @@ -658,6 +677,14 @@ func TestValidateRestoreRequest(t *testing.T) { r.Spec = &ateletpb.WorkloadSpec{Containers: []*ateletpb.Container{{Name: "_sandbox", Image: testDigestImage}}} }), want: field.ErrorList{field.Invalid(field.NewPath("spec", "containers").Index(0).Child("name"), nil, "").WithOrigin("format=k8s-short-name")}, + }, { + name: "external volume with a 64 character volume_type", + obj: valid(withVolumeType(strings.Repeat("a", 64))), + want: field.ErrorList{field.TooLong(field.NewPath("spec", "volumes").Index(0).Child("external", "volume_type"), nil, 63).WithOrigin("maxLength")}, + }, { + name: "external volume with a substrate.io prefixed volume_type", + obj: valid(withVolumeType("substrate.io/mock")), + want: field.ErrorList{field.Invalid(field.NewPath("spec", "volumes").Index(0).Child("external", "volume_type"), nil, "").WithOrigin("format=k8s-long-name")}, }, { name: "missing snapshot", obj: valid(func(r *ateletpb.RestoreRequest) { r.Snapshot = nil }), @@ -1378,7 +1405,7 @@ func TestValidateVolume(t *testing.T) { external := func(mutate ...func(*ateletpb.ExternalVolumeSource)) *ateletpb.Volume { e := &ateletpb.ExternalVolumeSource{ StorageVolumeId: "projects/p/zones/z/disks/vol-1", - VolumeType: "substrate.io/mock", + VolumeType: "mock.ate.dev", VolumeContext: map[string]string{"fsType": "ext4"}, } for _, m := range mutate { @@ -1448,7 +1475,7 @@ func TestValidateVolume(t *testing.T) { }, { name: "external: storage_volume_id with a control character", obj: external(func(e *ateletpb.ExternalVolumeSource) { e.StorageVolumeId = "vol\x01" }), - want: field.ErrorList{field.Invalid(extPath.Child("storage_volume_id"), nil, "")}, + want: field.ErrorList{field.Invalid(extPath.Child("storage_volume_id"), nil, "").WithOrigin("format=ate-volume-storage-id")}, }, { name: "external: storage_volume_id too long", obj: external(func(e *ateletpb.ExternalVolumeSource) { e.StorageVolumeId = strings.Repeat("x", 257) }), @@ -1456,10 +1483,25 @@ func TestValidateVolume(t *testing.T) { }, { name: "external: unset volume_type is allowed", obj: external(func(e *ateletpb.ExternalVolumeSource) { e.VolumeType = "" }), + }, { + name: "external: volume_type with 63 characters", + obj: external(func(e *ateletpb.ExternalVolumeSource) { e.VolumeType = strings.Repeat("a", 63) }), + }, { + name: "external: invalid volume_type: 64 characters", + obj: external(func(e *ateletpb.ExternalVolumeSource) { e.VolumeType = strings.Repeat("a", 64) }), + want: field.ErrorList{field.TooLong(extPath.Child("volume_type"), nil, 63).WithOrigin("maxLength")}, + }, { + name: "external: invalid volume_type: ate.dev prefix", + obj: external(func(e *ateletpb.ExternalVolumeSource) { e.VolumeType = "ate.dev/mock" }), + want: field.ErrorList{field.Invalid(extPath.Child("volume_type"), nil, "").WithOrigin("format=k8s-long-name")}, + }, { + name: "external: invalid volume_type: substrate.io prefix", + obj: external(func(e *ateletpb.ExternalVolumeSource) { e.VolumeType = "substrate.io/mock" }), + want: field.ErrorList{field.Invalid(extPath.Child("volume_type"), nil, "").WithOrigin("format=k8s-long-name")}, }, { name: "external: invalid volume_type: uppercase", - obj: external(func(e *ateletpb.ExternalVolumeSource) { e.VolumeType = "substrate.io/Mock" }), - want: field.ErrorList{field.Invalid(extPath.Child("volume_type"), nil, "")}, + obj: external(func(e *ateletpb.ExternalVolumeSource) { e.VolumeType = "Mock" }), + want: field.ErrorList{field.Invalid(extPath.Child("volume_type"), nil, "").WithOrigin("format=k8s-long-name")}, }, { name: "external: volume_context with one long value, as a CSI driver may return", obj: external(func(e *ateletpb.ExternalVolumeSource) { @@ -1721,7 +1763,7 @@ func TestValidateContainer(t *testing.T) { }, { name: "env: name with equals sign", obj: env(func(e *ateletpb.EnvVar) { e.Name = "A=B" }), - want: field.ErrorList{field.Invalid(envPath.Child("name"), nil, "")}, + want: field.ErrorList{field.Invalid(envPath.Child("name"), nil, "").WithOrigin("format=ate-env-var-name")}, }, { name: "env: name too long", obj: env(func(e *ateletpb.EnvVar) { e.Name = strings.Repeat("N", 257) }), @@ -1785,7 +1827,7 @@ func TestValidateContainer(t *testing.T) { }, { name: "probe: path without a leading slash", obj: probe(func(p *ateletpb.WakeupProbe) { p.HttpGet.Path = "healthz" }), - want: field.ErrorList{field.Invalid(httpGetPath.Child("path"), nil, "")}, + want: field.ErrorList{field.Invalid(httpGetPath.Child("path"), nil, "").WithOrigin("format=ate-http-probe-path")}, }, { name: "probe: missing port", obj: probe(func(p *ateletpb.WakeupProbe) { p.HttpGet.Port = 0 }), diff --git a/cmd/atelet/internal/apivalidation/workloadspec.go b/cmd/atelet/internal/apivalidation/workloadspec.go index 6d4fc67536..b112ec63e1 100644 --- a/cmd/atelet/internal/apivalidation/workloadspec.go +++ b/cmd/atelet/internal/apivalidation/workloadspec.go @@ -59,10 +59,6 @@ func ValidateCustom_Container_Image(_ context.Context, _ operation.Operation, fl return resources.ValidatePinnedImage(fldPath, *value) } -func ValidateCustom_EnvVar_Name(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateEnvVarName(fldPath, *value) -} - func ValidateCustom_VolumeMount_MountPath(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { return resources.ValidateMountPath(fldPath, *value) } @@ -85,18 +81,6 @@ func ValidateCustom_Capabilities_Drop(_ context.Context, _ operation.Operation, return resources.ValidateDropCapabilities(fldPath, value) } -func ValidateCustom_HttpGetAction_Path(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateHTTPGetPath(fldPath, *value) -} - -func ValidateCustom_ExternalVolumeSource_StorageVolumeId(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateStorageVolumeID(fldPath, *value) -} - -func ValidateCustom_ExternalVolumeSource_VolumeType(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateVolumeType(fldPath, *value) -} - func ValidateCustom_ExternalVolumeSource_VolumeContext(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ map[string]string) field.ErrorList { return resources.ValidateCSIMap(fldPath, value) } diff --git a/cmd/atelet/internal/apivalidation/zz_generated.validation.go b/cmd/atelet/internal/apivalidation/zz_generated.validation.go index f315f19709..2b7375c01e 100644 --- a/cmd/atelet/internal/apivalidation/zz_generated.validation.go +++ b/cmd/atelet/internal/apivalidation/zz_generated.validation.go @@ -21,6 +21,7 @@ package apivalidation import ( context "context" + regexp "regexp" ateletpb "go.ate.dev/substrate/internal/proto/ateletpb" operation "k8s.io/apimachinery/pkg/api/operation" @@ -1190,6 +1191,8 @@ func Validate_EgressGateway( return errs } +var formatPattern_ate_env_var_name = regexp.MustCompile("(^$|^[ -<>-~]+$)") + // Validate_EnvVar validates an instance of EnvVar according // to declarative validation rules in the API schema. func Validate_EnvVar( @@ -1216,8 +1219,7 @@ func Validate_EnvVar( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_EnvVar_Name(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_env_var_name, "may contain any printable ASCII character except '='", "format=ate-env-var-name"); len(e) != 0 { errs = append(errs, e...) } if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256); len(e) != 0 { @@ -1266,6 +1268,8 @@ func Validate_EnvVar( return errs } +var formatPattern_ate_volume_storage_id = regexp.MustCompile("^[^\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x9F]*$") + // Validate_ExternalVolumeSource validates an instance of ExternalVolumeSource according // to declarative validation rules in the API schema. func Validate_ExternalVolumeSource( @@ -1292,8 +1296,7 @@ func Validate_ExternalVolumeSource( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_ExternalVolumeSource_StorageVolumeId(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_volume_storage_id, "must not contain control characters", "format=ate-volume-storage-id"); len(e) != 0 { errs = append(errs, e...) } if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 256); len(e) != 0 { @@ -1327,11 +1330,10 @@ func Validate_ExternalVolumeSource( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_ExternalVolumeSource_VolumeType(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.LongName(ctx, op, fldPath, obj, oldObj); len(e) != 0 { errs = append(errs, e...) } - if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 253); len(e) != 0 { + if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 63); len(e) != 0 { errs = append(errs, e...) } return @@ -1483,6 +1485,8 @@ func Validate_GetActorEgressPolicyRequest( return errs } +var formatPattern_ate_http_probe_path = regexp.MustCompile("(^$|^/([A-Za-z0-9\\-._~!$&'\\(\\)*+,;=:@/]|%[0-9A-Fa-f]{2})*$)") + // Validate_HttpGetAction validates an instance of HttpGetAction according // to declarative validation rules in the API schema. func Validate_HttpGetAction( @@ -1509,8 +1513,7 @@ func Validate_HttpGetAction( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_HttpGetAction_Path(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_probe_path, "must be a valid HTTP path (RFC 3986)", "format=ate-http-probe-path"); len(e) != 0 { errs = append(errs, e...) } if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 1024); len(e) != 0 { @@ -2258,6 +2261,37 @@ func Validate_ReportActorCrashedRequest( errs = append(errs, fn(fldPath.Child("message"), &obj.Message, oldVal, oldObj != nil)...) } + { // field ateletpb.ReportActorCrashedRequest.ActivationUid + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ateletpb.ReportActorCrashedRequest) *string { + return &oldObj.ActivationUid + }) + errs = append(errs, fn(fldPath.Child("activation_uid"), &obj.ActivationUid, oldVal, oldObj != nil)...) + } + return errs } @@ -2828,6 +2862,37 @@ func Validate_RestoreRequest( errs = append(errs, fn(fldPath.Child("sandbox_runtime"), obj.SandboxRuntime, oldVal, oldObj != nil)...) } + { // field ateletpb.RestoreRequest.ActivationUid + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ateletpb.RestoreRequest) *string { + return &oldObj.ActivationUid + }) + errs = append(errs, fn(fldPath.Child("activation_uid"), &obj.ActivationUid, oldVal, oldObj != nil)...) + } + return errs } @@ -3149,6 +3214,37 @@ func Validate_RunRequest( errs = append(errs, fn(fldPath.Child("sandbox_runtime"), obj.SandboxRuntime, oldVal, oldObj != nil)...) } + { // field ateletpb.RunRequest.ActivationUid + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ateletpb.RunRequest) *string { + return &oldObj.ActivationUid + }) + errs = append(errs, fn(fldPath.Child("activation_uid"), &obj.ActivationUid, oldVal, oldObj != nil)...) + } + return errs } diff --git a/cmd/atelet/internal/ateletpath/ateletpath.go b/cmd/atelet/internal/ateletpath/ateletpath.go index b372ff5fb6..7e75464625 100644 --- a/cmd/atelet/internal/ateletpath/ateletpath.go +++ b/cmd/atelet/internal/ateletpath/ateletpath.go @@ -44,9 +44,10 @@ var ( // SandboxAssetScratchDir holds short-lived destination directories for // asset fetches that have no actor and no worker directory to link into: - // the assets the worker sandbox syncer stages when checking a version. - // Wiped at startup. Under BasePath so the links the cache serves into it - // are on the cache's mount. + // the assets the worker sandbox syncer stages when checking a restorable + // version, and the runsc it probes for CPU features. Wiped at startup. + // Under BasePath so the links the cache serves into it are on the + // cache's mount. SandboxAssetScratchDir = filepath.Join(nodepath.BasePath, "sandbox-asset-scratch") // SandboxRuntimeIndexFile holds every sandbox runtime a worker on this @@ -109,10 +110,24 @@ func ActorSandboxAssetsFile(actorUID string) string { func ActorSnapshotStateFile(actorUID string) string { return filepath.Join( ActorPath(actorUID), - "snapshot-state.json", + snapshotStateFileName, ) } +// NextSnapshotStateFile is where the next release keeps the actor's snapshot +// state file: directly under ActorSnapshotPath. The file moves there over two +// releases (see docs/reference/version-skew-policy.md). atelet moves a file it +// finds here back to ActorSnapshotStateFile at startup, so a rollback from the +// next release keeps the actor's snapshots. +func NextSnapshotStateFile(actorUID string) string { + return filepath.Join( + ActorSnapshotPath(actorUID), + snapshotStateFileName, + ) +} + +const snapshotStateFileName = "snapshot-state.json" + // SandboxAssetsDir holds the actor's sandbox runtime assets, one entry per // asset name, each a hard link (or a directory of hard links, for a gVisor // release) from SandboxAssetCacheDir. The worker runs binaries from here diff --git a/cmd/atelet/internal/ateletpath/ateletpath_test.go b/cmd/atelet/internal/ateletpath/ateletpath_test.go index 74f9a54f23..9c6a0b4599 100644 --- a/cmd/atelet/internal/ateletpath/ateletpath_test.go +++ b/cmd/atelet/internal/ateletpath/ateletpath_test.go @@ -40,12 +40,14 @@ func TestActorDirs(t *testing.T) { "system_info_volume_roots_dir": actorDirs.GetSystemInfoVolumeRootsDir(), "external_volume_mounts_dir": actorDirs.GetExternalVolumeMountsDir(), "sandbox_assets_dir": actorDirs.GetSandboxAssetsDir(), + "snapshot_state_file": ActorSnapshotStateFile(actorUID), } underSnapshotRoot := map[string]string{ - "checkpoint_dir": actorDirs.GetCheckpointDir(), - "restore_dir": actorDirs.GetRestoreDir(), - "local_checkpoints_dir": LocalCheckpointsDir(actorUID), - "local_snapshot_dir": LocalSnapshotDir(actorUID, "snap-1"), + "checkpoint_dir": actorDirs.GetCheckpointDir(), + "restore_dir": actorDirs.GetRestoreDir(), + "local_checkpoints_dir": LocalCheckpointsDir(actorUID), + "local_snapshot_dir": LocalSnapshotDir(actorUID, "snap-1"), + "next_snapshot_state_file": NextSnapshotStateFile(actorUID), } seen := map[string]string{} diff --git a/cmd/atelet/internal/snapshottracker/background.go b/cmd/atelet/internal/snapshottracker/background.go index 88e88e2508..aa57814505 100644 --- a/cmd/atelet/internal/snapshottracker/background.go +++ b/cmd/atelet/internal/snapshottracker/background.go @@ -19,6 +19,7 @@ import ( "log/slog" "time" + "go.ate.dev/substrate/cmd/atelet/internal/actordirs" "go.ate.dev/substrate/internal/proto/ateletpb" ) @@ -140,11 +141,12 @@ type actorOp struct { } // Start reads each actor's snapshot state file on this node, deletes any local -// snapshot from before a node reboot, queues the actor for when its next -// background upload or detach is due and for any report due, so its background -// work resumes after an atelet restart, and starts each queue's workers and -// the report workers. With instruments, it also adds each actor's undurable -// local snapshot to their tally before any worker runs. +// snapshot from before a node reboot (and, for an actor not started since, its +// other files on this node except the snapshot state file), queues the actor +// for when its next background upload or detach is due and for any report due, +// so its background work resumes after an atelet restart, and starts each +// queue's workers and the report workers. With instruments, it also adds each +// actor's undurable local snapshot to their tally before any worker runs. func (t *Tracker) Start() { if t.store != nil || t.reporting.reporter != nil || t.undurableActorsTally != nil || t.fromCurrentBoot != nil { actorUIDs, err := savedActorUIDs() @@ -179,9 +181,12 @@ func (t *Tracker) Start() { // prunePreRebootLocalLocked deletes the actor's local snapshots and stops // tracking them when one it tracks was written before the node rebooted, since -// its files may be torn. A LatestLocal written on this boot stays. A -// LatestLocal already durable is reported as detached, or detached again later -// if deleting its files fails. One not yet uploaded is lost. +// its files may be torn. When that is LatestLocal and no Run or Restore has +// started the actor since, it also deletes the actor's other files on this +// node except its snapshot state file, as a detach does. A LatestLocal written +// on this boot stays. A LatestLocal already durable is reported as detached, +// or, for an actor not started since, detached again later if deleting its +// files fails. One not yet uploaded is lost. func (t *Tracker) prunePreRebootLocalLocked(a *actorSnapshots) { if t.fromCurrentBoot == nil { return @@ -192,21 +197,26 @@ func (t *Tracker) prunePreRebootLocalLocked(a *actorSnapshots) { return } t.addLocked(a) - // Only LatestLocal can need keeping. Uploading is never newer than - // LatestLocal, so it is from an earlier boot whenever LatestLocal is, - // except after a detach that atelet stopped partway through deleting the - // actor's copies, since a deleted copy counts as from an earlier boot. - // That detach made LatestLocal durable first, so deleting Uploading too - // finishes it. - var keep []string - if a.LatestLocal != nil && !localPreReboot { - keep = []string{a.LatestLocal.uuid()} + // When LatestLocal's copy is from an earlier boot or was deleted by an + // interrupted detach, and no Run or Restore has started the actor since, + // remove the actor's files except its snapshot state file, as finishDetach + // does. Uploading is never newer than LatestLocal, and that detach made + // LatestLocal durable first, so Uploading's copy can go too. Otherwise + // delete every local snapshot except a LatestLocal from this boot. + var pruneErr error + if localPreReboot && !a.Started { + pruneErr = actordirs.RemoveActorFilesExceptState(a.actorUID) + } else { + var keep []string + if a.LatestLocal != nil && !localPreReboot { + keep = []string{a.LatestLocal.uuid()} + } + pruneErr = PruneLocalCheckpoints(t.ctx, a.actorUID, keep...) } - pruneErr := PruneLocalCheckpoints(t.ctx, a.actorUID, keep...) if pruneErr != nil { // Restore and uploads refuse what is left, which the actor's next // checkpoint or terminate deletes. - slog.WarnContext(t.ctx, "Failed to delete local snapshots left by an earlier boot or an interrupted detach", + slog.WarnContext(t.ctx, "Failed to delete files left by an earlier boot or an interrupted detach", slog.String("actorUID", a.actorUID), slog.Any("err", pruneErr)) } if uploadingPreReboot { @@ -218,11 +228,15 @@ func (t *Tracker) prunePreRebootLocalLocked(a *actorSnapshots) { slog.WarnContext(t.ctx, "Lost a local snapshot that was not uploaded before the node rebooted", slog.String("actorUID", a.actorUID), slog.String("snapshot", a.LatestLocal.uuid())) t.clearLatestLocalLocked(a) - case pruneErr != nil: + case pruneErr != nil && !a.Started: + // Detach again later. A detach deletes the actor's other files, + // so none may run once the actor has started. a.DetachAt = later(a.DetachAt, t.backOffLocked(a)) default: - slog.InfoContext(t.ctx, "Deleted an uploaded local snapshot left by an earlier boot or an interrupted detach", - slog.String("actorUID", a.actorUID), slog.String("snapshot", a.LatestLocal.uuid())) + if pruneErr == nil { + slog.InfoContext(t.ctx, "Deleted an uploaded local snapshot left by an earlier boot or an interrupted detach", + slog.String("actorUID", a.actorUID), slog.String("snapshot", a.LatestLocal.uuid())) + } t.clearLatestLocalLocked(a) t.markReportDueLocked(a) } @@ -428,20 +442,6 @@ func (t *Tracker) endOpLocked(actorUID string, op *actorOp) *actorSnapshots { return a } -// endOp ends op, queues the actor for its next background operation and any -// report due, and returns the actor's state, or opErr if non-nil. -func (t *Tracker) endOp(actorUID string, op *actorOp, opErr error) (*ateletpb.ActorSnapshotState, error) { - t.lock(actorUID) - defer t.unlock(actorUID) - a := t.endOpLocked(actorUID, op) - t.requeueLocked(a) - t.queueReportLocked(a) - if opErr != nil { - return nil, opErr - } - return t.stateLocked(a), nil -} - // waitIdleLocked waits, as long as ctx allows, until the actor has no // operation in progress (whether started by a background worker or an atelet // RPC), and returns the actor's entry, which may be nil. It releases the diff --git a/cmd/atelet/internal/snapshottracker/background_test.go b/cmd/atelet/internal/snapshottracker/background_test.go index cb708b6f64..f049c1d1a4 100644 --- a/cmd/atelet/internal/snapshottracker/background_test.go +++ b/cmd/atelet/internal/snapshottracker/background_test.go @@ -222,7 +222,10 @@ func TestStartQueuesActorsWithSnapshotState(t *testing.T) { // With WithBootCheck, Start deletes any local snapshot written before the node // rebooted and stops tracking it: it reports an already-durable one as // detached, and queues no background upload or detach for an undurable one. -// Local snapshots from the current boot stay. +// For an actor not started since, it also deletes the actor's other files +// except the snapshot state file, and the actor's directory goes once the +// detach report is acknowledged. A started actor keeps its other files and its +// snapshot state file. Local snapshots from the current boot stay. func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { useTempNodeDirs(t) writeLocalSnapshot := func(actorUID, snapUUID string) string { @@ -236,9 +239,13 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { return dir } + // One directory under ActorPath and one under ActorSnapshotPath, to check + // which of the actor's other files Start deletes. for _, actorUID := range []string{"actor-suspended-old", "actor-running-old", "actor-same-boot", "actor-undurable-old"} { - if err := os.MkdirAll(ateletpath.ActorPath(actorUID), 0o700); err != nil { - t.Fatal(err) + for _, dir := range []string{ateletpath.OCIBundleDir(actorUID), ateletpath.RestoreStateDir(actorUID)} { + if err := os.MkdirAll(dir, 0o700); err != nil { + t.Fatal(err) + } } } @@ -269,6 +276,30 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { before.CommitLocal("actor-undurable-old", s4) undurableOldDir := writeLocalSnapshot("actor-undurable-old", "s4") + // Started on this boot from a durable LatestLocal whose local copy is gone, + // as after a detach that deleted the copy and then failed. Its files must + // stay, since its workload may be running. + startedNoCopyFiles := []string{ + filepath.Join(ateletpath.DurableDirVolumeMountsDir("actor-started-no-copy"), "data"), + filepath.Join(ateletpath.OCIBundleDir("actor-started-no-copy"), "c1", "upper", "file"), + } + for _, path := range startedNoCopyFiles { + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + } + s5 := testRef("s5", 1, t0) + before.CommitDurable("actor-started-no-copy", s5) + before.CommitLocal("actor-started-no-copy", s5) + endStart, err = before.BeginStart(t.Context(), "actor-started-no-copy") + if err != nil { + t.Fatalf("BeginStart: %v", err) + } + endStart() + reporter := newFakeReporter() clk := clocktesting.NewFakeClock(time.Unix(1_700_000_000, 0)) after := New(t.Context(), newFakeSnapshotStore(), clk, @@ -281,13 +312,35 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { for _, tc := range []struct { actorUID string snapUUID string - dir string + gone []string + kept []string }{ - {"actor-suspended-old", "s1", suspendedOldDir}, - {"actor-running-old", "s2", runningOldDir}, + { + actorUID: "actor-suspended-old", + snapUUID: "s1", + gone: []string{suspendedOldDir, ateletpath.ActorSnapshotPath("actor-suspended-old"), ateletpath.OCIBundleDir("actor-suspended-old")}, + }, + { + actorUID: "actor-running-old", + snapUUID: "s2", + gone: []string{runningOldDir}, + kept: []string{ateletpath.OCIBundleDir("actor-running-old"), ateletpath.RestoreStateDir("actor-running-old")}, + }, + { + actorUID: "actor-started-no-copy", + snapUUID: "s5", + kept: startedNoCopyFiles, + }, } { - if _, err := os.Stat(tc.dir); !errors.Is(err, os.ErrNotExist) { - t.Errorf("%s local snapshot dir stat = %v, want not exist", tc.actorUID, err) + for _, path := range tc.gone { + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Errorf("%s stat(%s) = %v, want not exist", tc.actorUID, path, err) + } + } + for _, path := range tc.kept { + if _, err := os.Stat(path); err != nil { + t.Errorf("%s stat(%s) = %v, want kept", tc.actorUID, path, err) + } } st := after.State(tc.actorUID) if got := uuidOf(st.GetLatestLocal()); got != "" { @@ -298,15 +351,19 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { } } - if _, err := os.Stat(sameBootDir); err != nil { - t.Errorf("actor-same-boot local snapshot dir stat = %v, want kept", err) + for _, path := range []string{sameBootDir, ateletpath.OCIBundleDir("actor-same-boot"), ateletpath.RestoreStateDir("actor-same-boot")} { + if _, err := os.Stat(path); err != nil { + t.Errorf("actor-same-boot stat(%s) = %v, want kept", path, err) + } } if got := uuidOf(after.State("actor-same-boot").GetLatestLocal()); got != "s3" { t.Errorf("actor-same-boot latest_local = %q, want s3", got) } - if _, err := os.Stat(undurableOldDir); !errors.Is(err, os.ErrNotExist) { - t.Errorf("actor-undurable-old local snapshot dir stat = %v, want not exist", err) + for _, path := range []string{undurableOldDir, ateletpath.ActorSnapshotPath("actor-undurable-old"), ateletpath.OCIBundleDir("actor-undurable-old")} { + if _, err := os.Stat(path); !errors.Is(err, os.ErrNotExist) { + t.Errorf("actor-undurable-old stat(%s) = %v, want not exist", path, err) + } } if got := after.State("actor-undurable-old").GetLatestLocal(); got != nil { t.Errorf("actor-undurable-old latest_local = %v, want nil", got) @@ -329,7 +386,7 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { } var reportedActors []string - for range 2 { + for range 3 { processNextReport(t, after) r := waitReported(t, reporter) if r.state.GetLatestLocal() != nil { @@ -338,9 +395,16 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { reportedActors = append(reportedActors, r.actorUID) } slices.Sort(reportedActors) - if want := []string{"actor-running-old", "actor-suspended-old"}; !slices.Equal(reportedActors, want) { + if want := []string{"actor-running-old", "actor-started-no-copy", "actor-suspended-old"}; !slices.Equal(reportedActors, want) { t.Errorf("reported detached actors = %v, want %v", reportedActors, want) } + if _, err := os.Stat(ateletpath.ActorPath("actor-suspended-old")); !errors.Is(err, os.ErrNotExist) { + t.Errorf("actor-suspended-old actor dir stat after detach report = %v, want not exist", err) + } + // A started actor keeps its snapshot state, and so its directory. + if _, err := os.Stat(ateletpath.ActorSnapshotStateFile("actor-running-old")); err != nil { + t.Errorf("actor-running-old snapshot-state.json stat after detach report = %v, want kept", err) + } if n := after.reporting.queue.Len(); n != 0 { t.Errorf("reports still queued = %d, want 0", n) } @@ -351,9 +415,10 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { s1 := testRef("s1", 1, before.clock.Now()) before.CommitDurable(trackedActorUID, s1) before.CommitLocal(trackedActorUID, s1) - // With no local-checkpoint directory on disk, PruneLocalCheckpoints is a - // no-op and succeeds even when the actor directory is read-only, while - // saving the updated snapshot state file fails. + // With only snapshot-state.json in the actor directory, + // RemoveActorFilesExceptState removes nothing under it and succeeds + // even when the actor directory is read-only, while saving the updated + // snapshot state file fails. actorDir := ateletpath.ActorPath(trackedActorUID) if err := os.Chmod(actorDir, 0o500); err != nil { t.Fatal(err) @@ -371,6 +436,39 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { t.Run("schedules detach retry when pruning fails", func(t *testing.T) { useActorDir(t) + // With no detach delay, the detach is due at the commit, before the + // retry, and the actor stays unstarted. + before := newStoreTracker(t, newFakeSnapshotStore(), WithDetachDelay(0)) + s1 := testRef("s1", 1, before.clock.Now()) + before.CommitDurable(trackedActorUID, s1) + before.CommitLocal(trackedActorUID, s1) + + dir := writeLocalSnapshot(trackedActorUID, "s1") + nested := filepath.Join(dir, "sub") + if err := os.MkdirAll(nested, 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(nested, "keep"), []byte("x"), 0o600); err != nil { + t.Fatal(err) + } + if err := os.Chmod(nested, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(nested, 0o700) }) + + after := newStoreTracker(t, newFakeSnapshotStore(), withCurrentBoot()) + setWorkers(after, 0, 0) + after.Start() + + if got := uuidOf(after.State(trackedActorUID).GetLatestLocal()); got != "s1" { + t.Errorf("latest_local = %q, want s1 still recorded when prune fails", got) + } + if got := detachDueOf(after, trackedActorUID); !got.Equal(after.clock.Now().Add(testRetryDelay)) { + t.Errorf("detachDue = %v, want %v", got, after.clock.Now().Add(testRetryDelay)) + } + }) + + t.Run("schedules no detach for a started actor when pruning fails", func(t *testing.T) { before := newIdleTestTracker(t, newFakeSnapshotStore()) s1 := testRef("s1", 1, before.clock.Now()) before.CommitDurable(trackedActorUID, s1) @@ -380,6 +478,10 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { t.Fatalf("BeginStart: %v", err) } endStart() + bundleDir := ateletpath.OCIBundleDir(trackedActorUID) + if err := os.MkdirAll(bundleDir, 0o700); err != nil { + t.Fatal(err) + } dir := writeLocalSnapshot(trackedActorUID, "s1") nested := filepath.Join(dir, "sub") @@ -398,11 +500,14 @@ func TestStartPrunesLocalSnapshotsFromEarlierBoot(t *testing.T) { setWorkers(after, 0, 0) after.Start() - if got := uuidOf(after.State(trackedActorUID).GetLatestLocal()); got != "s1" { - t.Errorf("latest_local = %q, want s1 still recorded when prune fails", got) + if got := detachDueOf(after, trackedActorUID); !got.IsZero() { + t.Errorf("detachDue = %v, want no detach for a started actor", got) } - if got := detachDueOf(after, trackedActorUID); !got.Equal(after.clock.Now().Add(testRetryDelay)) { - t.Errorf("detachDue = %v, want %v", got, after.clock.Now().Add(testRetryDelay)) + if got := after.State(trackedActorUID).GetLatestLocal(); got != nil { + t.Errorf("latest_local = %v, want nil", got) + } + if _, err := os.Stat(bundleDir); err != nil { + t.Errorf("bundle dir stat = %v, want kept", err) } }) @@ -734,7 +839,7 @@ func TestLogOp(t *testing.T) { } // A failed background detach logs a warning rather than a cancellation: -// finishDetach logs before endOp ends the detach's context. +// finishDetach logs before endOpLocked ends the detach's context. func TestBackgroundDetachFailureLogsWarning(t *testing.T) { store := newFakeSnapshotStore() store.setErr(errors.New("boom")) diff --git a/cmd/atelet/internal/snapshottracker/detach.go b/cmd/atelet/internal/snapshottracker/detach.go index 5aa34db753..51545184cf 100644 --- a/cmd/atelet/internal/snapshottracker/detach.go +++ b/cmd/atelet/internal/snapshottracker/detach.go @@ -169,23 +169,33 @@ func (t *Tracker) finishDetach(ctx context.Context, actorUID string, op *actorOp if err == nil { err = actordirs.RemoveActorFilesExceptState(actorUID) } - t.updateOp(actorUID, func(a *actorSnapshots) { - switch { - case err == nil: - t.clearLatestLocalLocked(a) - t.markReportDueLocked(a) - case ctx.Err() == nil: - // Detach again once the retry delay has passed, and no sooner - // than the detach was due. - a.DetachAt = later(a.DetachAt, t.backOffLocked(a)) - } - }) - - // Log and record before endOp, which ends ctx. + // Log and record before endOpLocked, which ends ctx. elapsed := t.clock.Since(detachStart) logOp(ctx, actorUID, op.kind, target, uploaded, background, elapsed, err) if background && recordDetach { t.instruments.recordDetach(ctx, target, elapsed, err) } - return t.endOp(actorUID, op, err) + + t.lock(actorUID) + defer t.unlock(actorUID) + // Forget cancels ctx under the actor's lock, so read it under the lock. + canceled := ctx.Err() != nil + a := t.endOpLocked(actorUID, op) + switch { + case err == nil: + t.clearLatestLocalLocked(a) + t.markReportDueLocked(a) + t.saveLocked(a) + case !canceled: + // Detach again once the retry delay has passed, and no sooner than + // the detach was due. + a.DetachAt = later(a.DetachAt, t.backOffLocked(a)) + t.saveLocked(a) + } + t.requeueLocked(a) + t.queueReportLocked(a) + if err != nil { + return nil, err + } + return t.stateLocked(a), nil } diff --git a/cmd/atelet/internal/snapshottracker/detach_test.go b/cmd/atelet/internal/snapshottracker/detach_test.go index 85477d78b4..90ac9e35b8 100644 --- a/cmd/atelet/internal/snapshottracker/detach_test.go +++ b/cmd/atelet/internal/snapshottracker/detach_test.go @@ -29,6 +29,7 @@ import ( "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/proto/ateletpb" "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" "google.golang.org/protobuf/proto" clocktesting "k8s.io/utils/clock/testing" ) @@ -391,6 +392,7 @@ func TestTrackerDetachTimer(t *testing.T) { store := newFakeSnapshotStore() tr := newIdleTestTracker(t, store) tr.CommitLocal(trackedActorUID, testRef("s1", 1, tr.clock.Now())) + s1Due := detachDueOf(tr, trackedActorUID) endStart, err := tr.BeginStart(t.Context(), trackedActorUID) if err != nil { @@ -403,6 +405,11 @@ func TestTrackerDetachTimer(t *testing.T) { if due := detachDueOf(tr, trackedActorUID); !due.IsZero() { t.Fatalf("detachDue after the start = %v, want zero whether or not it succeeded", due) } + stepTo(tr, s1Due) + processNext(t, tr, opDetach) + if got := uuidOf(tr.State(trackedActorUID).GetLatestLocal()); got != "s1" { + t.Fatalf("latest_local after s1's unscheduled timer fired = %q, want s1 kept", got) + } tr.CommitLocal(trackedActorUID, testRef("s2", 2, tr.clock.Now())) due := detachDueOf(tr, trackedActorUID) @@ -613,6 +620,21 @@ func TestTrackerFailedDetach(t *testing.T) { }) } +// A detach whose upload attempt ran out of time fails with Unavailable and +// keeps the snapshot local for the next attempt, so the caller can retry. +func TestTrackerDetachUploadTimeoutIsUnavailable(t *testing.T) { + store := newFakeSnapshotStore() + store.setErr(status.Error(codes.DeadlineExceeded, "object-store plugin upload of gs://bucket/snapshot timed out")) + tr := newIdleTestTracker(t, store) + tr.CommitLocal(trackedActorUID, testRef("s1", 1, tr.clock.Now().Add(-testUploadDelay))) + if _, err := tr.Detach(t.Context(), trackedActorUID); apierror.Code(err) != codes.Unavailable { + t.Fatalf("detach = %v, want Unavailable", err) + } + if got := uuidOf(tr.State(trackedActorUID).GetLatestLocal()); got != "s1" { + t.Errorf("latest_local = %q after the timed-out upload, want s1 kept", got) + } +} + // A detach whose cleanup fails (e.g. because an external volume mount directory // is still populated) keeps LatestLocal and its local snapshot on disk, records // the snapshot as durable, and is retried: the retry finds the snapshot durable @@ -1235,8 +1257,8 @@ func TestTrackerDetachUploadTimeout(t *testing.T) { stepTo(tr, tr.clock.Now().Add(testUploadTimeout)) select { case err := <-detached: - if !errors.Is(err, context.DeadlineExceeded) { - t.Fatalf("Detach = %v, want %v", err, context.DeadlineExceeded) + if !errors.Is(err, context.DeadlineExceeded) || apierror.Code(err) != codes.Unavailable { + t.Fatalf("Detach = %v, want Unavailable wrapping %v", err, context.DeadlineExceeded) } case <-time.After(10 * time.Second): t.Fatal("Detach still running past the upload timeout") diff --git a/cmd/atelet/internal/snapshottracker/queues_test.go b/cmd/atelet/internal/snapshottracker/queues_test.go index 79a92c281f..81340013e2 100644 --- a/cmd/atelet/internal/snapshottracker/queues_test.go +++ b/cmd/atelet/internal/snapshottracker/queues_test.go @@ -73,8 +73,8 @@ func TestTrackerDetachDoesNotWaitBehindUploads(t *testing.T) { // When both an upload and a detach are due for the same actor, whichever // starts first holds a.op and causes the other queue's worker to skip the -// actor. When the upload runs first, endOp requeues the detach, which then -// prunes the now-durable snapshot without uploading again. +// actor. When the upload runs first, requeueLocked queues the detach, which +// then prunes the now-durable snapshot without uploading again. func TestTrackerSameActorUploadAndDetachDue(t *testing.T) { t.Run("upload first", func(t *testing.T) { store := newFakeSnapshotStore() @@ -114,7 +114,7 @@ func TestTrackerSameActorUploadAndDetachDue(t *testing.T) { t.Fatalf("state after upload = %v, want s1 both local and durable", st) } if got := tr.queues[opDetach].Len(); got != 1 { - t.Fatalf("detach queue len after upload endOp = %d, want 1", got) + t.Fatalf("detach queue len after the upload ended = %d, want 1", got) } // The requeued detach sees s1 durable and prunes without uploading again. @@ -210,7 +210,7 @@ func TestTrackerUploadRunsDuringCheckpointHoldWhileDetachWaits(t *testing.T) { t.Fatalf("state after opUpload = %v, want s1 both local and durable", st) } - // endOp from opUpload requeues opDetach, which still waits while held. + // The upload's requeueLocked queues opDetach, which still waits while held. processNext(t, tr, opDetach) if got := uuidOf(tr.State(trackedActorUID).GetLatestLocal()); got != "s1" { t.Fatalf("latest_local while still held = %q, want s1", got) diff --git a/cmd/atelet/internal/snapshottracker/state.go b/cmd/atelet/internal/snapshottracker/state.go index 02507a25e9..1e3fd7f9ac 100644 --- a/cmd/atelet/internal/snapshottracker/state.go +++ b/cmd/atelet/internal/snapshottracker/state.go @@ -20,6 +20,7 @@ import ( "fmt" "log/slog" "os" + "path/filepath" "syscall" "go.ate.dev/substrate/cmd/atelet/internal/ateletpath" @@ -120,3 +121,65 @@ func savedActorUIDs() ([]string, error) { } return actorUIDs, nil } + +// MigrateSnapshotStateFiles moves each actor's snapshot state file from +// ateletpath.NextSnapshotStateFile, where a future release keeps it, to +// ateletpath.ActorSnapshotStateFile. atelet calls it once at startup, before +// it creates the tracker: only one atelet runs on a node, so a file there was +// written before this atelet started, and from then on only +// ActorSnapshotStateFile is used. It syncs each moved file before removing the +// original, so a crash in between leaves two identical copies, which the next +// startup moves again. A file whose actor directory is gone is removed, as +// saveLocked keeps no state for such an actor. The actor's snapshot directory +// is then removed too if that left it empty, since nothing else removes it once +// the actor has detached or is gone. +func MigrateSnapshotStateFiles() error { + entries, err := os.ReadDir(nodepath.SnapshotsDir) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("while listing %s: %w", nodepath.SnapshotsDir, err) + } + for _, entry := range entries { + if !entry.IsDir() { + continue + } + if err := migrateSnapshotStateFile(entry.Name()); err != nil { + return err + } + } + return nil +} + +func migrateSnapshotStateFile(actorUID string) error { + from := ateletpath.NextSnapshotStateFile(actorUID) + data, err := os.ReadFile(from) + if errors.Is(err, os.ErrNotExist) { + return nil + } + if err != nil { + return fmt.Errorf("while reading %s: %w", from, err) + } + if _, err := os.Stat(ateletpath.ActorPath(actorUID)); errors.Is(err, os.ErrNotExist) { + slog.Warn("Removing the snapshot state file of an actor whose directory is gone", slog.String("actorUID", actorUID), slog.String("path", from)) + } else if err != nil { + return fmt.Errorf("while checking the actor directory: %w", err) + } else { + to := ateletpath.ActorSnapshotStateFile(actorUID) + if err := os.MkdirAll(filepath.Dir(to), 0o700); err != nil { + return fmt.Errorf("while creating %s: %w", filepath.Dir(to), err) + } + if err := atomicfile.WriteSync(to, data, 0o600); err != nil { + return fmt.Errorf("while writing %s: %w", to, err) + } + slog.Info("Moved the actor's snapshot state file", slog.String("actorUID", actorUID), slog.String("from", from), slog.String("to", to)) + } + if err := os.Remove(from); err != nil { + return fmt.Errorf("while removing %s: %w", from, err) + } + if err := os.Remove(ateletpath.ActorSnapshotPath(actorUID)); err != nil && !errors.Is(err, os.ErrNotExist) && !errors.Is(err, syscall.ENOTEMPTY) && !errors.Is(err, syscall.EEXIST) { + slog.Warn("Failed to remove the actor's empty snapshot directory", slog.String("actorUID", actorUID), slog.Any("err", err)) + } + return nil +} diff --git a/cmd/atelet/internal/snapshottracker/state_test.go b/cmd/atelet/internal/snapshottracker/state_test.go new file mode 100644 index 0000000000..c525813cb8 --- /dev/null +++ b/cmd/atelet/internal/snapshottracker/state_test.go @@ -0,0 +1,176 @@ +// Copyright 2026 The Agent Substrate 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 snapshottracker + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" + "time" + + "go.ate.dev/substrate/cmd/atelet/internal/ateletpath" + "go.ate.dev/substrate/internal/proto/ateletpb" + "google.golang.org/protobuf/proto" +) + +// writeNextSnapshotState writes, where a future release keeps it, a snapshot +// state file recording local snapshot uuid for the tracked actor, and returns +// its contents. +func writeNextSnapshotState(t *testing.T, uuid string) []byte { + t.Helper() + ref := testRef(uuid, 1, time.Now()) + data, err := json.Marshal(actorSnapshotsRecord{LatestLocal: &ref}) + if err != nil { + t.Fatal(err) + } + path := ateletpath.NextSnapshotStateFile(trackedActorUID) + if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, data, 0o600); err != nil { + t.Fatal(err) + } + return data +} + +func assertNotExist(t *testing.T, path string) { + t.Helper() + if _, err := os.Stat(path); !os.IsNotExist(err) { + t.Errorf("stat(%s) = %v, want not exist", path, err) + } +} + +// A state file a future release wrote is moved to where this release keeps it, +// so the actor keeps its snapshots after a rollback. When both copies exist, as +// after a crash partway through an earlier move, the move is finished. The +// snapshot directory goes if the move left it empty, as for an actor that had +// detached, and stays if it holds anything else. +func TestMigrateSnapshotStateFiles(t *testing.T) { + for _, tc := range []struct { + name string + bothCopy bool + // otherFile is a file left in the snapshot directory, if not empty. + otherFile string + }{ + {name: "moves the file"}, + {name: "finishes an interrupted move", bothCopy: true}, + {name: "keeps a snapshot directory that holds other files", otherFile: "restore-state"}, + } { + t.Run(tc.name, func(t *testing.T) { + useTempNodeDirs(t) + if err := os.MkdirAll(ateletpath.ActorPath(trackedActorUID), 0o700); err != nil { + t.Fatal(err) + } + want := writeNextSnapshotState(t, "s1") + if tc.otherFile != "" { + if err := os.MkdirAll(filepath.Join(ateletpath.ActorSnapshotPath(trackedActorUID), tc.otherFile), 0o700); err != nil { + t.Fatal(err) + } + } + to := ateletpath.ActorSnapshotStateFile(trackedActorUID) + if tc.bothCopy { + if err := os.MkdirAll(filepath.Dir(to), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(to, want, 0o600); err != nil { + t.Fatal(err) + } + } + + if err := MigrateSnapshotStateFiles(); err != nil { + t.Fatalf("MigrateSnapshotStateFiles() = %v", err) + } + if got, err := os.ReadFile(to); err != nil || string(got) != string(want) { + t.Errorf("%s = (%q, %v), want (%q, nil)", to, got, err, want) + } + assertNotExist(t, ateletpath.NextSnapshotStateFile(trackedActorUID)) + if tc.otherFile == "" { + assertNotExist(t, ateletpath.ActorSnapshotPath(trackedActorUID)) + } else if _, err := os.Stat(filepath.Join(ateletpath.ActorSnapshotPath(trackedActorUID), tc.otherFile)); err != nil { + t.Errorf("snapshot directory entry %s: %v, want kept", tc.otherFile, err) + } + if got := uuidOf(newTracker(t).State(trackedActorUID).GetLatestLocal()); got != "s1" { + t.Errorf("latest_local = %q, want s1", got) + } + }) + } +} + +// A state file whose actor directory is gone, as after a terminate that a +// crash interrupted, is removed rather than moved, so the actor's state does +// not come back. +func TestMigrateSnapshotStateFilesRemovesFileOfGoneActor(t *testing.T) { + useTempNodeDirs(t) + writeNextSnapshotState(t, "s1") + + if err := MigrateSnapshotStateFiles(); err != nil { + t.Fatalf("MigrateSnapshotStateFiles() = %v", err) + } + assertNotExist(t, ateletpath.NextSnapshotStateFile(trackedActorUID)) + assertNotExist(t, ateletpath.ActorSnapshotPath(trackedActorUID)) + assertNotExist(t, ateletpath.ActorPath(trackedActorUID)) + if got := newTracker(t).State(trackedActorUID); !proto.Equal(got, &ateletpb.ActorSnapshotState{}) { + t.Errorf("State() = %v, want empty", got) + } +} + +// A move that fails keeps the original file, so the actor's state is not lost, +// and returns the error, so atelet does not start without it. +func TestMigrateSnapshotStateFilesKeepsFileWhenMoveFails(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root ignores directory permissions, so no write can be made to fail") + } + useTempNodeDirs(t) + if err := os.MkdirAll(ateletpath.ActorPath(trackedActorUID), 0o700); err != nil { + t.Fatal(err) + } + want := writeNextSnapshotState(t, "s1") + // A read-only destination directory makes the write fail. + toDir := filepath.Dir(ateletpath.ActorSnapshotStateFile(trackedActorUID)) + if err := os.MkdirAll(toDir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.Chmod(toDir, 0o500); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(toDir, 0o700) }) + + if err := MigrateSnapshotStateFiles(); err == nil { + t.Fatal("MigrateSnapshotStateFiles() = nil, want an error") + } + from := ateletpath.NextSnapshotStateFile(trackedActorUID) + if got, err := os.ReadFile(from); err != nil || string(got) != string(want) { + t.Errorf("%s = (%q, %v), want (%q, nil)", from, got, err, want) + } +} + +// A node with nothing to move needs no change. +func TestMigrateSnapshotStateFilesWithNothingToMove(t *testing.T) { + useTempNodeDirs(t) + if err := MigrateSnapshotStateFiles(); err != nil { + t.Fatalf("MigrateSnapshotStateFiles() = %v, want nil on a node with no directories", err) + } + if err := os.MkdirAll(ateletpath.LocalCheckpointsDir(trackedActorUID), 0o700); err != nil { + t.Fatal(err) + } + if err := os.MkdirAll(ateletpath.ActorPath(trackedActorUID), 0o700); err != nil { + t.Fatal(err) + } + if err := MigrateSnapshotStateFiles(); err != nil { + t.Fatalf("MigrateSnapshotStateFiles() = %v, want nil with no state file to move", err) + } + assertNotExist(t, ateletpath.ActorSnapshotStateFile(trackedActorUID)) +} diff --git a/cmd/atelet/internal/snapshottracker/tracker.go b/cmd/atelet/internal/snapshottracker/tracker.go index fe22d16282..a0c947f49e 100644 --- a/cmd/atelet/internal/snapshottracker/tracker.go +++ b/cmd/atelet/internal/snapshottracker/tracker.go @@ -153,7 +153,8 @@ type Tracker struct { clock clock.WithTicker // fromCurrentBoot reports whether an actor's local snapshot was written // since the node last booted, or is nil without WithBootCheck. When set, - // atelet deletes any local snapshot written before the node rebooted (see + // atelet deletes any local snapshot written before the node rebooted, and + // the other files of an actor not started since (see // prunePreRebootLocalLocked). fromCurrentBoot func(actorUID, snapshotUUID string) bool // uploadDelay is how long after UndurableSince the actor's latest local @@ -231,7 +232,8 @@ type Option func(*Tracker) // WithBootCheck sets how atelet tells whether an actor's local snapshot was // written since the node last booted. A snapshot whose local copy is gone must // count as written before. With it, atelet deletes any local snapshot written -// before the node rebooted, whose files may be torn. +// before the node rebooted, whose files may be torn, and the other files on +// this node of an actor not started since. func WithBootCheck(fromCurrentBoot func(actorUID, snapshotUUID string) bool) Option { return func(t *Tracker) { t.fromCurrentBoot = fromCurrentBoot diff --git a/cmd/atelet/internal/snapshottracker/upload.go b/cmd/atelet/internal/snapshottracker/upload.go index 6e3d67e597..14b8fa3c33 100644 --- a/cmd/atelet/internal/snapshottracker/upload.go +++ b/cmd/atelet/internal/snapshottracker/upload.go @@ -19,6 +19,10 @@ import ( "log/slog" "math" "time" + + "go.ate.dev/substrate/internal/apierror" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // beginUploadLocked begins a background upload of the actor's nextUploadTarget, @@ -78,7 +82,21 @@ func (t *Tracker) uploadSnapshot(ctx context.Context, actorUID string, target Sn if background { t.instruments.recordUpload(uploadCtx, target, elapsed, uploaded, err) } - return uploaded, elapsed, err + return uploaded, elapsed, uploadCallError(ctx, uploadCtx, target, elapsed, err) +} + +// uploadCallError returns err, or Unavailable when the attempt ran out of its +// own time while ctx is live. The local copy stays and the next attempt +// retries it, so a Detach that waited on this attempt can be retried too +// instead of failing its resume. +func uploadCallError(ctx, uploadCtx context.Context, target SnapshotRef, elapsed time.Duration, err error) error { + if err == nil || ctx.Err() != nil { + return err + } + if uploadCtx.Err() == nil && status.Code(err) != codes.DeadlineExceeded { + return err + } + return apierror.Unavailable("upload of snapshot %s timed out after %s: %w", target.uuid(), elapsed.Round(time.Second), err) } // uploadTimeoutFor returns how long an upload attempt of target may diff --git a/cmd/atelet/lifecycle_test.go b/cmd/atelet/lifecycle_test.go index bdad038105..c638ffad17 100644 --- a/cmd/atelet/lifecycle_test.go +++ b/cmd/atelet/lifecycle_test.go @@ -83,6 +83,8 @@ type fakeWorker struct { // restored holds the file contents staged into the restore dir by the // most recent RestoreWorkload. restored map[string]string + // runErr, if set, fails every RunWorkload after it recorded the request. + runErr error // restoreErr, if set, fails every RestoreWorkload after it recorded the // request, as a worker that could not start the sandbox would. restoreErr error @@ -96,6 +98,8 @@ type fakeWorker struct { preserveRestoreDir bool // workerEpoch is the epoch RunWorkload and RestoreWorkload report. workerEpoch int64 + // activationUID is the most recent RunWorkload or RestoreWorkload identity. + activationUID string // fidelities records the fidelity each checkpoint or restore arrived // with, by RPC name. fidelities map[string]ateworkerpb.SnapshotFidelity @@ -156,7 +160,13 @@ func (f *fakeWorker) recordActorDirs(rpc string, actorDirs *ateworkerpb.ActorDir func (f *fakeWorker) RunWorkload(_ context.Context, req *ateworkerpb.RunWorkloadRequest) (*ateworkerpb.RunWorkloadResponse, error) { f.recordActorDirs("RunWorkload", req.GetActorDirs()) + if f.runErr != nil { + return nil, f.runErr + } f.setStoppedBy(nil) + f.mu.Lock() + f.activationUID = req.GetActivationUid() + f.mu.Unlock() return &ateworkerpb.RunWorkloadResponse{WorkerEpoch: f.workerEpoch}, nil } @@ -196,6 +206,9 @@ func (f *fakeWorker) CheckpointWorkload(ctx context.Context, req *ateworkerpb.Ch } func (f *fakeWorker) RestoreWorkload(_ context.Context, req *ateworkerpb.RestoreWorkloadRequest) (*ateworkerpb.RestoreWorkloadResponse, error) { + f.mu.Lock() + f.activationUID = req.GetActivationUid() + f.mu.Unlock() f.recordActorDirs("RestoreWorkload", req.GetActorDirs()) f.recordFidelity("RestoreWorkload", req.GetFidelity()) f.preserveRestoreDir = req.GetPreserveRestoreDir() @@ -298,6 +311,8 @@ func runLocalSnapshotGC(t *testing.T, fidelity ateletpb.SnapshotFidelity, useDir ) const workerEpoch = 7 + const activationUID = "9947dd8d-f20a-4708-9fd0-1a00f1903519" + const restoreUID = "387adf79-f4de-4bb6-b4cf-c19df3566b3c" worker := &fakeWorker{snapshotFiles: map[string]string{"checkpoint.img": "guest-memory"}, workerEpoch: workerEpoch} serveFakeWorker(t, worker) @@ -322,6 +337,7 @@ func runLocalSnapshotGC(t *testing.T, fidelity ateletpb.SnapshotFidelity, useDir advertiseRuntime(t, s, sandboxRec) runResp, err := s.Run(ctx, &ateletpb.RunRequest{ + ActivationUid: activationUID, Atespace: atespace, ActorName: actorName, ActorUid: actorUID, @@ -339,6 +355,12 @@ func runLocalSnapshotGC(t *testing.T, fidelity ateletpb.SnapshotFidelity, useDir if got := runResp.GetWorkerEpoch(); got != workerEpoch { t.Errorf("Run worker_epoch = %d, want %d", got, workerEpoch) } + worker.mu.Lock() + runUID := worker.activationUID + worker.mu.Unlock() + if runUID != activationUID { + t.Errorf("RunWorkload activation_uid = %q, want %q", runUID, activationUID) + } // Async suspend: a deferred checkpoint, which leaves the snapshot on this node. resp, err := s.Checkpoint(ctx, &ateletpb.CheckpointRequest{ @@ -375,6 +397,7 @@ func runLocalSnapshotGC(t *testing.T, fidelity ateletpb.SnapshotFidelity, useDir // Resume: atelet must restore from that local snapshot, not from // Snapshot.Object. restoreResp, err := s.Restore(ctx, &ateletpb.RestoreRequest{ + ActivationUid: restoreUID, Atespace: atespace, ActorName: actorName, ActorUid: actorUID, @@ -391,6 +414,12 @@ func runLocalSnapshotGC(t *testing.T, fidelity ateletpb.SnapshotFidelity, useDir if got := restoreResp.GetWorkerEpoch(); got != workerEpoch { t.Errorf("Restore worker_epoch = %d, want %d", got, workerEpoch) } + worker.mu.Lock() + restoredUID := worker.activationUID + worker.mu.Unlock() + if restoredUID != restoreUID { + t.Errorf("RestoreWorkload activation_uid = %q, want %q", restoredUID, restoreUID) + } if got := worker.restored["checkpoint.img"]; got != "guest-memory" { t.Fatalf("restore staged %q for worker, want the pause snapshot's %q", got, "guest-memory") } @@ -570,7 +599,8 @@ func TestRestoreUsesRequestSandboxRuntime(t *testing.T) { // Restore writes the sandbox record before calling RestoreWorkload, so a // Restore that fails or times out after reaching the worker still leaves - // the record for a subsequent Terminate to tear the sandbox down. + // the record, and the assets it names, for the worker's own cleanup and a + // subsequent Terminate to tear the sandbox down. if err := os.Remove(ateletpath.ActorSandboxAssetsFile(actorUID)); err != nil { t.Fatalf("removing sandbox record: %v", err) } @@ -578,6 +608,9 @@ func TestRestoreUsesRequestSandboxRuntime(t *testing.T) { if _, err := s.Restore(ctx, restoreReq); err == nil { t.Fatal("Restore succeeded when RestoreWorkload failed") } + if _, err := os.Stat(stagedRunsc(actorUID)); err != nil { + t.Errorf("runsc after failed RestoreWorkload: %v, want it kept", err) + } got, err := readSandboxRecord(actorUID) if err != nil { t.Fatalf("reading on-node sandbox record after failed RestoreWorkload: %v", err) @@ -815,6 +848,42 @@ func TestRunFailureAfterRegistrationRemovesOwnRegistration(t *testing.T) { } } +// A Run whose RunWorkload fails, here as a canceled caller, keeps the staged +// runsc: the worker may still be deleting the containers it started with it. +func TestRunFailureAtWorkerKeepsSandboxAssets(t *testing.T) { + useTempNodeDirs(t) + const actorUID = "0f6c2b0e-1b7e-4b3f-9a6a-1d2c3e4f5a64" + worker := &fakeWorker{runErr: status.Error(codes.Canceled, "context canceled")} + serveFakeWorker(t, worker) + host := imageVolumeTestRegistry(t) + pinnedImage := pushTestImage(t, host+"/actor:v1", singleFileLayer(t, "bin/app", "app")) + release := newGVisorTestRelease(t) + s := &Atelet{ + workerDialer: newWorkerDialer(1), + imageCache: newImageVolumeStore(t), + sandboxAssetCache: newTestAssetCache(t), + anonGCSClient: fakeObjectStorage{data: release.tarball}, + systemInfoVolumes: newSystemInfoVolumeRefresher(nil, nil), + snapshots: snapshottracker.New(t.Context(), nil, clock.RealClock{}), + } + rec := testSandboxRecord(release) + advertiseRuntime(t, s, rec) + _, err := s.Run(t.Context(), &ateletpb.RunRequest{ + Atespace: "team-a", + ActorName: "actor-run", + ActorUid: actorUID, + WorkerPodUid: "5f1c0d2e-3a4b-4c5d-8e9f-0a1b2c3d4e5f", + SandboxRuntime: runtimeFor(t, rec), + Spec: &ateletpb.WorkloadSpec{Containers: []*ateletpb.Container{{Name: "app", Image: pinnedImage, Command: []string{"/bin/app"}}}}, + }) + if status.Code(err) != codes.Canceled { + t.Fatalf("Run = %v, want the worker's Canceled", err) + } + if _, err := os.Stat(stagedRunsc(actorUID)); err != nil { + t.Errorf("runsc after failed RunWorkload: %v, want it kept", err) + } +} + // missingImage returns a digest-pinned reference that passes request // validation but names a manifest the local test registry does not serve, so // the pull fails only once OCI bundle preparation starts. diff --git a/cmd/atelet/main.go b/cmd/atelet/main.go index 25ac0fb263..9c8422bfd0 100644 --- a/cmd/atelet/main.go +++ b/cmd/atelet/main.go @@ -66,12 +66,12 @@ import ( "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/resources" "go.ate.dev/substrate/internal/serverboot" + "go.ate.dev/substrate/internal/serverboot/pprofserver" "go.ate.dev/substrate/internal/substratex509" "go.ate.dev/substrate/internal/version" "go.ate.dev/substrate/internal/volume" "go.ate.dev/substrate/internal/volume/csi" "go.ate.dev/substrate/pkg/client/clientset/versioned" - "go.ate.dev/substrate/pkg/client/informers/externalversions" "go.ate.dev/substrate/pkg/objectstorage" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "go.opentelemetry.io/otel" @@ -89,7 +89,6 @@ import ( "k8s.io/apimachinery/pkg/fields" k8sruntime "k8s.io/apimachinery/pkg/runtime" utilruntime "k8s.io/apimachinery/pkg/util/runtime" - kubeinformers "k8s.io/client-go/informers" "k8s.io/client-go/kubernetes" clientgoscheme "k8s.io/client-go/kubernetes/scheme" "k8s.io/client-go/rest" @@ -103,6 +102,7 @@ var ( port = pflag.Int("port", atelet.DefaultPort, "The port to listen on") metricsListenAddr = pflag.String("metrics-listen-addr", ":9090", "Address and port the prometheus metrics server should listen on.") healthListenAddr = pflag.String("health-listen-addr", ":9091", "Address and port the /readyz and /healthz probe server should listen on.") + pprofCfg = pprofserver.RegisterFlags(pflag.CommandLine) grpcServerCredBundle = pflag.String("grpc-server-cred-bundle", "/run/podidentity.podcert.ate.dev/credential-bundle.pem", "Credential bundle atelet presents as its gRPC serving certificate.") clientCACerts = pflag.String("client-ca-certs", "/run/podidentity.podcert.ate.dev/trust-bundle.pem", "CA bundle used to verify gRPC client certificates.") @@ -129,6 +129,7 @@ var ( otlpRelaySocket = pflag.String("otlp-relay-socket", nodepath.AteletOTLPSocketPath(), "Unix socket to serve the OTLP relay on, which forwards the node's worker telemetry to OTEL_EXPORTER_OTLP_ENDPOINT so worker pods need no network path to the collector. Empty disables the relay.") actorStatsPollInterval = pflag.Duration("actor-stats-poll-interval", time.Minute, fmt.Sprintf("Actor resource utilization sampling frequency. 0 disables the sampling entirely; minimum accepted value is %v.", minActorStatsPollInterval)) + watchNamespace = pflag.String("watch-namespace", "", "Namespace containing the WorkerPools and worker Pods to watch. Empty watches all namespaces. Does not scope cluster resources.") drainDelay = pflag.Duration("drain-delay", 0, "How long to keep accepting new RPCs after SIGTERM before starting the gRPC drain.") drainTimeout = pflag.Duration("drain-timeout", 5*time.Minute, "Deadline for the graceful gRPC drain on shutdown. In-flight RPCs still running past it are forcefully cancelled.") @@ -157,10 +158,17 @@ func main() { if err := serverboot.SetLogLevel(*logLevelFlag); err != nil { serverboot.Fatal(ctx, "Invalid --log-level", err) } - if err := preview.Init(*previewFlags...); err != nil { + if _, err := preview.New(*previewFlags...); err != nil { serverboot.Fatal(ctx, "Invalid --preview", err) } + if err := pprofCfg.Validate(); err != nil { + serverboot.Fatal(ctx, "Invalid pprof configuration", err) + } slog.InfoContext(ctx, "atelet starting", slog.String("version", version.Version)) + if err := serverboot.ValidateWatchNamespace(*watchNamespace); err != nil { + serverboot.Fatal(ctx, "Invalid --watch-namespace", err) + } + slog.InfoContext(ctx, "Resolved workload watch scope", "watch-namespace", *watchNamespace, "all-namespaces", *watchNamespace == "") if err := rejectStorageEnv(); err != nil { serverboot.Fatal(ctx, "Invalid environment", err) } @@ -214,6 +222,7 @@ func main() { serving := make(chan struct{}) readiness.AddCheck("serving", servingCheck(serving)) go serverboot.StartMetricsServer(ctx, *metricsListenAddr) + go pprofserver.Start(ctx, pprofCfg) go serverboot.StartHealthServer(ctx, *healthListenAddr, readiness) // The OTLP relay lets the worker pods on this node export telemetry over a @@ -340,7 +349,7 @@ func main() { // crash-looping every actor operation on the node. slog.ErrorContext(ctx, "Actor stats sampling disabled: failed to create instruments", slog.Any("err", err)) } else { - startStatsPoller(ctx, interval, statsInst, k8sClient) + startStatsPoller(ctx, interval, statsInst, k8sClient, *watchNamespace) } } @@ -408,6 +417,9 @@ func main() { reporter = &trackerReporter{workers: workerService} } + if err := snapshottracker.MigrateSnapshotStateFiles(); err != nil { + serverboot.Fatal(ctx, "Failed to migrate the actors' snapshot state files", err) + } // The snapshot tracker's workers get a context of their own, cancelled only // once the gRPC server has drained, so background snapshot work keeps // running while in-flight RPCs finish. @@ -527,22 +539,7 @@ func main() { // binary) is logged by the informer and leaves the files as they are. // // 0 disables periodic resync. Both react to watch events and retry on their own. - ateFactory := externalversions.NewSharedInformerFactory(ateClient, 0) - // Watch only worker pods on this node, the same way the kubelet watches only its own pods. - // The apiserver indexes pods by spec.nodeName, so list and watch cost scales with - // the pods on this node, not the whole cluster. - workerPodFactory := kubeinformers.NewSharedInformerFactoryWithOptions(k8sClient, 0, - kubeinformers.WithTweakListOptions(func(o *metav1.ListOptions) { - o.FieldSelector = "spec.nodeName=" + nodeName - o.LabelSelector = workerPoolLabel - })) - // Link each local worker's default runtime under the worker's directory - // as the syncer plans the worker, so it stays cached while no actor runs - // it. - // Best-effort: on failure the on-demand fetch in ensureSandboxAssets - // still covers correctness. - prewarmer := newRuntimePrewarmer(runtimes, wmService) - go prewarmer.run(ctx) + ateFactory, workerPodFactory := newWorkerInformers(ateClient, k8sClient, *watchNamespace, nodeName) eventBroadcaster := events.NewBroadcaster(&events.EventSinkImpl{Interface: k8sClient.EventsV1()}) if err := eventBroadcaster.StartRecordingToSinkWithContext(ctx); err != nil { serverboot.Fatal(ctx, "Failed to start the event broadcaster", err) @@ -551,13 +548,15 @@ func main() { // Keep a sandbox runtimes file in each local worker's directory: the // runtimes of the enabled versions of its pool's SandboxConfig, - // rewritten when the config changes. + // rewritten when the config changes, with the default runtime's assets + // linked under the directory so they stay cached while no actor runs + // them. _, err = startWorkerSandboxSyncer(ctx, workerPodFactory.Core().V1().Pods(), ateFactory.Ate().V1().WorkerPools(), ateFactory.Ate().V1().SandboxConfigs(), wmService, - nodepath.WorkersDir(), runtimes, prewarmer, + nodepath.WorkersDir(), runtimes, eventBroadcaster.NewRecorder(newEventScheme(), "atelet")) if err != nil { // Without the syncer no runtime is ever indexed, so no actor could run. @@ -891,13 +890,16 @@ func (s *Atelet) Run(ctx context.Context, req *ateletpb.RunRequest) (resp *atele _ = os.RemoveAll(staging) return nil, err } - committed := false + committed, workerCalled := false, false defer func() { if err == nil { return } _ = os.RemoveAll(staging) - if committed { + // A failed RunWorkload can return before the worker has deleted the + // containers it started with these binaries, so they stay until + // Terminate or the next Run or Restore. + if committed && !workerCalled { _ = os.RemoveAll(ateletpath.SandboxAssetsDir(actorUID)) } }() @@ -907,10 +909,6 @@ func (s *Atelet) Run(ctx context.Context, req *ateletpb.RunRequest) (resp *atele return nil, status.Errorf(codes.Canceled, "while resetting actor dirs: %v", err) } - if err := s.mountExternalVolumes(ctx, actorUID, req.GetSpec().GetVolumes()); err != nil { - return nil, err - } - // Record the sandbox binaries this actor is running so a later Checkpoint // (whose request no longer carries the sandbox config) can re-fetch the same // version and pin it into the snapshot manifest. @@ -931,10 +929,19 @@ func (s *Atelet) Run(ctx context.Context, req *ateletpb.RunRequest) (resp *atele if registration, err = s.systemInfoVolumes.Register(actorUID, actorRef, systemInfoVolumesFor(actorUID, req.GetSpec())); err != nil { return nil, err } - containerSpecs, err := s.prepareOCIBundles(ctx, actorUID, actorRef, req.GetSpec()) + containerSpecs, err := s.prepareOCIBundles(ctx, actorUID, req.GetSpec()) + if err != nil { + return nil, err + } + // Mount after the containers' users are known, since a volume's group + // comes from them. + groups, err := externalVolumeGroups(req.GetSpec(), containerSpecs) if err != nil { return nil, err } + if err := s.mountExternalVolumes(ctx, actorUID, req.GetSpec().GetVolumes(), groups); err != nil { + return nil, err + } client, err := s.dialWorker(ctx, req.GetWorkerPodUid()) if err != nil { @@ -948,7 +955,9 @@ func (s *Atelet) Run(ctx context.Context, req *ateletpb.RunRequest) (resp *atele // Tell worker to start the workload. gVisor uses RunscPath; the micro-VM // runtime uses the full RuntimeAssetPaths set. + workerCalled = true workerResp, err := client.RunWorkload(ctx, &ateworkerpb.RunWorkloadRequest{ + ActivationUid: req.GetActivationUid(), Atespace: actorRef.Atespace, ActorName: actorRef.Name, ActorTemplateAtespace: req.GetActorTemplateAtespace(), @@ -1726,26 +1735,22 @@ func (s *Atelet) Restore(ctx context.Context, req *ateletpb.RestoreRequest) (res if err := resetSandboxAssetsDir(actorUID); err != nil { return nil, err } - // The record below is written before RestoreWorkload, so until then it - // describes the previous activation; a failed restore must not leave this - // one's asset links behind for a later Terminate to take for that record's. - // Nor its snapshot files: staged ones are links into the snapshot cache - // or copies, and either would hold the cache's entries, or disk, until - // the next lifecycle call resets the directory. + // The record below is written just before RestoreWorkload. Until then it + // describes the previous activation, so a failed restore removes this + // one's asset links. Once RestoreWorkload is issued, the assets stay: the + // call can fail before the worker has deleted the containers it started + // with them. Staged snapshot files are always removed, so their links or + // copies do not hold the snapshot cache's entries, or disk. + workerCalled := false defer func() { if err != nil { - _ = os.RemoveAll(ateletpath.SandboxAssetsDir(actorUID)) + if !workerCalled { + _ = os.RemoveAll(ateletpath.SandboxAssetsDir(actorUID)) + } _ = os.RemoveAll(ateletpath.RestoreStateDir(actorUID)) } }() - tMount := time.Now() - mountErr := s.mountExternalVolumes(ctx, actorUID, req.GetSpec().GetVolumes()) - dMount = time.Since(tMount) - if mountErr != nil { - return nil, mountErr - } - checkpointDir := ateletpath.RestoreStateDir(actorUID) localDir := ateletpath.LocalSnapshotDir(actorUID, req.GetSnapshot().GetSnapshotUuid()) directLocal := false @@ -1848,7 +1853,7 @@ func (s *Atelet) Restore(ctx context.Context, req *ateletpb.RestoreRequest) (res return err } t := time.Now() - containerSpecs, err = s.prepareOCIBundles(gctx, actorUID, actorRef, req.GetSpec()) + containerSpecs, err = s.prepareOCIBundles(gctx, actorUID, req.GetSpec()) dBundles = time.Since(t) if err != nil { prepFailedPhase = ateattr.SnapshotPhaseOCIUnpack @@ -1865,6 +1870,17 @@ func (s *Atelet) Restore(ctx context.Context, req *ateletpb.RestoreRequest) (res } return nil, err } + // Mount after the containers' users are known, as Run does. + groups, err := externalVolumeGroups(req.GetSpec(), containerSpecs) + if err != nil { + return nil, err + } + tMount := time.Now() + mountErr := s.mountExternalVolumes(ctx, actorUID, req.GetSpec().GetVolumes(), groups) + dMount = time.Since(tMount) + if mountErr != nil { + return nil, mountErr + } client, err := s.dialWorker(ctx, req.GetWorkerPodUid()) if err != nil { @@ -1891,7 +1907,9 @@ func (s *Atelet) Restore(ctx context.Context, req *ateletpb.RestoreRequest) (res // The worker_restore phase is opaque from here; worker logs its own breakdown of // this call as "Actor restore phases". tWorker := time.Now() + workerCalled = true workerResp, err := client.RestoreWorkload(ctx, &ateworkerpb.RestoreWorkloadRequest{ + ActivationUid: req.GetActivationUid(), Atespace: actorRef.Atespace, ActorName: actorRef.Name, ActorTemplateAtespace: req.GetActorTemplateAtespace(), @@ -2257,7 +2275,6 @@ func prepareDurableDirVolume(path string) error { func (s *Atelet) prepareOCIBundles( ctx context.Context, actorUID string, - actorRef resources.ActorRef, spec *ateletpb.WorkloadSpec, ) ([]*ateworkerpb.ContainerSpec, error) { // Prepare host folders for volume types that need them. @@ -2423,6 +2440,10 @@ func toWorkerWakeupProbe(in *ateletpb.WakeupProbe) *ateworkerpb.WakeupProbe { } type WorkerDialer struct { + // mu makes the lookup, create and insert in DialWorkerPod atomic, so + // concurrent dials for a pod share one conn. NewClient does no I/O, so + // holding mu across it is cheap. + mu sync.Mutex conns *lru.Cache } @@ -2454,6 +2475,9 @@ var workerSocketPath = nodepath.WorkerSocketPath func (d *WorkerDialer) DialWorkerPod(ctx context.Context, podUID string) (*grpc.ClientConn, error) { key := podUID + d.mu.Lock() + defer d.mu.Unlock() + connAny, ok := d.conns.Get(key) if ok { return connAny.(*grpc.ClientConn), nil diff --git a/cmd/atelet/main_test.go b/cmd/atelet/main_test.go index ab78be5982..03cedfa650 100644 --- a/cmd/atelet/main_test.go +++ b/cmd/atelet/main_test.go @@ -258,7 +258,7 @@ func TestPrepareOCIBundlesFillsContainerSpec(t *testing.T) { } s := &Atelet{imageCache: newImageVolumeStore(t)} - got, err := s.prepareOCIBundles(t.Context(), "actor-uid-1", resources.ActorRef{}, spec) + got, err := s.prepareOCIBundles(t.Context(), "actor-uid-1", spec) if err != nil { t.Fatalf("prepareOCIBundles: %v", err) } @@ -288,7 +288,7 @@ func TestPrepareOCIBundlesResolvesUsers(t *testing.T) { s := &Atelet{imageCache: newImageVolumeStore(t)} spec := &ateletpb.WorkloadSpec{Containers: []*ateletpb.Container{{Name: "app", Image: app}}} - got, err := s.prepareOCIBundles(t.Context(), "actor-uid-1", resources.ActorRef{}, spec) + got, err := s.prepareOCIBundles(t.Context(), "actor-uid-1", spec) if err != nil { t.Fatalf("prepareOCIBundles: %v", err) } @@ -299,7 +299,7 @@ func TestPrepareOCIBundlesResolvesUsers(t *testing.T) { unresolvable := pushTestImageWithConfig(t, host+"/nobody:v1", v1.Config{User: "nobody", Cmd: []string{"/bin/app"}}) spec = &ateletpb.WorkloadSpec{Containers: []*ateletpb.Container{{Name: "app", Image: unresolvable}}} - if _, err := s.prepareOCIBundles(t.Context(), "actor-uid-2", resources.ActorRef{}, spec); err == nil { + if _, err := s.prepareOCIBundles(t.Context(), "actor-uid-2", spec); err == nil { t.Error("prepareOCIBundles succeeded with a USER the image has no passwd entry for, want an error") } } @@ -314,7 +314,7 @@ func TestPrepareOCIBundlesStartsInTheImageWorkdir(t *testing.T) { const actorUID = "actor-uid-1" s := &Atelet{imageCache: newImageVolumeStore(t)} - got, err := s.prepareOCIBundles(t.Context(), actorUID, resources.ActorRef{}, spec) + got, err := s.prepareOCIBundles(t.Context(), actorUID, spec) if err != nil { t.Fatalf("prepareOCIBundles: %v", err) } diff --git a/cmd/atelet/runtime_prewarm.go b/cmd/atelet/runtime_prewarm.go deleted file mode 100644 index 4210d09d49..0000000000 --- a/cmd/atelet/runtime_prewarm.go +++ /dev/null @@ -1,224 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 ( - "context" - "errors" - "fmt" - "io/fs" - "log/slog" - "os" - "time" - - "k8s.io/client-go/util/workqueue" -) - -// defaultPrewarmAttemptTimeout bounds one prewarm attempt. The queue is -// drained by one worker, so an attempt that never returned would block -// every other runtime's prewarm. -const defaultPrewarmAttemptTimeout = 10 * time.Minute - -// prewarmMaxRetries bounds how often one failed prewarm is retried before -// it is dropped until the worker is planned again (or first use, which -// stays the correctness path). The backoff below caps at 5 minutes, so -// this covers transient bucket or registry outages of several minutes -// without hammering a permanently broken runtime forever. -const prewarmMaxRetries = 8 - -// sandboxAssetFetcher is the slice of Atelet the prewarmer and the syncer -// need. Staging through the same methods as the Run/Restore path keeps the -// fetches from ever diverging on cache layout or validation. -type sandboxAssetFetcher interface { - ensureSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, dstDir string) (map[string]string, error) - stageSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, dstDir string) (map[string]string, error) -} - -// prewarmItem is one default runtime of a worker to prewarm: the hash to -// fetch, and the directory the worker sandbox syncer made for it under the -// worker's own, to link the assets into. -type prewarmItem struct { - hash string - dir string -} - -// runtimePrewarmer links the default runtime of each worker on this node -// from the asset cache into the worker's default-runtime directory (fetching -// on a cache miss after eviction), so the fetch inside the first Run/Restore -// on the node is a cache hit instead of a download+extract on the critical -// path. The worker sandbox syncer hands it each default runtime a worker -// advertises, once the worker's file says so, with a directory to stage it -// into; the index holds the record. -// -// The assets are linked into that directory and left there: the cache -// never evicts a linked entry, so a default runtime stays cached while no -// actor runs it. The directory is the syncer's to make and to remove: it -// exists while the worker advertises the runtime as a default, and goes -// with the worker's directory when the pod does. The prewarmer only fills -// what exists. A directory gone before or while an item is staged means a -// later sync or the worker's removal no longer wants it, and the item ends -// without fetching, retrying, or recreating anything. -// -// Prewarming is purely a latency optimization: every failure is logged and -// left to the on-demand fetch in ensureSandboxAssets, which remains the -// correctness path. Only default runtimes are linked here; non-default -// versions stay unlinked while no actor runs them. -type runtimePrewarmer struct { - index *runtimeIndex - assets sandboxAssetFetcher - // queue carries items. It dedupes while an item waits, and it - // rate-limits retries after failures. A single worker drains it. - queue workqueue.TypedRateLimitingInterface[prewarmItem] - // done is closed when the worker goroutine exits; wait blocks on it. - done chan struct{} - - // attemptTimeout is defaultPrewarmAttemptTimeout. Shortened in tests. - attemptTimeout time.Duration - // onFinished, if set, observes the result of each prewarm attempt once - // the worker's call has returned. Tests set it to wait for that call - // before tearing down what it writes into. - onFinished func(item prewarmItem, err error) -} - -func newRuntimePrewarmer(index *runtimeIndex, assets sandboxAssetFetcher) *runtimePrewarmer { - return &runtimePrewarmer{ - index: index, - assets: assets, - attemptTimeout: defaultPrewarmAttemptTimeout, - // Downloads fail on the scale of network timeouts, not API conflicts, - // so back off in seconds and cap in minutes rather than the - // millisecond-based controller default. - queue: workqueue.NewTypedRateLimitingQueue( - workqueue.NewTypedItemExponentialFailureRateLimiter[prewarmItem](time.Second, 5*time.Minute)), - done: make(chan struct{}), - } -} - -// enqueue asks for the runtime advertised under hash to be prewarmed into -// dir, which the syncer created. The syncer calls it once the worker's -// file advertises the runtime as a default. -func (p *runtimePrewarmer) enqueue(hash, dir string) { - p.queue.Add(prewarmItem{hash: hash, dir: dir}) -} - -// run drains the queue until ctx ends. -func (p *runtimePrewarmer) run(ctx context.Context) { - defer close(p.done) - go func() { - <-ctx.Done() - p.queue.ShutDown() - }() - for { - item, shutdown := p.queue.Get() - if shutdown { - return - } - p.process(ctx, item) - } -} - -// wait blocks until the worker has exited, which happens after the context -// given to run is canceled and the in-flight item finishes. Tests wait here -// before tearing down what the worker writes into. -func (p *runtimePrewarmer) wait() { - <-p.done -} - -// process prewarms the item, requeueing with backoff on failure. -func (p *runtimePrewarmer) process(ctx context.Context, item prewarmItem) { - defer p.queue.Done(item) - rt, ok := p.index.lookup(item.hash) - if !ok { - // The syncer registers before it enqueues, and the index never - // forgets, so this is a programming error rather than a race. - slog.ErrorContext(ctx, "Sandbox runtime to prewarm is not in the index", slog.String("runtime_hash", item.hash)) - p.queue.Forget(item) - return - } - err := p.prewarm(ctx, item, rt) - if p.onFinished != nil { - p.onFinished(item, err) - } - if err == nil { - p.queue.Forget(item) - return - } - if ctx.Err() != nil { - // Shutting down, not a prewarm failure; drop without retry noise. - return - } - if retries := p.queue.NumRequeues(item); retries < prewarmMaxRetries { - slog.WarnContext(ctx, "Sandbox runtime prewarm failed; will retry", - slog.String("runtime_hash", item.hash), slog.String("config", rt.config), slog.String("version", rt.version), - slog.Int("retries", retries), slog.Any("err", err)) - p.queue.AddRateLimited(item) - return - } - // Best-effort: give up until the worker is synced again or first use. - slog.WarnContext(ctx, "Sandbox runtime prewarm failed; giving up", - slog.String("runtime_hash", item.hash), slog.String("config", rt.config), slog.String("version", rt.version), - slog.Int("retries", prewarmMaxRetries), slog.Any("err", err)) - p.queue.Forget(item) -} - -// prewarm links the runtime's assets from the asset cache into the item's -// directory, fetching on a cache miss after eviction. Racing an on-demand -// ensureSandboxAssets for the same assets is safe: the asset cache runs one -// download per asset and serves every caller from it. A directory the syncer -// already filled costs a stat per asset. -// -// Nothing here creates a directory: the staging goes into the item's -// directory as it is, so a directory removed before or during the work, by -// a later sync or the worker's removal, makes the next step fail, and the -// item ends without an error and without recreating anything. -func (p *runtimePrewarmer) prewarm(ctx context.Context, item prewarmItem, rt *indexedRuntime) error { - ctx, cancel := context.WithTimeout(ctx, p.attemptTimeout) - defer cancel() - t := time.Now() - if gone, err := dirGone(item.dir); err != nil || gone { - if gone { - slog.DebugContext(ctx, "Sandbox runtime prewarm superseded; its directory is gone", slog.String("runtime_hash", item.hash), slog.String("dir", item.dir)) - } - return err - } - - if _, err := p.assets.stageSandboxAssets(ctx, rt.rec, item.dir); err != nil { - if gone, gerr := dirGone(item.dir); gerr == nil && gone { - slog.DebugContext(ctx, "Sandbox runtime prewarm superseded while staging", slog.String("runtime_hash", item.hash), slog.String("dir", item.dir)) - return nil - } - return err - } - slog.InfoContext(ctx, "Sandbox runtime prewarmed", - slog.String("runtime_hash", item.hash), - slog.String("config", rt.config), - slog.String("version", rt.version), - slog.Int("assets", len(rt.rec.Assets)), - slog.String("dir", item.dir), - slog.Duration("duration", time.Since(t))) - return nil -} - -// dirGone reports whether dir does not exist. -func dirGone(dir string) (bool, error) { - _, err := os.Stat(dir) - if errors.Is(err, fs.ErrNotExist) { - return true, nil - } - if err != nil { - return false, fmt.Errorf("while checking the prewarm directory: %w", err) - } - return false, nil -} diff --git a/cmd/atelet/runtime_prewarm_test.go b/cmd/atelet/runtime_prewarm_test.go deleted file mode 100644 index 0b332d6bf5..0000000000 --- a/cmd/atelet/runtime_prewarm_test.go +++ /dev/null @@ -1,493 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 ( - "context" - "crypto/sha256" - "errors" - "fmt" - "io" - "os" - "path/filepath" - "runtime" - "slices" - "strings" - "sync" - "sync/atomic" - "testing" - "time" - - metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" - k8sruntime "k8s.io/apimachinery/pkg/runtime" - kubeinformers "k8s.io/client-go/informers" - kubefake "k8s.io/client-go/kubernetes/fake" - "k8s.io/client-go/tools/events" - - atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" - "go.ate.dev/substrate/cmd/atelet/internal/ateletpath" - "go.ate.dev/substrate/cmd/atelet/internal/filecache" - atefake "go.ate.dev/substrate/pkg/client/clientset/versioned/fake" - "go.ate.dev/substrate/pkg/client/informers/externalversions" -) - -func gvisorConfig(name, url, sha string) *atev1.SandboxConfig { - return &atev1.SandboxConfig{ - ObjectMeta: metav1.ObjectMeta{Name: name}, - Spec: atev1.SandboxConfigSpec{ - SandboxClass: atev1.SandboxClassGvisor, - DefaultVersion: "v1", - Versions: []atev1.SandboxVersionConfig{{ - Name: "v1", - Assets: map[string]map[string]atev1.AssetFile{ - runtime.GOARCH: { - gvisorAssetName: {URL: url, SHA256: sha}, - }, - }, - }}, - }, - } -} - -// hangingObjectStorage blocks GetObject until the caller's context ends, -// simulating a bucket read that stalls without failing. -type hangingObjectStorage struct{} - -func (hangingObjectStorage) GetObject(ctx context.Context, _, _ string) (io.ReadCloser, error) { - <-ctx.Done() - return nil, ctx.Err() -} - -func (hangingObjectStorage) PutObject(_ context.Context, _, _ string, _ io.Reader) error { return nil } - -// indexedTestRuntime registers a runtime with one gvisor release asset, the -// tarball content, as a worker's default, and returns its hash. -func indexedTestRuntime(t *testing.T, index *runtimeIndex, content []byte) string { - t.Helper() - return indexedTestRuntimeAt(t, index, "gs://bucket/gvisor.tar", content) -} - -// indexedTestRuntimeAt is indexedTestRuntime with the asset at url. -func indexedTestRuntimeAt(t *testing.T, index *runtimeIndex, url string, content []byte) string { - t.Helper() - rec := &sandboxAssetsRecord{ - SandboxClass: "gvisor", - Assets: map[string]assetEntry{gvisorAssetName: {URL: url, SHA256: fmt.Sprintf("%x", sha256.Sum256(content))}}, - } - hash := bundleHash(rec) - index.register("pod-a", advertisedClass{class: atev1.SandboxClassGvisor, config: "gvisor-release", hashed: []hashedVersion{{ - versionPlan: versionPlan{name: "v1", isDefault: true, rec: rec}, hash: hash, - }}}) - return hash -} - -// defaultItem makes the directory the syncer would make for hash as a -// default of pod-a under root, so the links land on the cache's -// filesystem, and returns the item the syncer would hand the prewarmer. -func defaultItem(t *testing.T, root, hash string) prewarmItem { - t.Helper() - dir := filepath.Join(root, "workers", "pod-a", defaultRuntimeDirsName, strings.ReplaceAll(hash, ":", "-")) - if err := os.MkdirAll(dir, 0o700); err != nil { - t.Fatal(err) - } - return prewarmItem{hash: hash, dir: dir} -} - -// TestRuntimePrewarmProcess covers the worker's failure handling: a failed -// prewarm is requeued with backoff until prewarmMaxRetries and then dropped, -// and an item naming a hash that is not in the index is dropped at once. -func TestRuntimePrewarmProcess(t *testing.T) { - ctx := context.Background() - index := newRuntimeIndex() - hash := indexedTestRuntime(t, index, gvisorReleaseTarball(t)) - root := t.TempDir() - herder := &Atelet{sandboxAssetCache: newTestAssetCacheAt(t, root), anonGCSClient: fakeObjectStorage{err: errors.New("bucket unavailable")}} - p := newRuntimePrewarmer(index, herder) - - item := defaultItem(t, root, hash) - for i := 1; i <= prewarmMaxRetries; i++ { - p.process(ctx, item) - if got := p.queue.NumRequeues(item); got != i { - t.Fatalf("NumRequeues after %d failed prewarms = %d, want %d (requeued with backoff)", i, got, i) - } - } - p.process(ctx, item) - if got := p.queue.NumRequeues(item); got != 0 { - t.Errorf("NumRequeues after giving up = %d, want 0 (forgotten)", got) - } - - unknown := prewarmItem{hash: "sha256:not-in-the-index", dir: item.dir} - p.process(ctx, unknown) - if got := p.queue.NumRequeues(unknown); got != 0 { - t.Errorf("NumRequeues for an unknown hash = %d, want 0 (forgotten)", got) - } -} - -// TestRuntimePrewarmSuperseded pins what a prewarm does once the syncer -// removed its directory, after a later sync or the worker's removal: no -// fetch, nothing recreated, and no retry, whether the directory went -// before the item ran or while it staged. -func TestRuntimePrewarmSuperseded(t *testing.T) { - ctx := context.Background() - index := newRuntimeIndex() - content := gvisorReleaseTarball(t) - hash := indexedTestRuntime(t, index, content) - root := t.TempDir() - herder := &Atelet{sandboxAssetCache: newTestAssetCacheAt(t, root), anonGCSClient: fakeObjectStorage{data: content}} - - t.Run("directory gone before the item runs", func(t *testing.T) { - item := defaultItem(t, root, hash) - if err := os.RemoveAll(item.dir); err != nil { - t.Fatal(err) - } - p := newRuntimePrewarmer(index, herder) - p.process(ctx, item) - if got := p.queue.NumRequeues(item); got != 0 { - t.Errorf("NumRequeues after a superseded prewarm = %d, want 0 (not retried)", got) - } - if n := cachedAssets(t, root); n != 0 { - t.Errorf("a superseded prewarm fetched %d assets, want 0", n) - } - if exists(item.dir) { - t.Error("a superseded prewarm recreated its directory") - } - }) - - t.Run("worker gone while staging", func(t *testing.T) { - item := defaultItem(t, root, hash) - removing := &removingFetcher{inner: herder, remove: filepath.Join(root, "workers", "pod-a")} - p := newRuntimePrewarmer(index, removing) - p.process(ctx, item) - if got := p.queue.NumRequeues(item); got != 0 { - t.Errorf("NumRequeues after the worker went mid-staging = %d, want 0 (not retried)", got) - } - if exists(filepath.Join(root, "workers", "pod-a")) { - t.Error("a prewarm recreated the directory of a worker removed while it staged") - } - }) -} - -// removingFetcher removes a directory the moment staging starts, standing in -// for a worker deleted after the prewarm found its directory in place. -type removingFetcher struct { - inner sandboxAssetFetcher - remove string -} - -func (r *removingFetcher) ensureSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, dstDir string) (map[string]string, error) { - return r.inner.ensureSandboxAssets(ctx, rec, dstDir) -} - -func (r *removingFetcher) stageSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, dstDir string) (map[string]string, error) { - if err := os.RemoveAll(r.remove); err != nil { - return nil, err - } - return r.inner.stageSandboxAssets(ctx, rec, dstDir) -} - -// TestRuntimePrewarmFillsTheAssetCache covers a successful prewarm: the asset -// lands in the asset cache, linked into the runtime's directory so an -// eviction pass keeps it. A second prewarm of the same directory fetches -// nothing. -func TestRuntimePrewarmFillsTheAssetCache(t *testing.T) { - ctx := context.Background() - content := gvisorReleaseTarball(t) - index := newRuntimeIndex() - hash := indexedTestRuntime(t, index, content) - rt, _ := index.lookup(hash) - - root := t.TempDir() - var gets atomic.Int32 - // No min age, so the only thing standing between the entry and a pass is - // the directory's link. - s := &Atelet{sandboxAssetCache: newTestAssetCacheAt(t, root, filecache.WithMinAge(0)), anonGCSClient: fakeObjectStorage{data: content, gets: &gets}} - p := newRuntimePrewarmer(index, s) - item := defaultItem(t, root, hash) - if err := p.prewarm(ctx, item, rt); err != nil { - t.Fatalf("prewarm: %v", err) - } - if n := cachedAssets(t, root); n != 1 { - t.Errorf("asset cache holds %d assets after prewarm, want 1", n) - } - if _, err := os.Stat(filepath.Join(item.dir, gvisorAssetName, "runsc")); err != nil { - t.Errorf("prewarm did not link the runtime's asset into its directory: %v", err) - } - stats, err := s.sandboxAssetCache.EvictUnused(ctx, 1<<40, false) - if err != nil { - t.Fatalf("EvictUnused: %v", err) - } - if stats.Retired != 0 || stats.SkippedLinked != 1 || cachedAssets(t, root) != 1 { - t.Errorf("after an eviction pass: stats=%+v, cached=%d; want the linked asset kept", stats, cachedAssets(t, root)) - } - - // A re-sync with the same default hands the same directory over again: - // the staging finds every asset in place and downloads nothing. - before := gets.Load() - if err := p.prewarm(ctx, item, rt); err != nil { - t.Fatalf("second prewarm: %v", err) - } - if got := gets.Load(); got != before { - t.Errorf("a prewarm of a complete directory fetched %d times, want 0", got-before) - } - - // The worker goes, and its directory with it: the entry is evictable. - if err := os.RemoveAll(filepath.Join(root, "workers", "pod-a")); err != nil { - t.Fatal(err) - } - if stats, _ := s.sandboxAssetCache.EvictUnused(ctx, 1<<40, true); stats.Retired != 1 { - t.Errorf("after the worker went, a pass would retire %d entries, want 1", stats.Retired) - } -} - -// TestRuntimePrewarmAssetFailure pins that a failing asset fetch fails the -// prewarm. -func TestRuntimePrewarmAssetFailure(t *testing.T) { - ctx := context.Background() - index := newRuntimeIndex() - hash := indexedTestRuntime(t, index, gvisorReleaseTarball(t)) - rt, _ := index.lookup(hash) - - root := t.TempDir() - p := newRuntimePrewarmer(index, &Atelet{sandboxAssetCache: newTestAssetCacheAt(t, root), anonGCSClient: fakeObjectStorage{err: errors.New("bucket unavailable")}}) - if err := p.prewarm(ctx, defaultItem(t, root, hash), rt); err == nil { - t.Error("prewarm returned nil despite the asset fetch failing") - } -} - -// TestRuntimePrewarmAttemptTimeout verifies a single attempt is bounded by -// the prewarmer's attempt timeout: the queue has one worker, so an attempt -// that never returned would block every other runtime's prewarm. -func TestRuntimePrewarmAttemptTimeout(t *testing.T) { - index := newRuntimeIndex() - hash := indexedTestRuntime(t, index, gvisorReleaseTarball(t)) - rt, _ := index.lookup(hash) - root := t.TempDir() - p := newRuntimePrewarmer(index, &Atelet{sandboxAssetCache: newTestAssetCacheAt(t, root), anonGCSClient: hangingObjectStorage{}}) - p.attemptTimeout = 50 * time.Millisecond - - item := defaultItem(t, root, hash) - done := make(chan error, 1) - go func() { done <- p.prewarm(context.Background(), item, rt) }() - select { - case err := <-done: - if err == nil { - t.Error("prewarm returned nil despite the download hanging") - } - case <-time.After(10 * time.Second): - t.Fatal("prewarm never returned; a hung download would block the worker forever") - } -} - -// TestSyncPodPrewarmsDefaultRuntime pins the hand-off: once a worker's file -// is written, its default runtime, and only that, is handed to the -// prewarmer in a directory of its own under the pod's, and the pod's -// default-runtime directory is made to match the file: a retired default's -// directory goes, the current one stays as it is. A build that fails hands -// nothing over and touches no directory, and the pod's removal takes them -// all. -func TestSyncPodPrewarmsDefaultRuntime(t *testing.T) { - pod := workerPod("pod-a", "pool") - s := newTestSyncer(t, pod, resolvedPool("pool", "gvisor-release"), multiVersionConfig()) - rec := &recordingPrewarm{} - s.prewarm = rec - s.assets = &fakeAssetFetcher{ - fn: func(ctx context.Context, r *sandboxAssetsRecord) (map[string]string, error) { - if rec.count() != 0 { - t.Error("the default runtime was handed to the prewarmer before the build finished") - } - return newTestAssetFetcher().ensureSandboxAssets(ctx, r, "") - }, - } - dirs := filepath.Join(s.podDir("pod-a"), defaultRuntimeDirsName) - // Left by an earlier sync: a default the pool no longer runs, which must - // go, and a stray file in the parent, which must go too. - stale := filepath.Join(dirs, "sha256-stale") - if err := os.MkdirAll(stale, 0o700); err != nil { - t.Fatal(err) - } - if _, err := s.syncPod(context.Background(), pod); err != nil { - t.Fatalf("syncPod: %v", err) - } - wr, ok := s.index.worker("pod-a") - if !ok { - t.Fatal("pod-a not indexed") - } - cr, _ := wr.class(atev1.SandboxClassGvisor) - want := []prewarmItem{{hash: cr.defaultHash, dir: s.defaultRuntimeDir("pod-a", cr.defaultHash)}} - if got := rec.items(); !slices.Equal(got, want) { - t.Errorf("prewarm handed %+v, want %+v", got, want) - } - if !exists(want[0].dir) { - t.Error("the default's directory was not created") - } - if exists(stale) { - t.Error("a retired default's directory survived the sync") - } - if len(cr.hashes) < 2 { - t.Fatalf("config advertises %d runtimes, want several so the test proves only the default is prewarmed", len(cr.hashes)) - } - - // A re-sync with the same default: the directory, and what the - // prewarmer put in it, stays; the default is handed over again. - marker := filepath.Join(want[0].dir, "staged") - if err := os.WriteFile(marker, nil, 0o600); err != nil { - t.Fatal(err) - } - if _, err := s.syncPod(context.Background(), pod); err != nil { - t.Fatalf("syncPod again: %v", err) - } - if got := rec.items(); len(got) != 2 || got[1] != want[0] { - t.Errorf("prewarm handed %+v after a re-sync, want the same item twice", got) - } - if !exists(marker) { - t.Error("a re-sync with the same default emptied its directory") - } - if err := s.removeDir(context.Background(), "pod-a"); err != nil { - t.Fatal(err) - } - if exists(dirs) { - t.Error("the default runtime directories survived the pod's removal") - } - - // A build that fails on the default's probe writes nothing, hands - // nothing over, and leaves the directories as they were. - s = newTestSyncer(t, pod, resolvedPool("pool", "gvisor-release"), multiVersionConfig()) - rec = &recordingPrewarm{} - s.prewarm = rec - s.runCPUFeatures = func(context.Context, string) ([]string, error) { return nil, errors.New("runsc failed") } - previous := s.defaultRuntimeDir("pod-a", "sha256:previous") - if err := os.MkdirAll(previous, 0o700); err != nil { - t.Fatal(err) - } - if _, err := s.syncPod(context.Background(), pod); err == nil { - t.Fatal("syncPod with the default's probe failing = nil, want an error") - } - if got := rec.items(); len(got) != 0 { - t.Errorf("prewarm handed %+v after a failed build, want nothing", got) - } - if !exists(previous) { - t.Error("a failed build removed the previous default's directory") - } - if _, ok := s.index.worker("pod-a"); ok { - t.Error("a failed build registered the worker") - } -} - -// recordingPrewarm stands in for the prewarmer in syncer tests. Safe to -// read while a syncer's workers call it. -type recordingPrewarm struct { - mu sync.Mutex - enqueued []prewarmItem -} - -func (r *recordingPrewarm) enqueue(hash, dir string) { - r.mu.Lock() - defer r.mu.Unlock() - r.enqueued = append(r.enqueued, prewarmItem{hash: hash, dir: dir}) -} - -func (r *recordingPrewarm) items() []prewarmItem { - r.mu.Lock() - defer r.mu.Unlock() - return append([]prewarmItem(nil), r.enqueued...) -} - -func (r *recordingPrewarm) count() int { - r.mu.Lock() - defer r.mu.Unlock() - return len(r.enqueued) -} - -// TestDefaultRuntimePrewarmThroughSyncer runs the whole path: a worker pod, -// its pool and SandboxConfig in fake clientsets flow through the informers -// into the syncer, which indexes the pod's runtimes, writes its file, and -// hands its default runtime to the prewarmer, which lands the asset in the -// cache, linked under the worker's directory, without any Run/Restore -// request. -func TestDefaultRuntimePrewarmThroughSyncer(t *testing.T) { - useTempAssetScratch(t) // the syncer's runsc probe stages into it - // The worker's own prewarm call returns only when the asset has landed. - // Waiting for the call keeps its last writes from racing the TempDir - // cleanup. - prewarmed := make(chan error, 1) - onFinished := func(_ prewarmItem, err error) { - // Non-blocking: a failed attempt is retried, and the worker must not - // block on a result nobody reads. - select { - case prewarmed <- err: - default: - } - } - - content := gvisorReleaseTarball(t) - cfg := gvisorConfig("gvisor-release", "gs://bucket/gvisor.tar", fmt.Sprintf("%x", sha256.Sum256(content))) - - kube := kubefake.NewClientset([]k8sruntime.Object{workerPod("pod-a", "pool")}...) - ate := atefake.NewSimpleClientset(resolvedPool("pool", "gvisor-release"), cfg) - podFactory := kubeinformers.NewSharedInformerFactory(kube, 0) - ateFactory := externalversions.NewSharedInformerFactory(ate, 0) - ctx, cancel := context.WithCancel(context.Background()) - - root := t.TempDir() - workersDir := filepath.Join(root, "workers") // on the cache's filesystem - index := newRuntimeIndex() - herder := &Atelet{sandboxAssetCache: newTestAssetCacheAt(t, root), anonGCSClient: fakeObjectStorage{data: content}} - p := newRuntimePrewarmer(index, herder) - p.onFinished = onFinished - go p.run(ctx) - // Join the worker before the TempDir cleanups remove what it writes into. - t.Cleanup(func() { - cancel() - p.wait() - podFactory.Shutdown() - ateFactory.Shutdown() - }) - - s, err := startWorkerSandboxSyncer(ctx, - podFactory.Core().V1().Pods(), - ateFactory.Ate().V1().WorkerPools(), - ateFactory.Ate().V1().SandboxConfigs(), - newScriptAssetFetcher(t), // the syncer's runsc probe; prewarm goes through herder - workersDir, index, p, &events.FakeRecorder{}) - if err != nil { - t.Fatalf("startWorkerSandboxSyncer: %v", err) - } - ateFactory.Start(ctx.Done()) - podFactory.Start(ctx.Done()) - - select { - case err := <-prewarmed: - if err != nil { - t.Fatalf("prewarm: %v", err) - } - case <-time.After(30 * time.Second): - t.Fatal("prewarm never finished") - } - if n := cachedAssets(t, root); n != 1 { - t.Fatalf("asset cache holds %d assets after prewarm, want 1", n) - } - waitFor(t, "the worker's runtimes file to be written", func() bool { return exists(s.runtimesFile("pod-a")) }) - waitFor(t, "the probe's scratch dir to be removed", func() bool { - left, err := os.ReadDir(ateletpath.SandboxAssetScratchDir) - return err == nil && len(left) == 0 - }) - wr, _ := index.worker("pod-a") - cr, _ := wr.class(atev1.SandboxClassGvisor) - linked := filepath.Join(s.defaultRuntimeDir("pod-a", cr.defaultHash), gvisorAssetName, "runsc") - waitFor(t, "the worker's default runtime to be linked under its directory", func() bool { return exists(linked) }) - if dirs, err := os.ReadDir(filepath.Join(s.podDir("pod-a"), defaultRuntimeDirsName)); err != nil || len(dirs) != 1 { - t.Errorf("default runtime directories under the worker's = %v, %v; want exactly one", dirs, err) - } -} diff --git a/cmd/atelet/sandbox_asset_cache_test.go b/cmd/atelet/sandbox_asset_cache_test.go index d730e5537a..baad70ad78 100644 --- a/cmd/atelet/sandbox_asset_cache_test.go +++ b/cmd/atelet/sandbox_asset_cache_test.go @@ -54,7 +54,7 @@ func TestValidateSandboxAssetCacheFlags(t *testing.T) { func TestOpenSandboxAssetCacheResetsScratch(t *testing.T) { useTempNodeDirs(t) useTempAssetScratch(t) - leftover := filepath.Join(ateletpath.SandboxAssetScratchDir, "cpu-features-123", "runsc") + leftover := filepath.Join(ateletpath.SandboxAssetScratchDir, "sandbox-assets-123", "runsc") if err := os.MkdirAll(filepath.Dir(leftover), 0o755); err != nil { t.Fatal(err) } diff --git a/cmd/atelet/sandbox_assets.go b/cmd/atelet/sandbox_assets.go index 62eacbd0e5..51cc705dd5 100644 --- a/cmd/atelet/sandbox_assets.go +++ b/cmd/atelet/sandbox_assets.go @@ -124,22 +124,15 @@ type sandboxAssetsRecord struct { // hard link, so the download runs once per node, concurrent callers for one // asset share it, and what an actor was handed stays valid whatever the // cache evicts later. An asset already present under dstDir is kept as it -// is: dstDir is the actor's own, reset at Run and Restore, so a Checkpoint -// or Terminate finds exactly what its activation staged. +// is: an actor's dstDir is its own, reset at Run and Restore, so a +// Checkpoint or Terminate finds exactly what its activation staged, and a +// worker's default runtime directory, once filled, costs a stat per asset. func (s *Atelet) ensureSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, dstDir string) (map[string]string, error) { // Owner-only, like the actor's bundle dir: the worker runs the binaries // as root, and nothing else needs to see them. if err := os.MkdirAll(dstDir, 0o700); err != nil { return nil, wrapFileSystemErr("while creating sandbox assets dir", err) } - return s.stageSandboxAssets(ctx, rec, dstDir) -} - -// stageSandboxAssets is ensureSandboxAssets into a dstDir that exists: it -// creates nothing above the assets, so a caller whose dstDir may be removed -// under it, as the prewarmer's is when its worker goes, fails instead of -// recreating the directory. -func (s *Atelet) stageSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, dstDir string) (map[string]string, error) { paths := make(map[string]string, len(rec.Assets)) for name, entry := range rec.Assets { if !plainAssetName(name) { @@ -645,6 +638,14 @@ func writeSandboxRecord(actorUID string, rec *sandboxAssetsRecord) error { if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil { return wrapFileSystemErr("while creating actor dir", err) } + // Replacing a file by rename makes ext4 write the new one out first, which + // waits behind whatever the disk is busy writing. Restoring from a local + // snapshot writes the same record unless the runtime changed, so leave an + // unchanged one alone. + // https://github.com/torvalds/linux/blob/v6.12/fs/ext4/namei.c#L3869-L3870 + if old, err := os.ReadFile(path); err == nil && bytes.Equal(old, data) { + return nil + } if err := atomicfile.Write(path, data, 0o600); err != nil { return wrapFileSystemErr("while writing sandbox record", err) } diff --git a/cmd/atelet/sandbox_assets_test.go b/cmd/atelet/sandbox_assets_test.go index fb93eaa47b..675e4854f2 100644 --- a/cmd/atelet/sandbox_assets_test.go +++ b/cmd/atelet/sandbox_assets_test.go @@ -490,3 +490,41 @@ func TestEnsureSandboxAssetsRejectsBadAssetNames(t *testing.T) { t.Errorf("kata-kernel staged at %q (%v), want a regular file at %s", paths["kata-kernel"], err, filepath.Join(dstDir, "kata-kernel")) } } + +func TestWriteSandboxRecordKeepsAnUnchangedRecord(t *testing.T) { + useTempNodeDirs(t) + const actorUID = "5d1b7c8e-2f3a-4b5c-8d9e-0a1b2c3d4e5f" + rec := &sandboxAssetsRecord{ + SandboxClass: "gvisor", + Assets: map[string]assetEntry{gvisorAssetName: {URL: "gs://test-bucket/gvisor-release.tar.gz", SHA256: strings.Repeat("a", 64)}}, + } + if err := writeSandboxRecord(actorUID, rec); err != nil { + t.Fatalf("writeSandboxRecord: %v", err) + } + path := ateletpath.ActorSandboxAssetsFile(actorUID) + before, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if err := writeSandboxRecord(actorUID, rec); err != nil { + t.Fatalf("writeSandboxRecord: %v", err) + } + after, err := os.Stat(path) + if err != nil { + t.Fatal(err) + } + if !os.SameFile(before, after) { + t.Error("rewrote an unchanged sandbox record") + } + rec.Assets[gvisorAssetName] = assetEntry{URL: "gs://test-bucket/gvisor-release.tar.gz", SHA256: strings.Repeat("b", 64)} + if err := writeSandboxRecord(actorUID, rec); err != nil { + t.Fatalf("writeSandboxRecord: %v", err) + } + got, err := readSandboxRecord(actorUID) + if err != nil { + t.Fatal(err) + } + if sha := got.Assets[gvisorAssetName].SHA256; sha != strings.Repeat("b", 64) { + t.Errorf("sandbox record sha256 = %q after a change, want the new one", sha) + } +} diff --git a/cmd/atelet/sandbox_runtime_index.go b/cmd/atelet/sandbox_runtime_index.go index 016e138b81..c3b9bd716c 100644 --- a/cmd/atelet/sandbox_runtime_index.go +++ b/cmd/atelet/sandbox_runtime_index.go @@ -41,8 +41,7 @@ import ( // never forgets an entry: a request may carry a hash a worker advertised // earlier, config churn is rare, and an entry is a few URLs. workers, by // worker pod UID, holds what each worker currently advertises and lives -// with the pod; it is where the default runtime to prewarm and to protect -// from eviction comes from. +// with the pod. // // runtimes is also kept on disk, as one file that is the map serialized, // rewritten durably before a new entry is added and loaded again by diff --git a/cmd/atelet/statspoller.go b/cmd/atelet/statspoller.go index 305cfaf04b..5cfe04e8d1 100644 --- a/cmd/atelet/statspoller.go +++ b/cmd/atelet/statspoller.go @@ -428,14 +428,14 @@ func (p *statsPoller) resolveWorkerPools(ctx context.Context, podUIDs []string) // Deliberately not a standing informer: at the poll cadence the apiserver // cost is negligible, there is no informer cache to sync before the first // sweep, and resolveWorkerPools already absorbs failed lists. -func newWorkerPoolFetcher(client kubernetes.Interface, nodeName string) func(ctx context.Context) map[string]workerPoolRef { +func newWorkerPoolFetcher(client kubernetes.Interface, namespace, nodeName string) func(ctx context.Context) map[string]workerPoolRef { return func(ctx context.Context) map[string]workerPoolRef { // Bounded so a hung apiserver cannot stall the sweep: past the // deadline the fetch returns nil and resolveWorkerPools falls back // to the cache. listCtx, cancel := context.WithTimeout(ctx, workerPoolListTimeout) defer cancel() - pods, err := client.CoreV1().Pods(metav1.NamespaceAll).List(listCtx, metav1.ListOptions{ + pods, err := client.CoreV1().Pods(namespace).List(listCtx, metav1.ListOptions{ FieldSelector: "spec.nodeName=" + nodeName, LabelSelector: workerPoolLabel, }) @@ -582,7 +582,7 @@ func (i *statsInstruments) addCPU(ctx context.Context, aggs map[templateKey]*tem // The poller dials its own short-lived connection per probe (see // dialWorkerStats) and takes no WorkerDialer: the isolation from the lifecycle // RPCs' connection cache is structural, not just behavioral. -func startStatsPoller(ctx context.Context, interval time.Duration, inst *statsInstruments, k8sClient kubernetes.Interface) { +func startStatsPoller(ctx context.Context, interval time.Duration, inst *statsInstruments, k8sClient kubernetes.Interface, namespace string) { poller := &statsPoller{ interval: interval, workersDir: nodepath.WorkersDir(), @@ -599,7 +599,7 @@ func startStatsPoller(ctx context.Context, interval time.Duration, inst *statsIn // NODE_NAME comes from the Downward API; without it the samples still // flow, just grouped without pool labels. if nodeName := os.Getenv("NODE_NAME"); nodeName != "" { - poller.fetchWorkerPools = newWorkerPoolFetcher(k8sClient, nodeName) + poller.fetchWorkerPools = newWorkerPoolFetcher(k8sClient, namespace, nodeName) } else { slog.WarnContext(ctx, "NODE_NAME not set; actor stats will carry no worker pool labels") } diff --git a/cmd/atelet/statspoller_test.go b/cmd/atelet/statspoller_test.go index f2dc0c727a..f2106d63a9 100644 --- a/cmd/atelet/statspoller_test.go +++ b/cmd/atelet/statspoller_test.go @@ -33,6 +33,7 @@ import ( corev1 "k8s.io/api/core/v1" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" k8sfake "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" "go.ate.dev/substrate/internal/proto/ateworkerpb" ) @@ -464,28 +465,51 @@ func TestStatsPollerCPUDeltaSaturatesCorruptCounter(t *testing.T) { // TestNewWorkerPoolFetcher pins the fetcher's ingestion rules: a labeled worker // maps by pod UID, an empty label value names no pool and never enters the // map (the presence-only selector matches it anyway), and unlabeled pods are -// not workers at all. The fake clientset honors label selectors but not the -// spec.nodeName field selector, so node scoping is not assertable here. +// not workers at all. The fake clientset does not filter by spec.nodeName, +// so check that selector on the LIST request. func TestNewWorkerPoolFetcher(t *testing.T) { - client := k8sfake.NewSimpleClientset( - &corev1.Pod{ObjectMeta: metav1.ObjectMeta{ - Name: "worker-a", Namespace: "pool-ns", UID: "uid-a", - Labels: map[string]string{workerPoolLabel: "pool-a"}, - }}, - &corev1.Pod{ObjectMeta: metav1.ObjectMeta{ - Name: "worker-empty", Namespace: "pool-ns", UID: "uid-empty", - Labels: map[string]string{workerPoolLabel: ""}, - }}, - &corev1.Pod{ObjectMeta: metav1.ObjectMeta{ - Name: "bystander", Namespace: "other-ns", UID: "uid-bystander", - }}, - ) - - got := newWorkerPoolFetcher(client, "node-1")(context.Background()) - - want := map[string]workerPoolRef{"uid-a": {namespace: "pool-ns", name: "pool-a"}} - if diff := cmp.Diff(want, got, cmp.AllowUnexported(workerPoolRef{})); diff != "" { - t.Errorf("newWorkerPoolFetcher mismatch (-want +got):\n%s", diff) + for _, namespace := range []string{"pool-ns", ""} { + t.Run("namespace="+namespace, func(t *testing.T) { + client := k8sfake.NewClientset( + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{ + Name: "worker-a", Namespace: "pool-ns", UID: "uid-a", + Labels: map[string]string{workerPoolLabel: "pool-a"}, + }}, + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{ + Name: "worker-other", Namespace: "other-ns", UID: "uid-other", + Labels: map[string]string{workerPoolLabel: "pool-a"}, + }}, + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{ + Name: "worker-empty", Namespace: "pool-ns", UID: "uid-empty", + Labels: map[string]string{workerPoolLabel: ""}, + }}, + &corev1.Pod{ObjectMeta: metav1.ObjectMeta{ + Name: "bystander", Namespace: "other-ns", UID: "uid-bystander", + }}, + ) + + got := newWorkerPoolFetcher(client, namespace, "node-1")(t.Context()) + + want := map[string]workerPoolRef{"uid-a": {namespace: "pool-ns", name: "pool-a"}} + if namespace == "" { + want["uid-other"] = workerPoolRef{namespace: "other-ns", name: "pool-a"} + } + if diff := cmp.Diff(want, got, cmp.AllowUnexported(workerPoolRef{})); diff != "" { + t.Errorf("newWorkerPoolFetcher mismatch (-want +got):\n%s", diff) + } + actions := client.Actions() + if len(actions) != 1 { + t.Fatalf("got %d API requests, want one LIST", len(actions)) + } + action, ok := actions[0].(k8stesting.ListAction) + if !ok || action.GetNamespace() != namespace { + t.Fatalf("got %v, want LIST in namespace %q", actions[0], namespace) + } + selectors := action.GetListRestrictions() + if selectors.Fields.String() != "spec.nodeName=node-1" || selectors.Labels.String() != workerPoolLabel { + t.Errorf("LIST selectors = %v, want node-1 and %s", selectors, workerPoolLabel) + } + }) } } diff --git a/cmd/atelet/volumes.go b/cmd/atelet/volumes.go index eb34d769e8..7f569549e0 100644 --- a/cmd/atelet/volumes.go +++ b/cmd/atelet/volumes.go @@ -20,16 +20,26 @@ import ( "fmt" "log/slog" "os" + "strconv" + "strings" + "syscall" "go.ate.dev/substrate/cmd/atelet/internal/ateletpath" + "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/proto/ateletpb" + "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/volume" "go.ate.dev/substrate/internal/volume/csi" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) -func (s *Atelet) mountExternalVolumes(ctx context.Context, actorUID string, volumes []*ateletpb.Volume) error { +// mountExternalVolumes mounts each external volume. groups maps a volume to +// the primary group of the non-root containers that mount it, from +// externalVolumeGroups. A driver that supports VOLUME_MOUNT_GROUP gets that +// group at mount. Otherwise atelet sets it on the volume's top directory, and +// logs a warning if that fails. +func (s *Atelet) mountExternalVolumes(ctx context.Context, actorUID string, volumes []*ateletpb.Volume, groups map[string]uint32) error { for _, vol := range volumes { // Given that external volumes has been in the codebase for a while and // its preview-ness is solely around the API, and that the impact of @@ -49,18 +59,108 @@ func (s *Atelet) mountExternalVolumes(ctx context.Context, actorUID string, volu if err != nil { return fmt.Errorf("failed to get volume plugin for %q: %w", ext.GetVolumeType(), err) } - if err := plugin.MountVolume(ctx, volume.MountVolumeRequest{ + req := volume.MountVolumeRequest{ VolumeID: ext.GetStorageVolumeId(), TargetPath: hostPath, VolumeContext: ext.GetVolumeContext(), PublishContext: ext.GetPublishContext(), - }); err != nil { + } + gid, setGroup := groups[vol.GetName()] + if setGroup && plugin.SupportsVolumeMountGroup() { + req.VolumeMountGroup = strconv.FormatUint(uint64(gid), 10) + setGroup = false + } + if err := plugin.MountVolume(ctx, req); err != nil { return fmt.Errorf("failed to mount volume %q to %q: %w", ext.GetStorageVolumeId(), hostPath, err) } + if setGroup { + // A failure doesn't fail the mount. Filesystems like root_squash NFS + // or FUSE refuse chgrp, and atelet has no other way to grant access. + if err := setVolumeGroup(ctx, hostPath, gid); err != nil { + slog.WarnContext(ctx, "Could not set the group of an external volume, so non-root containers may not be able to write to it", + slog.String("volume", vol.GetName()), slog.Any("error", err)) + } + } } return nil } +// externalVolumeModeBits are the mode bits atelet adds to an external volume's +// top directory when it sets its group, as Kubernetes fsGroup adds owner and +// group rwx and setgid. The others bits stay as the driver created them. +// Setgid makes new files and directories inherit the volume's group. +const externalVolumeModeBits = os.ModeSetgid | 0o770 + +// externalVolumeGroups maps each external volume that non-root containers +// mount to their primary group. Volumes that only root containers mount are +// left out. It fails if the non-root containers mounting a volume have +// different primary groups. +func externalVolumeGroups(spec *ateletpb.WorkloadSpec, containerSpecs []*ateworkerpb.ContainerSpec) (map[string]uint32, error) { + external := make(map[string]bool) + for _, vol := range spec.GetVolumes() { + if vol.GetExternal() != nil { + external[vol.GetName()] = true + } + } + groups := make(map[string]uint32) + mounters := make(map[string][]string) + conflicts := make(map[string]bool) + for i, ctr := range spec.GetContainers() { + user := containerSpecs[i].GetUser() + if user.GetUid() == 0 { + continue + } + seen := make(map[string]bool) + for _, vm := range ctr.GetVolumeMounts() { + name := vm.GetName() + if !external[name] || seen[name] { + continue + } + seen[name] = true + if gid, ok := groups[name]; ok && gid != user.GetGid() { + conflicts[name] = true + } + groups[name] = user.GetGid() + mounters[name] = append(mounters[name], fmt.Sprintf("%s (group %d)", ctr.GetName(), user.GetGid())) + } + } + for _, vol := range spec.GetVolumes() { + if name := vol.GetName(); conflicts[name] { + return nil, apierror.InvalidArgument("non-root containers that mount volume %q must share a primary group: %s", name, strings.Join(mounters[name], ", ")) + } + } + return groups, nil +} + +// setVolumeGroup sets the group of the directory at path to gid and adds +// externalVolumeModeBits to its mode. The owner stays as the driver created it. +func setVolumeGroup(ctx context.Context, path string, gid uint32) error { + info, err := os.Stat(path) + if err != nil { + return err + } + stat, ok := info.Sys().(*syscall.Stat_t) + if !ok { + return fmt.Errorf("no owner information for %q", path) + } + mode := info.Mode() & (os.ModePerm | os.ModeSetuid | os.ModeSetgid | os.ModeSticky) + if stat.Gid == gid && mode&externalVolumeModeBits == externalVolumeModeBits { + return nil + } + if stat.Gid != 0 && stat.Gid != gid { + slog.WarnContext(ctx, "Changing the group of an external volume from another non-root group, so containers in the old group may lose write access", + slog.String("host_path", path), slog.Any("old_gid", stat.Gid), slog.Any("new_gid", gid)) + } + if stat.Gid != gid { + // Owner -1 keeps the owner, so this is chgrp. + if err := os.Chown(path, -1, int(gid)); err != nil { + return err + } + } + // Chmod after Chown, which can clear the setgid bit. + return os.Chmod(path, mode|externalVolumeModeBits) +} + func (s *Atelet) unmountExternalVolumes(ctx context.Context, actorUID string, volumes []*ateletpb.Volume) error { var errs []error for _, vol := range volumes { diff --git a/cmd/atelet/volumes_test.go b/cmd/atelet/volumes_test.go index 060be7e3ad..4970a3a614 100644 --- a/cmd/atelet/volumes_test.go +++ b/cmd/atelet/volumes_test.go @@ -18,6 +18,7 @@ import ( "context" "errors" "fmt" + "math" "os" "path/filepath" "strings" @@ -28,31 +29,35 @@ import ( "go.ate.dev/substrate/cmd/atelet/internal/actordirs" "go.ate.dev/substrate/cmd/atelet/internal/ateletpath" "go.ate.dev/substrate/internal/proto/ateletpb" + "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/volume" "go.ate.dev/substrate/pkg/client/clientset/versioned/fake" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) type mountCall struct { - volumeID string - targetPath string - attributes map[string]string + volumeID string + targetPath string + attributes map[string]string + volumeMountGroup string } type fakeWorkerPlugin struct { - mountErr error - mountErrs map[string]error - unmountErr error - unmountErrs map[string]error - unmounted []string - mountCalls []mountCall + mountErr error + mountErrs map[string]error + unmountErr error + unmountErrs map[string]error + unmounted []string + mountCalls []mountCall + supportsVolumeMountGroup bool } func (f *fakeWorkerPlugin) MountVolume(ctx context.Context, req volume.MountVolumeRequest) error { f.mountCalls = append(f.mountCalls, mountCall{ - volumeID: req.VolumeID, - targetPath: req.TargetPath, - attributes: req.VolumeContext, + volumeID: req.VolumeID, + targetPath: req.TargetPath, + attributes: req.VolumeContext, + volumeMountGroup: req.VolumeMountGroup, }) if f.mountErrs != nil { if err, ok := f.mountErrs[req.VolumeID]; ok { @@ -72,6 +77,10 @@ func (f *fakeWorkerPlugin) UnmountVolume(ctx context.Context, volumeID string, t return f.unmountErr } +func (f *fakeWorkerPlugin) SupportsVolumeMountGroup() bool { + return f.supportsVolumeMountGroup +} + var _ volume.VolumePluginWorkerPlane = (*fakeWorkerPlugin)(nil) func TestUnmountExternalVolumes(t *testing.T) { @@ -189,7 +198,7 @@ func TestMountExternalVolumes(t *testing.T) { }, } - err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, durableVol, extVol2}) + err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, durableVol, extVol2}, nil) if err != nil { t.Fatalf("mountExternalVolumes failed unexpectedly: %v", err) } @@ -223,6 +232,69 @@ func TestMountExternalVolumes(t *testing.T) { } }) + t.Run("sets the group of volumes non-root containers mount", func(t *testing.T) { + // The test's own group, which a non-root process may give its files. + gid := uint32(os.Getgid()) + for _, supported := range []bool{false, true} { + t.Run(fmt.Sprintf("VOLUME_MOUNT_GROUP=%t", supported), func(t *testing.T) { + useTempNodeDirs(t) + fake := &fakeWorkerPlugin{supportsVolumeMountGroup: supported} + s := &Atelet{ + volumePlugins: map[string]volume.VolumePluginWorkerPlane{ + "mock-driver": fake, + }, + } + groups := map[string]uint32{"vol-1": gid} + if err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}, groups); err != nil { + t.Fatalf("mountExternalVolumes failed unexpectedly: %v", err) + } + + // A driver with VOLUME_MOUNT_GROUP gets the group and the + // directory is left alone. Otherwise atelet sets the group. + wantMountGroup, wantMode := "", os.ModeSetgid|0o770 + if supported { + wantMountGroup, wantMode = fmt.Sprint(gid), 0o750 + } + if got := fake.mountCalls[0].volumeMountGroup; got != wantMountGroup { + t.Errorf("vol-1 volumeMountGroup = %q, want %q", got, wantMountGroup) + } + if got := fake.mountCalls[1].volumeMountGroup; got != "" { + t.Errorf("vol-2 volumeMountGroup = %q, want empty", got) + } + for name, want := range map[string]os.FileMode{"vol-1": wantMode, "vol-2": 0o750} { + info, err := os.Stat(ateletpath.ExternalVolumeHostPath(actorUID, name)) + if err != nil { + t.Fatal(err) + } + if got := info.Mode() & (os.ModePerm | os.ModeSetgid | os.ModeSticky); got != want { + t.Errorf("%s mode = %v, want %v", name, got, want) + } + } + }) + } + }) + + t.Run("mounts the volume when setting the group fails", func(t *testing.T) { + if os.Geteuid() == 0 { + t.Skip("root may set any group, so chgrp can't be made to fail") + } + useTempNodeDirs(t) + fake := &fakeWorkerPlugin{} + s := &Atelet{ + volumePlugins: map[string]volume.VolumePluginWorkerPlane{ + "mock-driver": fake, + }, + } + // A group the test user isn't in, so chgrp fails with EPERM. + groups := map[string]uint32{"vol-1": math.MaxInt32 - 1} + if err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1}, groups); err != nil { + t.Fatalf("mountExternalVolumes failed unexpectedly: %v", err) + } + if len(fake.mountCalls) != 1 { + t.Errorf("mountCalls = %d, want 1", len(fake.mountCalls)) + } + }) + t.Run("target directory already exists is handled cleanly", func(t *testing.T) { useTempNodeDirs(t) @@ -238,7 +310,7 @@ func TestMountExternalVolumes(t *testing.T) { }, } - err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1}) + err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1}, nil) if err != nil { t.Fatalf("mountExternalVolumes with existing directory failed: %v", err) } @@ -262,7 +334,7 @@ func TestMountExternalVolumes(t *testing.T) { volumePlugins: map[string]volume.VolumePluginWorkerPlane{}, } - err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{unknownVol}) + err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{unknownVol}, nil) if err == nil { t.Fatal("expected mountExternalVolumes to fail with unknown plugin, got nil") } @@ -283,7 +355,7 @@ func TestMountExternalVolumes(t *testing.T) { }, } - err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1}) + err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1}, nil) if err == nil { t.Fatal("expected mountExternalVolumes to fail, got nil") } @@ -304,7 +376,7 @@ func TestMountExternalVolumes(t *testing.T) { }, } - err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}) + err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}, nil) if err == nil { t.Fatal("expected mountExternalVolumes to fail, got nil") } @@ -330,7 +402,7 @@ func TestMountExternalVolumes(t *testing.T) { }, } - err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}) + err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}, nil) if err == nil { t.Fatal("expected mountExternalVolumes to fail when vol-2 fails, got nil") } @@ -392,7 +464,7 @@ func TestVolumeHostDirectoryCleanup(t *testing.T) { }, } - if err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}); err != nil { + if err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}, nil); err != nil { t.Fatalf("mountExternalVolumes failed: %v", err) } @@ -427,7 +499,7 @@ func TestVolumeHostDirectoryCleanup(t *testing.T) { } // Mount and then unmount external volumes. - if err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}); err != nil { + if err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}, nil); err != nil { t.Fatalf("mountExternalVolumes failed: %v", err) } if err := s.unmountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1, extVol2}); err != nil { @@ -474,7 +546,7 @@ func TestVolumeHostDirectoryCleanup(t *testing.T) { }, } - if err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1}); err != nil { + if err := s.mountExternalVolumes(ctx, actorUID, []*ateletpb.Volume{extVol1}, nil); err != nil { t.Fatalf("mountExternalVolumes failed: %v", err) } @@ -541,3 +613,118 @@ func TestDirectCSIDriverConfigGetter(t *testing.T) { t.Fatalf("expected error for missing driver, got nil") } } + +func TestExternalVolumeGroups(t *testing.T) { + volumes := []*ateletpb.Volume{ + {Name: "data", External: &ateletpb.ExternalVolumeSource{StorageVolumeId: "vol-1"}}, + {Name: "scratch", DurableDir: &ateletpb.DurableDirVolumeSource{}}, + } + type ctr struct { + name string + user *ateworkerpb.ProcessUser + mounts []string + } + root := (*ateworkerpb.ProcessUser)(nil) + user := func(uid, gid uint32) *ateworkerpb.ProcessUser { + return &ateworkerpb.ProcessUser{Uid: uid, Gid: gid} + } + tests := []struct { + name string + ctrs []ctr + want map[string]uint32 + wantErr string + }{ + { + name: "root containers only", + ctrs: []ctr{{"a", root, []string{"data"}}, {"b", user(0, 500), []string{"data"}}}, + want: map[string]uint32{}, + }, + { + name: "one non-root container", + ctrs: []ctr{{"a", user(1000, 500), []string{"data"}}}, + want: map[string]uint32{"data": 500}, + }, + { + name: "non-root containers share a group, root ignored", + ctrs: []ctr{{"a", user(1000, 500), []string{"data"}}, {"b", user(2001, 500), []string{"data"}}, {"c", root, []string{"data"}}}, + want: map[string]uint32{"data": 500}, + }, + { + name: "non-root container with group 0", + ctrs: []ctr{{"a", user(1000, 0), []string{"data"}}}, + want: map[string]uint32{"data": 0}, + }, + { + name: "durable dir and unmounted volume left out", + ctrs: []ctr{{"a", user(1000, 500), []string{"scratch"}}, {"b", user(2001, 600), nil}}, + want: map[string]uint32{}, + }, + { + name: "non-root containers with different groups", + ctrs: []ctr{{"a", user(1000, 500), []string{"data", "data"}}, {"b", user(2001, 600), []string{"data"}}}, + wantErr: `non-root containers that mount volume "data" must share a primary group: a (group 500), b (group 600)`, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + spec := &ateletpb.WorkloadSpec{Volumes: volumes} + var containerSpecs []*ateworkerpb.ContainerSpec + for _, c := range tc.ctrs { + var mounts []*ateletpb.VolumeMount + for _, m := range c.mounts { + mounts = append(mounts, &ateletpb.VolumeMount{Name: m, MountPath: "/" + m}) + } + spec.Containers = append(spec.Containers, &ateletpb.Container{Name: c.name, VolumeMounts: mounts}) + containerSpecs = append(containerSpecs, &ateworkerpb.ContainerSpec{User: c.user}) + } + got, err := externalVolumeGroups(spec, containerSpecs) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("externalVolumeGroups() error = %v, want %q", err, tc.wantErr) + } + return + } + if err != nil { + t.Fatalf("externalVolumeGroups() failed: %v", err) + } + if diff := cmp.Diff(tc.want, got); diff != "" { + t.Errorf("externalVolumeGroups() mismatch (-want +got):\n%s", diff) + } + }) + } +} + +func TestSetVolumeGroup(t *testing.T) { + tests := []struct { + mode os.FileMode + want os.FileMode + }{ + {0o755, os.ModeSetgid | 0o775}, + {0o750, os.ModeSetgid | 0o770}, + {0o700, os.ModeSetgid | 0o770}, + {0o777, os.ModeSetgid | 0o777}, + {os.ModeSticky | 0o777, os.ModeSetgid | os.ModeSticky | 0o777}, + } + for _, tc := range tests { + t.Run(tc.mode.String(), func(t *testing.T) { + dir := filepath.Join(t.TempDir(), "vol") + if err := os.Mkdir(dir, 0o700); err != nil { + t.Fatal(err) + } + if err := os.Chmod(dir, tc.mode); err != nil { + t.Fatal(err) + } + // The test's own group, which a non-root process may give its files. + if err := setVolumeGroup(context.Background(), dir, uint32(os.Getgid())); err != nil { + t.Fatalf("setVolumeGroup() failed: %v", err) + } + info, err := os.Stat(dir) + if err != nil { + t.Fatal(err) + } + if got := info.Mode() & (os.ModePerm | os.ModeSetgid | os.ModeSticky); got != tc.want { + t.Errorf("mode = %v, want %v", got, tc.want) + } + }) + } +} diff --git a/cmd/atelet/worker_informers.go b/cmd/atelet/worker_informers.go new file mode 100644 index 0000000000..9ff5b0d9af --- /dev/null +++ b/cmd/atelet/worker_informers.go @@ -0,0 +1,35 @@ +// Copyright 2026 The Agent Substrate 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 ( + "go.ate.dev/substrate/pkg/client/clientset/versioned" + "go.ate.dev/substrate/pkg/client/informers/externalversions" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + kubeinformers "k8s.io/client-go/informers" + "k8s.io/client-go/kubernetes" +) + +func newWorkerInformers(ateClient versioned.Interface, k8sClient kubernetes.Interface, namespace, nodeName string) (externalversions.SharedInformerFactory, kubeinformers.SharedInformerFactory) { + ateFactory := externalversions.NewSharedInformerFactoryWithOptions(ateClient, 0, externalversions.WithNamespace(namespace)) + // The node selector keeps LIST/WATCH costs proportional to this node's workers. + podFactory := kubeinformers.NewSharedInformerFactoryWithOptions(k8sClient, 0, + kubeinformers.WithNamespace(namespace), + kubeinformers.WithTweakListOptions(func(o *metav1.ListOptions) { + o.FieldSelector = "spec.nodeName=" + nodeName + o.LabelSelector = workerPoolLabel + })) + return ateFactory, podFactory +} diff --git a/cmd/atelet/worker_informers_test.go b/cmd/atelet/worker_informers_test.go new file mode 100644 index 0000000000..c0bc4c3fa8 --- /dev/null +++ b/cmd/atelet/worker_informers_test.go @@ -0,0 +1,118 @@ +// Copyright 2026 The Agent Substrate 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 ( + "context" + "testing" + "time" + + atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" + atefake "go.ate.dev/substrate/pkg/client/clientset/versioned/fake" + corev1 "k8s.io/api/core/v1" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/runtime" + k8swatch "k8s.io/apimachinery/pkg/watch" + kubefake "k8s.io/client-go/kubernetes/fake" + k8stesting "k8s.io/client-go/testing" + "k8s.io/client-go/tools/cache" +) + +func TestWorkerInformersNamespace(t *testing.T) { + for _, namespace := range []string{"workers", ""} { + t.Run("namespace="+namespace, func(t *testing.T) { + kube := kubefake.NewClientset(workerPod("local", "pool"), &corev1.Pod{ + ObjectMeta: metav1.ObjectMeta{Name: "other", Namespace: "other", Labels: map[string]string{workerPoolLabel: "pool"}}, + }) + ate := atefake.NewSimpleClientset(resolvedPool("pool", "config"), + &atev1.WorkerPool{ObjectMeta: metav1.ObjectMeta{Name: "pool", Namespace: "other"}}, + &atev1.SandboxConfig{ObjectMeta: metav1.ObjectMeta{Name: "config"}}, + ) + actions := make(chan k8stesting.Action, 10) + for _, client := range []*k8stesting.Fake{&kube.Fake, &ate.Fake} { + client.PrependReactor("list", "*", func(action k8stesting.Action) (bool, runtime.Object, error) { + actions <- action + return false, nil, nil + }) + client.PrependWatchReactor("*", func(action k8stesting.Action) (bool, k8swatch.Interface, error) { + actions <- action + return false, nil, nil + }) + } + ateFactory, podFactory := newWorkerInformers(ate, kube, namespace, "node-1") + pods := podFactory.Core().V1().Pods().Informer() + pools := ateFactory.Ate().V1().WorkerPools().Informer() + configs := ateFactory.Ate().V1().SandboxConfigs().Informer() + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + t.Cleanup(func() { + cancel() + podFactory.Shutdown() + ateFactory.Shutdown() + }) + podFactory.Start(ctx.Done()) + ateFactory.Start(ctx.Done()) + seen := make(map[string]bool) + for range 6 { + select { + case action := <-actions: + resource := action.GetResource().Resource + key := action.GetVerb() + " " + resource + if seen[key] { + t.Fatalf("duplicate request: %s", key) + } + seen[key] = true + wantNamespace := namespace + if resource == "sandboxconfigs" { + wantNamespace = "" + } + if action.GetNamespace() != wantNamespace { + t.Errorf("%s namespace = %q, want %q", key, action.GetNamespace(), wantNamespace) + } + if resource == "pods" { + var fields, labels string + switch action := action.(type) { + case k8stesting.ListAction: + fields = action.GetListRestrictions().Fields.String() + labels = action.GetListRestrictions().Labels.String() + case k8stesting.WatchAction: + fields = action.GetWatchRestrictions().Fields.String() + labels = action.GetWatchRestrictions().Labels.String() + } + if fields != "spec.nodeName=node-1" || labels != workerPoolLabel { + t.Errorf("%s selectors = %q, %q, want node-1 and %s", key, fields, labels, workerPoolLabel) + } + } + case <-ctx.Done(): + t.Fatalf("waiting for LIST/WATCH requests: %v (seen %v)", ctx.Err(), seen) + } + } + if !cache.WaitForCacheSync(ctx.Done(), pods.HasSynced, pools.HasSynced, configs.HasSynced) { + t.Fatal("worker caches did not sync") + } + want := 1 + if namespace == "" { + want = 2 + } + for name, informer := range map[string]cache.SharedIndexInformer{"Pods": pods, "WorkerPools": pools} { + if got := len(informer.GetStore().List()); got != want { + t.Errorf("%s cache has %d objects, want %d", name, got, want) + } + } + if _, exists, err := configs.GetStore().GetByKey("config"); err != nil || !exists { + t.Fatalf("cluster-scoped SandboxConfig missing: exists=%v, err=%v", exists, err) + } + }) + } +} diff --git a/cmd/atelet/worker_sandbox_syncer.go b/cmd/atelet/worker_sandbox_syncer.go index 843bd9f699..771c6ccbc0 100644 --- a/cmd/atelet/worker_sandbox_syncer.go +++ b/cmd/atelet/worker_sandbox_syncer.go @@ -32,7 +32,6 @@ import ( "context" "errors" "fmt" - "io/fs" "log/slog" "math/rand/v2" "os" @@ -110,27 +109,23 @@ const ( // workerSandboxSyncer keeps a sandbox runtimes file in each local worker's // directory under workersDir: the runtimes of the enabled versions of the -// SandboxConfig the worker's pool uses. It creates a worker's directory once -// it writes the pod's file and removes it when the pod is gone. +// SandboxConfig the worker's pool uses, with the default's assets linked +// under the directory so they stay cached. It creates a worker's directory +// when it first stages the pod's default and removes it when the pod is gone. type workerSandboxSyncer struct { resolver *workerSandboxResolver // index is told each pod's runtimes before its file is written, and // what the pod advertises once it is. index *runtimeIndex - // prewarm, if set, is handed each default runtime a pod's file - // advertises, with a directory under the pod's to link the assets into, - // so they are fetched before an actor asks for them and stay cached - // while none runs them. - prewarm runtimePrewarm // recorder emits a Warning event on the worker pod when syncing its // sandbox runtimes file fails. recorder events.EventRecorder // pods holds this node's worker pods, indexed by podUIDIndex. pods cache.Indexer assets sandboxAssetFetcher - // scratchDir is where buildFile stages assets to verify them (and run - // the runsc probe), read from ateletpath once here so a test can point - // a syncer elsewhere. + // scratchDir is where buildFile stages a restorable version's assets to + // verify them, and the runsc it probes for any version, read from + // ateletpath once here so a test can point a syncer elsewhere. scratchDir string // queue carries pod UIDs. A workqueue never hands the same key to two // workers at once, so a pod's file is never written and its directory @@ -144,28 +139,27 @@ type workerSandboxSyncer struct { probeCPUIdentity func() (vendor, model string, err error) // runCPUFeatures is runRunscCPUFeatures. Overridable in tests. runCPUFeatures func(ctx context.Context, runscPath string) ([]string, error) - // mu guards hostCPU, cpuFeatures and microvmAssets across the syncWorkers - // in run: hostCPU is the probed host CPU identity, nil until a probe - // succeeds; cpuFeatures is the encoded cpu_features of each runsc binary - // by its gVisor asset's SHA256 digest; and microvmAssets holds the - // bundle hashes of microVM versions whose assets have been verified in - // this atelet process. Restorable microVM versions are verified once per - // atelet process (except when two workers meet a version before either + // mu guards hostCPU, cpuFeatures and verifiedBundles across the + // syncWorkers in run: hostCPU is the probed host CPU identity, nil until + // a probe succeeds; cpuFeatures is the encoded cpu_features of each + // runsc binary by its gVisor asset's SHA256 digest; and verifiedBundles + // holds the bundle hashes of versions whose assets have been verified in + // this atelet process. A restorable version is verified once per atelet + // process (except when two workers meet a version before either // memoizes it); the default version is staged on every sync. - mu sync.Mutex - hostCPU *cpuIdentity - cpuFeatures map[string]string - microvmAssets map[string]bool + mu sync.Mutex + hostCPU *cpuIdentity + cpuFeatures map[string]string + verifiedBundles map[string]bool } -func newWorkerSandboxSyncer(resolver *workerSandboxResolver, pods cache.Indexer, assets sandboxAssetFetcher, workersDir string, index *runtimeIndex, prewarm runtimePrewarm, recorder events.EventRecorder) *workerSandboxSyncer { +func newWorkerSandboxSyncer(resolver *workerSandboxResolver, pods cache.Indexer, assets sandboxAssetFetcher, workersDir string, index *runtimeIndex, recorder events.EventRecorder) *workerSandboxSyncer { return &workerSandboxSyncer{ resolver: resolver, pods: pods, assets: assets, scratchDir: ateletpath.SandboxAssetScratchDir, index: index, - prewarm: prewarm, recorder: recorder, // Backoff doubles from 1s for informer lag and unresolved pools, and // caps at 5m where uncapped retries for transient asset fetch or probe @@ -178,23 +172,24 @@ func newWorkerSandboxSyncer(resolver *workerSandboxResolver, pods cache.Indexer, probeCPUIdentity: hardware.ProbeCPUIdentity, runCPUFeatures: runRunscCPUFeatures, cpuFeatures: make(map[string]string), - microvmAssets: make(map[string]bool), + verifiedBundles: make(map[string]bool), } } -// runtimePrewarm is what the syncer asks of the runtime prewarmer: fetch a -// default runtime and link its assets into the given directory. -type runtimePrewarm interface { - enqueue(hash, dir string) +// sandboxAssetFetcher is the slice of Atelet the syncer needs. Staging +// through the same method as the Run/Restore path keeps the fetches from +// ever diverging on cache layout or validation. +type sandboxAssetFetcher interface { + ensureSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, dstDir string) (map[string]string, error) } // defaultRuntimeDirsName is the directory under a worker's own that holds // one directory per default runtime the worker advertises, by bundle hash, -// one per sandbox class, which the prewarmer links the runtime's assets -// into. The links are what keeps the assets cached while no actor runs -// them: the cache never evicts a linked entry. The syncer makes a runtime's -// directory when the worker's file first advertises it as a default and -// removes it when the file stops; they all go with the worker's directory. +// one per sandbox class, which the build stages the runtime's assets into. +// The links are what keeps the assets cached while no actor runs them: the +// cache never evicts a linked entry. The build fills a runtime's directory +// before the worker's file advertises it as a default, and the syncer +// removes it once the file stops; they all go with the worker's directory. const defaultRuntimeDirsName = "default-runtime" // defaultRuntimeDir is the directory for the default runtime hash of the @@ -203,17 +198,14 @@ func (s *workerSandboxSyncer) defaultRuntimeDir(uid, hash string) string { return filepath.Join(s.podDir(uid), defaultRuntimeDirsName, strings.ReplaceAll(hash, ":", "-")) } -// syncDefaultRuntimeDirs makes the worker pod's default-runtime directory -// hold one directory per hash in defaults and nothing else: the others are -// removed, which unlinks the runtimes the worker no longer advertises, and -// the missing ones are created empty for the prewarmer to fill. Called -// once the pod's file advertises defaults, so nothing it removes is a -// runtime the worker still names. -func (s *workerSandboxSyncer) syncDefaultRuntimeDirs(uid string, defaults []string) error { +// pruneDefaultRuntimeDirs removes everything in the worker pod's +// default-runtime directory but the directories of the hashes in defaults, +// which unlinks the runtimes the worker no longer advertises as a default. +// Called once the pod's file advertises defaults, each staged into its +// directory by the build, so nothing it removes is a runtime the worker +// still names. +func (s *workerSandboxSyncer) pruneDefaultRuntimeDirs(uid string, defaults []string) error { parent := filepath.Join(s.podDir(uid), defaultRuntimeDirsName) - if err := os.MkdirAll(parent, 0o700); err != nil { - return fmt.Errorf("while creating the worker's default runtime dir: %w", err) - } want := make(map[string]bool, len(defaults)) for _, hash := range defaults { want[filepath.Base(s.defaultRuntimeDir(uid, hash))] = true @@ -229,11 +221,6 @@ func (s *workerSandboxSyncer) syncDefaultRuntimeDirs(uid string, defaults []stri } } } - for name := range want { - if err := os.Mkdir(filepath.Join(parent, name), 0o700); err != nil && !errors.Is(err, fs.ErrExist) { - return fmt.Errorf("while creating a default runtime dir: %w", err) - } - } return nil } @@ -249,7 +236,7 @@ func (s *workerSandboxSyncer) syncDefaultRuntimeDirs(uid string, defaults []stri // or a list/watch fails (e.g. Forbidden while an RBAC rollout lags the // binary), existing files and index entries stay as they are and only // changes wait. -func startWorkerSandboxSyncer(ctx context.Context, pods coreinformers.PodInformer, workerPools ateinformers.WorkerPoolInformer, configs ateinformers.SandboxConfigInformer, assets sandboxAssetFetcher, workersDir string, index *runtimeIndex, prewarm runtimePrewarm, recorder events.EventRecorder) (*workerSandboxSyncer, error) { +func startWorkerSandboxSyncer(ctx context.Context, pods coreinformers.PodInformer, workerPools ateinformers.WorkerPoolInformer, configs ateinformers.SandboxConfigInformer, assets sandboxAssetFetcher, workersDir string, index *runtimeIndex, recorder events.EventRecorder) (*workerSandboxSyncer, error) { if err := pods.Informer().AddIndexers(cache.Indexers{podUIDIndex: func(obj any) ([]string, error) { pod, ok := obj.(*corev1.Pod) if !ok { @@ -263,7 +250,7 @@ func startWorkerSandboxSyncer(ctx context.Context, pods coreinformers.PodInforme workerPools: workerPools.Lister(), configs: configs.Lister(), } - s := newWorkerSandboxSyncer(resolver, pods.Informer().GetIndexer(), assets, workersDir, index, prewarm, recorder) + s := newWorkerSandboxSyncer(resolver, pods.Informer().GetIndexer(), assets, workersDir, index, recorder) if err := watch(ctx, "worker pod", pods.Informer(), s.podHandler()); err != nil { return nil, err } diff --git a/cmd/atelet/worker_sandbox_syncer_test.go b/cmd/atelet/worker_sandbox_syncer_test.go index 33bfd458be..8bd46bc28c 100644 --- a/cmd/atelet/worker_sandbox_syncer_test.go +++ b/cmd/atelet/worker_sandbox_syncer_test.go @@ -62,18 +62,20 @@ func testCPUFeatures() []string { } } -// fakeAssetFetcher answers ensureSandboxAssets from fn. The paths it returns -// are not under dstDir: the syncer only runs what it is handed, so where the -// fake says a binary is does not matter. +// fakeAssetFetcher answers ensureSandboxAssets from fn. It creates dstDir as +// the real fetcher does, but the paths it returns are not under it: the +// syncer only runs what it is handed, so where the fake says a binary is +// does not matter. type fakeAssetFetcher struct { fn func(ctx context.Context, rec *sandboxAssetsRecord) (map[string]string, error) } -func (f *fakeAssetFetcher) ensureSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, _ string) (map[string]string, error) { - return f.fn(ctx, rec) -} - -func (f *fakeAssetFetcher) stageSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, _ string) (map[string]string, error) { +func (f *fakeAssetFetcher) ensureSandboxAssets(ctx context.Context, rec *sandboxAssetsRecord, dstDir string) (map[string]string, error) { + if dstDir != "" { + if err := os.MkdirAll(dstDir, 0o700); err != nil { + return nil, err + } + } return f.fn(ctx, rec) } @@ -174,7 +176,7 @@ func newTestSyncer(t *testing.T, objs ...any) *workerSandboxSyncer { s := newWorkerSandboxSyncer(&workerSandboxResolver{ workerPools: atelisters.NewWorkerPoolLister(pools), configs: atelisters.NewSandboxConfigLister(configs), - }, pods, newTestAssetFetcher(), t.TempDir(), newRuntimeIndex(), nil, events.NewFakeRecorder(64)) + }, pods, newTestAssetFetcher(), t.TempDir(), newRuntimeIndex(), events.NewFakeRecorder(64)) // The queue starts a goroutine; stop it with the test. t.Cleanup(s.queue.ShutDown) s.scratchDir = t.TempDir() // buildFile stages assets there @@ -934,7 +936,7 @@ func TestStartWorkerSandboxSyncer(t *testing.T) { ateFactory.Ate().V1().WorkerPools(), ateFactory.Ate().V1().SandboxConfigs(), newScriptAssetFetcher(t), - dir, newRuntimeIndex(), nil, &events.FakeRecorder{}) + dir, newRuntimeIndex(), &events.FakeRecorder{}) if err != nil { t.Fatalf("startWorkerSandboxSyncer() error = %v", err) } diff --git a/cmd/atelet/worker_sandbox_versions.go b/cmd/atelet/worker_sandbox_versions.go index 220ff7ce21..de59f1336e 100644 --- a/cmd/atelet/worker_sandbox_versions.go +++ b/cmd/atelet/worker_sandbox_versions.go @@ -19,10 +19,12 @@ package main // - resolve: find the SandboxConfig of the pod's WorkerPool // - plan: pick the config's versions this node can run // - build: hash each version's asset digests into its sandbox_bundle_hash, -// verify its assets in the cache, and probe what a snapshot taken on the -// runtime must find again: the host CPU identity for microVM, the runsc -// binary's CPU features for gVisor +// stage the default version's assets under the worker's directory and +// verify each restorable version's in the cache, and probe what a +// snapshot taken on the runtime must find again: the host CPU identity +// for microVM, the runsc binary's CPU features for gVisor // - write: replace the file in the worker directory if its content changed +// - prune: remove the directories of defaults the file no longer names // // worker_sandbox_syncer.go decides when each pod is synced, and creates and // removes the worker directories. @@ -235,29 +237,32 @@ func hashVersions(plan *sandboxPlan) []hashedVersion { } // buildFile returns the file content naming the runtimes of the hashed -// versions, the default first. A version whose bundle hash equals an -// earlier one's is left out, so the file lists each runtime once. The -// default version's failure fails the sync, which leaves the existing file -// in place until a retry succeeds. A restorable version whose attributes -// cannot be built is left out; when the failure is transient the file is -// returned with an error wrapping errIncomplete, so the caller writes the -// runtimes that resolved right away and retries for the rest. +// versions, the default first, for the worker pod with the given UID. A +// version whose bundle hash equals an earlier one's is left out, so the file +// lists each runtime once. The default version's failure fails the sync, +// which leaves the existing file in place until a retry succeeds. A +// restorable version whose attributes cannot be built is left out; when the +// failure is transient the file is returned with an error wrapping +// errIncomplete, so the caller writes the runtimes that resolved right away +// and retries for the rest. // // TODO: write the file as soon as the default version's attributes are known // and add restorable runtimes on a later pass. On a fresh node the first // worker cannot register until every restorable version's assets have been // fetched and probed, serially. // -// The first time this atelet process sees a gVisor runsc digest or a -// restorable microVM bundle hash, buildFile fetches the version's assets into -// the cache (and runs runsc for gVisor); a microVM default version is staged -// on every build so promoting an evicted version to default verifies it in the -// cache before unpinning the previous default. Once the file is written, the -// syncer links the default runtime under the worker's directory so cache GC -// never evicts it. Run and Restore fetch any evicted restorable version on -// demand. A version with a bad sha256 fails verification without being cached -// or memoized, so retries re-download it until the SandboxConfig is fixed. -func (s *workerSandboxSyncer) buildFile(ctx context.Context, plan *sandboxPlan, hashed []hashedVersion) (*sandboxruntimes.File, error) { +// Every build stages the default version's assets into its directory under +// the worker's (see defaultRuntimeDirsName), fetching what the cache lacks, +// so promoting an evicted version to default verifies it in the cache, and +// links it, before the previous default is unlinked; a re-sync with the same +// default costs a stat per asset. A restorable version is staged into a +// scratch directory, removed again, the first time this atelet process sees +// its bundle hash; Run and Restore fetch an evicted restorable version on +// demand. The first time the process sees a gVisor runsc digest it runs the +// binary for its cpu_features. A version with a bad sha256 fails +// verification without being cached or memoized, so retries re-download it +// until the SandboxConfig is fixed. +func (s *workerSandboxSyncer) buildFile(ctx context.Context, uid string, plan *sandboxPlan, hashed []hashedVersion) (*sandboxruntimes.File, error) { class := sandboxruntimes.Class{SandboxClass: string(plan.sandboxClass)} seen := make(map[string]bool, len(hashed)) var incomplete error @@ -265,7 +270,7 @@ func (s *workerSandboxSyncer) buildFile(ctx context.Context, plan *sandboxPlan, if seen[v.hash] { continue } - attrs, err := s.versionAttrs(ctx, plan.sandboxClass, v.rec, v.hash, v.isDefault) + attrs, err := s.versionAttrs(ctx, uid, plan.sandboxClass, v) if err != nil { err = fmt.Errorf("SandboxConfig %q, version %q: %w", plan.config, v.name, err) if v.isDefault { @@ -296,15 +301,15 @@ func (s *workerSandboxSyncer) buildFile(ctx context.Context, plan *sandboxPlan, return out, nil } -// versionAttrs returns the attributes of one version's runtime, whose -// sandbox_bundle_hash is hash: architecture and the hash for every class, -// the host CPU identity for a microVM runtime (with its assets verified in -// the local cache), and the runsc binary's cpu_features for a gVisor one. -// isDefault makes the microVM asset check skip the memo. -func (s *workerSandboxSyncer) versionAttrs(ctx context.Context, class atev1.SandboxClass, rec *sandboxAssetsRecord, hash string, isDefault bool) (sandboxruntimes.Attributes, error) { +// versionAttrs returns the attributes of v's runtime: architecture and the +// bundle hash for every class, the host CPU identity for a microVM runtime +// and the runsc binary's cpu_features for a gVisor one, with the version's +// assets staged for the worker pod with the given UID (see stageDefault and +// stageScratch). +func (s *workerSandboxSyncer) versionAttrs(ctx context.Context, uid string, class atev1.SandboxClass, v hashedVersion) (sandboxruntimes.Attributes, error) { attrs := sandboxruntimes.Attributes{ hardware.AttrArchitecture: runtime.GOARCH, - hardware.AttrSandboxBundleHash: hash, + hardware.AttrSandboxBundleHash: v.hash, } switch class { case atev1.SandboxClassMicroVM: @@ -312,12 +317,12 @@ func (s *workerSandboxSyncer) versionAttrs(ctx context.Context, class atev1.Sand if err != nil { return nil, fmt.Errorf("while probing host CPU identity: %w", err) } - if err := s.ensureMicroVMAssets(ctx, rec, hash, isDefault); err != nil { + if err := s.ensureMicroVMAssets(ctx, uid, v); err != nil { return nil, err } attrs[hardware.AttrCPUVendor], attrs[hardware.AttrCPUModel] = vendor, model case atev1.SandboxClassGvisor: - mask, err := s.gvisorCPUFeatures(ctx, rec) + mask, err := s.gvisorCPUFeatures(ctx, uid, v) if err != nil { return nil, err } @@ -347,76 +352,108 @@ func (s *workerSandboxSyncer) hostCPUIdentity() (vendor, model string, err error return s.hostCPU.vendor, s.hostCPU.model, nil } -// ensureMicroVMAssets stages a microVM version's assets into a scratch -// directory so a version whose assets cannot be fetched or fail SHA256 -// verification is not advertised in the worker's sandbox runtimes file. -// Restorable versions are checked once per atelet process; the default version -// is checked on every sync (a cache hit once prewarmed) so promoting an -// evicted version to default verifies it in the cache before unpinning the -// previous default. -func (s *workerSandboxSyncer) ensureMicroVMAssets(ctx context.Context, rec *sandboxAssetsRecord, hash string, isDefault bool) error { - if !isDefault { - s.mu.Lock() - ok := s.microvmAssets[hash] - s.mu.Unlock() - if ok { - return nil - } - } +// stageDefault stages the default version v into its directory under the +// worker pod's, through the cache, fetching what it lacks, so a default +// whose assets cannot be fetched or fail SHA256 verification is not +// advertised. The links stay and keep the assets cached while no actor runs +// them; once the directory is filled this costs a stat per asset. +func (s *workerSandboxSyncer) stageDefault(ctx context.Context, uid string, v hashedVersion) error { + // Backstop for the sync worker this runs on; see probeFetchTimeout. + ctx, cancel := context.WithTimeout(ctx, probeFetchTimeout) + defer cancel() + _, err := s.assets.ensureSandboxAssets(ctx, v.rec, s.defaultRuntimeDir(uid, v.hash)) + return err +} + +// stageScratch stages rec's assets into a scratch directory, which done +// removes, and returns the staged paths; the cache keeps the entry. This +// verifies a restorable version's assets, and gives the gVisor probe a runsc +// linked for it alone. +func (s *workerSandboxSyncer) stageScratch(ctx context.Context, rec *sandboxAssetsRecord) (paths map[string]string, done func(), err error) { ctx, cancel := context.WithTimeout(ctx, probeFetchTimeout) defer cancel() - scratch, err := os.MkdirTemp(s.scratchDir, "microvm-assets-") + scratch, err := os.MkdirTemp(s.scratchDir, "sandbox-assets-") if err != nil { - return fmt.Errorf("while creating microvm-assets scratch dir: %w", err) + return nil, nil, fmt.Errorf("while creating sandbox assets scratch dir: %w", err) } - defer func() { _ = os.RemoveAll(scratch) }() - if _, err := s.assets.ensureSandboxAssets(ctx, rec, scratch); err != nil { - return err + done = func() { _ = os.RemoveAll(scratch) } + paths, err = s.assets.ensureSandboxAssets(ctx, rec, scratch) + if err != nil { + done() + return nil, nil, err } + return paths, done, nil +} + +// ensureMicroVMAssets stages a microVM version: the default on every sync +// (see stageDefault), so promoting an evicted version to default verifies it +// in the cache before the previous default is unlinked; a restorable version +// once per atelet process (see stageScratch). +func (s *workerSandboxSyncer) ensureMicroVMAssets(ctx context.Context, uid string, v hashedVersion) error { s.mu.Lock() - s.microvmAssets[hash] = true + verified := s.verifiedBundles[v.hash] + s.mu.Unlock() + switch { + case v.isDefault: + if err := s.stageDefault(ctx, uid, v); err != nil { + return err + } + case !verified: + _, done, err := s.stageScratch(ctx, v.rec) + if err != nil { + return err + } + done() + default: + return nil + } + s.mu.Lock() + s.verifiedBundles[v.hash] = true s.mu.Unlock() return nil } -// gvisorCPUFeatures returns the encoded cpu_features of rec's runsc binary. -// The first time this atelet sees the binary's digest it fetches the binary -// into the local asset cache and runs ` cpu-features`. -func (s *workerSandboxSyncer) gvisorCPUFeatures(ctx context.Context, rec *sandboxAssetsRecord) (string, error) { - digest := rec.Assets[gvisorAssetName].SHA256 +// gvisorCPUFeatures returns the encoded cpu_features of v's runsc binary. It +// stages the version like ensureMicroVMAssets, and runs ` +// cpu-features` the first time this atelet process sees the binary's digest, +// on a runsc linked into scratch for the probe alone, never on the one under +// the worker's directory. The memo is per digest, so a bundle that adds an +// asset beside a known runsc is staged for that asset without running runsc +// again. +func (s *workerSandboxSyncer) gvisorCPUFeatures(ctx context.Context, uid string, v hashedVersion) (string, error) { + digest := v.rec.Assets[gvisorAssetName].SHA256 if digest == "" { return "", fmt.Errorf("%w: gvisor version has no %q asset", errPermanent, gvisorAssetName) } s.mu.Lock() - mask, ok := s.cpuFeatures[digest] + mask, probed := s.cpuFeatures[digest] + verified := s.verifiedBundles[v.hash] s.mu.Unlock() - if ok { - return mask, nil - } - // Backstop for the sync worker this runs on; see probeFetchTimeout. - ctx, cancel := context.WithTimeout(ctx, probeFetchTimeout) - defer cancel() - // The probe has no actor to stage the binary for: it links it into a - // scratch dir it removes again, and the cache keeps the entry. - scratch, err := os.MkdirTemp(s.scratchDir, "cpu-features-") - if err != nil { - return "", fmt.Errorf("while creating cpu-features scratch dir: %w", err) - } - defer func() { _ = os.RemoveAll(scratch) }() - paths, err := s.assets.ensureSandboxAssets(ctx, rec, scratch) - if err != nil { - return "", err - } - names, err := s.runCPUFeatures(ctx, runscPathFor(paths)) - if err != nil { - return "", err + if v.isDefault { + if err := s.stageDefault(ctx, uid, v); err != nil { + return "", err + } + verified = true } - mask, err = hardware.EncodeCPUFeatures(runtime.GOARCH, names) - if err != nil { - return "", fmt.Errorf("%w: %w", errPermanent, err) + if !verified || !probed { + paths, done, err := s.stageScratch(ctx, v.rec) + if err != nil { + return "", err + } + defer done() + if !probed { + names, err := s.runCPUFeatures(ctx, runscPathFor(paths)) + if err != nil { + return "", err + } + if mask, err = hardware.EncodeCPUFeatures(runtime.GOARCH, names); err != nil { + return "", fmt.Errorf("%w: %w", errPermanent, err) + } + } } s.mu.Lock() s.cpuFeatures[digest] = mask + s.verifiedBundles[v.hash] = true s.mu.Unlock() return mask, nil } @@ -490,13 +527,19 @@ func bundleHash(rec *sandboxAssetsRecord) string { // - plan: resolve the pool's config and its versions for this node // - hash: hash each version's runtime, and make each resolvable by its // hash before the file can let the worker register it -// - build: verify each version's assets in the cache and probe what a -// snapshot taken on the runtime must find again +// - build: stage the default version into its directory under the pod's, +// verify each restorable version's assets in the cache, and probe what +// a snapshot taken on the runtime must find again // - write: replace the file if its content changed, then record what // the worker now advertises in the index -// - prewarm: make the pod's default-runtime directories match what the -// file now advertises, and have each default's assets linked into its -// directory, off this goroutine +// - prune: remove the directories of the defaults the file no longer +// names, which unlinks them +// +// The default's directory is filled before the file names it and removed +// only after the file stops, so a worker's default stays cached while no +// actor runs it. A build that fails leaves the file, and so the previous +// default's directory, as they were; the directory of a default it staged +// before failing stays until a later sync writes the file and prunes it. // // A file missing restorable runtimes for a transient reason is written all // the same, and the errIncomplete from build is returned so finish retries. @@ -513,39 +556,33 @@ func (s *workerSandboxSyncer) syncPod(ctx context.Context, pod *corev1.Pod) (k8s if err := s.index.registerRuntimes(plan.config, hashed); err != nil { return related, err } - want, buildErr := s.buildFile(ctx, plan, hashed) + uid := string(pod.UID) + want, buildErr := s.buildFile(ctx, uid, plan, hashed) if buildErr != nil && !errors.Is(buildErr, errIncomplete) { return related, buildErr } - if err := s.write(ctx, string(pod.UID), plan.config, want); err != nil { + if err := s.write(ctx, uid, plan.config, want); err != nil { return related, err } // What the worker advertises is what its file now says: a sync that // failed before the write left the previous entry, and one that wrote // a partial file names only the runtimes in it. One class per pool // today; a pool that runs several will yield one plan per class here. - if err := s.index.register(string(pod.UID), advertisedClass{class: plan.sandboxClass, config: plan.config, hashed: writtenVersions(hashed, want)}); err != nil { + written := writtenVersions(hashed, want) + if err := s.index.register(uid, advertisedClass{class: plan.sandboxClass, config: plan.config, hashed: written}); err != nil { return related, err } - // Only now, with the file naming its defaults: a sync that failed above - // left the file, and so the directories, as they were. The build staged - // a microVM default just now and fetched a gVisor default the first time - // it saw its digest, so the prewarm is links unless an evicted gVisor - // version was promoted to default. - if s.prewarm != nil { - var defaults []string - for _, v := range writtenVersions(hashed, want) { - if v.isDefault { - defaults = append(defaults, v.hash) - } - } - if err := s.syncDefaultRuntimeDirs(string(pod.UID), defaults); err != nil { - return related, err - } - for _, hash := range defaults { - s.prewarm.enqueue(hash, s.defaultRuntimeDir(string(pod.UID), hash)) + // Only now, with the file naming its defaults, each linked into its + // directory by the build. + var defaults []string + for _, v := range written { + if v.isDefault { + defaults = append(defaults, v.hash) } } + if err := s.pruneDefaultRuntimeDirs(uid, defaults); err != nil { + return related, err + } return related, buildErr } @@ -568,10 +605,9 @@ func writtenVersions(hashed []hashedVersion, file *sandboxruntimes.File) []hashe return out } +// write replaces the pod's file if its content changed. The build created +// the pod's directory when it staged the default (see stageDefault). func (s *workerSandboxSyncer) write(ctx context.Context, uid, config string, want *sandboxruntimes.File) error { - if err := os.MkdirAll(s.podDir(uid), 0o700); err != nil { - return fmt.Errorf("while creating worker directory: %w", err) - } wrote, err := sandboxruntimes.Write(s.runtimesFile(uid), want) if err != nil { return err diff --git a/cmd/atelet/worker_sandbox_versions_test.go b/cmd/atelet/worker_sandbox_versions_test.go index 99e5f35431..735d080b74 100644 --- a/cmd/atelet/worker_sandbox_versions_test.go +++ b/cmd/atelet/worker_sandbox_versions_test.go @@ -68,6 +68,26 @@ func multiVersionConfig() *atev1.SandboxConfig { } } +// gvisorConfig is a gVisor config with one version, "v1", the default, whose +// gvisor asset is at url with the given sha256. +func gvisorConfig(name, url, sha string) *atev1.SandboxConfig { + return &atev1.SandboxConfig{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: atev1.SandboxConfigSpec{ + SandboxClass: atev1.SandboxClassGvisor, + DefaultVersion: "v1", + Versions: []atev1.SandboxVersionConfig{{ + Name: "v1", + Assets: map[string]map[string]atev1.AssetFile{ + runtime.GOARCH: { + gvisorAssetName: {URL: url, SHA256: sha}, + }, + }, + }}, + }, + } +} + func TestRecordForArch(t *testing.T) { sha := fmt.Sprintf("%x", sha256.Sum256([]byte("gvisor release"))) tests := []struct { @@ -270,7 +290,7 @@ func planAndBuild(s *workerSandboxSyncer, pod *corev1.Pod) (*sandboxruntimes.Fil if err != nil { return nil, err } - return s.buildFile(context.Background(), plan, hashVersions(plan)) + return s.buildFile(context.Background(), string(pod.UID), plan, hashVersions(plan)) } func TestPlanAndBuild(t *testing.T) { @@ -472,146 +492,406 @@ func TestPlanAndBuildMicroVM(t *testing.T) { } } -// TestSyncPodMicroVMAssetCacheAndEviction runs syncPod for a microVM pool -// against the real sandboxAssetCache and runtimePrewarmer: -// - buildFile stages each version's assets into scratchDir and cleans up; -// - the prewarmer links only the default version under the worker's directory, -// so EvictUnused reclaims the unlinked restorable version; -// - once memoized, syncing a new worker pod does not re-download the evicted -// restorable version, and re-syncing while the bucket is failing keeps the -// restorable version in sandbox-runtimes.json; -// - promoting the evicted restorable version to default while the bucket is -// failing fails the sync and leaves the file and the old default's -// directory as they were. -func TestSyncPodMicroVMAssetCacheAndEviction(t *testing.T) { - ctx := context.Background() - v1Bytes, v2Bytes := []byte("kernel v1"), []byte("kernel v2") - v1SHA := fmt.Sprintf("%x", sha256.Sum256(v1Bytes)) - v2SHA := fmt.Sprintf("%x", sha256.Sum256(v2Bytes)) - - pool := resolvedPoolOf(atev1.SandboxClassMicroVM, "microvm-pool", "microvm-release") - version := func(name, sha string) atev1.SandboxVersionConfig { - return atev1.SandboxVersionConfig{ - Name: name, - Assets: map[string]map[string]atev1.AssetFile{ - runtime.GOARCH: {"kernel": {URL: "gs://assets/kernel-" + name, SHA256: sha}}, +// TestSyncPodAssetCacheAndEviction runs syncPod for microVM and gVisor pools +// against the real sandboxAssetCache, with no min age, so a directory's link +// is all that keeps an entry: +// - the build links the default under the worker's default-runtime +// directory and stages a restorable version in scratchDir, which it +// cleans up, so EvictUnused reclaims the restorable version alone; +// - once memoized, syncing a new worker pod does not re-download the +// evicted restorable version, and re-syncing while the bucket is failing +// keeps the restorable version in sandbox-runtimes.json; +// - promoting the evicted restorable version to default while the bucket +// is failing fails the sync and leaves the file and the old default's +// directory as they were; +// - once the bucket serves the version again, the promotion links it under +// the worker before the file names it, without re-running the probes, +// and removes the retired default's directory: a pass right after the +// sync keeps the new default, and takes the old one once no pod links it; +// - a default's directory emptied under the syncer, as an older atelet +// leaves it, is filled from the cache again without a download, and a new +// atelet process finds the directory filled and probes a scratch link. +func TestSyncPodAssetCacheAndEviction(t *testing.T) { + for _, tc := range []struct { + class atev1.SandboxClass + assetName string + urlSuffix string + // binary is the file under the staged asset the syncer runs, for a + // gVisor release tree; the asset itself for a single-file asset. + binary string + v1Bytes []byte + v2Bytes []byte + wantAttrs func(rec *sandboxAssetsRecord) sandboxruntimes.Attributes + }{ + { + class: atev1.SandboxClassMicroVM, + assetName: "kernel", + v1Bytes: []byte("kernel v1"), + v2Bytes: []byte("kernel v2"), + wantAttrs: func(rec *sandboxAssetsRecord) sandboxruntimes.Attributes { + return sandboxruntimes.Attributes{ + hardware.AttrArchitecture: runtime.GOARCH, + hardware.AttrCPUVendor: testCPUVendor, + hardware.AttrCPUModel: testCPUModel, + hardware.AttrSandboxBundleHash: bundleHash(rec), + } }, - } - } - cfg := &atev1.SandboxConfig{ - ObjectMeta: metav1.ObjectMeta{Name: "microvm-release"}, - Spec: atev1.SandboxConfigSpec{ - SandboxClass: atev1.SandboxClassMicroVM, - DefaultVersion: "v2", - Versions: []atev1.SandboxVersionConfig{ - version("v1", v1SHA), - version("v2", v2SHA), + }, + { + class: atev1.SandboxClassGvisor, + assetName: gvisorAssetName, + urlSuffix: ".tar", + binary: "runsc", + v1Bytes: gvisorReleaseTarballWith(t, "runsc v1"), + v2Bytes: gvisorReleaseTarballWith(t, "runsc v2"), + wantAttrs: func(rec *sandboxAssetsRecord) sandboxruntimes.Attributes { + return sandboxruntimes.Attributes{ + hardware.AttrArchitecture: runtime.GOARCH, + hardware.AttrCPUFeatures: "3", + hardware.AttrSandboxBundleHash: bundleHash(rec), + } }, }, + } { + t.Run(string(tc.class), func(t *testing.T) { + ctx := context.Background() + v1SHA := fmt.Sprintf("%x", sha256.Sum256(tc.v1Bytes)) + v2SHA := fmt.Sprintf("%x", sha256.Sum256(tc.v2Bytes)) + + poolName := string(tc.class) + "-pool" + cfgName := string(tc.class) + "-release" + pool := resolvedPoolOf(tc.class, poolName, cfgName) + objKey := func(name string) string { + return "assets/" + tc.assetName + "-" + name + tc.urlSuffix + } + version := func(name, sha string) atev1.SandboxVersionConfig { + return atev1.SandboxVersionConfig{ + Name: name, + Assets: map[string]map[string]atev1.AssetFile{ + runtime.GOARCH: {tc.assetName: {URL: "gs://" + objKey(name), SHA256: sha}}, + }, + } + } + cfg := &atev1.SandboxConfig{ + ObjectMeta: metav1.ObjectMeta{Name: cfgName}, + Spec: atev1.SandboxConfigSpec{ + SandboxClass: tc.class, + DefaultVersion: "v2", + Versions: []atev1.SandboxVersionConfig{ + version("v1", v1SHA), + version("v2", v2SHA), + }, + }, + } + wantVersion := func(sha string) sandboxruntimes.Attributes { + return tc.wantAttrs(&sandboxAssetsRecord{Assets: map[string]assetEntry{tc.assetName: {SHA256: sha}}}) + } + hashOf := func(sha string) string { return wantVersion(sha)[hardware.AttrSandboxBundleHash] } + want := classFile(tc.class, wantVersion(v2SHA), wantVersion(v1SHA)) + + root := t.TempDir() + storage := &bucketStorage{ + objects: map[string][]byte{ + objKey("v1"): tc.v1Bytes, + objKey("v2"): tc.v2Bytes, + }, + } + herder := &Atelet{ + sandboxAssetCache: newTestAssetCacheAt(t, root, filecache.WithMinAge(0)), + anonGCSClient: storage, + } + // newSyncer is a syncer as a new atelet process would start it: + // the same directories, nothing memoized. + newSyncer := func() *workerSandboxSyncer { + s := newTestSyncer(t, pool, cfg) + s.assets = herder + s.workersDir = filepath.Join(root, "workers") + s.scratchDir = filepath.Join(root, "scratch") + if err := os.MkdirAll(s.scratchDir, 0o700); err != nil { + t.Fatal(err) + } + return s + } + s := newSyncer() + // staged is the asset the build stages for the version with the + // given sha under the pod's default-runtime directory; linked is + // the binary in it, a hard link into the cache. + staged := func(uid, sha string) string { + return filepath.Join(s.defaultRuntimeDir(uid, hashOf(sha)), tc.assetName) + } + linked := func(uid, sha string) string { return filepath.Join(staged(uid, sha), tc.binary) } + defaultDirs := func(uid string) []string { + entries, err := os.ReadDir(filepath.Join(s.podDir(uid), defaultRuntimeDirsName)) + if err != nil { + t.Fatal(err) + } + names := make([]string, 0, len(entries)) + for _, e := range entries { + names = append(names, e.Name()) + } + return names + } + evict := func() filecache.EvictStats { + t.Helper() + stats, err := herder.sandboxAssetCache.EvictUnused(ctx, 1<<40, false) + if err != nil { + t.Fatalf("EvictUnused: %v", err) + } + return stats + } + readFile := func(uid string) *sandboxruntimes.File { + t.Helper() + got, err := sandboxruntimes.Read(s.runtimesFile(uid)) + if err != nil { + t.Fatalf("sandboxruntimes.Read(%s): %v", uid, err) + } + return got + } + + if _, err := s.syncPod(ctx, workerPod("pod-a", poolName)); err != nil { + t.Fatalf("syncPod(pod-a): %v", err) + } + if left, err := os.ReadDir(s.scratchDir); err != nil || len(left) != 0 { + t.Errorf("scratchDir entries after syncPod = %v, %v; want empty", left, err) + } + if got := storage.gets.Load(); got != 2 { + t.Fatalf("bucket gets after first sync = %d, want 2", got) + } + if n := cachedAssets(t, root); n != 2 { + t.Fatalf("cached assets after first sync = %d, want 2", n) + } + if !exists(linked("pod-a", v2SHA)) { + t.Fatalf("the default is not linked under pod-a's directory after its first sync") + } + if got, want := defaultDirs("pod-a"), []string{filepath.Base(s.defaultRuntimeDir("pod-a", hashOf(v2SHA)))}; !slices.Equal(got, want) { + t.Errorf("pod-a's default-runtime directories = %v, want %v", got, want) + } + + // The restorable version (v1) is unlinked, so a pass takes it and + // keeps the linked default (v2). + if stats := evict(); stats.Retired != 1 || stats.SkippedLinked != 1 || cachedAssets(t, root) != 1 { + t.Fatalf("after EvictUnused: stats=%+v, cached=%d; want 1 retired (v1) and 1 linked kept (v2)", stats, cachedAssets(t, root)) + } + + // Take the bucket offline and verify that syncing a new pod (pod-b) and + // re-syncing pod-a neither re-download v1 nor drop it from the written file. + storage.mu.Lock() + clear(storage.objects) + storage.mu.Unlock() + + for _, uid := range []string{"pod-b", "pod-a"} { + if _, err := s.syncPod(ctx, workerPod(uid, poolName)); err != nil { + t.Fatalf("syncPod(%s) after eviction with bucket offline: %v", uid, err) + } + if diff := cmp.Diff(want, readFile(uid)); diff != "" { + t.Errorf("sandbox-runtimes.json for %s mismatch (-want +got):\n%s", uid, diff) + } + } + if got := storage.gets.Load(); got != 2 { + t.Errorf("bucket gets after syncing pod-b and re-syncing pod-a = %d, want 2 (no re-downloads)", got) + } + if !exists(linked("pod-b", v2SHA)) { + t.Error("the default is not linked under pod-b's directory after its first sync") + } + + // Promoting the evicted v1 to default while the bucket is offline must fail + // the sync and keep pod-a's previous file and default-runtime link in place. + cfg.Spec.DefaultVersion = "v1" + if _, err := s.syncPod(ctx, workerPod("pod-a", poolName)); err == nil { + t.Fatal("syncPod(pod-a) after promoting evicted v1 to default with bucket offline = nil, want error") + } + if diff := cmp.Diff(want, readFile("pod-a")); diff != "" { + t.Errorf("sandbox-runtimes.json for pod-a after failed default promotion (-want +got):\n%s", diff) + } + if !exists(linked("pod-a", v2SHA)) { + t.Error("a failed sync removed pod-a's link to the previous default") + } + if n := cachedAssets(t, root); n != 1 { + t.Errorf("cached assets after failed default promotion = %d, want 1 (v2 still linked)", n) + } + if got := storage.gets.Load(); got != 3 { + t.Errorf("bucket gets after promoting evicted v1 to default = %d, want 3 (the default is checked, not memoized)", got) + } + + // Once the bucket serves v1 again, the promotion links v1 under + // pod-a before the file names it, without re-running the probes, + // and removes pod-a's v2 directory. A pass right after the sync + // keeps v1 by pod-a's link and v2 by pod-b's, until pod-b follows. + storage.mu.Lock() + storage.objects[objKey("v1")] = tc.v1Bytes + storage.mu.Unlock() + s.probeCPUIdentity = func() (string, string, error) { + return "", "", errors.New("re-probed memoized host CPU identity") + } + s.runCPUFeatures = func(context.Context, string) ([]string, error) { + return nil, errors.New("re-ran runsc cpu-features for a memoized digest") + } + if _, err := s.syncPod(ctx, workerPod("pod-a", poolName)); err != nil { + t.Fatalf("syncPod(pod-a) after bucket recovery: %v", err) + } + wantPromoted := classFile(tc.class, wantVersion(v1SHA), wantVersion(v2SHA)) + if diff := cmp.Diff(wantPromoted, readFile("pod-a")); diff != "" { + t.Errorf("sandbox-runtimes.json for pod-a after default promotion (-want +got):\n%s", diff) + } + if !exists(linked("pod-a", v1SHA)) { + t.Error("the promoted default is not linked under pod-a's directory") + } + if got, want := defaultDirs("pod-a"), []string{filepath.Base(s.defaultRuntimeDir("pod-a", hashOf(v1SHA)))}; !slices.Equal(got, want) { + t.Errorf("pod-a's default-runtime directories after promotion = %v, want %v", got, want) + } + if stats := evict(); stats.Retired != 0 || stats.SkippedLinked != 2 { + t.Errorf("EvictUnused right after the promotion: %+v; want both defaults kept by their links", stats) + } + if _, err := s.syncPod(ctx, workerPod("pod-b", poolName)); err != nil { + t.Fatalf("syncPod(pod-b) after default promotion: %v", err) + } + if stats := evict(); stats.Retired != 1 || stats.SkippedLinked != 1 || cachedAssets(t, root) != 1 { + t.Errorf("EvictUnused once pod-b followed: stats=%+v, cached=%d; want the retired default (v2) taken and v1 kept", stats, cachedAssets(t, root)) + } + if got := storage.gets.Load(); got != 4 { + t.Errorf("bucket gets after the promotion = %d, want 4 (v1 once)", got) + } + + // A directory emptied under the syncer, as an older atelet leaves + // one it created before linking into it, is filled from the + // cache again without a download. + if err := os.RemoveAll(staged("pod-a", v1SHA)); err != nil { + t.Fatal(err) + } + if _, err := s.syncPod(ctx, workerPod("pod-a", poolName)); err != nil { + t.Fatalf("syncPod(pod-a) with its default's directory emptied: %v", err) + } + if !exists(linked("pod-a", v1SHA)) { + t.Error("a re-sync did not link the default into its emptied directory") + } + if got := storage.gets.Load(); got != 4 { + t.Errorf("bucket gets after filling an emptied directory = %d, want 4 (a cache hit)", got) + } + + // A new atelet process has nothing memoized. The default's + // directory is filled, so the default is a stat per asset and, + // for gVisor, one probe of a scratch link to it; the evicted + // restorable version is downloaded again. + storage.mu.Lock() + storage.objects[objKey("v2")] = tc.v2Bytes + storage.mu.Unlock() + s = newSyncer() + var probed []string + s.probeCPUIdentity = func() (string, string, error) { + probed = append(probed, "host") + return testCPUVendor, testCPUModel, nil + } + s.runCPUFeatures = func(_ context.Context, runscPath string) ([]string, error) { + probed = append(probed, runscPath) + return testCPUFeatures(), nil + } + if _, err := s.syncPod(ctx, workerPod("pod-a", poolName)); err != nil { + t.Fatalf("syncPod(pod-a) in a new process: %v", err) + } + if got := storage.gets.Load(); got != 5 { + t.Errorf("bucket gets after a sync in a new process = %d, want 5 (the evicted v2 only)", got) + } + switch tc.class { + case atev1.SandboxClassMicroVM: + if want := []string{"host"}; !slices.Equal(probed, want) { + t.Errorf("probes in a new process = %v, want %v", probed, want) + } + case atev1.SandboxClassGvisor: + // One probe per digest, each on a runsc linked into scratch + // for it, never on the one under the worker's directory. + if len(probed) != 2 { + t.Fatalf("probes in a new process = %v, want one per version", probed) + } + for _, p := range probed { + if !strings.HasPrefix(p, s.scratchDir) || p == linked("pod-a", v1SHA) { + t.Errorf("probe ran %s, want a runsc linked into %s", p, s.scratchDir) + } + } + if left, err := os.ReadDir(s.scratchDir); err != nil || len(left) != 0 { + t.Errorf("scratchDir entries after the probes = %v, %v; want empty", left, err) + } + } + }) } - wantMicroVM := func(sha string) sandboxruntimes.Attributes { - rec := &sandboxAssetsRecord{Assets: map[string]assetEntry{"kernel": {SHA256: sha}}} - return sandboxruntimes.Attributes{ - hardware.AttrArchitecture: runtime.GOARCH, - hardware.AttrCPUVendor: testCPUVendor, - hardware.AttrCPUModel: testCPUModel, - hardware.AttrSandboxBundleHash: bundleHash(rec), - } - } - want := classFile(atev1.SandboxClassMicroVM, wantMicroVM(v2SHA), wantMicroVM(v1SHA)) +} - root := t.TempDir() - storage := &bucketStorage{ - objects: map[string][]byte{ - "assets/kernel-v1": v1Bytes, - "assets/kernel-v2": v2Bytes, - }, +// TestSyncPodPinsDefaultRuntime pins the default-runtime directory lifecycle +// around a faked fetch: once a worker's file is written, its default-runtime +// directory holds the directory the build staged the default into and +// nothing else, so a retired default's directory goes and the current one +// stays as it is. A build that fails on the default's probe writes nothing +// and leaves the previous default's directory, and the pod's removal takes +// them all. +func TestSyncPodPinsDefaultRuntime(t *testing.T) { + pod := workerPod("pod-a", "pool") + s := newTestSyncer(t, pod, resolvedPool("pool", "gvisor-release"), multiVersionConfig()) + dirs := filepath.Join(s.podDir("pod-a"), defaultRuntimeDirsName) + // Left by an earlier sync: a default the pool no longer runs, which must + // go. + stale := filepath.Join(dirs, "sha256-stale") + if err := os.MkdirAll(stale, 0o700); err != nil { + t.Fatal(err) } - herder := &Atelet{ - sandboxAssetCache: newTestAssetCacheAt(t, root, filecache.WithMinAge(0)), - anonGCSClient: storage, + if _, err := s.syncPod(context.Background(), pod); err != nil { + t.Fatalf("syncPod: %v", err) } - s := newTestSyncer(t, pool, cfg) - s.assets = herder - s.workersDir = filepath.Join(root, "workers") - s.scratchDir = filepath.Join(root, "scratch") - if err := os.MkdirAll(s.scratchDir, 0o700); err != nil { - t.Fatal(err) + wr, ok := s.index.worker("pod-a") + if !ok { + t.Fatal("pod-a not indexed") } - recPrewarm := &recordingPrewarm{} - s.prewarm = recPrewarm - - if _, err := s.syncPod(ctx, workerPod("pod-a", "microvm-pool")); err != nil { - t.Fatalf("syncPod(pod-a): %v", err) + cr, _ := wr.class(atev1.SandboxClassGvisor) + def := s.defaultRuntimeDir("pod-a", cr.defaultHash) + if !exists(def) { + t.Error("the default's directory was not created") } - if left, err := os.ReadDir(s.scratchDir); err != nil || len(left) != 0 { - t.Errorf("scratchDir entries after syncPod = %v, %v; want empty", left, err) + if exists(stale) { + t.Error("a retired default's directory survived the sync") } - if got := storage.gets.Load(); got != 2 { - t.Fatalf("bucket gets after first sync = %d, want 2", got) + if len(cr.hashes) < 2 { + t.Fatalf("config advertises %d runtimes, want several so the test proves only the default gets a directory", len(cr.hashes)) } - if n := cachedAssets(t, root); n != 2 { - t.Fatalf("cached assets after first sync = %d, want 2", n) + if entries, err := os.ReadDir(dirs); err != nil || len(entries) != 1 { + t.Errorf("default-runtime directories = %v, %v; want the default's alone", entries, err) } - // Link the default version (v2) into pod-a's default-runtime directory via - // the prewarmer, leaving the restorable version (v1) unlinked. - p := newRuntimePrewarmer(s.index, herder) - for _, item := range recPrewarm.items() { - p.process(ctx, item) + // A re-sync with the same default: the directory, and what is in it, + // stays. + marker := filepath.Join(def, "staged") + if err := os.WriteFile(marker, nil, 0o600); err != nil { + t.Fatal(err) } - stats, err := herder.sandboxAssetCache.EvictUnused(ctx, 1<<40, false) - if err != nil { - t.Fatalf("EvictUnused: %v", err) + if _, err := s.syncPod(context.Background(), pod); err != nil { + t.Fatalf("syncPod again: %v", err) } - if stats.Retired != 1 || stats.SkippedLinked != 1 || cachedAssets(t, root) != 1 { - t.Fatalf("after EvictUnused: stats=%+v, cached=%d; want 1 retired (v1) and 1 linked kept (v2)", stats, cachedAssets(t, root)) + if !exists(marker) { + t.Error("a re-sync with the same default emptied its directory") } - - // Take the bucket offline and verify that syncing a new pod (pod-b) and - // re-syncing pod-a neither re-download v1 nor drop it from the written file. - storage.mu.Lock() - clear(storage.objects) - storage.mu.Unlock() - - for _, uid := range []string{"pod-b", "pod-a"} { - if _, err := s.syncPod(ctx, workerPod(uid, "microvm-pool")); err != nil { - t.Fatalf("syncPod(%s) after eviction with bucket offline: %v", uid, err) - } - got, err := sandboxruntimes.Read(s.runtimesFile(uid)) - if err != nil { - t.Fatalf("sandboxruntimes.Read(%s): %v", uid, err) - } - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("sandbox-runtimes.json for %s mismatch (-want +got):\n%s", uid, diff) - } + if err := s.removeDir(context.Background(), "pod-a"); err != nil { + t.Fatal(err) } - if got := storage.gets.Load(); got != 2 { - t.Errorf("bucket gets after syncing pod-b and re-syncing pod-a = %d, want 2 (no re-downloads)", got) + if exists(dirs) { + t.Error("the default runtime directories survived the pod's removal") } - // Promoting the evicted v1 to default while the bucket is offline must fail - // the sync and keep pod-a's previous file and default-runtime pin in place. - cfg.Spec.DefaultVersion = "v1" - if _, err := s.syncPod(ctx, workerPod("pod-a", "microvm-pool")); err == nil { - t.Fatal("syncPod(pod-a) after promoting evicted v1 to default with bucket offline = nil, want error") - } - got, err := sandboxruntimes.Read(s.runtimesFile("pod-a")) - if err != nil { - t.Fatalf("sandboxruntimes.Read(pod-a): %v", err) + // A build that fails on the default's probe writes nothing and leaves + // the previous default's directory as it was. + s = newTestSyncer(t, pod, resolvedPool("pool", "gvisor-release"), multiVersionConfig()) + s.runCPUFeatures = func(context.Context, string) ([]string, error) { return nil, errors.New("runsc failed") } + previous := s.defaultRuntimeDir("pod-a", "sha256:previous") + if err := os.MkdirAll(previous, 0o700); err != nil { + t.Fatal(err) } - if diff := cmp.Diff(want, got); diff != "" { - t.Errorf("sandbox-runtimes.json for pod-a after failed default promotion (-want +got):\n%s", diff) + if _, err := s.syncPod(context.Background(), pod); err == nil { + t.Fatal("syncPod with the default's probe failing = nil, want an error") } - v2Hash := want.SandboxClasses[0].DefaultRuntime.Version[hardware.AttrSandboxBundleHash] - if !exists(s.defaultRuntimeDir("pod-a", v2Hash)) { - t.Error("a failed sync removed pod-a's default-runtime directory for v2") + if !exists(previous) { + t.Error("a failed build removed the previous default's directory") } - if n := cachedAssets(t, root); n != 1 { - t.Errorf("cached assets after failed default promotion = %d, want 1 (v2 still linked)", n) + if exists(s.runtimesFile("pod-a")) { + t.Error("a failed build wrote the worker's file") } - if got := storage.gets.Load(); got != 3 { - t.Errorf("bucket gets after promoting evicted v1 to default = %d, want 3 (the default is checked, not memoized)", got) + if _, ok := s.index.worker("pod-a"); ok { + t.Error("a failed build registered the worker") } } @@ -645,7 +925,7 @@ func TestGVisorCPUFeaturesMemoizationAndErrors(t *testing.T) { } }) - t.Run("memoizes runsc cpu-features by asset digest across versions and syncs", func(t *testing.T) { + t.Run("memoizes runsc cpu-features by asset digest and verification by bundle", func(t *testing.T) { cfg := multiVersionConfig() // Add a third version "v3" that shares v1's gvisor asset digest ("sha-v1") // but has one more asset, so it has a distinct bundle hash while it @@ -654,10 +934,14 @@ func TestGVisorCPUFeaturesMemoizationAndErrors(t *testing.T) { v3.Name = "v3" v3.Assets[runtime.GOARCH]["extra"] = atev1.AssetFile{URL: "gs://bucket/extra", SHA256: "sha-extra"} cfg.Spec.Versions = append(cfg.Spec.Versions, v3) + v3Rec := &sandboxAssetsRecord{Assets: map[string]assetEntry{gvisorAssetName: {SHA256: "sha-v1"}, "extra": {SHA256: "sha-extra"}}} + hashOf := func(name string) string { return wantRuntime(name)[hardware.AttrSandboxBundleHash] } s := newTestSyncer(t, resolvedPool("pool", "gvisor-release"), cfg) + var staged []string s.assets = &fakeAssetFetcher{ fn: func(_ context.Context, rec *sandboxAssetsRecord) (map[string]string, error) { + staged = append(staged, bundleHash(rec)) return map[string]string{gvisorAssetName: "/cache/" + rec.Assets[gvisorAssetName].SHA256 + "/runsc"}, nil }, } @@ -674,7 +958,6 @@ func TestGVisorCPUFeaturesMemoizationAndErrors(t *testing.T) { if err != nil { t.Fatalf("first planAndBuild() error = %v", err) } - v3Rec := &sandboxAssetsRecord{Assets: map[string]assetEntry{gvisorAssetName: {SHA256: "sha-v1"}, "extra": {SHA256: "sha-extra"}}} want := gvisorFile( wantRuntimeWithFeatures("v2", "3"), wantRuntimeWithFeatures("v1", "1"), @@ -687,16 +970,23 @@ func TestGVisorCPUFeaturesMemoizationAndErrors(t *testing.T) { if diff := cmp.Diff(want, got); diff != "" { t.Errorf("planAndBuild() mismatch (-want +got):\n%s", diff) } - - // Syncing again must answer from the memo alone: no fetch, no runsc. - s.assets = &fakeAssetFetcher{ - fn: func(context.Context, *sandboxAssetsRecord) (map[string]string, error) { - return nil, errors.New("fetched a runsc whose cpu_features are memoized") - }, + // The default is staged into the pod's directory and then into + // scratch for its probe; each restorable bundle once, v3 for the + // asset it adds beside a runsc already probed for v1. + if diff := cmp.Diff([]string{hashOf("v2"), hashOf("v2"), hashOf("v1"), bundleHash(v3Rec)}, staged); diff != "" { + t.Errorf("bundles staged by the first build (-want +got):\n%s", diff) } + + // Syncing another pod stages the default again, into that pod's + // directory, and answers the restorable versions from the memo + // alone: no fetch, no runsc. + staged = nil if _, err := planAndBuild(s, workerPod("pod-b", "pool")); err != nil { t.Fatalf("second planAndBuild() error = %v", err) } + if diff := cmp.Diff([]string{hashOf("v2")}, staged); diff != "" { + t.Errorf("bundles staged by the second build (-want +got):\n%s", diff) + } wantCalls := map[string]int{ "/cache/sha-v2/runsc": 1, "/cache/sha-v1/runsc": 1, diff --git a/cmd/atelet/workerdialer_test.go b/cmd/atelet/workerdialer_test.go index 087ab7e98b..c4636232c6 100644 --- a/cmd/atelet/workerdialer_test.go +++ b/cmd/atelet/workerdialer_test.go @@ -16,8 +16,10 @@ package main import ( "context" + "sync" "testing" + "google.golang.org/grpc" "google.golang.org/grpc/connectivity" ) @@ -61,3 +63,34 @@ func TestWorkerDialerReusesCachedConn(t *testing.T) { t.Errorf("cached conn is shut down; want it live") } } + +// TestWorkerDialerConcurrentDialsShareConn pins that concurrent first dials +// for a pod share one conn. Without that, each caller creates its own, and +// the cache's Add replaces all but the last without closing them. +func TestWorkerDialerConcurrentDialsShareConn(t *testing.T) { + d := newWorkerDialer(1) + + var mu sync.Mutex + conns := map[*grpc.ClientConn]bool{} + start := make(chan struct{}) + var wg sync.WaitGroup + for range 64 { + wg.Go(func() { + <-start + c, err := d.DialWorkerPod(context.Background(), "pod-a") + if err != nil { + t.Errorf("DialWorkerPod(pod-a) error = %v", err) + return + } + mu.Lock() + conns[c] = true + mu.Unlock() + }) + } + close(start) + wg.Wait() + + if len(conns) != 1 { + t.Errorf("distinct conns from concurrent dials = %d, want 1", len(conns)) + } +} diff --git a/cmd/atelet/workersupport.go b/cmd/atelet/workersupport.go index 68851c028d..9408965f5d 100644 --- a/cmd/atelet/workersupport.go +++ b/cmd/atelet/workersupport.go @@ -363,8 +363,9 @@ func (s *workerSupportServer) ReportActorCrashed(ctx context.Context, req *atele Atespace: req.GetActorAtespace(), Name: req.GetActorName(), }, - ActorUid: req.GetActorUid(), - Message: req.GetMessage(), + ActorUid: req.GetActorUid(), + Message: req.GetMessage(), + ActivationUid: req.GetActivationUid(), }); err != nil { return nil, err } diff --git a/cmd/atelet/workersupport_test.go b/cmd/atelet/workersupport_test.go index 1ec7324779..350c12e8c1 100644 --- a/cmd/atelet/workersupport_test.go +++ b/cmd/atelet/workersupport_test.go @@ -659,14 +659,16 @@ func TestReportActorCrashedNamesTheCallingWorker(t *testing.T) { ActorName: "actor-1", ActorUid: "01234567-89ab-cdef-0123-456789abcdef", Message: "cloud-hypervisor exited", + ActivationUid: "bbde9529-e971-4147-8b2a-49e0aa4d55b0", }); err != nil { t.Fatalf("ReportActorCrashed() failed: %v", err) } want := []*ateapi.ReportActorCrashedRequest{{ - Worker: &ateapi.ObjectRef{Name: "pod-a"}, - Actor: &ateapi.ObjectRef{Atespace: "team-a", Name: "actor-1"}, - ActorUid: "01234567-89ab-cdef-0123-456789abcdef", - Message: "cloud-hypervisor exited", + Worker: &ateapi.ObjectRef{Name: "pod-a"}, + Actor: &ateapi.ObjectRef{Atespace: "team-a", Name: "actor-1"}, + ActorUid: "01234567-89ab-cdef-0123-456789abcdef", + Message: "cloud-hypervisor exited", + ActivationUid: "bbde9529-e971-4147-8b2a-49e0aa4d55b0", }} if diff := cmp.Diff(want, workers.gotCrashed, protocmp.Transform()); diff != "" { t.Errorf("forwarded request mismatch (-want +got):\n%s", diff) diff --git a/cmd/atenet/internal/root.go b/cmd/atenet/internal/root.go index 02d54a9af5..f4951d9c1c 100644 --- a/cmd/atenet/internal/root.go +++ b/cmd/atenet/internal/root.go @@ -25,7 +25,10 @@ import ( "go.ate.dev/substrate/internal/version" ) -var previewFlags []string +var ( + previewFlags []string + previewGates *preview.Gates +) var rootCmd = &cobra.Command{ Use: "atenet", @@ -33,9 +36,11 @@ var rootCmd = &cobra.Command{ Long: `atenet is a combined daemon for all networking functionality.`, Version: version.String(), PersistentPreRunE: func(cmd *cobra.Command, args []string) error { - if err := preview.Init(previewFlags...); err != nil { + gates, err := preview.New(previewFlags...) + if err != nil { return fmt.Errorf("invalid --preview: %w", err) } + previewGates = gates return nil }, } @@ -49,6 +54,6 @@ func Execute() { func init() { rootCmd.PersistentFlags().StringSliceVar(&previewFlags, "preview", nil, "Preview gates to enable.") - rootCmd.AddCommand(router.NewRouterCmd()) + rootCmd.AddCommand(router.NewRouterCmd(func() *preview.Gates { return previewGates })) rootCmd.AddCommand(sdsmint.NewSdsmintCmd()) } diff --git a/cmd/atenet/internal/router/README.md b/cmd/atenet/internal/router/README.md index 3150638ef0..281c03d42b 100644 --- a/cmd/atenet/internal/router/README.md +++ b/cmd/atenet/internal/router/README.md @@ -105,7 +105,7 @@ rule, `egress_passthrough` under a `tls_passthrough` rule, and `denied`, which matches no chain and closes the connection, when neither covers the SNI. The passthrough chain resolves the SNI and relays the bytes to it on the dialed port; the address the actor dialed plays no part (see -`docs/guides/network-egress.md`). +`docs/guides/egress-traffic.md`). Identity on the request legs is `dev.ate.actor.identity`, the actor's SPIFFE ID that the outer chain set from the verified peer certificate and shares with @@ -119,7 +119,9 @@ tunnel can write any of this; a callout without an identity is refused. Policies are read through a per-actor cache (`--egress-policy-cache-ttl`, 10s by default; 0 disables it). The TTL is exactly how stale a decision can be: a create, update or delete is visible to new requests within one TTL, and a -deleted policy becomes a deny. Every policy denial answers a fixed +deleted policy becomes a deny. Entries are keyed by atespace and actor name, +so an actor recreated under the same name is decided with its predecessor's +policy until the entry expires. Every policy denial answers a fixed `egress denied` body; the reason is in the sidecar's log. Credential injection (`replace_headers`) runs on both request legs: a header @@ -202,6 +204,22 @@ ingress dataplane, `atenet-egress` the egress gateway. `--atenet-dataplane` selects the dataplane for both Deployments. Each gateway has its own static configuration because ingress and egress scale independently. +## Kernel socket buffers + +A client that reads slowly makes the bytes Envoy relays to it wait in the +kernel's socket queues. That memory is charged to the Envoy container but +missing from Envoy's statistics. The router sets `TCP_NOTSENT_LOWAT` to +16 KiB on the Envoy ingress router's TCP sockets, through the xDS +configuration: the ones its TLS listeners accept from clients and the ones it +dials to atunnel. A slow reader then backs data up behind Envoy's buffer +limits instead of in the kernel. + +The option is set on the listening socket, and the connections it accepts +inherit it. Internal listeners and clusters have no kernel sockets and get +none. The router doesn't set `SO_SNDBUF` or `SO_RCVBUF`: a fixed buffer size +turns off the kernel's autotuning and caps a connection at about the buffer +size per round trip. + ## Ingress client authentication and authorization The Envoy ingress router serves only TLS listeners, and every client must diff --git a/cmd/atenet/internal/router/cmd.go b/cmd/atenet/internal/router/cmd.go index ac169ecc55..d39a1b7d93 100644 --- a/cmd/atenet/internal/router/cmd.go +++ b/cmd/atenet/internal/router/cmd.go @@ -25,15 +25,22 @@ import ( "go.ate.dev/substrate/cmd/atenet/internal/router/egress" "go.ate.dev/substrate/cmd/atenet/internal/router/ingress" "go.ate.dev/substrate/internal/installdefaults" + "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/internal/serverboot/pprofserver" ) -func NewRouterCmd() *cobra.Command { +// NewRouterCmd returns the router command. gates returns the root command's +// preview gates, initialized before RunE runs. +func NewRouterCmd(gates func() *preview.Gates) *cobra.Command { var cfg routerConfig cmd := &cobra.Command{ Use: "router", Short: "Router components including the Envoy xDS server and the ext_proc gateway processing server", RunE: func(cmd *cobra.Command, args []string) error { + if gates != nil { + cfg.Gates = gates() + } srv, err := NewRouterServer(cfg) if err != nil { return fmt.Errorf("failed to create router server: %w", err) @@ -55,6 +62,7 @@ func bindRouterFlags(fs *pflag.FlagSet, cfg *routerConfig) { fs.StringVar(&cfg.MetricsAddr, "metrics-listen-addr", ":9090", "Address and port the prometheus metrics server should listen on.") fs.StringVar(&cfg.HealthAddr, "health-listen-addr", ":9091", "Address and port the /readyz and /healthz probe server should listen on.") + cfg.Pprof = pprofserver.RegisterFlags(fs) fs.StringVar(&cfg.AtenetRouter, "atenet-dataplane", string(atenetRouterEnvoy), "Atenet ingress and egress dataplane: envoy or agentgateway") fs.StringVar(&cfg.Namespace, "namespace", "default", "Target operations namespace") fs.StringVar(&cfg.RouterServiceName, "router-service-name", installdefaults.RouterServiceName, "Service name of this atenet-router in the operations namespace. Override when the deployment renames the Service.") @@ -80,6 +88,9 @@ func bindRouterFlags(fs *pflag.FlagSet, cfg *routerConfig) { fs.StringVar(&cfg.ActorIdentityCAFile, "actor-identity-ca-file", "", "PEM trust bundle for the actor-identity CA, used to verify the actor client certificates presented on egress CONNECTs. Required by the egress gateway's ext_proc sidecar; empty (the default) leaves egress authentication unconfigured and every egress CONNECT is denied.") + fs.DurationVar(&cfg.IngressCache.TTL, "ingress-cache-ttl", DefaultIngressCacheTTL, "How long the ingress cache routes an actor to its cached worker before resolving it through ext_proc again, in whole seconds. Only applies with the IngressCache preview gate") + // Each Envoy worker thread has its own cache, so this bounds each one. + fs.IntVar(&cfg.IngressCache.MaxCachedActors, "ingress-cache-max-cached-actors", DefaultIngressCacheMaxCachedActors, "Most actors the ingress cache holds per Envoy worker thread. When full, it drops expired entries before caching another actor, and doesn't cache it if none had expired. Only applies with the IngressCache preview gate") fs.DurationVar(&cfg.EgressPolicyCacheTTL, "egress-policy-cache-ttl", egress.DefaultPolicyCacheTTL, "How long the egress gateway keeps acting on an actor's EgressPolicy before fetching it from ateapi again, which bounds the lag between a policy change and its effect on new requests. 0 disables the cache (concurrent callouts for one actor still share a fetch)") // Egress credential injection (MITM leg). Only the egress gateway sets these, @@ -92,6 +103,7 @@ func bindRouterFlags(fs *pflag.FlagSet, cfg *routerConfig) { fs.StringVar(&cfg.CredentialProvider.ClientCert, "credential-provider-client-cert", "", "Credential bundle presented to the credential provider as the client certificate; required unless --credential-provider-insecure is set") fs.StringArrayVar(&cfg.CredentialProvider.ServerNames, "credential-provider-server-name", nil, "SAN/SNI expected on a credential provider's serving certificate. Repeat once per --credential-provider-address, in the same order, or omit") fs.BoolVar(&cfg.CredentialProvider.Insecure, "credential-provider-insecure", false, "Dial the credential provider WITHOUT TLS. Development only: secrets cross the network in the clear. Without this, a missing --credential-provider-ca-file or --credential-provider-client-cert fails startup instead of silently downgrading") + fs.StringVar(&cfg.TokenExchangeCAFile, "token-exchange-ca-file", "", "PEM certificates the egress gateway trusts for token exchange endpoints, in addition to the system roots. A missing file or one with no certificates fails startup") // Envoy learns the collector over xDS rather than from its own environment, // so the router has to carry the address for it. Defaulting to @@ -101,7 +113,7 @@ func bindRouterFlags(fs *pflag.FlagSet, cfg *routerConfig) { fs.StringVar(&cfg.Auth.AteapiCAFile, "ateapi-ca-file", "", "PEM file with CAs trusted to verify the ateapi server cert. Required.") fs.StringVar(&cfg.Auth.AteapiClientCertPath, "ateapi-client-cert", "", "Credential bundle presented as the client certificate when dialing ateapi. Required.") fs.StringVar(&cfg.Auth.AteapiServerName, "ateapi-server-name", "", "SNI / hostname expected on the ateapi server cert. Optional.") - fs.DurationVar(&cfg.RouteTimeout, "route-timeout", defaultRouteTimeout, "Envoy's end-to-end timeout on the workload route, bounding one request from the ingress listener to the actor's response. The default is generous because an agent relaying a model completion holds the request open for the whole generation; lower it to cap how long one turn may hold a request. This does not cover the resume that may precede the request; see --parked-request-budget. Shutdown is sized separately and does not follow this flag; to let long turns survive a drain, raise --drain-timeout and terminationGracePeriodSeconds too") + fs.DurationVar(&cfg.RouteTimeout, "route-timeout", defaultRouteTimeout, "Envoy's ingress timeout for the complete actor's response. The default is generous because an agent relaying a model completion holds the request open for the whole generation; lower it if actors responses expected to be quick. This does not cover the resume that may precede the request; see --parked-request-budget. Shutdown is sized separately and does not follow this flag; to let long turns survive a drain, raise --drain-timeout and terminationGracePeriodSeconds too") fs.DurationVar(&cfg.ParkedRequest.Budget, "parked-request-budget", ingress.DefaultParkedRequestBudget, "Maximum time a resume flight keeps a request parked (held and retried) waiting for its actor to become routable; concurrent requests for the same actor share one flight and its budget") fs.IntVar(&cfg.ParkedRequest.Max, "parked-request-max", ingress.DefaultParkedRequestMax, "Maximum number of requests that may be parked simultaneously; excess requests are shed with 503. 0 disables parking (requests fail fast on worker-pool saturation)") fs.DurationVar(&cfg.ParkedRequest.RetryInterval, "parked-request-retry-interval", ingress.DefaultParkedRequestRetryInterval, "Delay before a parked request's first resume retry") diff --git a/cmd/atenet/internal/router/config.go b/cmd/atenet/internal/router/config.go index 73a32b8dfb..8fcf3c5839 100644 --- a/cmd/atenet/internal/router/config.go +++ b/cmd/atenet/internal/router/config.go @@ -22,6 +22,8 @@ import ( "github.com/spiffe/go-spiffe/v2/spiffeid" "go.ate.dev/substrate/cmd/atenet/internal/router/ingress" + "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/internal/serverboot/pprofserver" ) type atenetRouter string @@ -179,15 +181,26 @@ type routerConfig struct { // the cache. EgressPolicyCacheTTL time.Duration + // Gates are the router's preview gates. + Gates *preview.Gates + + // IngressCache configures the ingress-cache filter. It only applies with + // the IngressCache preview gate. + IngressCache IngressCacheConfig + // CredentialProvider configures egress credential injection on the MITM leg. // Only the egress gateway sets it, and only when injection is enabled: a // CredentialProvider with no Addresses leaves the injector disabled, so a // request that needs an injection is denied. See egress.Handler. CredentialProvider credentialProviderConfig + // TokenExchangeCAFile holds PEM certificates the egress gateway trusts for + // token exchange endpoints, in addition to the system roots. + TokenExchangeCAFile string LogLevel string MetricsAddr string HealthAddr string + Pprof *pprofserver.Config // OtlpCollectorAddress is the OTLP gRPC collector that Envoy reports // tracing spans to, as host:port or an http:// URL. It defaults to // OTEL_EXPORTER_OTLP_ENDPOINT — Envoy gets its whole configuration over @@ -307,6 +320,9 @@ func (c routerConfig) validate() error { if err := c.CredentialProvider.validate(); err != nil { return err } + if err := c.Pprof.Validate(); err != nil { + return err + } if c.ExtProcMaxRequests < 0 { return fmt.Errorf("--extproc-max-requests must not be negative, got %d (0 derives it from --parked-request-max)", c.ExtProcMaxRequests) diff --git a/cmd/atenet/internal/router/config_test.go b/cmd/atenet/internal/router/config_test.go index 80e3737a14..7436a3caac 100644 --- a/cmd/atenet/internal/router/config_test.go +++ b/cmd/atenet/internal/router/config_test.go @@ -22,6 +22,8 @@ import ( "github.com/spf13/pflag" "go.ate.dev/substrate/cmd/atenet/internal/router/ingress" + "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/internal/serverboot/pprofserver" ) func TestRouterConfigValidate(t *testing.T) { @@ -47,6 +49,11 @@ func TestRouterConfigValidate(t *testing.T) { cfg: routerConfig{Mode: ModeIngress, AtenetRouter: "blah"}, wantErr: "--atenet-dataplane must be", }, + { + name: "negative pprof mutex fraction rejected", + cfg: routerConfig{Mode: ModeIngress, Pprof: &pprofserver.Config{MutexFraction: -1}}, + wantErr: "--pprof-mutex-fraction (ATE_PPROF_MUTEX_FRACTION) must not be negative", + }, { name: "credential providers paired by position are valid", cfg: routerConfig{Mode: ModeEgress, CredentialProvider: credentialProviderConfig{ @@ -414,7 +421,7 @@ func routerManifestFlags(t *testing.T) *pflag.FlagSet { if c.Name != "atenet-router" { continue } - cmd := NewRouterCmd() + cmd := NewRouterCmd(nil) if len(c.Args) == 0 || c.Args[0] != cmd.Name() { t.Fatalf("the atenet-router container's args are %v; they should invoke the %q subcommand", c.Args, cmd.Name()) } @@ -528,3 +535,30 @@ func TestSetOtlpCollectorClearsPreviousCollector(t *testing.T) { t.Errorf("buildTracing() = %v, want nil after a rejected address", tr) } } + +func TestNewRouterServer_RequiresGates(t *testing.T) { + t.Run("NewRouterServer", func(t *testing.T) { + _, err := NewRouterServer(routerConfig{Mode: ModeEgress}) + if err == nil || !strings.Contains(err.Error(), "Gates") { + t.Fatalf("NewRouterServer() error = %v, want error naming Gates", err) + } + }) + for _, tc := range []struct { + name string + gates func() *preview.Gates + }{ + {name: "nil getter"}, + {name: "getter returns nil", gates: func() *preview.Gates { return nil }}, + } { + t.Run("NewRouterCmd/"+tc.name, func(t *testing.T) { + cmd := NewRouterCmd(tc.gates) + cmd.SilenceUsage = true + cmd.SilenceErrors = true + cmd.SetArgs([]string{"--mode=egress"}) + err := cmd.Execute() + if err == nil || !strings.Contains(err.Error(), "Gates") { + t.Fatalf("Execute() error = %v, want error naming Gates", err) + } + }) + } +} diff --git a/cmd/atenet/internal/router/dataplane.go b/cmd/atenet/internal/router/dataplane.go index 1fa0594419..4989558548 100644 --- a/cmd/atenet/internal/router/dataplane.go +++ b/cmd/atenet/internal/router/dataplane.go @@ -20,12 +20,12 @@ import ( "log/slog" "net" "strconv" - "time" "golang.org/x/sync/errgroup" "go.ate.dev/substrate/cmd/atenet/internal/router/ingress" "go.ate.dev/substrate/internal/credbundle" + "go.ate.dev/substrate/internal/preview" ) type dataplaneHealthCheck struct { @@ -33,9 +33,12 @@ type dataplaneHealthCheck struct { expectedBody string } -// Both dataplanes resolve the worker address from ext_proc's dynamic -// metadata (see ingress.OriginalDstMetadataKey). Actor identity is carried in -// explicit headers, so ingress.New needs no per-dataplane routing mode. +// ingress.New's Go ext_proc handler resolves the worker address and writes +// it to ext_proc's dynamic metadata (see ingress.OriginalDstMetadataKey). +// Only the Envoy dataplane calls it; agentgateway resolves the worker +// address itself, in-process, via its own substrateIngress policy. Actor +// identity is carried in explicit headers either way, so ingress.New needs +// no per-dataplane routing mode. func (r atenetRouter) healthCheck() dataplaneHealthCheck { switch r { @@ -98,7 +101,7 @@ func (s *RouterServer) newEnvoyXdsServer(ctx context.Context, parkCfg ingress.Pa if parkCfg.Enabled() { // Envoy must keep a parked request open at least as long as the router // will hold it; add a margin so the router surfaces its own 503 first. - xdsSrv.SetExtProcMessageTimeout(parkCfg.Budget + 5*time.Second) + xdsSrv.SetExtProcMessageTimeout(parkCfg.Budget + ingress.ExtProcTimeoutMargin) } xdsSrv.SetTlsConfig(s.cfg.HttpsPort, s.cfg.EnvoyCertPath) @@ -118,6 +121,16 @@ func (s *RouterServer) newEnvoyXdsServer(ctx context.Context, parkCfg ingress.Pa } xdsSrv.SetUpstreamTls(s.cfg.UpstreamCredentialBundlePath, s.cfg.UpstreamTrustBundlePath) xdsSrv.SetUpstreamConnect(s.cfg.UpstreamConnect) + ingressCache := s.cfg.Gates.IsEnabled(preview.GateIngressCache) + if ingressCache { + if err := s.cfg.IngressCache.validate(); err != nil { + return nil, err + } + } + xdsSrv.SetIngressCache(ingressCache, s.cfg.IngressCache) + slog.InfoContext(ctx, "Ingress cache", slog.Bool("enabled", ingressCache), + slog.Duration("ttl", s.cfg.IngressCache.TTL), + slog.Int("max_cached_actors", s.cfg.IngressCache.MaxCachedActors)) // The snapshot is a pure function of the configuration applied above, so it // is built exactly once; an Envoy that connects later is served from the diff --git a/cmd/atenet/internal/router/egress/credentials.go b/cmd/atenet/internal/router/egress/credentials.go index c52a696600..156048726b 100644 --- a/cmd/atenet/internal/router/egress/credentials.go +++ b/cmd/atenet/internal/router/egress/credentials.go @@ -104,16 +104,28 @@ func (h *Handler) applyEffects(ctx context.Context, ref resources.ActorRef, dest var secret []byte var err error - if src := inj.GetActorJwt(); src != nil { - secret, err = h.actorJWT(ctx, ref, dest, src) + switch { + case inj.GetActorJwt() != nil: + secret, err = h.actorJWT(ctx, ref, dest, inj.GetActorJwt()) if err != nil { return nil, fmt.Errorf("minting an actor JWT for header %s: %w", inj.GetHeader(), err) } - } else { + case inj.GetTokenExchange() != nil: + slog.ErrorContext(ctx, "egress denied: token exchange is not supported by this gateway", + slog.Any("actor", ref), slog.String("host", dest.Hostname), slog.String("header", inj.GetHeader())) + return nil, extproc.NewReqError(envoy_type.StatusCode_InternalServerError, deniedBody) + case inj.GetCredentialUri() != "": secret, err = h.providerCredential(ctx, ref, dest, inj.GetCredentialUri()) if err != nil { return nil, fmt.Errorf("fetching credential %s for header %s: %w", inj.GetCredentialUri(), inj.GetHeader(), err) } + default: + // A source this gateway doesn't know, such as one added to the + // API after it was built. Never fall through to the provider with + // an empty URI. + slog.ErrorContext(ctx, "egress denied: policy names no supported credential source", + slog.Any("actor", ref), slog.String("host", dest.Hostname), slog.String("header", inj.GetHeader())) + return nil, extproc.NewReqError(envoy_type.StatusCode_InternalServerError, deniedBody) } // Overwrite any header the actor set itself, so a client cannot pre-seed a diff --git a/cmd/atenet/internal/router/egress/credentials_test.go b/cmd/atenet/internal/router/egress/credentials_test.go index fabe82c203..634dea6502 100644 --- a/cmd/atenet/internal/router/egress/credentials_test.go +++ b/cmd/atenet/internal/router/egress/credentials_test.go @@ -76,19 +76,26 @@ func withAuthorization(md *extproc.RequestMetadata) *extproc.RequestMetadata { // and overwrite the header the request carries. func TestInjectionOnRequestLegs(t *testing.T) { for _, tc := range []struct { - name string - leg string - policy *ateapi.EgressPolicy + name string + leg string + policy *ateapi.EgressPolicy + websocket bool }{ {name: "https", leg: extproc.EgressTLSMITMFilterChainName, policy: credentialInjectionPolicySample("api.example.com")}, {name: "http", leg: extproc.EgressCleartextFilterChainName, policy: cleartextInjectionPolicy("api.example.com")}, + {name: "wss handshake", leg: extproc.EgressTLSMITMFilterChainName, policy: credentialInjectionPolicySample("api.example.com"), websocket: true}, + {name: "ws handshake", leg: extproc.EgressCleartextFilterChainName, policy: cleartextInjectionPolicy("api.example.com"), websocket: true}, } { t.Run(tc.name, func(t *testing.T) { provider := &fakeProvider{resp: bearerTokenResponse("s3cr3t\n")} h := injectionHandlerFor(tc.policy, provider, injectionProviderName) - res, err := h.HandleRequestHeaders(context.Background(), - withAuthorization(innerMetadata(tc.leg, "GET", "api.example.com", nil))) + md := withAuthorization(innerMetadata(tc.leg, "GET", "api.example.com", nil)) + if tc.websocket { + md.Headers["connection"] = "Upgrade" + md.Headers["upgrade"] = "websocket" + } + res, err := h.HandleRequestHeaders(context.Background(), md) if err != nil { t.Fatalf("HandleRequestHeaders: %v", err) } @@ -463,3 +470,45 @@ func TestActorJWTInjectionDenials(t *testing.T) { }) } } + +// A token exchange entry denies even with a provider configured, so its empty +// credential_uri is never fetched. +func TestTokenExchangeInjectionDenied(t *testing.T) { + for _, leg := range requestLegs { + t.Run(leg, func(t *testing.T) { + provider := &fakeProvider{resp: bearerTokenResponse("s3cr3t")} + h := injectionHandlerFor(replaceHeadersPolicy(leg, &ateapi.CredentialHeader{ + Header: "authorization", + Prefix: "Bearer ", + TokenExchange: &ateapi.TokenExchangeSource{ + TokenUrl: "https://sts.example.com/token", + SubjectActorJwt: &ateapi.ActorJwtSource{Audiences: []string{"https://sts.example.com"}, ExpirationSeconds: 900}, + Audiences: []string{"https://api.example.com"}, + }, + }), provider, "") + _, err := h.HandleRequestHeaders(context.Background(), + withAuthorization(innerMetadata(leg, "GET", "api.example.com", nil))) + wantStatus(t, err, envoy_type.StatusCode_InternalServerError) + if provider.got != nil { + t.Errorf("provider was asked for %v, want no fetch", provider.got) + } + }) + } +} + +// An entry with no source this gateway knows denies instead of asking the +// provider for an empty credential_uri. +func TestInjectionWithoutSourceDenied(t *testing.T) { + for _, leg := range requestLegs { + t.Run(leg, func(t *testing.T) { + provider := &fakeProvider{resp: bearerTokenResponse("s3cr3t")} + h := injectionHandlerFor(replaceHeadersPolicy(leg, &ateapi.CredentialHeader{Header: "authorization"}), provider, "") + _, err := h.HandleRequestHeaders(context.Background(), + withAuthorization(innerMetadata(leg, "GET", "api.example.com", nil))) + wantStatus(t, err, envoy_type.StatusCode_InternalServerError) + if provider.got != nil { + t.Errorf("provider was asked for %v, want no fetch", provider.got) + } + }) + } +} diff --git a/cmd/atenet/internal/router/egress/request.go b/cmd/atenet/internal/router/egress/request.go index 308f8accea..d6ebb3c13b 100644 --- a/cmd/atenet/internal/router/egress/request.go +++ b/cmd/atenet/internal/router/egress/request.go @@ -24,6 +24,7 @@ import ( extprocv3 "github.com/envoyproxy/go-control-plane/envoy/service/ext_proc/v3" envoy_type "github.com/envoyproxy/go-control-plane/envoy/type/v3" + "golang.org/x/net/http/httpguts" "go.ate.dev/substrate/cmd/atenet/internal/router/extproc" "go.ate.dev/substrate/internal/egresspolicy" @@ -31,8 +32,8 @@ import ( ) const ( - websocketDeniedBody = "WebSocket egress is not supported" - connectDeniedBody = "CONNECT egress is not supported" + upgradeDeniedBody = "Only WebSocket upgrades are supported" + connectDeniedBody = "CONNECT egress is not supported" ) // handleRequest authorizes one request the gateway can read: cleartext HTTP, @@ -44,16 +45,23 @@ const ( // where the connection's SNI must fall under an https rule too. An allowed // request is dialed by the name it was decided on, on the port the actor // dialed. +// +// A WebSocket handshake is decided like any other request. Policy and +// credentials apply to the handshake only: the gateway does not read the +// frames that follow. func (h *Handler) handleRequest(ctx context.Context, md *extproc.RequestMetadata, leg string) (extproc.Result, error) { - if isWebSocketUpgrade(md) { - slog.WarnContext(ctx, "egress denied: WebSocket upgrades are not supported", slog.String("leg", leg), slog.String("host", md.Host)) - return extproc.Result{}, extproc.NewReqError(envoy_type.StatusCode_Forbidden, websocketDeniedBody) - } // We don't support Actor making a CONNECT (inside the tunnel). if strings.EqualFold(md.Method, http.MethodConnect) { slog.WarnContext(ctx, "egress denied: CONNECT inside the egress tunnel is not supported", slog.String("leg", leg), slog.String("authority", md.Host)) return extproc.Result{}, extproc.NewReqError(envoy_type.StatusCode_Forbidden, connectDeniedBody) } + // Envoy forwards any upgrade this handler allows, whatever protocol it + // names, so only a WebSocket handshake goes on to the policy. + if isUpgrade(md) && !isWebSocketHandshake(md) { + slog.WarnContext(ctx, "egress denied: only WebSocket upgrades are supported", + slog.String("leg", leg), slog.String("host", md.Host), slog.String("method", md.Method), slog.String("upgrade", md.Header("upgrade"))) + return extproc.Result{}, extproc.NewReqError(envoy_type.StatusCode_Forbidden, upgradeDeniedBody) + } ref, err := actorFromFilterState(md) if err != nil { @@ -138,17 +146,24 @@ func dialHost(dest egresspolicy.Destination) string { } } -func isWebSocketUpgrade(md *extproc.RequestMetadata) bool { - return md.Method == "GET" && hasHTTPToken(md.Header("connection"), "upgrade") && hasHTTPToken(md.Header("upgrade"), "websocket") +// isUpgrade reports whether md asks to switch protocols. Envoy removes the +// Upgrade header from every request it will not forward as an upgrade, so the +// header being present is the whole test. +func isUpgrade(md *extproc.RequestMetadata) bool { + _, ok := md.Headers["upgrade"] + return ok } -func hasHTTPToken(value, want string) bool { - for _, token := range strings.Split(value, ",") { - if strings.EqualFold(strings.TrimSpace(token), want) { - return true - } - } - return false +// isWebSocketHandshake reports whether md opens a WebSocket: a GET whose +// Upgrade is the single token websocket and whose Connection lists upgrade. +// Envoy compares these in ASCII, so this does too. A looser match would allow +// a request here that Envoy forwards as some other upgrade. +func isWebSocketHandshake(md *extproc.RequestMetadata) bool { + upgrade := md.Header("upgrade") + return md.Method == http.MethodGet && + !strings.Contains(upgrade, ",") && + httpguts.HeaderValuesContainsToken([]string{upgrade}, "websocket") && + httpguts.HeaderValuesContainsToken([]string{md.Header("connection")}, "upgrade") } // connectionDestination is the SNI a decrypted connection presented, on the diff --git a/cmd/atenet/internal/router/egress/request_test.go b/cmd/atenet/internal/router/egress/request_test.go index 49ceb6d60b..5855e5f2af 100644 --- a/cmd/atenet/internal/router/egress/request_test.go +++ b/cmd/atenet/internal/router/egress/request_test.go @@ -328,17 +328,50 @@ func TestRequestLegPicksRulesByLeg(t *testing.T) { } } -func TestRequestLegDeniesHTTP1WebSocketUpgrade(t *testing.T) { - h := policyHandler(allowAllPolicy()) - for _, leg := range []string{extproc.EgressCleartextFilterChainName, extproc.EgressTLSMITMFilterChainName} { - t.Run(leg, func(t *testing.T) { - md := innerMetadata(leg, "GET", "api.example.com", nil) - md.Headers["connection"] = "keep-alive, UpGrAdE" - md.Headers["upgrade"] = "WebSocket" - _, err := h.HandleRequestHeaders(context.Background(), md) +// A WebSocket handshake is decided by the leg's rules like any other request. +// Every other upgrade is refused, whatever the policy allows. +func TestRequestLegDecidesUpgrades(t *testing.T) { + const ( + cleartext = extproc.EgressCleartextFilterChainName + mitm = extproc.EgressTLSMITMFilterChainName + ) + all := allowAllPolicy() + websocket := map[string]string{"connection": "Upgrade", "upgrade": "websocket"} + for _, tc := range []struct { + name string + leg string + policy *ateapi.EgressPolicy + method string + headers map[string]string + wantBody string // "" means allowed; otherwise the body of the 403 + }{ + {name: "ordinary GET", leg: mitm, policy: all, method: "GET"}, + {name: "websocket over cleartext", leg: cleartext, policy: all, method: "GET", headers: websocket}, + {name: "websocket over TLS", leg: mitm, policy: all, method: "GET", headers: websocket}, + {name: "websocket in mixed case", leg: mitm, policy: all, method: "GET", headers: map[string]string{"connection": "keep-alive, UpGrAdE", "upgrade": "WebSocket"}}, + {name: "websocket to a host under no rule", leg: cleartext, policy: httpPolicy("other.example"), method: "GET", headers: websocket, wantBody: deniedBody}, + {name: "websocket over TLS under an http rule", leg: mitm, policy: httpPolicy("api.example.com"), method: "GET", headers: websocket, wantBody: deniedBody}, + {name: "other protocol", leg: mitm, policy: all, method: "GET", headers: map[string]string{"connection": "Upgrade", "upgrade": "foo"}, wantBody: upgradeDeniedBody}, + {name: "not a GET", leg: mitm, policy: all, method: "POST", headers: websocket, wantBody: upgradeDeniedBody}, + {name: "websocket in a list", leg: mitm, policy: all, method: "GET", headers: map[string]string{"connection": "Upgrade", "upgrade": "websocket, foo"}, wantBody: upgradeDeniedBody}, + // Envoy joins a repeated header with a comma. + {name: "repeated upgrade header", leg: mitm, policy: all, method: "GET", headers: map[string]string{"connection": "Upgrade", "upgrade": "websocket,websocket"}, wantBody: upgradeDeniedBody}, + // Unicode case folding reads U+017F as s; Envoy compares in ASCII. + {name: "non-ASCII spelling", leg: mitm, policy: all, method: "GET", headers: map[string]string{"connection": "Upgrade", "upgrade": "webſocket"}, wantBody: upgradeDeniedBody}, + {name: "connection without the upgrade token", leg: mitm, policy: all, method: "GET", headers: map[string]string{"connection": "keep-alive", "upgrade": "websocket"}, wantBody: upgradeDeniedBody}, + {name: "empty upgrade", leg: mitm, policy: all, method: "GET", headers: map[string]string{"connection": "Upgrade", "upgrade": ""}, wantBody: upgradeDeniedBody}, + } { + t.Run(tc.name, func(t *testing.T) { + md := innerMetadata(tc.leg, tc.method, "api.example.com", nil) + maps.Copy(md.Headers, tc.headers) + res, err := policyHandler(tc.policy).HandleRequestHeaders(context.Background(), md) + if tc.wantBody == "" { + wantDial(t, res, err, extproc.EgressDialName) + return + } wantStatus(t, err, envoy_type.StatusCode_Forbidden) - if err.Error() != websocketDeniedBody { - t.Errorf("denial body = %q, want %q", err, websocketDeniedBody) + if err.Error() != tc.wantBody { + t.Errorf("denial body = %q, want %q", err, tc.wantBody) } }) } @@ -365,29 +398,6 @@ func TestRequestLegDeniesConnect(t *testing.T) { } } -func TestRequestLegAllowsOrdinaryHTTPSRequest(t *testing.T) { - h := policyHandler(allowAllPolicy()) - for _, tc := range []struct { - name string - method string - connection string - upgrade string - }{ - {name: "ordinary GET", method: "GET"}, - {name: "other upgrade", method: "GET", connection: "Upgrade", upgrade: "h2c"}, - {name: "upgrade without connection token", method: "GET", connection: "keep-alive", upgrade: "websocket"}, - {name: "non-GET", method: "POST", connection: "Upgrade", upgrade: "websocket"}, - } { - t.Run(tc.name, func(t *testing.T) { - md := innerMetadata(extproc.EgressTLSMITMFilterChainName, tc.method, "api.example.com", nil) - md.Headers["connection"] = tc.connection - md.Headers["upgrade"] = tc.upgrade - res, err := h.HandleRequestHeaders(context.Background(), md) - wantDial(t, res, err, extproc.EgressDialName) - }) - } -} - // Without the identity the outer chain shares, a request cannot be attributed // to any actor and is refused. func TestRequestLegRequiresIdentity(t *testing.T) { diff --git a/cmd/atenet/internal/router/egress/tokenexchange/broker.go b/cmd/atenet/internal/router/egress/tokenexchange/broker.go new file mode 100644 index 0000000000..44b3a4e872 --- /dev/null +++ b/cmd/atenet/internal/router/egress/tokenexchange/broker.go @@ -0,0 +1,198 @@ +// Copyright 2026 The Agent Substrate 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 tokenexchange + +import ( + "context" + "crypto/sha256" + "encoding/hex" + "errors" + "fmt" + "slices" + "time" + + "golang.org/x/sync/singleflight" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + "k8s.io/apimachinery/pkg/util/cache" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/proto/tokenexchangepb" + "go.ate.dev/substrate/internal/resources" +) + +const ( + // Bounds an exchange that outlives its caller so a hung endpoint cannot hold + // its singleflight key forever. + exchangeTimeout = 10 * time.Second + minReuseMargin = 30 * time.Second + unknownExpiryReuse = 60 * time.Second +) + +// ErrMint wraps a failure to mint the subject JWT, so callers can tell it from +// a failed exchange. +var ErrMint = errors.New("minting the subject token") + +type subjectMinter interface { + Token(ctx context.Context, ref resources.ActorRef, src *ateapi.ActorJwtSource) (string, error) +} + +// Broker exchanges actor JWTs for tokens and reuses each token until a third +// of its lifetime, or 30 seconds, remains, whichever comes first. Tokens are +// cached per actor (atespace and name, not UID) and exchange configuration; +// because the subject JWT minter also caches by actor name, a recreated actor +// can inherit its predecessor's identity until both caches refresh. +type Broker struct { + minter subjectMinter + client *Client + tokens *cache.Expiring + flight singleflight.Group +} + +// NewBroker returns a Broker that mints subject JWTs with minter and exchanges +// them with client. +func NewBroker(minter subjectMinter, client *Client) *Broker { + return &Broker{ + minter: minter, + client: client, + tokens: cache.NewExpiring(), + } +} + +// Token returns a token for the actor ref names, exchanged as src describes. +// Errors carry a gRPC status code as Client.Exchange's do, and a failed mint +// also wraps ErrMint. +func (b *Broker) Token(ctx context.Context, ref resources.ActorRef, src *ateapi.TokenExchangeSource) (string, error) { + if b == nil || b.client == nil || b.minter == nil { + return "", status.Error(codes.FailedPrecondition, "token exchange broker is not configured") + } + if src.GetSubjectActorJwt() == nil { + return "", status.Error(codes.FailedPrecondition, "token exchange source has no subject_actor_jwt") + } + subj := &ateapi.ActorJwtSource{ + Audiences: slices.Sorted(slices.Values(src.GetSubjectActorJwt().GetAudiences())), + ExpirationSeconds: src.GetSubjectActorJwt().GetExpirationSeconds(), + } + params := make([]FormEntry, 0, len(src.GetAdditionalParameters())) + for _, p := range src.GetAdditionalParameters() { + params = append(params, FormEntry{Key: p.GetKey(), Value: p.GetValue()}) + } + req := Request{ + TokenURL: src.GetTokenUrl(), + Resources: slices.Sorted(slices.Values(src.GetResources())), + Audiences: slices.Sorted(slices.Values(src.GetAudiences())), + Scopes: slices.Sorted(slices.Values(src.GetScopes())), + RequestedTokenType: src.GetRequestedTokenType(), + AdditionalParameters: params, + } + key, err := tokenKey(ref, subj, req) + if err != nil { + return "", err + } + if token, ok := b.cached(key); ok { + return token, nil + } + if err := ctx.Err(); err != nil { + return "", status.FromContextError(err).Err() + } + + // Outlives the caller so a slow exchange still warms the cache for retries. + ch := b.flight.DoChan(key, func() (any, error) { + ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), exchangeTimeout) + defer cancel() + return b.exchange(ctx, key, ref, subj, req) + }) + select { + case <-ctx.Done(): + return "", status.FromContextError(ctx.Err()).Err() + case res := <-ch: + if res.Err != nil { + return "", res.Err + } + return res.Val.(string), nil + } +} + +func (b *Broker) exchange(ctx context.Context, key string, ref resources.ActorRef, subj *ateapi.ActorJwtSource, req Request) (string, error) { + if token, ok := b.cached(key); ok { + return token, nil + } + subject, err := b.minter.Token(ctx, ref, subj) + if err != nil { + // Rewrite detached mint cancellations and bare context errors so + // codes.Canceled unambiguously means the caller canceled. + if st, ok := status.FromError(err); ok { + if st.Code() == codes.Canceled { + err = status.Error(codes.Unavailable, st.Message()) + } + } else { + switch { + case errors.Is(err, context.DeadlineExceeded): + err = status.Error(codes.DeadlineExceeded, err.Error()) + case errors.Is(err, context.Canceled): + err = status.Error(codes.Unavailable, err.Error()) + } + } + return "", fmt.Errorf("%w: %w", ErrMint, err) + } + req.SubjectToken = subject + token, err := b.client.Exchange(ctx, req) + if err != nil { + return "", fmt.Errorf("exchanging a token for %s at %s: %w", ref, req.TokenURL, err) + } + if reuse := reuseFor(token); reuse > 0 { + b.tokens.Set(key, token.AccessToken, reuse) + } + return token.AccessToken, nil +} + +func reuseFor(token Token) time.Duration { + if token.ExpiresAt.IsZero() { + return unknownExpiryReuse + } + lifetime := time.Until(token.ExpiresAt) + return lifetime - max(lifetime/3, minReuseMargin) +} + +func (b *Broker) cached(key string) (string, bool) { + v, ok := b.tokens.Get(key) + s, _ := v.(string) + return s, ok +} + +func tokenKey(ref resources.ActorRef, subj *ateapi.ActorJwtSource, req Request) (string, error) { + entries := make([]*tokenexchangepb.TokenCacheKey_FormEntry, len(req.AdditionalParameters)) + for i, p := range req.AdditionalParameters { + entries[i] = &tokenexchangepb.TokenCacheKey_FormEntry{Key: p.Key, Value: p.Value} + } + raw, err := proto.MarshalOptions{Deterministic: true}.Marshal(&tokenexchangepb.TokenCacheKey{ + Atespace: ref.Atespace, + ActorName: ref.Name, + TokenUrl: req.TokenURL, + SubjectJwtAudiences: subj.GetAudiences(), + SubjectJwtExpirationSeconds: subj.GetExpirationSeconds(), + Resources: req.Resources, + Audiences: req.Audiences, + Scopes: req.Scopes, + RequestedTokenType: req.RequestedTokenType, + AdditionalParameters: entries, + }) + if err != nil { + return "", fmt.Errorf("encoding the token key: %w", err) + } + sum := sha256.Sum256(raw) + return hex.EncodeToString(sum[:]), nil +} diff --git a/cmd/atenet/internal/router/egress/tokenexchange/broker_test.go b/cmd/atenet/internal/router/egress/tokenexchange/broker_test.go new file mode 100644 index 0000000000..bf637a17ce --- /dev/null +++ b/cmd/atenet/internal/router/egress/tokenexchange/broker_test.go @@ -0,0 +1,658 @@ +// Copyright 2026 The Agent Substrate 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 tokenexchange + +import ( + "context" + "errors" + "fmt" + "io" + "net/http" + "net/url" + "strings" + "sync" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/resources" +) + +var testActor = resources.ActorRef{Atespace: "default", Name: "my-actor"} + +func testSource() *ateapi.TokenExchangeSource { + return &ateapi.TokenExchangeSource{ + TokenUrl: "https://sts.example.com/token", + SubjectActorJwt: &ateapi.ActorJwtSource{ + Audiences: []string{"https://sts.example.com"}, + ExpirationSeconds: 3600, + }, + Resources: []string{"https://api.example.com/v1"}, + Audiences: []string{"api.example.com"}, + Scopes: []string{"write", "read"}, + RequestedTokenType: tokenTypeAccessToken, + AdditionalParameters: []*ateapi.FormEntry{ + {Key: "identity_provider_id", Value: "idp-1"}, + }, + } +} + +// fakeMinter's nth call returns "subject-", or err when set. With hang +// set, it instead blocks until its ctx ends and returns the bare ctx error, +// as actorjwt.Minter does. +type fakeMinter struct { + calls atomic.Int32 + last atomic.Pointer[ateapi.ActorJwtSource] + err error + hang bool +} + +func (m *fakeMinter) Token(ctx context.Context, _ resources.ActorRef, src *ateapi.ActorJwtSource) (string, error) { + n := m.calls.Add(1) + m.last.Store(src) + if m.hang { + <-ctx.Done() + return "", ctx.Err() + } + if m.err != nil { + return "", m.err + } + return fmt.Sprintf("subject-%d", n), nil +} + +// fakeEndpoint answers the nth exchange with access token "at-" and +// expiresIn, a JSON member such as `,"expires_in":900` or "" for none. A +// status other than 0 or 200 answers with an OAuth error instead. gate, when +// non-nil, blocks each exchange until it is closed or its request ends. +type fakeEndpoint struct { + calls atomic.Int32 + lastForm atomic.Pointer[url.Values] + expiresIn string + status int + token string + delay time.Duration + gate chan struct{} +} + +func (e *fakeEndpoint) RoundTrip(req *http.Request) (*http.Response, error) { + n := e.calls.Add(1) + body, err := io.ReadAll(req.Body) + if err != nil { + return nil, err + } + form, err := url.ParseQuery(string(body)) + if err != nil { + return nil, err + } + e.lastForm.Store(&form) + if e.delay > 0 { + select { + case <-time.After(e.delay): + case <-req.Context().Done(): + return nil, req.Context().Err() + } + } + if e.gate != nil { + select { + case <-e.gate: + case <-req.Context().Done(): + return nil, req.Context().Err() + } + } + tok := e.token + if tok == "" { + tok = fmt.Sprintf("at-%d", n) + } + code, answer := http.StatusOK, fmt.Sprintf(`{"access_token":%q%s}`, tok, e.expiresIn) + if e.status != 0 && e.status != http.StatusOK { + code, answer = e.status, `{"error":"temporarily_unavailable"}` + } + return &http.Response{StatusCode: code, Body: io.NopCloser(strings.NewReader(answer)), Header: http.Header{}, Request: req}, nil +} + +func newTestBroker(m *fakeMinter, e *fakeEndpoint) *Broker { + return NewBroker(m, &Client{httpClient: &http.Client{Transport: e}}) +} + +func mustToken(t *testing.T, b *Broker, src *ateapi.TokenExchangeSource) string { + t.Helper() + token, err := b.Token(t.Context(), testActor, src) + if err != nil { + t.Fatalf("Token: %v", err) + } + return token +} + +func TestTokenReuse(t *testing.T) { + for _, tt := range []struct { + name string + expiresIn string + reuse time.Duration + }{ + {"until a third of the lifetime remains", `,"expires_in":900`, 600 * time.Second}, + {"until 30 seconds remain", `,"expires_in":60`, 30 * time.Second}, + {"for 60 seconds without expires_in", "", 60 * time.Second}, + {"for two thirds of a 24-hour token", `,"expires_in":86400`, 16 * time.Hour}, + {"with the longest expires_in", `,"expires_in":9223372036854775807`, time.Duration(maxExpiresIn) * time.Second * 2 / 3}, + } { + t.Run(tt.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + b := newTestBroker(&fakeMinter{}, &fakeEndpoint{expiresIn: tt.expiresIn}) + if got := mustToken(t, b, testSource()); got != "at-1" { + t.Fatalf("first token = %q, want at-1", got) + } + time.Sleep(tt.reuse - time.Second) + if got := mustToken(t, b, testSource()); got != "at-1" { + t.Errorf("token %v later = %q, want the cached at-1", tt.reuse-time.Second, got) + } + time.Sleep(2 * time.Second) + if got := mustToken(t, b, testSource()); got != "at-2" { + t.Errorf("token %v later = %q, want a new at-2", tt.reuse+time.Second, got) + } + }) + }) + } +} + +func TestDoNotCacheShortLivedTokens(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + endpoint := &fakeEndpoint{expiresIn: `,"expires_in":30`} + b := newTestBroker(&fakeMinter{}, endpoint) + mustToken(t, b, testSource()) + if got := mustToken(t, b, testSource()); got != "at-2" { + t.Errorf("second token = %q, want a new at-2", got) + } + }) +} + +func TestExchangeSendsMintedSubjectToken(t *testing.T) { + minter, endpoint := &fakeMinter{}, &fakeEndpoint{} + src := testSource() + src.Resources = []string{"https://api.example.com/v2", "https://api.example.com/v1"} + src.Audiences = []string{"b.example.com", "a.example.com"} + src.AdditionalParameters = []*ateapi.FormEntry{ + {Key: "identity_provider_id", Value: "idp-1"}, + {Key: "tag", Value: "first"}, + {Key: "tag", Value: "second"}, + } + mustToken(t, newTestBroker(minter, endpoint), src) + + wantMint := &ateapi.ActorJwtSource{Audiences: []string{"https://sts.example.com"}, ExpirationSeconds: 3600} + if got := minter.last.Load(); !proto.Equal(got, wantMint) { + t.Errorf("minted %v, want %v", got, wantMint) + } + wantForm := url.Values{ + "grant_type": {grantTypeTokenExchange}, + "subject_token": {"subject-1"}, + "subject_token_type": {tokenTypeJWT}, + "resource": {"https://api.example.com/v1", "https://api.example.com/v2"}, + "audience": {"a.example.com", "b.example.com"}, + "scope": {"read write"}, + "requested_token_type": {tokenTypeAccessToken}, + "identity_provider_id": {"idp-1"}, + "tag": {"first", "second"}, + } + if diff := cmp.Diff(wantForm, *endpoint.lastForm.Load()); diff != "" { + t.Errorf("form (-want +got):\n%s", diff) + } +} + +func TestMissingPreconditions(t *testing.T) { + for _, tt := range []struct { + name string + nilClient bool + src *ateapi.TokenExchangeSource + }{ + {name: "nil source", src: nil}, + {name: "nil subject_actor_jwt", src: func() *ateapi.TokenExchangeSource { s := testSource(); s.SubjectActorJwt = nil; return s }()}, + {name: "nil client", nilClient: true, src: testSource()}, + } { + t.Run(tt.name, func(t *testing.T) { + minter, endpoint := &fakeMinter{}, &fakeEndpoint{} + var b *Broker + if tt.nilClient { + b = NewBroker(minter, nil) + } else { + b = newTestBroker(minter, endpoint) + } + if _, err := b.Token(t.Context(), testActor, tt.src); status.Code(err) != codes.FailedPrecondition { + t.Errorf("Token error = %v, want FailedPrecondition", err) + } + if minter.calls.Load() != 0 || endpoint.calls.Load() != 0 { + t.Errorf("calls = (%d mint, %d exchange), want (0, 0)", minter.calls.Load(), endpoint.calls.Load()) + } + }) + } +} + +func TestCollapseConcurrentExchanges(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + endpoint := &fakeEndpoint{gate: make(chan struct{})} + b := newTestBroker(&fakeMinter{}, endpoint) + tokens := make([]string, 10) + var wg sync.WaitGroup + for i := range tokens { + wg.Go(func() { tokens[i] = mustToken(t, b, testSource()) }) + } + synctest.Wait() + close(endpoint.gate) + wg.Wait() + if n := endpoint.calls.Load(); n != 1 { + t.Errorf("%d exchanges, want 1", n) + } + for i, got := range tokens { + if got != "at-1" { + t.Errorf("caller %d got %q, want at-1", i, got) + } + } + }) +} + +// A caller that gives up gets DeadlineExceeded, and the exchange it started +// still fills the cache. +func TestExchangeOutlivesCaller(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + endpoint := &fakeEndpoint{gate: make(chan struct{})} + b := newTestBroker(&fakeMinter{}, endpoint) + ctx, cancel := context.WithTimeout(t.Context(), 4*time.Second) + defer cancel() + if _, err := b.Token(ctx, testActor, testSource()); status.Code(err) != codes.DeadlineExceeded { + t.Fatalf("Token error = %v, want code DeadlineExceeded", err) + } + close(endpoint.gate) + synctest.Wait() + if got := mustToken(t, b, testSource()); got != "at-1" { + t.Errorf("token = %q, want at-1 from the abandoned exchange", got) + } + if n := endpoint.calls.Load(); n != 1 { + t.Errorf("%d exchanges, want 1", n) + } + }) +} + +// An endpoint that never answers releases its key after exchangeTimeout, so a +// later request starts a new exchange instead of joining the stuck one. +func TestHungExchangeTimesOut(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + endpoint := &fakeEndpoint{gate: make(chan struct{})} + b := newTestBroker(&fakeMinter{}, endpoint) + ctx, cancel := context.WithTimeout(t.Context(), 4*time.Second) + defer cancel() + if _, err := b.Token(ctx, testActor, testSource()); err == nil { + t.Fatal("Token succeeded, want an error") + } + // Just before the deadline, a new caller joins the stuck exchange + // rather than starting another. + time.Sleep(exchangeTimeout - 4*time.Second - time.Second) + ctx2, cancel2 := context.WithTimeout(t.Context(), 500*time.Millisecond) + defer cancel2() + if _, err := b.Token(ctx2, testActor, testSource()); status.Code(err) != codes.DeadlineExceeded { + t.Fatalf("Token before the deadline: error = %v, want code DeadlineExceeded", err) + } + if n := endpoint.calls.Load(); n != 1 { + t.Fatalf("%d exchanges before the deadline, want 1", n) + } + time.Sleep(2 * time.Second) + close(endpoint.gate) + if got := mustToken(t, b, testSource()); got != "at-2" { + t.Errorf("token = %q, want at-2 from a new exchange", got) + } + }) +} + +func TestKeyOnActorAndEverythingSent(t *testing.T) { + for _, tt := range []struct { + name string + actor resources.ActorRef + mutate func(*ateapi.TokenExchangeSource) + wantSame bool + }{ + {name: "another actor", actor: resources.ActorRef{Atespace: "default", Name: "other"}}, + {name: "another atespace", actor: resources.ActorRef{Atespace: "other", Name: "my-actor"}}, + {name: "atespace and name boundary", actor: resources.ActorRef{Atespace: "default/my", Name: "actor"}}, + {name: "another token URL", mutate: func(s *ateapi.TokenExchangeSource) { s.TokenUrl = "https://sts.example.com/v2/token" }}, + {name: "another subject JWT audience", mutate: func(s *ateapi.TokenExchangeSource) { + s.SubjectActorJwt.Audiences = []string{"https://other-sts.example.com"} + }}, + {name: "another subject JWT lifetime", mutate: func(s *ateapi.TokenExchangeSource) { s.SubjectActorJwt.ExpirationSeconds = 900 }}, + {name: "another resource", mutate: func(s *ateapi.TokenExchangeSource) { s.Resources = []string{"https://other.example.com/v1"} }}, + {name: "another audience", mutate: func(s *ateapi.TokenExchangeSource) { s.Audiences = []string{"other.example.com"} }}, + {name: "other scopes", mutate: func(s *ateapi.TokenExchangeSource) { s.Scopes = []string{"read"} }}, + {name: "reordered scopes", mutate: func(s *ateapi.TokenExchangeSource) { s.Scopes = []string{"read", "write"} }, wantSame: true}, + {name: "delimiter collision in scopes", mutate: func(s *ateapi.TokenExchangeSource) { s.Scopes = []string{"read write"} }}, + {name: "another requested_token_type", mutate: func(s *ateapi.TokenExchangeSource) { s.RequestedTokenType = "" }}, + {name: "another additional parameter", mutate: func(s *ateapi.TokenExchangeSource) { + s.AdditionalParameters = []*ateapi.FormEntry{{Key: "identity_provider_id", Value: "idp-2"}} + }}, + {name: "repeated additional parameter", mutate: func(s *ateapi.TokenExchangeSource) { + s.AdditionalParameters = append(s.AdditionalParameters, &ateapi.FormEntry{Key: "identity_provider_id", Value: "idp-1"}) + }}, + } { + t.Run(tt.name, func(t *testing.T) { + endpoint := &fakeEndpoint{expiresIn: `,"expires_in":900`} + b := newTestBroker(&fakeMinter{}, endpoint) + first := mustToken(t, b, testSource()) + actor, src := testActor, testSource() + if tt.actor != (resources.ActorRef{}) { + actor = tt.actor + } + if tt.mutate != nil { + tt.mutate(src) + } + second, err := b.Token(t.Context(), actor, src) + if err != nil { + t.Fatalf("Token: %v", err) + } + want := int32(2) + if tt.wantSame { + want = 1 + if second != first { + t.Errorf("second token = %q, want %q", second, first) + } + } else if second == first { + t.Errorf("second token = %q, want a distinct token from %q", second, first) + } + if n := endpoint.calls.Load(); n != want { + t.Errorf("%d exchanges, want %d", n, want) + } + }) + } +} + +func TestMintErrorWrapsErrMint(t *testing.T) { + endpoint := &fakeEndpoint{} + b := newTestBroker(&fakeMinter{err: status.Error(codes.NotFound, "actor not found")}, endpoint) + _, err := b.Token(t.Context(), testActor, testSource()) + if !errors.Is(err, ErrMint) || status.Code(err) != codes.NotFound { + t.Errorf("Token error = %v, want ErrMint with code NotFound", err) + } + if n := endpoint.calls.Load(); n != 0 { + t.Errorf("%d exchanges after a failed mint, want 0", n) + } +} + +func TestDoNotCacheErrors(t *testing.T) { + endpoint := &fakeEndpoint{status: http.StatusServiceUnavailable} + b := newTestBroker(&fakeMinter{}, endpoint) + _, err := b.Token(t.Context(), testActor, testSource()) + if status.Code(err) != codes.Unavailable || errors.Is(err, ErrMint) { + t.Fatalf("Token error = %v, want code Unavailable without ErrMint", err) + } + endpoint.status = http.StatusOK + if got := mustToken(t, b, testSource()); got != "at-2" { + t.Errorf("token after a failed exchange = %q, want at-2", got) + } +} + +// A mint that runs out the flight's time is DeadlineExceeded, which callers +// retry, not the Unknown of a bare context error. +func TestMintTimeoutIsDeadlineExceeded(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + endpoint := &fakeEndpoint{} + b := newTestBroker(&fakeMinter{hang: true}, endpoint) + ctx, cancel := context.WithTimeout(t.Context(), 2*exchangeTimeout) + defer cancel() + _, err := b.Token(ctx, testActor, testSource()) + if !errors.Is(err, ErrMint) || status.Code(err) != codes.DeadlineExceeded { + t.Errorf("Token error = %v (code %v), want ErrMint with code DeadlineExceeded", err, status.Code(err)) + } + if n := endpoint.calls.Load(); n != 0 { + t.Errorf("%d exchanges after a failed mint, want 0", n) + } + }) +} + +func TestDoNotCacheMintErrors(t *testing.T) { + minter := &fakeMinter{err: status.Error(codes.Unavailable, "ateapi unavailable")} + endpoint := &fakeEndpoint{expiresIn: `,"expires_in":900`} + b := newTestBroker(minter, endpoint) + if _, err := b.Token(t.Context(), testActor, testSource()); !errors.Is(err, ErrMint) { + t.Fatalf("Token error = %v, want ErrMint", err) + } + minter.err = nil + if got := mustToken(t, b, testSource()); got != "at-1" { + t.Errorf("token after a failed mint = %q, want at-1", got) + } + if n := minter.calls.Load(); n != 2 { + t.Errorf("%d mints, want 2", n) + } +} + +func TestCallerCancelIsCanceled(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + endpoint := &fakeEndpoint{gate: make(chan struct{})} + b := newTestBroker(&fakeMinter{}, endpoint) + ctx, cancel := context.WithCancel(t.Context()) + go func() { + synctest.Wait() + cancel() + }() + if _, err := b.Token(ctx, testActor, testSource()); status.Code(err) != codes.Canceled { + t.Errorf("Token error = %v, want code Canceled", err) + } + close(endpoint.gate) + }) +} + +func TestAlreadyCanceledCallerDoesNotExchange(t *testing.T) { + minter, endpoint := &fakeMinter{}, &fakeEndpoint{} + b := newTestBroker(minter, endpoint) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := b.Token(ctx, testActor, testSource()); status.Code(err) != codes.Canceled { + t.Errorf("Token error = %v, want code Canceled", err) + } + if minter.calls.Load() != 0 || endpoint.calls.Load() != 0 { + t.Errorf("calls = (%d mint, %d exchange), want (0, 0)", minter.calls.Load(), endpoint.calls.Load()) + } +} + +func TestLiveCallerSeesExchangeTimeout(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + endpoint := &fakeEndpoint{gate: make(chan struct{})} + b := newTestBroker(&fakeMinter{}, endpoint) + ctx, cancel := context.WithTimeout(t.Context(), 2*exchangeTimeout) + defer cancel() + if _, err := b.Token(ctx, testActor, testSource()); status.Code(err) != codes.DeadlineExceeded || errors.Is(err, ErrMint) { + t.Errorf("Token error = %v, want code DeadlineExceeded without ErrMint", err) + } + close(endpoint.gate) + }) +} + +func TestNilBrokerAndNilMinterReturnFailedPrecondition(t *testing.T) { + var nilBroker *Broker + if _, err := nilBroker.Token(t.Context(), testActor, testSource()); status.Code(err) != codes.FailedPrecondition { + t.Errorf("nil Broker: error = %v, want FailedPrecondition", err) + } + b := NewBroker(nil, &Client{}) + if _, err := b.Token(t.Context(), testActor, testSource()); status.Code(err) != codes.FailedPrecondition { + t.Errorf("nil minter: error = %v, want FailedPrecondition", err) + } +} + +func TestDetachedMintCanceledMapsToUnavailable(t *testing.T) { + for _, tt := range []struct { + name string + err error + }{ + {"bare context.Canceled", context.Canceled}, + {"wrapped gRPC Canceled", fmt.Errorf("minting actor JWT: %w", status.Error(codes.Canceled, "server draining"))}, + } { + t.Run(tt.name, func(t *testing.T) { + b := newTestBroker(&fakeMinter{err: tt.err}, &fakeEndpoint{}) + _, err := b.Token(t.Context(), testActor, testSource()) + if !errors.Is(err, ErrMint) || status.Code(err) != codes.Unavailable { + t.Errorf("Token error = %v (code %v), want ErrMint with code Unavailable", err, status.Code(err)) + } + }) + } +} + +func TestRejectsOversizedTokens(t *testing.T) { + endpoint := &fakeEndpoint{ + expiresIn: `,"expires_in":900`, + token: strings.Repeat("a", maxAccessTokenBytes+1), + } + b := newTestBroker(&fakeMinter{}, endpoint) + if _, err := b.Token(t.Context(), testActor, testSource()); status.Code(err) != codes.FailedPrecondition { + t.Errorf("Token error = %v, want code FailedPrecondition", err) + } +} + +func TestExchangeSnapshotsCallerSource(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + minter, endpoint := &fakeMinter{}, &fakeEndpoint{gate: make(chan struct{})} + b := newTestBroker(minter, endpoint) + src := testSource() + ctx, cancel := context.WithCancel(t.Context()) + go func() { + synctest.Wait() + cancel() + }() + if _, err := b.Token(ctx, testActor, src); status.Code(err) != codes.Canceled { + t.Fatalf("Token error = %v, want Canceled", err) + } + // Mutate caller's proto while the detached exchange is still in flight. + src.TokenUrl = "https://mutated.example.com/token" + src.RequestedTokenType = "mutated" + src.SubjectActorJwt.Audiences[0] = "https://mutated-sts.example.com" + src.SubjectActorJwt.ExpirationSeconds = 300 + close(endpoint.gate) + synctest.Wait() + + wantMint := &ateapi.ActorJwtSource{Audiences: []string{"https://sts.example.com"}, ExpirationSeconds: 3600} + if got := minter.last.Load(); !proto.Equal(got, wantMint) { + t.Errorf("detached mint saw %v, want original %v", got, wantMint) + } + if got := endpoint.lastForm.Load().Get("requested_token_type"); got != tokenTypeAccessToken { + t.Errorf("detached exchange saw requested_token_type %q, want %q", got, tokenTypeAccessToken) + } + if got := mustToken(t, b, testSource()); got != "at-1" { + t.Errorf("subsequent token = %q, want cached at-1", got) + } + }) +} + +func TestSlowExchangeReducesReuseTTL(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + // 5s round-trip with expires_in=60 leaves 55s at response time, so + // reuse is 55s - 30s = 25s. + b := newTestBroker(&fakeMinter{}, &fakeEndpoint{expiresIn: `,"expires_in":60`, delay: 5 * time.Second}) + if got := mustToken(t, b, testSource()); got != "at-1" { + t.Fatalf("first token = %q, want at-1", got) + } + time.Sleep(24 * time.Second) + if got := mustToken(t, b, testSource()); got != "at-1" { + t.Errorf("token after 24s = %q, want cached at-1", got) + } + time.Sleep(2 * time.Second) + if got := mustToken(t, b, testSource()); got != "at-2" { + t.Errorf("token after 26s = %q, want refreshed at-2", got) + } + }) + synctest.Test(t, func(t *testing.T) { + // 6s round-trip with expires_in=35 leaves 29s <= 30s, so don't cache. + b := newTestBroker(&fakeMinter{}, &fakeEndpoint{expiresIn: `,"expires_in":35`, delay: 6 * time.Second}) + mustToken(t, b, testSource()) + if got := mustToken(t, b, testSource()); got != "at-2" { + t.Errorf("second token = %q, want uncached at-2", got) + } + }) +} + +func TestKeyNormalizationAndOrderSensitivity(t *testing.T) { + base := func() *ateapi.TokenExchangeSource { + s := testSource() + s.SubjectActorJwt.Audiences = []string{"https://sts-b.example.com", "https://sts-a.example.com"} + s.Resources = []string{"https://api.example.com/v2", "https://api.example.com/v1"} + s.Audiences = []string{"b.example.com", "a.example.com"} + s.AdditionalParameters = []*ateapi.FormEntry{{Key: "tag", Value: "first"}, {Key: "tag", Value: "second"}} + return s + } + for _, tt := range []struct { + name string + mutate func(*ateapi.TokenExchangeSource) + wantSame bool + }{ + {name: "reordered subject JWT audiences", mutate: func(s *ateapi.TokenExchangeSource) { + s.SubjectActorJwt.Audiences = []string{"https://sts-a.example.com", "https://sts-b.example.com"} + }, wantSame: true}, + {name: "reordered resources", mutate: func(s *ateapi.TokenExchangeSource) { + s.Resources = []string{"https://api.example.com/v1", "https://api.example.com/v2"} + }, wantSame: true}, + {name: "reordered audiences", mutate: func(s *ateapi.TokenExchangeSource) { + s.Audiences = []string{"a.example.com", "b.example.com"} + }, wantSame: true}, + {name: "reordered repeated additional parameters", mutate: func(s *ateapi.TokenExchangeSource) { + s.AdditionalParameters = []*ateapi.FormEntry{{Key: "tag", Value: "second"}, {Key: "tag", Value: "first"}} + }}, + } { + t.Run(tt.name, func(t *testing.T) { + endpoint := &fakeEndpoint{expiresIn: `,"expires_in":900`} + b := newTestBroker(&fakeMinter{}, endpoint) + first := mustToken(t, b, base()) + secondSrc := base() + tt.mutate(secondSrc) + second := mustToken(t, b, secondSrc) + if tt.wantSame && second != first { + t.Errorf("second token = %q, want cached %q", second, first) + } + if !tt.wantSame && second == first { + t.Errorf("second token = %q, want distinct token from %q", second, first) + } + }) + } +} + +func TestFollowerSurvivesLeaderCancel(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + endpoint := &fakeEndpoint{gate: make(chan struct{})} + b := newTestBroker(&fakeMinter{}, endpoint) + + leaderCtx, cancelLeader := context.WithCancel(t.Context()) + leaderErr := make(chan error, 1) + go func() { + _, err := b.Token(leaderCtx, testActor, testSource()) + leaderErr <- err + }() + synctest.Wait() + + followerTok := make(chan string, 1) + go func() { + followerTok <- mustToken(t, b, testSource()) + }() + synctest.Wait() + + cancelLeader() + if err := <-leaderErr; status.Code(err) != codes.Canceled { + t.Fatalf("leader error = %v, want Canceled", err) + } + close(endpoint.gate) + if got := <-followerTok; got != "at-1" { + t.Errorf("follower token = %q, want at-1", got) + } + if n := endpoint.calls.Load(); n != 1 { + t.Errorf("%d exchanges, want 1", n) + } + }) +} diff --git a/cmd/atenet/internal/router/egress/tokenexchange/client.go b/cmd/atenet/internal/router/egress/tokenexchange/client.go new file mode 100644 index 0000000000..faae56d152 --- /dev/null +++ b/cmd/atenet/internal/router/egress/tokenexchange/client.go @@ -0,0 +1,306 @@ +// Copyright 2026 The Agent Substrate 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 tokenexchange exchanges actor JWTs for access tokens at OAuth 2.0 +// token exchange endpoints (RFC 8693). +package tokenexchange + +import ( + "context" + "crypto/tls" + "crypto/x509" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "os" + "strings" + "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +const ( + grantTypeTokenExchange = "urn:ietf:params:oauth:grant-type:token-exchange" + tokenTypeJWT = "urn:ietf:params:oauth:token-type:jwt" + tokenTypeAccessToken = "urn:ietf:params:oauth:token-type:access_token" + tokenTypeBearer = "Bearer" + tokenTypeNA = "N_A" + + maxResponseBytes = 1 << 20 + // maxAccessTokenBytes bounds the issued token so an oversized token cannot + // bloat caches or exceed HTTP header limits. + maxAccessTokenBytes = 16 * 1024 + // maxDetailBytes bounds the endpoint-supplied error fields an error carries. + maxDetailBytes = 200 + // maxExpiresIn bounds expires_in so its conversion to a Duration can't + // overflow. + maxExpiresIn = 365 * 24 * 60 * 60 +) + +// reservedParams are the RFC 8693 section 2.1 form parameters managed by +// structured fields on Request. +var reservedParams = map[string]bool{ + "grant_type": true, + "subject_token": true, + "subject_token_type": true, + "actor_token": true, + "actor_token_type": true, + "resource": true, + "audience": true, + "scope": true, + "requested_token_type": true, +} + +// deniedErrors are the OAuth error codes that mean the endpoint refused this +// actor's exchange: invalid_target from RFC 8693 section 2.2.2, the rest from +// RFC 6749 section 5.2. +var deniedErrors = map[string]bool{ + "invalid_grant": true, + "invalid_target": true, + "unauthorized_client": true, + "invalid_scope": true, +} + +// FormEntry is a single key-value entry in the exchange form body. +type FormEntry struct { + Key string + Value string +} + +// Request holds the parameters of one RFC 8693 token exchange. +type Request struct { + TokenURL string + SubjectToken string + Resources []string + Audiences []string + Scopes []string + RequestedTokenType string + AdditionalParameters []FormEntry +} + +// Token is a token issued by a token endpoint. +type Token struct { + AccessToken string + // ExpiresAt is zero when the endpoint did not return expires_in. + ExpiresAt time.Time +} + +// Client sends token exchange requests. +type Client struct { + httpClient *http.Client +} + +// New returns a Client that trusts the system roots plus the PEM certificates +// in caFile, when set, which must hold at least one. The client ignores proxy +// environment variables and does not follow redirects. +func New(caFile string) (*Client, error) { + transport := http.DefaultTransport.(*http.Transport).Clone() + transport.Proxy = nil + if caFile != "" { + certs, err := os.ReadFile(caFile) + if err != nil { + return nil, fmt.Errorf("reading token exchange CA file: %w", err) + } + roots, err := x509.SystemCertPool() + if err != nil { + return nil, fmt.Errorf("loading system roots: %w", err) + } + if !roots.AppendCertsFromPEM(certs) { + return nil, fmt.Errorf("token exchange CA file %q contains no certificates", caFile) + } + transport.TLSClientConfig = &tls.Config{RootCAs: roots} + } + return &Client{httpClient: &http.Client{ + Transport: transport, + CheckRedirect: func(*http.Request, []*http.Request) error { + return http.ErrUseLastResponse + }, + }}, nil +} + +// Exchange trades r.SubjectToken, a JWT, for a token at r.TokenURL within ctx. +// Empty optional fields (Resources, Audiences, Scopes, RequestedTokenType, +// AdditionalParameters) are omitted from the form post. Errors carry a gRPC +// code: PermissionDenied for a 403 or an OAuth denial, FailedPrecondition for +// a non-https TokenURL, a reserved AdditionalParameters key, an oversized +// access_token, or any other non-200 status below 429, DeadlineExceeded or +// Canceled when ctx ends before the response is read, and Unavailable for 429, +// 5xx, a failed connection, or an unusable 200 response. +func (c *Client) Exchange(ctx context.Context, r Request) (Token, error) { + form := url.Values{ + "grant_type": {grantTypeTokenExchange}, + "subject_token": {r.SubjectToken}, + "subject_token_type": {tokenTypeJWT}, + } + for _, res := range r.Resources { + form.Add("resource", res) + } + for _, aud := range r.Audiences { + form.Add("audience", aud) + } + if len(r.Scopes) > 0 { + form.Set("scope", strings.Join(r.Scopes, " ")) + } + if r.RequestedTokenType != "" { + form.Set("requested_token_type", r.RequestedTokenType) + } + for _, p := range r.AdditionalParameters { + if reservedParams[p.Key] { + return Token{}, status.Errorf(codes.FailedPrecondition, "additional parameter %q is a reserved RFC 8693 parameter", p.Key) + } + form.Add(p.Key, p.Value) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, r.TokenURL, strings.NewReader(form.Encode())) + if err != nil { + return Token{}, status.Errorf(codes.FailedPrecondition, "building token exchange request: %v", err) + } + // The form carries the subject token, which must not travel in cleartext + // (RFC 6749 section 3.2, RFC 8693 section 2.1). + if req.URL.Scheme != "https" { + return Token{}, status.Errorf(codes.FailedPrecondition, "token URL scheme is %q, want https", req.URL.Scheme) + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + + sentAt := time.Now() + resp, err := c.httpClient.Do(req) + if err != nil { + return Token{}, transportError(ctx, "token exchange request", err) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBytes+1)) + if err != nil { + return Token{}, transportError(ctx, "reading token exchange response", err) + } + if len(body) > maxResponseBytes { + return Token{}, status.Errorf(codes.Unavailable, "token exchange response exceeds %d bytes", maxResponseBytes) + } + + if resp.StatusCode == http.StatusOK { + return parseToken(body, r.RequestedTokenType, sentAt) + } + var oauthErr oauthError + // A body that is not an OAuth error response leaves both fields empty. + _ = json.Unmarshal(body, &oauthErr) + code := codes.FailedPrecondition + switch { + case resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500: + code = codes.Unavailable + case resp.StatusCode == http.StatusForbidden: + // Some endpoints deny an exchange with 403 rather than a 400 + // invalid_grant. + code = codes.PermissionDenied + case (resp.StatusCode == http.StatusBadRequest || resp.StatusCode == http.StatusUnauthorized) && deniedErrors[oauthErr.Error]: + code = codes.PermissionDenied + } + detail := oauthErr.detail() + if detail == "" && len(body) > 0 { + // The body is not an OAuth error response, for example a proxy's + // plain-text page, so report the body itself. + detail = fmt.Sprintf(": body %q", clip(string(body))) + } + return Token{}, status.Errorf(code, "token endpoint returned %d%s", resp.StatusCode, detail) +} + +// transportError maps an error from sending the request or reading the +// response. When ctx has ended, that is the cause, reported as +// DeadlineExceeded or Canceled; anything else, including a transport timeout +// while ctx is live, is Unavailable. +func transportError(ctx context.Context, what string, err error) error { + code := codes.Unavailable + if ctx.Err() != nil { + code = status.FromContextError(ctx.Err()).Code() + } + return status.Errorf(code, "%s: %v", what, err) +} + +// parseToken reads a successful token exchange response, anchoring ExpiresAt to +// sentAt so request latency and backend processing time are not added to expires_in. +func parseToken(body []byte, requestedTokenType string, sentAt time.Time) (Token, error) { + var r struct { + AccessToken string `json:"access_token"` + IssuedTokenType string `json:"issued_token_type"` + TokenType string `json:"token_type"` + ExpiresIn *int64 `json:"expires_in"` + } + if err := json.Unmarshal(body, &r); err != nil { + return Token{}, status.Errorf(codes.Unavailable, "parsing token exchange response: %q", clip(err.Error())) + } + if requestedTokenType != "" && r.IssuedTokenType != "" && r.IssuedTokenType != requestedTokenType { + return Token{}, status.Errorf(codes.Unavailable, "token endpoint issued token type %q, want %q", clip(r.IssuedTokenType), requestedTokenType) + } + // When token_type is present (case-insensitive per RFC 6749 section 7.1), + // require Bearer for access tokens, or Bearer/N_A for other token types; + // omitted token_type is tolerated for non-strict endpoints. + expectBearer := requestedTokenType == tokenTypeAccessToken || + (requestedTokenType == "" && (r.IssuedTokenType == "" || r.IssuedTokenType == tokenTypeAccessToken)) + if r.TokenType != "" { + if expectBearer && !strings.EqualFold(r.TokenType, tokenTypeBearer) { + return Token{}, status.Errorf(codes.Unavailable, "token endpoint issued token_type %q, want %q", clip(r.TokenType), tokenTypeBearer) + } + if !expectBearer && !strings.EqualFold(r.TokenType, tokenTypeBearer) && !strings.EqualFold(r.TokenType, tokenTypeNA) { + return Token{}, status.Errorf(codes.Unavailable, "token endpoint issued unsupported token_type %q", clip(r.TokenType)) + } + } + if !isAccessToken(r.AccessToken) { + return Token{}, status.Error(codes.Unavailable, "token endpoint returned an empty access_token or one with characters outside VSCHAR") + } + if len(r.AccessToken) > maxAccessTokenBytes { + return Token{}, status.Errorf(codes.FailedPrecondition, "token endpoint returned access_token exceeding %d bytes", maxAccessTokenBytes) + } + tok := Token{AccessToken: r.AccessToken} + if r.ExpiresIn != nil { + if *r.ExpiresIn <= 0 { + return Token{}, status.Errorf(codes.Unavailable, "token endpoint returned expires_in %d", *r.ExpiresIn) + } + tok.ExpiresAt = sentAt.Add(time.Duration(min(*r.ExpiresIn, maxExpiresIn)) * time.Second) + } + return tok, nil +} + +// isAccessToken reports whether s is 1*VSCHAR, the access-token syntax of +// RFC 6749 Appendix A.12: printable ASCII, space included. +func isAccessToken(s string) bool { + for i := 0; i < len(s); i++ { + if s[i] < ' ' || s[i] > '~' { + return false + } + } + return s != "" +} + +// oauthError is an OAuth 2.0 error response (RFC 6749 section 5.2). +type oauthError struct { + Error string `json:"error"` + Description string `json:"error_description"` +} + +// detail formats e for an error message, clipped and quoted, or "" when the +// response carried neither field. +func (e oauthError) detail() string { + if e.Error == "" && e.Description == "" { + return "" + } + return fmt.Sprintf(": error %q, error_description %q", clip(e.Error), clip(e.Description)) +} + +// clip caps s at maxDetailBytes for %q-formatted error messages. +func clip(s string) string { + if len(s) <= maxDetailBytes { + return s + } + return s[:maxDetailBytes] +} diff --git a/cmd/atenet/internal/router/egress/tokenexchange/client_test.go b/cmd/atenet/internal/router/egress/tokenexchange/client_test.go new file mode 100644 index 0000000000..0c82f7a188 --- /dev/null +++ b/cmd/atenet/internal/router/egress/tokenexchange/client_test.go @@ -0,0 +1,544 @@ +// Copyright 2026 The Agent Substrate 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 tokenexchange + +import ( + "context" + "encoding/pem" + "fmt" + "io" + "net/http" + "net/http/httptest" + "net/url" + "os" + "path/filepath" + "strings" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/google/go-cmp/cmp" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +const ( + subjectToken = "subject.jwt.token" + audience = "//iam.googleapis.com/projects/123/locations/global/workloadIdentityPools/ate/providers/actors" +) + +// newTestServer starts a TLS server running handler at /token and returns it +// with a Client that trusts its certificate. +func newTestServer(t *testing.T, handler http.HandlerFunc) (*httptest.Server, *Client) { + t.Helper() + mux := http.NewServeMux() + mux.HandleFunc("/token", handler) + srv := httptest.NewTLSServer(mux) + t.Cleanup(srv.Close) + c, err := New(writeCAFile(t, srv)) + if err != nil { + t.Fatalf("New: %v", err) + } + return srv, c +} + +func writeCAFile(t *testing.T, srv *httptest.Server) string { + t.Helper() + path := filepath.Join(t.TempDir(), "ca.crt") + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}) + if err := os.WriteFile(path, certPEM, 0o600); err != nil { + t.Fatal(err) + } + return path +} + +func respond(status int, body string) http.HandlerFunc { + return func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + fmt.Fprint(w, body) + } +} + +func testRequest(tokenURL string) Request { + return Request{ + TokenURL: tokenURL, + SubjectToken: subjectToken, + Audiences: []string{audience}, + RequestedTokenType: tokenTypeAccessToken, + } +} + +func TestExchangeSendsTokenExchangeForm(t *testing.T) { + for _, tt := range []struct { + name string + req Request + want url.Values + }{{ + name: "all RFC 8693 fields and repeated additional parameters", + req: Request{ + SubjectToken: subjectToken, + Resources: []string{"https://api.example.com/v1", "urn:example:service"}, + Audiences: []string{audience, "https://other.example.com"}, + Scopes: []string{"https://www.googleapis.com/auth/cloud-platform", "read"}, + RequestedTokenType: tokenTypeAccessToken, + AdditionalParameters: []FormEntry{ + {Key: "identity_provider_id", Value: "idp-1"}, + {Key: "tag", Value: "a"}, + {Key: "tag", Value: "b"}, + }, + }, + want: url.Values{ + "grant_type": {"urn:ietf:params:oauth:grant-type:token-exchange"}, + "subject_token": {subjectToken}, + "subject_token_type": {"urn:ietf:params:oauth:token-type:jwt"}, + "resource": {"https://api.example.com/v1", "urn:example:service"}, + "audience": {audience, "https://other.example.com"}, + "scope": {"https://www.googleapis.com/auth/cloud-platform read"}, + "requested_token_type": {"urn:ietf:params:oauth:token-type:access_token"}, + "identity_provider_id": {"idp-1"}, + "tag": {"a", "b"}, + }, + }, { + name: "optional fields omitted when empty", + req: Request{SubjectToken: subjectToken}, + want: url.Values{ + "grant_type": {"urn:ietf:params:oauth:grant-type:token-exchange"}, + "subject_token": {subjectToken}, + "subject_token_type": {"urn:ietf:params:oauth:token-type:jwt"}, + }, + }} { + t.Run(tt.name, func(t *testing.T) { + var got url.Values + srv, c := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method = %s, want POST", r.Method) + } + if ct := r.Header.Get("Content-Type"); ct != "application/x-www-form-urlencoded" { + t.Errorf("Content-Type = %q, want application/x-www-form-urlencoded", ct) + } + if err := r.ParseForm(); err != nil { + t.Errorf("ParseForm: %v", err) + } + got = r.PostForm + respond(http.StatusOK, `{"access_token":"at","issued_token_type":"urn:ietf:params:oauth:token-type:access_token","token_type":"Bearer","expires_in":600}`)(w, r) + }) + req := tt.req + req.TokenURL = srv.URL + "/token" + if _, err := c.Exchange(t.Context(), req); err != nil { + t.Fatalf("Exchange: %v", err) + } + if diff := cmp.Diff(tt.want, got); diff != "" { + t.Errorf("form (-want +got):\n%s", diff) + } + }) + } +} + +func TestExchangeRejectsReservedAdditionalParameter(t *testing.T) { + var requests atomic.Int32 + srv, c := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + respond(http.StatusOK, `{"access_token":"at"}`)(w, r) + }) + req := testRequest(srv.URL + "/token") + req.AdditionalParameters = []FormEntry{{Key: "subject_token", Value: "forged"}} + _, err := c.Exchange(t.Context(), req) + if got := status.Code(err); got != codes.FailedPrecondition { + t.Errorf("Exchange error = %v (code %v), want code %v", err, got, codes.FailedPrecondition) + } + if n := requests.Load(); n != 0 { + t.Errorf("the server got %d requests, want 0", n) + } +} + +func TestExchangeReturnsToken(t *testing.T) { + for _, tt := range []struct { + name string + requestedTokenType string // tokenTypeAccessToken unless set; "-" means empty + body string + wantToken string // fake.access.token unless set + wantExpiresIn time.Duration + }{{ + name: "with expires_in", + body: `{"access_token":"fake.access.token","issued_token_type":"urn:ietf:params:oauth:token-type:access_token","token_type":"Bearer","expires_in":600}`, + wantExpiresIn: 600 * time.Second, + }, { + name: "without expires_in or issued_token_type", + body: `{"access_token":"fake.access.token","token_type":"Bearer"}`, + }, { + name: "with an expires_in too large for a Duration", + body: `{"access_token":"fake.access.token","expires_in":9223372036854775807}`, + wantExpiresIn: maxExpiresIn * time.Second, + }, { + name: "with a space in access_token", + body: `{"access_token":"fake access token"}`, + wantToken: "fake access token", + }, { + name: "with token_type in another case", + body: `{"access_token":"fake.access.token","token_type":"bearer"}`, + }, { + name: "non-access requested_token_type with token_type N_A", + requestedTokenType: "urn:ietf:params:oauth:token-type:id-jag", + body: `{"access_token":"fake.access.token","issued_token_type":"urn:ietf:params:oauth:token-type:id-jag","token_type":"N_A"}`, + }, { + name: "omitted requested_token_type accepts non-access issued_token_type with N_A", + requestedTokenType: "-", + body: `{"access_token":"fake.access.token","issued_token_type":"urn:ietf:params:oauth:token-type:jwt","token_type":"N_A"}`, + }} { + t.Run(tt.name, func(t *testing.T) { + srv, c := newTestServer(t, respond(http.StatusOK, tt.body)) + req := testRequest(srv.URL + "/token") + if tt.requestedTokenType == "-" { + req.RequestedTokenType = "" + } else if tt.requestedTokenType != "" { + req.RequestedTokenType = tt.requestedTokenType + } + before := time.Now() + tok, err := c.Exchange(t.Context(), req) + after := time.Now() + if err != nil { + t.Fatalf("Exchange: %v", err) + } + want := tt.wantToken + if want == "" { + want = "fake.access.token" + } + if tok.AccessToken != want { + t.Errorf("AccessToken = %q, want %q", tok.AccessToken, want) + } + if tt.wantExpiresIn == 0 { + if !tok.ExpiresAt.IsZero() { + t.Errorf("ExpiresAt = %v, want zero", tok.ExpiresAt) + } + return + } + if tok.ExpiresAt.Before(before.Add(tt.wantExpiresIn)) || tok.ExpiresAt.After(after.Add(tt.wantExpiresIn)) { + t.Errorf("ExpiresAt = %v, want %v after the exchange", tok.ExpiresAt, tt.wantExpiresIn) + } + }) + } +} + +func TestExchangeErrors(t *testing.T) { + oauthError := func(code string) string { + return fmt.Sprintf(`{"error":%q,"error_description":"details"}`, code) + } + for _, tt := range []struct { + name string + status int + body string + wantCode codes.Code + }{ + {"invalid_grant", http.StatusBadRequest, oauthError("invalid_grant"), codes.PermissionDenied}, + {"invalid_target", http.StatusBadRequest, oauthError("invalid_target"), codes.PermissionDenied}, + {"unauthorized_client", http.StatusUnauthorized, oauthError("unauthorized_client"), codes.PermissionDenied}, + {"invalid_scope", http.StatusBadRequest, oauthError("invalid_scope"), codes.PermissionDenied}, + {"403 access_denied", http.StatusForbidden, oauthError("access_denied"), codes.PermissionDenied}, + {"403 without an error code", http.StatusForbidden, "forbidden", codes.PermissionDenied}, + {"access_denied, an authorization endpoint code", http.StatusBadRequest, oauthError("access_denied"), codes.FailedPrecondition}, + {"invalid_request", http.StatusBadRequest, oauthError("invalid_request"), codes.FailedPrecondition}, + {"invalid_client", http.StatusUnauthorized, oauthError("invalid_client"), codes.FailedPrecondition}, + {"unsupported_grant_type", http.StatusBadRequest, oauthError("unsupported_grant_type"), codes.FailedPrecondition}, + {"400 without an error code", http.StatusBadRequest, "bad request", codes.FailedPrecondition}, + {"404", http.StatusNotFound, "not found", codes.FailedPrecondition}, + {"429", http.StatusTooManyRequests, "slow down", codes.Unavailable}, + {"500", http.StatusInternalServerError, "", codes.Unavailable}, + {"503", http.StatusServiceUnavailable, oauthError("temporarily_unavailable"), codes.Unavailable}, + {"200 with a body that is not JSON", http.StatusOK, "", codes.Unavailable}, + {"200 without access_token", http.StatusOK, `{"token_type":"Bearer","expires_in":600}`, codes.Unavailable}, + {"200 with another issued_token_type", http.StatusOK, `{"access_token":"at","issued_token_type":"urn:ietf:params:oauth:token-type:jwt"}`, codes.Unavailable}, + {"200 with a control character in access_token", http.StatusOK, `{"access_token":"at\r\nX-Injected: 1"}`, codes.Unavailable}, + {"200 with non-ASCII in access_token", http.StatusOK, `{"access_token":"atÿ"}`, codes.Unavailable}, + {"200 with DEL in access_token", http.StatusOK, `{"access_token":"at\u007f"}`, codes.Unavailable}, + {"200 with token_type DPoP", http.StatusOK, `{"access_token":"at","token_type":"DPoP"}`, codes.Unavailable}, + {"200 with token_type N_A", http.StatusOK, `{"access_token":"at","token_type":"N_A"}`, codes.Unavailable}, + {"200 with a zero expires_in", http.StatusOK, `{"access_token":"at","expires_in":0}`, codes.Unavailable}, + {"200 with a negative expires_in", http.StatusOK, `{"access_token":"at","expires_in":-5}`, codes.Unavailable}, + {"200 over 1 MiB", http.StatusOK, `{"access_token":"at"}` + strings.Repeat(" ", maxResponseBytes), codes.Unavailable}, + } { + t.Run(tt.name, func(t *testing.T) { + srv, c := newTestServer(t, respond(tt.status, tt.body)) + _, err := c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if got := status.Code(err); got != tt.wantCode { + t.Fatalf("Exchange error = %v (code %v), want code %v", err, got, tt.wantCode) + } + if strings.Contains(err.Error(), subjectToken) { + t.Errorf("error %q contains the subject token", err) + } + }) + } +} + +func TestExchangeDoesNotFollowRedirects(t *testing.T) { + var followed atomic.Bool + srv, c := newTestServer(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Query().Has("redirected") { + followed.Store(true) + respond(http.StatusOK, `{"access_token":"at"}`)(w, r) + return + } + http.Redirect(w, r, "/token?redirected", http.StatusTemporaryRedirect) + }) + _, err := c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if got := status.Code(err); got != codes.FailedPrecondition { + t.Errorf("Exchange error = %v (code %v), want code %v", err, got, codes.FailedPrecondition) + } + if followed.Load() { + t.Error("the client followed the redirect") + } +} + +func TestExchangeRejectsPlainHTTP(t *testing.T) { + var requests atomic.Int32 + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + requests.Add(1) + respond(http.StatusOK, `{"access_token":"at"}`)(w, r) + })) + t.Cleanup(srv.Close) + c, err := New("") + if err != nil { + t.Fatalf("New: %v", err) + } + _, err = c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if got := status.Code(err); got != codes.FailedPrecondition { + t.Errorf("Exchange error = %v (code %v), want code %v", err, got, codes.FailedPrecondition) + } + if n := requests.Load(); n != 0 { + t.Errorf("the server got %d requests, want 0", n) + } +} + +func TestExchangeReportsUnparsedErrorBody(t *testing.T) { + long := strings.Repeat("b", maxDetailBytes+50) + for _, tt := range []struct { + name string + status int + body string + want string // the error's suffix after "token endpoint returned " + }{ + {"403 plain text", http.StatusForbidden, "blocked by policy", `: body "blocked by policy"`}, + {"403 with an error object", http.StatusForbidden, `{"error":{"code":403}}`, `: body "{\"error\":{\"code\":403}}"`}, + {"500 plain text", http.StatusInternalServerError, "upstream down", `: body "upstream down"`}, + {"long body is clipped", http.StatusBadGateway, long, fmt.Sprintf(": body %q", long[:maxDetailBytes])}, + {"empty body", http.StatusForbidden, "", ""}, + {"OAuth error", http.StatusForbidden, `{"error":"access_denied"}`, `: error "access_denied", error_description ""`}, + } { + t.Run(tt.name, func(t *testing.T) { + srv, c := newTestServer(t, respond(tt.status, tt.body)) + _, err := c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + want := fmt.Sprintf("token endpoint returned %d%s", tt.status, tt.want) + if got := status.Convert(err).Message(); got != want { + t.Errorf("Exchange error message = %q, want %q", got, want) + } + }) + } +} + +func TestExchangeClipsErrorDescription(t *testing.T) { + description := strings.Repeat("d", maxDetailBytes+50) + srv, c := newTestServer(t, respond(http.StatusBadRequest, fmt.Sprintf(`{"error":"invalid_request","error_description":%q}`, description))) + _, err := c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if err == nil { + t.Fatal("Exchange succeeded, want an error") + } + if !strings.Contains(err.Error(), `"`+description[:maxDetailBytes]+`"`) { + t.Errorf("error %q does not carry the description clipped to %d bytes", err, maxDetailBytes) + } +} + +func TestExchangeClipsParseError(t *testing.T) { + srv, c := newTestServer(t, respond(http.StatusOK, `{"access_token":"at","expires_in":`+strings.Repeat("9", 4096)+`}`)) + _, err := c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if status.Code(err) != codes.Unavailable || len(err.Error()) > 2*maxDetailBytes { + t.Errorf("Exchange error = %.300s... (%d bytes), want code Unavailable within %d bytes", err, len(err.Error()), 2*maxDetailBytes) + } +} + +func TestExchangeTruncatedResponse(t *testing.T) { + srv, c := newTestServer(t, func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Length", "100") + w.WriteHeader(http.StatusOK) + fmt.Fprint(w, `{"access_token"`) + }) + _, err := c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if got := status.Code(err); got != codes.Unavailable { + t.Errorf("Exchange error = %v (code %v), want code %v", err, got, codes.Unavailable) + } +} + +func TestExchangeHonorsContextDeadline(t *testing.T) { + srv, c := newTestServer(t, respond(http.StatusOK, `{"access_token":"at"}`)) + ctx, cancel := context.WithDeadline(t.Context(), time.Now()) + defer cancel() + _, err := c.Exchange(ctx, testRequest(srv.URL+"/token")) + if got := status.Code(err); got != codes.DeadlineExceeded { + t.Errorf("Exchange error = %v (code %v), want code %v", err, got, codes.DeadlineExceeded) + } +} + +func TestExchangeCanceledContext(t *testing.T) { + srv, c := newTestServer(t, respond(http.StatusOK, `{"access_token":"at"}`)) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + _, err := c.Exchange(ctx, testRequest(srv.URL+"/token")) + if got := status.Code(err); got != codes.Canceled { + t.Errorf("Exchange error = %v (code %v), want code %v", err, got, codes.Canceled) + } +} + +// roundTripFunc is an http.RoundTripper. +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } + +// ctxBody is a response body whose Read calls onRead, then waits for ctx to end +// and fails with its error. +type ctxBody struct { + ctx context.Context + onRead func() +} + +func (b ctxBody) Read([]byte) (int, error) { + b.onRead() + <-b.ctx.Done() + return 0, b.ctx.Err() +} + +func (ctxBody) Close() error { return nil } + +func TestExchangeContextEndsDuringBodyRead(t *testing.T) { + for _, tt := range []struct { + name string + // cancelOnRead cancels the context from the body read. Otherwise the + // read waits out the context's deadline on synctest's fake clock. + cancelOnRead bool + wantCode codes.Code + }{ + {"deadline", false, codes.DeadlineExceeded}, + {"cancel", true, codes.Canceled}, + } { + t.Run(tt.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + ctx, cancel := context.WithTimeout(t.Context(), time.Minute) + defer cancel() + var read bool + c := &Client{httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + return &http.Response{ + StatusCode: http.StatusOK, + Body: ctxBody{ctx: r.Context(), onRead: func() { + read = true + if tt.cancelOnRead { + cancel() + } + }}, + Request: r, + }, nil + })}} + _, err := c.Exchange(ctx, testRequest("https://sts.example/token")) + if got := status.Code(err); got != tt.wantCode { + t.Errorf("Exchange error = %v (code %v), want code %v", err, got, tt.wantCode) + } + if !read { + t.Error("Exchange did not read the response body") + } + }) + }) + } +} + +func TestExchangeUnreachableEndpoint(t *testing.T) { + srv, c := newTestServer(t, respond(http.StatusOK, `{"access_token":"at"}`)) + srv.Close() + _, err := c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if got := status.Code(err); got != codes.Unavailable { + t.Errorf("Exchange error = %v (code %v), want code %v", err, got, codes.Unavailable) + } +} + +func TestNewTrustsCAFile(t *testing.T) { + srv, trusting := newTestServer(t, respond(http.StatusOK, `{"access_token":"at"}`)) + if _, err := trusting.Exchange(t.Context(), testRequest(srv.URL+"/token")); err != nil { + t.Errorf("Exchange with the server's CA: %v", err) + } + + systemOnly, err := New("") + if err != nil { + t.Fatalf("New: %v", err) + } + _, err = systemOnly.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if got := status.Code(err); got != codes.Unavailable { + t.Errorf("Exchange without the server's CA: error = %v (code %v), want code %v", err, got, codes.Unavailable) + } +} + +func TestNewRejectsUnusableCAFile(t *testing.T) { + noCerts := filepath.Join(t.TempDir(), "empty.pem") + if err := os.WriteFile(noCerts, []byte("not a certificate\n"), 0o600); err != nil { + t.Fatal(err) + } + for name, path := range map[string]string{ + "missing file": filepath.Join(t.TempDir(), "missing.pem"), + "file without a cert": noCerts, + } { + t.Run(name, func(t *testing.T) { + if _, err := New(path); err == nil { + t.Errorf("New(%q) succeeded, want an error", path) + } + }) + } +} + +func TestExchangeAccessTokenSizeLimit(t *testing.T) { + exact := strings.Repeat("a", maxAccessTokenBytes) + srv, c := newTestServer(t, respond(http.StatusOK, fmt.Sprintf(`{"access_token":%q}`, exact))) + tok, err := c.Exchange(t.Context(), testRequest(srv.URL+"/token")) + if err != nil { + t.Fatalf("Exchange at exact limit: %v", err) + } + if tok.AccessToken != exact { + t.Errorf("AccessToken length = %d, want %d", len(tok.AccessToken), len(exact)) + } + + oversized := strings.Repeat("a", maxAccessTokenBytes+1) + srv2, c2 := newTestServer(t, respond(http.StatusOK, fmt.Sprintf(`{"access_token":%q}`, oversized))) + _, err = c2.Exchange(t.Context(), testRequest(srv2.URL+"/token")) + if got := status.Code(err); got != codes.FailedPrecondition { + t.Errorf("Exchange over limit: error = %v (code %v), want code %v", err, got, codes.FailedPrecondition) + } +} + +func TestExchangeAnchorsExpiresAtBeforeRequest(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + start := time.Now() + c := &Client{httpClient: &http.Client{Transport: roundTripFunc(func(r *http.Request) (*http.Response, error) { + time.Sleep(5 * time.Second) + return &http.Response{ + StatusCode: http.StatusOK, + Body: io.NopCloser(strings.NewReader(`{"access_token":"at","expires_in":60}`)), + Header: http.Header{}, + Request: r, + }, nil + })}} + tok, err := c.Exchange(t.Context(), testRequest("https://sts.example/token")) + if err != nil { + t.Fatalf("Exchange: %v", err) + } + if want := start.Add(60 * time.Second); !tok.ExpiresAt.Equal(want) { + t.Errorf("ExpiresAt = %v, want %v (anchored before the 5s round-trip)", tok.ExpiresAt, want) + } + }) +} diff --git a/cmd/atenet/internal/router/egressmanifest_test.go b/cmd/atenet/internal/router/egressmanifest_test.go index 20f1027d1d..efea3cbb88 100644 --- a/cmd/atenet/internal/router/egressmanifest_test.go +++ b/cmd/atenet/internal/router/egressmanifest_test.go @@ -165,7 +165,16 @@ func TestEgressManifestsSampleThePerRequestAccessLogs(t *testing.T) { if err := yaml.Unmarshal([]byte(wantSampledLogFilter), &want); err != nil { t.Fatalf("parsing wantSampledLogFilter: %v", err) } - logs := chainAccessLogsByLeg(bootstrapTree(t)) + tree := bootstrapTree(t) + // Without an admin layer, /runtime_modify fails and the keys keep their + // defaults. + if !slices.ContainsFunc(list(child(tree, "layered_runtime"), "layers"), func(l node) bool { + _, ok := l["admin_layer"] + return ok + }) { + t.Error("layered_runtime has no admin_layer, so /runtime_modify cannot set access_log.min_status or access_log.sample") + } + logs := chainAccessLogsByLeg(tree) sampledLegs := []string{"mitm", "cleartext"} for _, leg := range sampledLegs { t.Run(leg, func(t *testing.T) { diff --git a/cmd/atenet/internal/router/egresspolicymanifest_test.go b/cmd/atenet/internal/router/egresspolicymanifest_test.go index 710352c2b6..68bdf493d9 100644 --- a/cmd/atenet/internal/router/egresspolicymanifest_test.go +++ b/cmd/atenet/internal/router/egresspolicymanifest_test.go @@ -184,44 +184,70 @@ func TestEgressManifestsNameEveryExtProcChain(t *testing.T) { } } -func TestEgressManifestsDisableWebSocketUpgrades(t *testing.T) { - chains := list(mitmListener(t, bootstrapTree(t)), "filter_chains") - for _, name := range requestLegs { - chain := byName(chains, name) - if chain == nil { - t.Errorf("expected request-leg chain %q is absent", name) - continue - } - if !websocketDisabled(hcm(chain)) { - t.Errorf("chain %q must explicitly disable websocket upgrades", name) - } - var routes []node - for _, virtualHost := range list(child(hcm(chain), "route_config"), "virtual_hosts") { - routes = append(routes, list(virtualHost, "routes")...) +// On the MITM leg a WebSocket handshake has the first route, to a cluster that +// speaks only HTTP/1.1: on an HTTP/2 upstream connection Envoy sends the +// handshake as an extended CONNECT, which an origin that did not enable it +// refuses. The cluster otherwise matches egress_forward_proxy. +func TestEgressManifestsSendWebSocketUpstreamOverHTTP1(t *testing.T) { + tree := bootstrapTree(t) + chains := list(mitmListener(t, tree), "filter_chains") + var routes []node + for _, vh := range list(child(hcm(byName(chains, extproc.EgressTLSMITMFilterChainName)), "route_config"), "virtual_hosts") { + routes = append(routes, list(vh, "routes")...) + } + if len(routes) == 0 || !matchesWebSocket(child(routes[0], "match")) { + t.Fatalf("chain %q's first route does not match a WebSocket handshake; a route ahead of it could send the handshake to an HTTP/2 upstream", extproc.EgressTLSMITMFilterChainName) + } + all := clusters(tree) + name := str(child(routes[0], "route"), "cluster") + cluster := byName(all, name) + if cluster == nil { + t.Fatalf("the WebSocket route goes to cluster %q, which does not exist", name) + } + options := child(child(cluster, "typed_extension_protocol_options"), "envoy.extensions.upstreams.http.v3.HttpProtocolOptions") + explicit := child(options, "explicit_http_config") + if _, http1 := explicit["http_protocol_options"]; !http1 || len(explicit) != 1 { + t.Errorf("cluster %q is not limited to HTTP/1.1: explicit_http_config = %s", name, mustJSON(t, explicit)) + } + base := byName(all, "egress_forward_proxy") + for _, key := range []string{"cluster_type", "circuit_breakers", "transport_socket"} { + if want, got := mustJSON(t, child(base, key)), mustJSON(t, child(cluster, key)); want != got || want == "null" { + t.Errorf("cluster %q %s = %s, want egress_forward_proxy's %s", name, key, got, want) } - if len(routes) == 0 { - t.Errorf("chain %q has no routes", name) + } +} + +// Every cluster that opens TLS to an origin reads its roots from one SDS +// resource. ate-setup points that resource at an operator's bundle, and a +// cluster with roots of its own would not follow it. +func TestEgressManifestOriginClustersShareUpstreamRoots(t *testing.T) { + const resource = "egress_upstream_validation_context" + checked := 0 + for _, cluster := range clusters(bootstrapTree(t)) { + tls := child(child(cluster, "transport_socket"), "typed_config") + if str(child(cluster, "cluster_type"), "name") != "envoy.clusters.dynamic_forward_proxy" || tls == nil { + continue } - for i, route := range routes { - action := child(route, "route") - if action == nil { - t.Errorf("chain %q route %d has no route action", name, i) - continue - } - if !websocketDisabled(action) { - t.Errorf("chain %q route %d must explicitly disable websocket upgrades", name, i) - } + checked++ + // The validation context is a oneof, so a cluster that names the SDS + // resource has no roots of its own. + common := child(tls, "common_tls_context") + if got := str(child(common, "validation_context_sds_secret_config"), "name"); got != resource { + t.Errorf("cluster %q common_tls_context = %s, want the %s SDS validation context", str(cluster, "name"), mustJSON(t, common), resource) } } + if checked == 0 { + t.Fatal("no forward proxy cluster has a TLS transport socket") + } } -// websocketDisabled reports whether n's upgrade_configs turn websocket off -// explicitly. -func websocketDisabled(n node) bool { - for _, upgrade := range list(n, "upgrade_configs") { - if str(upgrade, "upgrade_type") == "websocket" { - enabled, ok := upgrade["enabled"].(bool) - return ok && !enabled +// matchesWebSocket reports whether a route match requires an Upgrade header +// naming websocket, compared the way Envoy's router compares it. +func matchesWebSocket(match node) bool { + for _, h := range list(match, "headers") { + sm := child(h, "string_match") + if ignoreCase, _ := sm["ignore_case"].(bool); ignoreCase && str(h, "name") == "upgrade" && str(sm, "exact") == "websocket" { + return true } } return false diff --git a/cmd/atenet/internal/router/egresssocketoptions_manifest_test.go b/cmd/atenet/internal/router/egresssocketoptions_manifest_test.go new file mode 100644 index 0000000000..3288b5a6cf --- /dev/null +++ b/cmd/atenet/internal/router/egresssocketoptions_manifest_test.go @@ -0,0 +1,103 @@ +// Copyright 2026 The Agent Substrate 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 router + +import ( + "testing" + + "sigs.k8s.io/yaml" +) + +// socketOption is an Envoy SocketOption as the manifest writes it. +type socketOption struct { + Level int64 `json:"level"` + Name int64 `json:"name"` + IntValue int64 `json:"int_value"` + State string `json:"state"` +} + +// notSentLowat is the TCP_NOTSENT_LOWAT value in opts, or 0, checking that it +// is set before the socket binds. +func notSentLowat(t *testing.T, where string, opts []socketOption) int64 { + t.Helper() + for _, o := range opts { + // IPPROTO_TCP and TCP_NOTSENT_LOWAT. + if o.Level == 6 && o.Name == 25 { + if o.State != "STATE_PREBIND" { + t.Errorf("%s sets TCP_NOTSENT_LOWAT in state %q, want STATE_PREBIND", where, o.State) + } + return o.IntValue + } + } + return 0 +} + +// TestEgressManifestSetsTCPNotSentLowat checks that the egress gateway sets +// TCP_NOTSENT_LOWAT on every socket it holds: the egress listener's, from +// atunnel, and every cluster's that dials destinations. A slow reader then +// backs data up behind Envoy's buffer limit rather than in a kernel send +// queue charged to the gateway's container. +func TestEgressManifestSetsTCPNotSentLowat(t *testing.T) { + var bootstrap struct { + StaticResources struct { + Listeners []struct { + Name string `json:"name"` + SocketOptions []socketOption `json:"socket_options"` + } `json:"listeners"` + Clusters []struct { + Name string `json:"name"` + ClusterType *struct { + Name string `json:"name"` + } `json:"cluster_type"` + UpstreamBindConfig *struct { + SocketOptions []socketOption `json:"socket_options"` + } `json:"upstream_bind_config"` + } `json:"clusters"` + } `json:"static_resources"` + } + if err := yaml.Unmarshal([]byte(envoyConfig(t)), &bootstrap); err != nil { + t.Fatalf("parsing envoy.yaml: %v", err) + } + listenerFound := false + for _, l := range bootstrap.StaticResources.Listeners { + if l.Name != "egress" { + continue + } + listenerFound = true + if got := notSentLowat(t, "listener egress", l.SocketOptions); got != 16384 { + t.Errorf("listener egress sets TCP_NOTSENT_LOWAT to %d, want 16384", got) + } + } + if !listenerFound { + t.Error("found no egress listener; the manifest changed shape and this test is checking nothing") + } + found := 0 + for _, c := range bootstrap.StaticResources.Clusters { + if c.ClusterType == nil || c.ClusterType.Name != "envoy.clusters.dynamic_forward_proxy" { + continue + } + found++ + var opts []socketOption + if c.UpstreamBindConfig != nil { + opts = c.UpstreamBindConfig.SocketOptions + } + if got := notSentLowat(t, "cluster "+c.Name, opts); got != 16384 { + t.Errorf("cluster %s sets TCP_NOTSENT_LOWAT to %d, want 16384", c.Name, got) + } + } + if found == 0 { + t.Fatal("found no dynamic_forward_proxy cluster; the manifest changed shape and this test is checking nothing") + } +} diff --git a/cmd/atenet/internal/router/envoyadmin_manifest_test.go b/cmd/atenet/internal/router/envoyadmin_manifest_test.go index 6f7bb578da..4455c5ac56 100644 --- a/cmd/atenet/internal/router/envoyadmin_manifest_test.go +++ b/cmd/atenet/internal/router/envoyadmin_manifest_test.go @@ -75,6 +75,7 @@ type envoyAdminBootstrap struct { } `json:"listeners"` Clusters []struct { Name string `json:"name"` + Type string `json:"type"` LoadAssignment struct { Endpoints []struct { LbEndpoints []struct { diff --git a/cmd/atenet/internal/router/extproc/egress_websocket_test.go b/cmd/atenet/internal/router/extproc/egress_websocket_test.go index 738d87c74b..6baabdd27d 100644 --- a/cmd/atenet/internal/router/extproc/egress_websocket_test.go +++ b/cmd/atenet/internal/router/extproc/egress_websocket_test.go @@ -27,7 +27,7 @@ import ( "go.ate.dev/substrate/cmd/atenet/internal/router/extproc" ) -const websocketDenialBody = "WebSocket egress is not supported" +const upgradeDenialBody = "Only WebSocket upgrades are supported" type websocketProcessStream struct { extprocv3.ExternalProcessor_ProcessServer @@ -52,7 +52,9 @@ func (s *websocketProcessStream) Send(resp *extprocv3.ProcessingResponse) error return nil } -func TestProcessReturnsWebSocketDenialAsImmediateResponse(t *testing.T) { +// Process runs the egress handler on each request it receives and sends back +// the refusal of an upgrade other than WebSocket as an immediate response. +func TestProcessReturnsUpgradeDenialAsImmediateResponse(t *testing.T) { for _, leg := range []string{extproc.EgressCleartextFilterChainName, extproc.EgressTLSMITMFilterChainName} { t.Run(leg, func(t *testing.T) { request := &extprocv3.ProcessingRequest{ @@ -62,7 +64,7 @@ func TestProcessReturnsWebSocketDenialAsImmediateResponse(t *testing.T) { {Key: ":method", RawValue: []byte("GET")}, {Key: ":authority", RawValue: []byte("api.example.com")}, {Key: "connection", RawValue: []byte("keep-alive, Upgrade")}, - {Key: "upgrade", RawValue: []byte("websocket")}, + {Key: "upgrade", RawValue: []byte("foo")}, }}, }, }, @@ -90,8 +92,8 @@ func TestProcessReturnsWebSocketDenialAsImmediateResponse(t *testing.T) { if got := response.GetStatus().GetCode(); got != 403 { t.Errorf("status = %d, want 403", got) } - if got := string(response.GetBody()); got != websocketDenialBody { - t.Errorf("body = %q, want %q", got, websocketDenialBody) + if got := string(response.GetBody()); got != upgradeDenialBody { + t.Errorf("body = %q, want %q", got, upgradeDenialBody) } }) } diff --git a/cmd/atenet/internal/router/ingress/errors.go b/cmd/atenet/internal/router/ingress/errors.go index feb001ab4d..b6c0149539 100644 --- a/cmd/atenet/internal/router/ingress/errors.go +++ b/cmd/atenet/internal/router/ingress/errors.go @@ -73,6 +73,13 @@ func parkingFullErr(actorID string, retryErr error) error { "actor %q unavailable: router at capacity", actorID) } +// stillResumingErr tells the client the actor is still resuming and to retry. +// It wraps context.DeadlineExceeded so metrics count it as a timeout. +func stillResumingErr(actorRef resources.ActorRef) error { + return extproc.WrapReqError(envoy_type.StatusCode_ServiceUnavailable, context.DeadlineExceeded, + "actor %s is still resuming, retry", actorRef) +} + // mapResumeError translates an ActorResumer error into a client-facing // denial. It maps gRPC status codes to appropriate HTTP status codes and // short, human-readable bodies. The original error is preserved via Unwrap diff --git a/cmd/atenet/internal/router/ingress/resumer.go b/cmd/atenet/internal/router/ingress/resumer.go index ac63003a40..a0f001188b 100644 --- a/cmd/atenet/internal/router/ingress/resumer.go +++ b/cmd/atenet/internal/router/ingress/resumer.go @@ -36,6 +36,15 @@ import ( // conflicts are retried; capacity errors fail immediately. const failFastResumeBudget = 15 * time.Second +// ExtProcTimeoutMargin is how much longer than the park budget Envoy waits for +// the router's reply. +const ExtProcTimeoutMargin = 5 * time.Second + +// routerExtProcTimeout is how much longer than the park budget the router +// waits before answering. It must be less than ExtProcTimeoutMargin: if +// Envoy's timeout fires first, Envoy sends the client an empty 504. +const routerExtProcTimeout = ExtProcTimeoutMargin - time.Second + // resumeBackoff builds the backoff between resume attempts while a request is // parked, from the configured retry parameters. // @@ -271,12 +280,19 @@ func flightResult(bgCtx context.Context, resumeResp *ateapi.ResumeActorResponse, // flight is retrying (or already was), the caller must hold a parking-lot slot // to keep waiting and is shed with a 503 when the lot is full. func (r *ActorResumer) awaitFlight(ctx context.Context, f *resumeActorFlight, actorRef resources.ActorRef, reqID uint64) (*ateapi.Actor, ResumeOutcome, error) { + // If the flight is still running just before Envoy's ext_proc timeout, the + // router ends the wait itself and sends the client a 503. Without this, + // Envoy would end the request with a 504 and no useful error message. The flight + // keeps going, and later requests join it. + maxWait := r.budget + routerExtProcTimeout + waitCtx, cancel := context.WithTimeout(ctx, maxWait) + defer cancel() + select { - case <-ctx.Done(): - // The caller's request context was canceled before the shared resume - // completed. The flight continues and may still activate the actor, so - // the outcome is "unknown", not "none". - return nil, ResumeOutcomeUnknown, ctx.Err() + case <-waitCtx.Done(): + // The caller stopped waiting, but the flight may still resume the + // actor, so the outcome is "unknown". + return nil, ResumeOutcomeUnknown, waitErr(ctx, actorRef) case <-f.done: // Fast path: the flight finished without ever retrying, or before this // caller saw retrying. The lot is never touched. @@ -303,8 +319,8 @@ func (r *ActorResumer) awaitFlight(ctx context.Context, f *resumeActorFlight, ac defer func() { release(parkOutcomeFor(finalErr)) }() select { - case <-ctx.Done(): - finalErr = ctx.Err() + case <-waitCtx.Done(): + finalErr = waitErr(ctx, actorRef) return nil, ResumeOutcomeUnknown, finalErr case <-f.done: actor, outcome, err := f.callerResult(reqID) @@ -313,6 +329,15 @@ func (r *ActorResumer) awaitFlight(ctx context.Context, f *resumeActorFlight, ac } } +// waitErr returns ctx's error if the request itself ended, or stillResumingErr +// if the router stopped waiting first. +func waitErr(ctx context.Context, actorRef resources.ActorRef) error { + if err := ctx.Err(); err != nil { + return err + } + return stillResumingErr(actorRef) +} + // enterLot admits the caller to the parking lot, treating a nil lot as // unbounded (no admission control). shedOutcome labels the rejection if the // lot is full. diff --git a/cmd/atenet/internal/router/ingress/resumer_test.go b/cmd/atenet/internal/router/ingress/resumer_test.go index 1bab54d649..f10023eb3b 100644 --- a/cmd/atenet/internal/router/ingress/resumer_test.go +++ b/cmd/atenet/internal/router/ingress/resumer_test.go @@ -505,6 +505,73 @@ func TestActorResumer_Parking(t *testing.T) { }) }) + t.Run("CallerStopsWaitingBeforeEnvoyTimeout", func(t *testing.T) { + for _, tc := range []struct { + name string + // firstErr, if set, fails the first attempt so the caller parks + // before the slow one. + firstErr error + wantCalls int32 + }{ + {"Resolving", nil, 1}, + {"Parked", status.Error(codes.ResourceExhausted, "no worker has room for the actor"), 2}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + const budget = 5 * time.Second + var calls atomic.Int32 + proceed := make(chan struct{}) + mock := &resumerMockClient{ + resumeFn: func(context.Context, *ateapi.ResumeActorRequest, ...grpc.CallOption) (*ateapi.ResumeActorResponse, error) { + if calls.Add(1) == 1 && tc.firstErr != nil { + return nil, tc.firstErr + } + // A restore slower than Envoy's timeout. + <-proceed + return &ateapi.ResumeActorResponse{ + Actor: &ateapi.Actor{Metadata: &ateapi.ResourceMetadata{Name: testActorName}, Status: &ateapi.ActorStatus{State: ateapi.ActorState_ACTOR_STATE_RUNNING, WorkerAssignment: &ateapi.WorkerAssignment{WorkerPodIps: []string{expectedIP}}}}, + Resumed: true, + }, nil + }, + } + resumer := NewActorResumer(mock, withParking(ParkedRequestConfig{Max: 2, Budget: budget})) + + // Envoy closes the stream at its timeout. + envoyTimeout := budget + ExtProcTimeoutMargin + ctx, cancel := context.WithTimeout(t.Context(), envoyTimeout) + defer cancel() + start := time.Now() + _, _, err := resumer.ResumeActor(ctx, testActorRef) + if waited := time.Since(start); waited >= envoyTimeout { + t.Errorf("caller waited %v, want less than Envoy's %v timeout", waited, envoyTimeout) + } + var reqErr *extproc.ReqError + if !errors.As(err, &reqErr) || reqErr.StatusCode != int(envoy_type.StatusCode_ServiceUnavailable) { + t.Fatalf("expected the router's 503, got %v", err) + } + if got := parkOutcomeFor(err); got != parkOutcomeTimeout { + t.Errorf("outcome = %q, want %q", got, parkOutcomeTimeout) + } + + // A later caller joins the running attempt and is served. + errCh := make(chan error, 1) + go func() { + _, _, err := resumer.ResumeActor(t.Context(), testActorRef) + errCh <- err + }() + synctest.Wait() + close(proceed) + if err := <-errCh; err != nil { + t.Fatalf("later caller: unexpected error: %v", err) + } + if got := calls.Load(); got != tc.wantCalls { + t.Errorf("expected %d resume attempts, got %d", tc.wantCalls, got) + } + }) + }) + } + }) + t.Run("LateNonRetryableErrorIsPreserved", func(t *testing.T) { for _, tc := range []struct { name string diff --git a/cmd/atenet/internal/router/router.go b/cmd/atenet/internal/router/router.go index c559ea4d49..175dac759a 100644 --- a/cmd/atenet/internal/router/router.go +++ b/cmd/atenet/internal/router/router.go @@ -39,6 +39,7 @@ import ( "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/api/credprovider/v1" "go.ate.dev/substrate/cmd/atenet/internal/router/egress" + "go.ate.dev/substrate/cmd/atenet/internal/router/egress/tokenexchange" "go.ate.dev/substrate/cmd/atenet/internal/router/extproc" "go.ate.dev/substrate/cmd/atenet/internal/router/ingress" "go.ate.dev/substrate/internal/ateapiauth" @@ -46,6 +47,7 @@ import ( "go.ate.dev/substrate/internal/k8sresolver" "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/serverboot" + "go.ate.dev/substrate/internal/serverboot/pprofserver" "go.ate.dev/substrate/internal/version" ) @@ -70,6 +72,9 @@ type RouterServer struct { } func NewRouterServer(cfg routerConfig) (*RouterServer, error) { + if cfg.Gates == nil { + return nil, errors.New("routerConfig.Gates must be set") + } var clientset kubernetes.Interface // Only ingress needs Kubernetes: the EndpointSlice resolver for the ateapi @@ -166,6 +171,7 @@ func (s *RouterServer) Run(ctx context.Context) error { // stays 200 for liveness. readiness := &serverboot.Readiness{} go serverboot.StartMetricsServer(ctx, s.cfg.MetricsAddr) + go pprofserver.Start(ctx, s.cfg.Pprof) go serverboot.StartHealthServer(ctx, s.cfg.HealthAddr, readiness) dialOpts, err := ateapiauth.DialOptions(ateapiauth.ClientConfig{ @@ -255,6 +261,12 @@ func (s *RouterServer) Run(ctx context.Context) error { slog.String("provider_name", providerName)) } + // TODO(#1661): pass the client to egress.New once the handler injects + // exchanged tokens. + if _, err := tokenexchange.New(s.cfg.TokenExchangeCAFile); err != nil { + return fmt.Errorf("loading --token-exchange-ca-file: %w", err) + } + egressHandler := egress.New(s.apiClient, loadActorIdentityRoots, s.cfg.EgressPolicyCacheTTL, providers) handlers[egressHandler.Direction()] = egressHandler } diff --git a/cmd/atenet/internal/router/socketoptions.go b/cmd/atenet/internal/router/socketoptions.go new file mode 100644 index 0000000000..398e06cb1c --- /dev/null +++ b/cmd/atenet/internal/router/socketoptions.go @@ -0,0 +1,52 @@ +// Copyright 2026 The Agent Substrate 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 router + +import ( + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" +) + +// TCP_NOTSENT_LOWAT's socket option level and name. Envoy takes them as +// numbers, and the router also builds on platforms whose syscall package lacks +// them. +const ( + ipprotoTCP = 6 // IPPROTO_TCP + tcpNotsentLowat = 25 // TCP_NOTSENT_LOWAT +) + +// notSentLowatBytes is the TCP_NOTSENT_LOWAT of Envoy's client and atunnel +// sockets, so a slow reader's backlog stays in Envoy's buffers, not in the +// kernel send queue. +const notSentLowatBytes = 16384 + +// notSentLowatSocketOptions returns the Envoy socket options that set +// TCP_NOTSENT_LOWAT to notSentLowatBytes. Connections a listening socket +// accepts inherit them. Internal listeners and clusters have no kernel +// sockets and get none. +func notSentLowatSocketOptions() []*corev3.SocketOption { + return []*corev3.SocketOption{{ + Description: "TCP_NOTSENT_LOWAT", + Level: ipprotoTCP, + Name: tcpNotsentLowat, + Value: &corev3.SocketOption_IntValue{IntValue: notSentLowatBytes}, + State: corev3.SocketOption_STATE_PREBIND, + }} +} + +// notSentLowatBindConfig returns the cluster bind config that sets +// TCP_NOTSENT_LOWAT to notSentLowatBytes. +func notSentLowatBindConfig() *corev3.BindConfig { + return &corev3.BindConfig{SocketOptions: notSentLowatSocketOptions()} +} diff --git a/cmd/atenet/internal/router/socketoptions_test.go b/cmd/atenet/internal/router/socketoptions_test.go new file mode 100644 index 0000000000..dc22af9c73 --- /dev/null +++ b/cmd/atenet/internal/router/socketoptions_test.go @@ -0,0 +1,102 @@ +// Copyright 2026 The Agent Substrate 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 router + +import ( + "testing" + + clusterv3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" + corev3 "github.com/envoyproxy/go-control-plane/envoy/config/core/v3" + listenerv3 "github.com/envoyproxy/go-control-plane/envoy/config/listener/v3" + resourcev3 "github.com/envoyproxy/go-control-plane/pkg/resource/v3" + "github.com/google/go-cmp/cmp" + "google.golang.org/protobuf/testing/protocmp" +) + +func TestNotSentLowatSocketOptions(t *testing.T) { + want := []*corev3.SocketOption{ + {Description: "TCP_NOTSENT_LOWAT", Level: 6, Name: 25, Value: &corev3.SocketOption_IntValue{IntValue: 16384}, State: corev3.SocketOption_STATE_PREBIND}, + } + if diff := cmp.Diff(want, notSentLowatSocketOptions(), protocmp.Transform()); diff != "" { + t.Errorf("notSentLowatSocketOptions() mismatch (-want +got):\n%s", diff) + } + if diff := cmp.Diff(&corev3.BindConfig{SocketOptions: want}, notSentLowatBindConfig(), protocmp.Transform()); diff != "" { + t.Errorf("notSentLowatBindConfig() mismatch (-want +got):\n%s", diff) + } +} + +// tcpOptionsSnapshot builds the default ingress snapshot, with both TLS +// listeners and upstream CONNECT. +func tcpOptionsSnapshot(t *testing.T, upstreamConnect bool) (map[string]*listenerv3.Listener, map[string]*clusterv3.Cluster) { + t.Helper() + server := NewXdsServer(18000) + server.SetConfig(50053, "127.0.0.1") + server.SetConnectTLSPort(8444) + setIngressTLS(server) + server.SetUpstreamTls("/run/bundle.pem", "/run/trust.pem") + server.SetUpstreamConnect(upstreamConnect) + listeners := snapshotListeners(t, server) + res, err := server.snapshot.GetSnapshot(NodeID) + if err != nil { + t.Fatal(err) + } + clusters := map[string]*clusterv3.Cluster{} + for name, raw := range res.GetResources(resourcev3.ClusterType) { + clusters[name] = raw.(*clusterv3.Cluster) + } + return listeners, clusters +} + +func TestXdsServer_TCPNotSentLowat(t *testing.T) { + for _, upstreamConnect := range []bool{true, false} { + listeners, clusters := tcpOptionsSnapshot(t, upstreamConnect) + + // Only listeners with kernel sockets get the options. + for name, l := range listeners { + want := []*corev3.SocketOption(nil) + if name == IngressHTTPSListener || name == "connect_terminate_tls" { + want = notSentLowatSocketOptions() + } + if diff := cmp.Diff(want, l.GetSocketOptions(), protocmp.Transform()); diff != "" { + t.Errorf("upstreamConnect=%t: listener %s socket options mismatch (-want +got):\n%s", upstreamConnect, name, diff) + } + // The dual-stack address inherits the listener's options only + // while it sets none of its own. + for _, a := range l.GetAdditionalAddresses() { + if a.GetSocketOptions() != nil { + t.Errorf("upstreamConnect=%t: listener %s additional address overrides the socket options", upstreamConnect, name) + } + } + } + + // Only the clusters that dial atunnel get the options. + actorCluster := OriginalDstClusterName + if upstreamConnect { + actorCluster = ActorConnectName + } + if _, ok := clusters[actorCluster]; !ok { + t.Fatalf("upstreamConnect=%t: snapshot has no %s cluster", upstreamConnect, actorCluster) + } + for name, c := range clusters { + want := (*corev3.BindConfig)(nil) + if name == actorCluster { + want = notSentLowatBindConfig() + } + if diff := cmp.Diff(want, c.GetUpstreamBindConfig(), protocmp.Transform()); diff != "" { + t.Errorf("upstreamConnect=%t: cluster %s bind config mismatch (-want +got):\n%s", upstreamConnect, name, diff) + } + } + } +} diff --git a/cmd/atenet/internal/router/status_test.go b/cmd/atenet/internal/router/status_test.go index 0e731108bc..2f8e09a250 100644 --- a/cmd/atenet/internal/router/status_test.go +++ b/cmd/atenet/internal/router/status_test.go @@ -38,6 +38,7 @@ import ( "go.ate.dev/substrate/cmd/atenet/internal/router/extproc" "go.ate.dev/substrate/cmd/atenet/internal/router/ingress" + "go.ate.dev/substrate/internal/preview" ) func TestStatuszEndpoint(t *testing.T) { @@ -60,11 +61,12 @@ func TestStatuszEndpoint(t *testing.T) { // Run() dials ateapi in mtls mode, which requires real TLS material; generate it. caPath, clientCertPath := writeTestTLSMaterial(t) - statusAddr, err := NewRouterCmd().Flags().GetString("status-address") + statusAddr, err := NewRouterCmd(nil).Flags().GetString("status-address") if err != nil { t.Fatal(err) } cfg := routerConfig{ + Gates: preview.NewForTest(t), Mode: ModeIngress, Namespace: "default", StatusPort: httpPort, diff --git a/cmd/atenet/internal/router/xds.go b/cmd/atenet/internal/router/xds.go index 80c9aa6133..525050f271 100644 --- a/cmd/atenet/internal/router/xds.go +++ b/cmd/atenet/internal/router/xds.go @@ -17,6 +17,7 @@ package router import ( "context" "crypto/rand" + "encoding/json" "fmt" "log/slog" "net" @@ -46,11 +47,14 @@ import ( routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" tracev3 "github.com/envoyproxy/go-control-plane/envoy/config/trace/v3" streamaccesslogv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/access_loggers/stream/v3" + dynamicmodulesv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/dynamic_modules/v3" setfilterstatecommonv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/common/set_filter_state/v3" + httpdynamicmodulesv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/dynamic_modules/v3" extprocv3filter "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ext_proc/v3" routerv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/router/v3" setfilterstatev3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/set_filter_state/v3" originaldstv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/listener/original_dst/v3" + networkdynamicmodulesv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/dynamic_modules/v3" hcmv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" setfilterstatenetworkv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/set_filter_state/v3" tcpproxyv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/tcp_proxy/v3" @@ -124,6 +128,37 @@ const ( // httpExtProcFilterName is envoy.filters.http.ext_proc's own well-known // name, used as the HttpFilter.Name in buildHcm. httpExtProcFilterName = "envoy.filters.http.ext_proc" + + // httpDynamicModulesFilterName is envoy.filters.http.dynamic_modules's + // well-known name, used as the HttpFilter.Name in buildHcm. + httpDynamicModulesFilterName = "envoy.filters.http.dynamic_modules" + + // ingressCacheDynamicModuleName is the shared library and filter name for + // the ingress-cache dynamic module. + ingressCacheDynamicModuleName = "envoy_substrate_ingress_cache" + + // networkDynamicModulesFilterName is envoy.filters.network.dynamic_modules's + // well-known name. + networkDynamicModulesFilterName = "envoy.filters.network.dynamic_modules" + + // ingressCacheTunnelWatcherFilterName is the ingress-cache module's network + // filter. It marks cache entries from what happens to the CONNECT tunnels + // they route to, so the HTTP filter can tell a refused tunnel from one cut + // off mid-request. It must load from the same library as the HTTP filter, + // which shares its per-thread cache. + ingressCacheTunnelWatcherFilterName = "tunnel_watcher" + + // DefaultIngressCacheTTL is --ingress-cache-ttl's default. + DefaultIngressCacheTTL = 5 * time.Second + // DefaultIngressCacheMaxCachedActors is --ingress-cache-max-cached-actors's default. + DefaultIngressCacheMaxCachedActors = 10000 + + // The ingress-cache dynamic module sets this dynamic metadata on a cache hit + // so route selection picks the route that disables ext_proc. Clients can't + // set dynamic metadata. + cacheHitMetadataNamespace = "ate.ingress_cache" + cacheHitMetadataKey = "hit" + cacheHitMetadataValue = "true" ) // defaultExtProcMessageTimeout is Envoy's per-message ext_proc response timeout @@ -252,6 +287,9 @@ type XdsServer struct { upstreamTrustBundlePath string // upstreamConnect: see SetUpstreamConnect. upstreamConnect bool + // ingressCache, ingressCacheConfig: see SetIngressCache. + ingressCache bool + ingressCacheConfig IngressCacheConfig // Downstream (client-facing) mTLS. Every TLS ingress listener requires a // client certificate that chains to downstreamClientCAPath and carries @@ -424,6 +462,56 @@ func (x *XdsServer) SetUpstreamConnect(enabled bool) { x.upstreamConnect = enabled } +// IngressCacheConfig is the ingress-cache filter's configuration. +type IngressCacheConfig struct { + // TTL is how long a binding is served from the cache. It's a whole number + // of seconds. + TTL time.Duration + // MaxCachedActors is the most actors cached per Envoy worker thread. Each + // thread has its own cache. + MaxCachedActors int +} + +// validate checks the flags cfg comes from. +func (cfg IngressCacheConfig) validate() error { + if cfg.TTL < time.Second || cfg.TTL%time.Second != 0 { + return fmt.Errorf("--ingress-cache-ttl must be a whole number of seconds, at least 1s, got %s", cfg.TTL) + } + if cfg.MaxCachedActors < 1 { + return fmt.Errorf("--ingress-cache-max-cached-actors must be at least 1, got %d", cfg.MaxCachedActors) + } + return nil +} + +// SetIngressCache installs the ingress-cache filter, configured by cfg, and, +// for each workload route, a copy that matches the cache-hit dynamic metadata and skips +// ext_proc. With upstream CONNECT it also installs the tunnel_watcher network +// filter on actor_connect. When disabled, none of these exist, so every +// request is resolved by ext_proc. +func (x *XdsServer) SetIngressCache(enabled bool, cfg IngressCacheConfig) { + x.mu.Lock() + defer x.mu.Unlock() + x.ingressCache = enabled + x.ingressCacheConfig = cfg +} + +// ingressCacheFilterConfig is the ingress-cache module's JSON filter config +// (Config in cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/config.rs). +// Envoy passes a StringValue to the module without the wrapper. +func (x *XdsServer) ingressCacheFilterConfig() *anypb.Any { + cfg, err := json.Marshal(struct { + CacheTTLSeconds int64 `json:"cache_ttl_seconds"` + MaxCachedActors int `json:"max_cached_actors"` + }{ + CacheTTLSeconds: int64(x.ingressCacheConfig.TTL / time.Second), + MaxCachedActors: x.ingressCacheConfig.MaxCachedActors, + }) + if err != nil { + panic(fmt.Sprintf("marshaling the ingress-cache filter config: %v", err)) + } + return newAny(wrapperspb.String(string(cfg))) +} + // SetOtlpCollector enables Envoy-side tracing pointed at the OTLP gRPC // collector. addr empty disables tracing. See normalizeOtlpCollector for the // accepted forms. @@ -563,7 +651,7 @@ func (x *XdsServer) UpdateSnapshot() error { // Listeners var listeners []types.Resource if x.upstreamConnect { - listeners = append(listeners, buildActorConnectListener()) + listeners = append(listeners, buildActorConnectListener(x.ingressCache)) } if connectEnabled { listeners = append(listeners, x.buildMainInternalListener()) @@ -878,8 +966,9 @@ func (x *XdsServer) buildMainInternalCluster() *clusterv3.Cluster { // the shared upstream transport socket (SPIFFE URI validation). func (x *XdsServer) buildOriginalDstCluster() *clusterv3.Cluster { cluster := &clusterv3.Cluster{ - Name: OriginalDstClusterName, - ConnectTimeout: durationpb.New(5 * time.Second), + Name: OriginalDstClusterName, + ConnectTimeout: durationpb.New(5 * time.Second), + UpstreamBindConfig: notSentLowatBindConfig(), ClusterDiscoveryType: &clusterv3.Cluster_Type{ Type: clusterv3.Cluster_ORIGINAL_DST, }, @@ -973,8 +1062,9 @@ func buildActorTunnelCluster(name string, http2 bool) *clusterv3.Cluster { // connection. func (x *XdsServer) buildActorConnectCluster() *clusterv3.Cluster { return &clusterv3.Cluster{ - Name: ActorConnectName, - ConnectTimeout: durationpb.New(5 * time.Second), + Name: ActorConnectName, + ConnectTimeout: durationpb.New(5 * time.Second), + UpstreamBindConfig: notSentLowatBindConfig(), ClusterDiscoveryType: &clusterv3.Cluster_Type{ Type: clusterv3.Cluster_ORIGINAL_DST, }, @@ -1012,28 +1102,26 @@ func (x *XdsServer) buildRoutes() *routev3.RouteConfiguration { if x.upstreamConnect { routes = x.buildActorTunnelRoutes() } else { - routes = []*routev3.Route{ - { - Match: &routev3.RouteMatch{ - PathSpecifier: &routev3.RouteMatch_Prefix{ - Prefix: "/", - }, - }, - Action: &routev3.Route_Route{ - Route: x.workloadRouteAction(OriginalDstClusterName), + routes = x.withCachedRoute(&routev3.Route{ + Match: &routev3.RouteMatch{ + PathSpecifier: &routev3.RouteMatch_Prefix{ + Prefix: "/", }, - RequestHeadersToAdd: []*corev3.HeaderValueOption{ - { - Header: &corev3.HeaderValue{ - Key: atunnelingress.TargetPortHeader, - Value: fmt.Sprintf("%%DYNAMIC_METADATA(%s:%s)%%", - ingress.OriginalDstMetadataKey, ingress.OriginalDstPortKey), - }, - AppendAction: corev3.HeaderValueOption_OVERWRITE_IF_EXISTS_OR_ADD, + }, + Action: &routev3.Route_Route{ + Route: x.workloadRouteAction(OriginalDstClusterName), + }, + RequestHeadersToAdd: []*corev3.HeaderValueOption{ + { + Header: &corev3.HeaderValue{ + Key: atunnelingress.TargetPortHeader, + Value: fmt.Sprintf("%%DYNAMIC_METADATA(%s:%s)%%", + ingress.OriginalDstMetadataKey, ingress.OriginalDstPortKey), }, + AppendAction: corev3.HeaderValueOption_OVERWRITE_IF_EXISTS_OR_ADD, }, }, - } + }) } return &routev3.RouteConfiguration{ Name: RouteName, @@ -1047,6 +1135,37 @@ func (x *XdsServer) buildRoutes() *routev3.RouteConfiguration { } } +// withCachedRoute returns a pair of routes: a copy of r that matches the +// cache-hit dynamic metadata and disables ext_proc, followed by r itself. +// Without the ingress cache it returns r alone, so no route skips ext_proc. +func (x *XdsServer) withCachedRoute(r *routev3.Route) []*routev3.Route { + if !x.ingressCache { + return []*routev3.Route{r} + } + cached := proto.Clone(r).(*routev3.Route) + cached.Match.DynamicMetadata = []*matcherv3.MetadataMatcher{{ + Filter: cacheHitMetadataNamespace, + Path: []*matcherv3.MetadataMatcher_PathSegment{{ + Segment: &matcherv3.MetadataMatcher_PathSegment_Key{Key: cacheHitMetadataKey}, + }}, + Value: &matcherv3.ValueMatcher{ + MatchPattern: &matcherv3.ValueMatcher_StringMatch{ + StringMatch: &matcherv3.StringMatcher{ + MatchPattern: &matcherv3.StringMatcher_Exact{Exact: cacheHitMetadataValue}, + }, + }, + }, + }} + cached.TypedPerFilterConfig = map[string]*anypb.Any{ + httpExtProcFilterName: newAny(&extprocv3filter.ExtProcPerRoute{ + Override: &extprocv3filter.ExtProcPerRoute_Disabled{ + Disabled: true, + }, + }), + } + return []*routev3.Route{cached, r} +} + func (x *XdsServer) workloadRouteAction(cluster string) *routev3.RouteAction { return &routev3.RouteAction{ ClusterSpecifier: &routev3.RouteAction_Cluster{ @@ -1103,10 +1222,8 @@ func (x *XdsServer) buildActorTunnelRoutes() []*routev3.Route { }, }, } - return []*routev3.Route{ - route(ActorTunnelHTTP2ClusterName, grpcHeaders...), - route(ActorTunnelHTTP1ClusterName), - } + routes := x.withCachedRoute(route(ActorTunnelHTTP2ClusterName, grpcHeaders...)) + return append(routes, x.withCachedRoute(route(ActorTunnelHTTP1ClusterName))...) } func (x *XdsServer) buildMainInternalListener() *listenerv3.Listener { @@ -1226,9 +1343,10 @@ func workerIdentityFilterStateFilter() *hcmv3.HttpFilter { // buildActorConnectListener turns each connection from an actor_tunnel cluster // into a CONNECT to atunnel, which takes the port from the authority and -// ignores the host. -func buildActorConnectListener() *listenerv3.Listener { - return &listenerv3.Listener{ +// ignores the host. With ingressCache, the tunnel_watcher network filter +// runs ahead of tcp_proxy. +func buildActorConnectListener(ingressCache bool) *listenerv3.Listener { + listener := &listenerv3.Listener{ Name: ActorConnectName, ListenerSpecifier: &listenerv3.Listener_InternalListener{ InternalListener: &listenerv3.Listener_InternalListenerConfig{}, @@ -1284,6 +1402,29 @@ func buildActorConnectListener() *listenerv3.Listener { }, }, } + if ingressCache { + chain := listener.GetFilterChains()[0] + proxy := chain.Filters[len(chain.Filters)-1] + chain.Filters = append(chain.Filters[:len(chain.Filters)-1], ingressCacheTunnelWatcherFilter(), proxy) + } + return listener +} + +// ingressCacheTunnelWatcherFilter is the ingress-cache module's network filter for +// actor_connect. It must run ahead of tcp_proxy to see the tunnel's bytes and +// close; see ingressCacheTunnelWatcherFilterName. +func ingressCacheTunnelWatcherFilter() *listenerv3.Filter { + return &listenerv3.Filter{ + Name: networkDynamicModulesFilterName, + ConfigType: &listenerv3.Filter_TypedConfig{ + TypedConfig: newAny(&networkdynamicmodulesv3.DynamicModuleNetworkFilter{ + DynamicModuleConfig: &dynamicmodulesv3.DynamicModuleConfig{ + Name: ingressCacheDynamicModuleName, + }, + FilterName: ingressCacheTunnelWatcherFilterName, + }), + }, + } } func (x *XdsServer) buildConnectTerminateHCM(statPrefix string) *anypb.Any { @@ -1410,12 +1551,28 @@ func (x *XdsServer) buildHcm(statPrefix string, captureActorRouting bool) *anypb if captureActorRouting { httpFilters = append(httpFilters, actorRoutingFilterStateFilter(false)) } - httpFilters = append(httpFilters, &hcmv3.HttpFilter{ - Name: httpExtProcFilterName, - ConfigType: &hcmv3.HttpFilter_TypedConfig{ - TypedConfig: extProcConfig, + if x.ingressCache { + httpFilters = append(httpFilters, &hcmv3.HttpFilter{ + Name: httpDynamicModulesFilterName, + ConfigType: &hcmv3.HttpFilter_TypedConfig{ + TypedConfig: newAny(&httpdynamicmodulesv3.DynamicModuleFilter{ + DynamicModuleConfig: &dynamicmodulesv3.DynamicModuleConfig{ + Name: ingressCacheDynamicModuleName, + }, + FilterName: ingressCacheDynamicModuleName, + FilterConfig: x.ingressCacheFilterConfig(), + }), + }, + }) + } + httpFilters = append(httpFilters, + &hcmv3.HttpFilter{ + Name: httpExtProcFilterName, + ConfigType: &hcmv3.HttpFilter_TypedConfig{ + TypedConfig: extProcConfig, + }, }, - }) + ) if x.upstreamConnect { httpFilters = append(httpFilters, actorTunnelFilterStateFilter()) } @@ -1572,7 +1729,8 @@ func (x *XdsServer) buildHttpsListener() *listenerv3.Listener { alpn := []string{"h2", "http/1.1"} return &listenerv3.Listener{ - Name: IngressHTTPSListener, + Name: IngressHTTPSListener, + SocketOptions: notSentLowatSocketOptions(), Address: &corev3.Address{ Address: &corev3.Address_SocketAddress{ SocketAddress: &corev3.SocketAddress{ @@ -1607,7 +1765,8 @@ func (x *XdsServer) buildConnectTerminateTLSListener() *listenerv3.Listener { hcm := x.buildConnectTerminateHCM("connect_terminate_tls") return &listenerv3.Listener{ - Name: "connect_terminate_tls", + Name: "connect_terminate_tls", + SocketOptions: notSentLowatSocketOptions(), Address: &corev3.Address{ Address: &corev3.Address_SocketAddress{ SocketAddress: &corev3.SocketAddress{ diff --git a/cmd/atenet/internal/router/xds_listen_test.go b/cmd/atenet/internal/router/xds_listen_test.go index 8721abb5a9..2eb415fe02 100644 --- a/cmd/atenet/internal/router/xds_listen_test.go +++ b/cmd/atenet/internal/router/xds_listen_test.go @@ -83,6 +83,9 @@ func TestXdsManifestIsLoopbackOnly(t *testing.T) { if cl.Name != "xds_cluster" { continue } + if cl.Type != "STATIC" { + t.Errorf("Envoy xds_cluster has type %q; it dials a loopback IP, so it must be STATIC", cl.Type) + } for _, ep := range cl.LoadAssignment.Endpoints { for _, lb := range ep.LbEndpoints { sa := lb.Endpoint.Address.SocketAddress diff --git a/cmd/atenet/internal/router/xds_test.go b/cmd/atenet/internal/router/xds_test.go index c7fcf8cdb1..aef988c41f 100644 --- a/cmd/atenet/internal/router/xds_test.go +++ b/cmd/atenet/internal/router/xds_test.go @@ -28,12 +28,14 @@ import ( "os" "path/filepath" "slices" + "strconv" "strings" "testing" "time" "google.golang.org/grpc" "google.golang.org/grpc/credentials/insecure" + "google.golang.org/protobuf/types/known/wrapperspb" "sigs.k8s.io/yaml" clusterv3 "github.com/envoyproxy/go-control-plane/envoy/config/cluster/v3" @@ -42,6 +44,8 @@ import ( routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" streamaccesslogv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/access_loggers/stream/v3" setfilterstatecommonv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/common/set_filter_state/v3" + httpdynamicmodulesv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/dynamic_modules/v3" + extprocv3filter "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/ext_proc/v3" setfilterstatev3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/set_filter_state/v3" hcmv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" tlsv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/transport_sockets/tls/v3" @@ -1184,11 +1188,13 @@ func TestXdsServer_RouteTimeout(t *testing.T) { if len(hosts) != 1 || len(hosts[0].GetRoutes()) != 1 { t.Fatalf("buildRoutes() = %d virtual hosts, want exactly 1 with 1 route", len(hosts)) } - action := hosts[0].GetRoutes()[0].GetRoute() - if got := action.GetCluster(); got != OriginalDstClusterName { - t.Fatalf("workload route targets cluster %q, want %q", got, OriginalDstClusterName) + for i, r := range hosts[0].GetRoutes() { + action := r.GetRoute() + if got := action.GetCluster(); got != OriginalDstClusterName { + t.Fatalf("workload route[%d] targets cluster %q, want %q", i, got, OriginalDstClusterName) + } } - return action + return hosts[0].GetRoutes()[0].GetRoute() } routeTimeout := func(t *testing.T, x *XdsServer) time.Duration { t.Helper() @@ -1351,25 +1357,212 @@ func TestXdsServer_ActorClusterProtocolOptions(t *testing.T) { } } -// TestXdsServer_BuildRoutesWritesTargetPortHeader ensures the route overwrites -// the target-port header with the value from ext_proc's trusted metadata. +// TestXdsServer_BuildRoutesWritesTargetPortHeader ensures every workload route, +// cached or not, overwrites the target-port header with the value from +// ext_proc's trusted metadata. func TestXdsServer_BuildRoutesWritesTargetPortHeader(t *testing.T) { + for _, ingressCache := range []bool{false, true} { + t.Run("ingressCache="+strconv.FormatBool(ingressCache), func(t *testing.T) { + x := NewXdsServer(18000) + x.SetIngressCache(ingressCache, defaultIngressCacheConfig) + routes := x.buildRoutes().GetVirtualHosts()[0].GetRoutes() + want := 1 + if ingressCache { + want = 2 + } + if len(routes) != want { + t.Fatalf("buildRoutes() = %d routes, want %d", len(routes), want) + } + + for i, route := range routes { + headers := route.GetRequestHeadersToAdd() + if len(headers) != 1 { + t.Fatalf("route[%d] adds request headers %v, want exactly one", i, headers) + } + header := headers[0] + if got, want := header.GetHeader().GetKey(), atunnelingress.TargetPortHeader; got != want { + t.Errorf("route[%d] header key = %q, want %q", i, got, want) + } + if got, want := header.GetHeader().GetValue(), "%DYNAMIC_METADATA(envoy.filters.listener.original_dst:port)%"; got != want { + t.Errorf("route[%d] header value = %q, want %q", i, got, want) + } + if got, want := header.GetAppendAction(), corev3.HeaderValueOption_OVERWRITE_IF_EXISTS_OR_ADD; got != want { + t.Errorf("route[%d] append action = %v, want %v", i, got, want) + } + } + }) + } +} + +// TestXdsServer_BuildRoutes_EndpointCachedRoute verifies that, with the ingress +// cache enabled, the first route matches on the cache-hit dynamic metadata and +// disables ext_proc via per-route config. +func TestXdsServer_BuildRoutes_EndpointCachedRoute(t *testing.T) { + x := NewXdsServer(18000) + x.SetIngressCache(true, defaultIngressCacheConfig) + routes := x.buildRoutes().GetVirtualHosts()[0].GetRoutes() + if len(routes) != 2 { + t.Fatalf("buildRoutes() = %d routes, want 2", len(routes)) + } + + cachedRoute := routes[0] + if cachedRoute.GetMatch().GetPrefix() != "/" { + t.Errorf("cached route match prefix = %q, want '/'", cachedRoute.GetMatch().GetPrefix()) + } + if headers := cachedRoute.GetMatch().GetHeaders(); len(headers) != 0 { + t.Errorf("cached route matches headers %v, want none: clients can forge headers", headers) + } + if !matchesCacheHit(cachedRoute) { + t.Errorf("cached route dynamic metadata matchers = %v, want %s.%s = %q", + cachedRoute.GetMatch().GetDynamicMetadata(), cacheHitMetadataNamespace, cacheHitMetadataKey, cacheHitMetadataValue) + } + + perFilterConfig := cachedRoute.GetTypedPerFilterConfig() + anyConfig, exists := perFilterConfig[httpExtProcFilterName] + if !exists { + t.Fatalf("cached route missing typed per-filter config for %q", httpExtProcFilterName) + } + extProcPerRoute := &extprocv3filter.ExtProcPerRoute{} + if err := anyConfig.UnmarshalTo(extProcPerRoute); err != nil { + t.Fatalf("failed to unmarshal ExtProcPerRoute: %v", err) + } + if !extProcPerRoute.GetDisabled() { + t.Errorf("cached route ExtProcPerRoute disabled = false, want true") + } + + fallbackRoute := routes[1] + if fallbackRoute.GetMatch().GetPrefix() != "/" { + t.Errorf("fallback route match prefix = %q, want '/'", fallbackRoute.GetMatch().GetPrefix()) + } + if len(fallbackRoute.GetMatch().GetHeaders()) != 0 { + t.Errorf("fallback route headers matchers = %v, want none", fallbackRoute.GetMatch().GetHeaders()) + } + if _, exists := fallbackRoute.GetTypedPerFilterConfig()[httpExtProcFilterName]; exists { + t.Errorf("fallback route should not have per-filter config for %q", httpExtProcFilterName) + } +} + +// TestXdsServer_BuildHcm_IngressCacheFilter verifies that, with the ingress +// cache enabled, the dynamic module filter is configured and inserted ahead of +// ext_proc in HCM. +func TestXdsServer_BuildHcm_IngressCacheFilter(t *testing.T) { x := NewXdsServer(18000) - route := x.buildRoutes().GetVirtualHosts()[0].GetRoutes()[0] + x.SetIngressCache(true, IngressCacheConfig{TTL: 30 * time.Second, MaxCachedActors: 500}) + hcmAny := x.buildHcm("test_prefix", false) + hcm := &hcmv3.HttpConnectionManager{} + if err := hcmAny.UnmarshalTo(hcm); err != nil { + t.Fatalf("failed to unmarshal HCM: %v", err) + } + + filters := hcm.GetHttpFilters() + var dynamicModuleIdx, extProcIdx int = -1, -1 + var dynamicModuleFilter *hcmv3.HttpFilter - headers := route.GetRequestHeadersToAdd() - if len(headers) != 1 { - t.Fatalf("route adds request headers %v, want exactly one", headers) + for i, f := range filters { + switch f.GetName() { + case httpDynamicModulesFilterName: + dynamicModuleIdx = i + dynamicModuleFilter = f + case httpExtProcFilterName: + extProcIdx = i + } } - header := headers[0] - if got, want := header.GetHeader().GetKey(), atunnelingress.TargetPortHeader; got != want { - t.Errorf("header key = %q, want %q", got, want) + + if dynamicModuleIdx == -1 { + t.Fatalf("HCM missing %q filter", httpDynamicModulesFilterName) } - if got, want := header.GetHeader().GetValue(), "%DYNAMIC_METADATA(envoy.filters.listener.original_dst:port)%"; got != want { - t.Errorf("header value = %q, want %q", got, want) + if extProcIdx == -1 { + t.Fatalf("HCM missing %q filter", httpExtProcFilterName) } - if got, want := header.GetAppendAction(), corev3.HeaderValueOption_OVERWRITE_IF_EXISTS_OR_ADD; got != want { - t.Errorf("append action = %v, want %v", got, want) + if dynamicModuleIdx >= extProcIdx { + t.Errorf("dynamic modules filter (idx %d) must precede ext_proc filter (idx %d)", dynamicModuleIdx, extProcIdx) + } + + dmConfig := &httpdynamicmodulesv3.DynamicModuleFilter{} + if err := dynamicModuleFilter.GetTypedConfig().UnmarshalTo(dmConfig); err != nil { + t.Fatalf("failed to unmarshal dynamic module filter config: %v", err) + } + if dmConfig.GetDynamicModuleConfig().GetName() != ingressCacheDynamicModuleName { + t.Errorf("dynamic module name = %q, want %q", dmConfig.GetDynamicModuleConfig().GetName(), ingressCacheDynamicModuleName) + } + if dmConfig.GetFilterName() != ingressCacheDynamicModuleName { + t.Errorf("filter name = %q, want %q", dmConfig.GetFilterName(), ingressCacheDynamicModuleName) + } + filterConfig := &wrapperspb.StringValue{} + if err := dmConfig.GetFilterConfig().UnmarshalTo(filterConfig); err != nil { + t.Fatalf("failed to unmarshal filter config: %v", err) + } + if got, want := filterConfig.GetValue(), `{"cache_ttl_seconds":30,"max_cached_actors":500}`; got != want { + t.Errorf("filter config = %s, want %s", got, want) + } +} + +func TestIngressCacheConfigValidate(t *testing.T) { + tests := []struct { + name string + cfg IngressCacheConfig + wantErr string // substring; empty means valid + }{ + {name: "defaults", cfg: defaultIngressCacheConfig}, + {name: "zero TTL", cfg: IngressCacheConfig{TTL: 0, MaxCachedActors: 1}, wantErr: "--ingress-cache-ttl"}, + {name: "fractional TTL", cfg: IngressCacheConfig{TTL: 1500 * time.Millisecond, MaxCachedActors: 1}, wantErr: "--ingress-cache-ttl"}, + {name: "zero max cached actors", cfg: IngressCacheConfig{TTL: time.Second, MaxCachedActors: 0}, wantErr: "--ingress-cache-max-cached-actors"}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + err := tt.cfg.validate() + if tt.wantErr == "" { + if err != nil { + t.Errorf("validate() = %v, want nil", err) + } + return + } + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Errorf("validate() = %v, want an error containing %q", err, tt.wantErr) + } + }) + } +} + +var defaultIngressCacheConfig = IngressCacheConfig{TTL: DefaultIngressCacheTTL, MaxCachedActors: DefaultIngressCacheMaxCachedActors} + +// matchesCacheHit reports whether r matches exactly the cache-hit dynamic metadata. +func matchesCacheHit(r *routev3.Route) bool { + m := r.GetMatch().GetDynamicMetadata() + return len(m) == 1 && + m[0].GetFilter() == cacheHitMetadataNamespace && + len(m[0].GetPath()) == 1 && m[0].GetPath()[0].GetKey() == cacheHitMetadataKey && + m[0].GetValue().GetStringMatch().GetExact() == cacheHitMetadataValue +} + +// TestXdsServer_IngressCacheDisabledByDefault verifies that without the +// IngressCache preview gate the router installs neither the ingress-cache +// filter nor any route that skips ext_proc, on either upstream transport. +func TestXdsServer_IngressCacheDisabledByDefault(t *testing.T) { + for _, upstreamConnect := range []bool{false, true} { + t.Run("upstreamConnect="+strconv.FormatBool(upstreamConnect), func(t *testing.T) { + x := NewXdsServer(18000) + x.SetUpstreamConnect(upstreamConnect) + + hcm := &hcmv3.HttpConnectionManager{} + if err := x.buildHcm("test_prefix", false).UnmarshalTo(hcm); err != nil { + t.Fatalf("failed to unmarshal HCM: %v", err) + } + for _, f := range hcm.GetHttpFilters() { + if f.GetName() == httpDynamicModulesFilterName { + t.Errorf("HCM has %q filter with the ingress cache disabled", httpDynamicModulesFilterName) + } + } + + for i, r := range x.buildRoutes().GetVirtualHosts()[0].GetRoutes() { + if got := r.GetMatch().GetDynamicMetadata(); len(got) != 0 { + t.Errorf("route[%d] matches dynamic metadata %v with the ingress cache disabled", i, got) + } + if _, ok := r.GetTypedPerFilterConfig()[httpExtProcFilterName]; ok { + t.Errorf("route[%d] overrides %q with the ingress cache disabled", i, httpExtProcFilterName) + } + } + }) } } diff --git a/cmd/atenet/internal/router/xds_upstream_connect_test.go b/cmd/atenet/internal/router/xds_upstream_connect_test.go index 3817c34642..ed795971f8 100644 --- a/cmd/atenet/internal/router/xds_upstream_connect_test.go +++ b/cmd/atenet/internal/router/xds_upstream_connect_test.go @@ -25,6 +25,7 @@ import ( routev3 "github.com/envoyproxy/go-control-plane/envoy/config/route/v3" setfilterstatecommonv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/common/set_filter_state/v3" setfilterstatev3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/http/set_filter_state/v3" + networkdynamicmodulesv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/dynamic_modules/v3" hcmv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/http_connection_manager/v3" setfilterstatenetworkv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/set_filter_state/v3" tcpproxyv3 "github.com/envoyproxy/go-control-plane/envoy/extensions/filters/network/tcp_proxy/v3" @@ -37,6 +38,7 @@ import ( "go.ate.dev/substrate/cmd/atenet/internal/router/extproc" "go.ate.dev/substrate/internal/atenet" atunnelingress "go.ate.dev/substrate/internal/atunnel/ingress" + "go.ate.dev/substrate/internal/preview" ) // upstreamConnectSnapshot also enables the CONNECT listener, so main_internal @@ -117,6 +119,7 @@ func TestUpstreamConnectFlag(t *testing.T) { t.Fatalf("validate() = %v, want valid", err) } + cfg.Gates = preview.NewForTest(t) s := &RouterServer{cfg: cfg} x, err := s.newEnvoyXdsServer(t.Context(), cfg.ParkedRequest.Normalized(), 0) if err != nil { @@ -136,9 +139,13 @@ func TestUpstreamConnectFlag(t *testing.T) { for _, r := range rc.GetVirtualHosts()[0].GetRoutes() { routed = append(routed, r.GetRoute().GetCluster()) } + // The IngressCache preview gate is off, so there are no cached routes. want := []string{OriginalDstClusterName} if tc.wantTunnels { - want = []string{ActorTunnelHTTP2ClusterName, ActorTunnelHTTP1ClusterName} + want = []string{ + ActorTunnelHTTP2ClusterName, + ActorTunnelHTTP1ClusterName, + } } if !slices.Equal(routed, want) { t.Errorf("routes send to %v, want %v", routed, want) @@ -253,20 +260,40 @@ func TestActorTunnelFilterStateFilter(t *testing.T) { func TestXdsServer_ActorTunnelRoutes(t *testing.T) { x := NewXdsServer(0) x.SetUpstreamConnect(true) + x.SetIngressCache(true, defaultIngressCacheConfig) routes := x.buildRoutes().GetVirtualHosts()[0].GetRoutes() - if len(routes) != 2 { - t.Fatalf("got %d routes, want 2", len(routes)) + if len(routes) != 4 { + t.Fatalf("got %d routes, want 4", len(routes)) + } + grpcCached, grpc, restCached, rest := routes[0], routes[1], routes[2], routes[3] + if got := grpcCached.GetRoute().GetCluster(); got != ActorTunnelHTTP2ClusterName { + t.Errorf("cached gRPC route sends to %q, want %q", got, ActorTunnelHTTP2ClusterName) } - grpc, rest := routes[0], routes[1] if got := grpc.GetRoute().GetCluster(); got != ActorTunnelHTTP2ClusterName { t.Errorf("gRPC route sends to %q, want %q", got, ActorTunnelHTTP2ClusterName) } + if got := restCached.GetRoute().GetCluster(); got != ActorTunnelHTTP1ClusterName { + t.Errorf("cached fallback route sends to %q, want %q", got, ActorTunnelHTTP1ClusterName) + } if got := rest.GetRoute().GetCluster(); got != ActorTunnelHTTP1ClusterName { t.Errorf("fallback route sends to %q, want %q", got, ActorTunnelHTTP1ClusterName) } if got := rest.GetMatch().GetHeaders(); len(got) != 0 { t.Errorf("fallback route matches headers %v, want none", got) } + if got := restCached.GetMatch().GetHeaders(); len(got) != 0 { + t.Errorf("cached fallback route matches headers %v, want none", got) + } + for _, r := range []*routev3.Route{grpcCached, restCached} { + if !matchesCacheHit(r) { + t.Errorf("cached route to %q doesn't match the cache-hit dynamic metadata", r.GetRoute().GetCluster()) + } + } + for _, r := range []*routev3.Route{grpc, rest} { + if got := r.GetMatch().GetDynamicMetadata(); len(got) != 0 { + t.Errorf("route to %q matches dynamic metadata %v, want none", r.GetRoute().GetCluster(), got) + } + } // Matches atunnel's isGRPC, minus the protocol check a route can't do. var method, contentType string @@ -315,7 +342,7 @@ func TestXdsServer_ActorTunnelRoutes(t *testing.T) { } func TestBuildActorConnectListener(t *testing.T) { - filters := buildActorConnectListener().GetFilterChains()[0].GetFilters() + filters := buildActorConnectListener(false).GetFilterChains()[0].GetFilters() if len(filters) != 2 { t.Fatalf("got %d network filters, want set_filter_state and tcp_proxy", len(filters)) } @@ -356,6 +383,33 @@ func TestBuildActorConnectListener(t *testing.T) { } } +// TestBuildActorConnectListenerIngressCache checks that with the ingress cache +// on, the tunnel_watcher network filter runs ahead of tcp_proxy and +// loads from the same library as the ingress-cache HTTP filter, whose +// per-thread cache it marks. +func TestBuildActorConnectListenerIngressCache(t *testing.T) { + filters := buildActorConnectListener(true).GetFilterChains()[0].GetFilters() + if len(filters) != 3 { + t.Fatalf("got %d network filters, want set_filter_state, tunnel_watcher and tcp_proxy", len(filters)) + } + watcher := filters[1] + if got := watcher.GetName(); got != networkDynamicModulesFilterName { + t.Errorf("filter[1] name = %q, want %q", got, networkDynamicModulesFilterName) + } + cfg := &networkdynamicmodulesv3.DynamicModuleNetworkFilter{} + if err := watcher.GetTypedConfig().UnmarshalTo(cfg); err != nil { + t.Fatalf("unmarshal tunnel_watcher: %v", err) + } + if got := cfg.GetDynamicModuleConfig().GetName(); got != ingressCacheDynamicModuleName { + t.Errorf("tunnel_watcher module = %q, want %q (the HTTP filter's library)", got, ingressCacheDynamicModuleName) + } + if got := cfg.GetFilterName(); got != ingressCacheTunnelWatcherFilterName { + t.Errorf("tunnel_watcher filter name = %q, want %q", got, ingressCacheTunnelWatcherFilterName) + } + if got := filters[2].GetName(); got != "envoy.filters.network.tcp_proxy" { + t.Errorf("last filter = %q, want tcp_proxy", got) + } +} func TestXdsServer_ActorTunnelClusters(t *testing.T) { protocolOptions := func(t *testing.T, c *clusterv3.Cluster) *httpv3.HttpProtocolOptions { t.Helper() diff --git a/cmd/ateworker-gvisor/cleanup_test.go b/cmd/ateworker-gvisor/cleanup_test.go index 4e41380fd9..7d236e1cb1 100644 --- a/cmd/ateworker-gvisor/cleanup_test.go +++ b/cmd/ateworker-gvisor/cleanup_test.go @@ -20,7 +20,10 @@ import ( "context" "errors" "maps" + "os" + "path/filepath" "slices" + "strings" "testing" "go.ate.dev/substrate/internal/proto/ateworkerpb" @@ -41,23 +44,16 @@ func newFakeRunsc(containers ...string) *fakeRunsc { return f } -func (f *fakeRunsc) cmdState(_ context.Context, name string) error { - f.calls = append(f.calls, "state "+name) - if !f.containers[name] { - return errors.New("exit status 128") +// cmdDelete succeeds for a container runsc has no record of, as +// runsc delete -force does. +func (f *fakeRunsc) cmdDelete(_ context.Context, names ...string) error { + f.calls = append(f.calls, "delete "+strings.Join(names, " ")) + for _, name := range names { + delete(f.containers, name) } return nil } -func (f *fakeRunsc) cmdDelete(_ context.Context, name string) error { - f.calls = append(f.calls, "delete "+name) - if !f.containers[name] { - return errors.New("exit status 128") - } - delete(f.containers, name) - return nil -} - func (f *fakeRunsc) cmdKill(_ context.Context, name, signal string) error { f.calls = append(f.calls, "kill "+name+" "+signal) return nil @@ -68,11 +64,6 @@ func (f *fakeRunsc) cmdWait(_ context.Context, name string) error { return nil } -func (f *fakeRunsc) cmdList(context.Context) ([]string, error) { - f.calls = append(f.calls, "list") - return slices.Sorted(maps.Keys(f.containers)), nil -} - func assertCalls(t *testing.T, f *fakeRunsc, want ...string) { t.Helper() if !slices.Equal(f.calls, want) { @@ -82,43 +73,31 @@ func assertCalls(t *testing.T, f *fakeRunsc, want ...string) { var appContainers = []*ateworkerpb.Container{{Name: "app"}} -func TestCleanupContainers_DeletesEveryContainerRunscKnows(t *testing.T) { - f := newFakeRunsc("app", "_sandbox") - - if err := cleanupContainers(context.Background(), f, appContainers); err != nil { - t.Fatalf("cleanupContainers: %v", err) +// cleanupContainers deletes the application containers before the sandbox, +// with one runsc command, whatever runsc still has a record of. +func TestCleanupContainers(t *testing.T) { + tests := []struct { + name string + present []string + }{ + {name: "every container present", present: []string{"app", "_sandbox"}}, + {name: "sandbox already gone", present: []string{"app"}}, + {name: "everything already gone"}, } - - // Happy path: no `runsc list` at all. - assertCalls(t, f, "state app", "state _sandbox", "delete app", "delete _sandbox") - if len(f.containers) != 0 { - t.Errorf("containers survived cleanup: %v", slices.Sorted(maps.Keys(f.containers))) - } - if err := cleanupContainers(context.Background(), f, appContainers); err != nil { - t.Fatalf("repeated cleanupContainers: %v", err) + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + f := newFakeRunsc(tc.present...) + if err := cleanupContainers(context.Background(), f, appContainers); err != nil { + t.Fatalf("cleanupContainers: %v", err) + } + assertCalls(t, f, "delete app _sandbox") + if len(f.containers) != 0 { + t.Errorf("containers survived cleanup: %v", slices.Sorted(maps.Keys(f.containers))) + } + }) } } -func TestCleanupContainers_SkipsContainersRunscHasNoRecordOf(t *testing.T) { - f := newFakeRunsc("app") - - if err := cleanupContainers(context.Background(), f, appContainers); err != nil { - t.Fatalf("cleanupContainers: %v", err) - } - - assertCalls(t, f, "state app", "state _sandbox", "list", "delete app") -} - -func TestCleanupContainers_SucceedsWhenEverythingIsAlreadyGone(t *testing.T) { - f := newFakeRunsc() - - if err := cleanupContainers(context.Background(), f, appContainers); err != nil { - t.Fatalf("cleanupContainers: %v", err) - } - - assertCalls(t, f, "state app", "list", "state _sandbox", "list") -} - // The sandbox must outlive the deletes of the // containers inside it, so stopping the actor leaves it to cleanup. func TestStopContainersLeavesTheSandboxToCleanup(t *testing.T) { @@ -130,3 +109,114 @@ func TestStopContainersLeavesTheSandboxToCleanup(t *testing.T) { } assertCalls(t, f, want...) } + +func TestTerminateContainers(t *testing.T) { + containers := []*ateworkerpb.Container{{Name: "app"}, {Name: "sidecar"}} + tests := []struct { + name string + sandboxExited bool + wantStopCalls []string + }{ + {name: "sandbox exited", sandboxExited: true}, + { + name: "sandbox exit unconfirmed", + wantStopCalls: []string{"kill app SIGKILL", "wait app", "kill sidecar SIGKILL", "wait sidecar"}, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + f := newFakeRunsc("app", "sidecar", "_sandbox") + if err := terminateContainers(context.Background(), f, containers, tc.sandboxExited); err != nil { + t.Fatalf("terminateContainers: %v", err) + } + want := append(tc.wantStopCalls, "delete app sidecar _sandbox") + assertCalls(t, f, want...) + }) + } +} + +func TestTeardownContainers(t *testing.T) { + for _, tc := range []struct { + name string + deleteErr error + // leaf, if set, holds the files the sandbox's cgroup leaf starts with. + leaf map[string]string + // wantKilled is what cgroup.kill holds afterwards. + wantKilled string + // wantReleased is whether runsc's records are dropped. + wantReleased bool + // wantAppLeafRemoved is whether the app container's empty leaf is + // removed. + wantAppLeafRemoved bool + // wantCkptKilled is what the checkpoint cgroup's cgroup.kill holds + // afterwards. + wantCkptKilled string + wantErr bool + }{{ + name: "deleted", + leaf: map[string]string{"cgroup.kill": ""}, + wantReleased: true, + }, { + name: "delete failed, no sandbox leaf", + deleteErr: errors.New("exit status 128"), + wantReleased: true, + wantAppLeafRemoved: true, + wantCkptKilled: "1", + }, { + // A missing cgroup.events fails the wait for the leaf to empty, as a + // sandbox that does not die would. The app leaf is still removed. + name: "delete and kill failed", + deleteErr: errors.New("exit status 128"), + leaf: map[string]string{"cgroup.kill": ""}, + wantKilled: "1", + wantAppLeafRemoved: true, + wantCkptKilled: "1", + wantErr: true, + }} { + t.Run(tc.name, func(t *testing.T) { + s := &AteWorkerService{cgroupRoot: t.TempDir()} + leaf := s.sandboxLeaf(testActor.UID) + if tc.leaf != nil { + if err := os.Mkdir(leaf, 0o755); err != nil { + t.Fatal(err) + } + writeCgroupFiles(t, leaf, tc.leaf) + } + appLeaf := s.containerLeaf(testActor.UID, "app") + if err := os.Mkdir(appLeaf, 0o755); err != nil { + t.Fatal(err) + } + // The checkpoint cgroup of a checkpoint in progress, which empties + // once killed. + ckpt := checkpointCgroupDir(s.cgroupRoot, testActor.UID) + if err := os.Mkdir(ckpt, 0o755); err != nil { + t.Fatal(err) + } + writeCgroupFiles(t, ckpt, map[string]string{"cgroup.kill": "", "cgroup.events": "populated 0\n"}) + actorDirs := &ateworkerpb.ActorDirs{RootDir: t.TempDir(), OciBundleDir: t.TempDir()} + record := filepath.Join(runscStateDir(actorDirs), "app") + if err := os.MkdirAll(record, 0o700); err != nil { + t.Fatal(err) + } + + err := s.teardownContainers(context.Background(), testActor.UID, actorDirs, []string{"app"}, func() error { return tc.deleteErr }) + if (err != nil) != tc.wantErr { + t.Fatalf("teardownContainers() = %v, want error %t", err, tc.wantErr) + } + if tc.leaf != nil { + if got, err := os.ReadFile(filepath.Join(leaf, "cgroup.kill")); err != nil || string(got) != tc.wantKilled { + t.Errorf("cgroup.kill = %q, %v; want %q", got, err, tc.wantKilled) + } + } + if _, err := os.Stat(record); os.IsNotExist(err) != tc.wantReleased { + t.Errorf("runsc record stat error = %v, want released %t", err, tc.wantReleased) + } + if _, err := os.Stat(appLeaf); os.IsNotExist(err) != tc.wantAppLeafRemoved { + t.Errorf("app leaf stat error = %v, want removed %t", err, tc.wantAppLeafRemoved) + } + if got, err := os.ReadFile(filepath.Join(ckpt, "cgroup.kill")); err != nil || string(got) != tc.wantCkptKilled { + t.Errorf("checkpoint cgroup.kill = %q, %v; want %q", got, err, tc.wantCkptKilled) + } + }) + } +} diff --git a/cmd/ateworker-gvisor/containerexit.go b/cmd/ateworker-gvisor/containerexit.go new file mode 100644 index 0000000000..833d2ba752 --- /dev/null +++ b/cmd/ateworker-gvisor/containerexit.go @@ -0,0 +1,126 @@ +//go:build linux + +// Copyright 2026 The Agent Substrate 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 ( + "context" + "log/slog" + "os" + "time" + + "go.ate.dev/substrate/internal/actorlog" + "go.ate.dev/substrate/internal/ateattr" +) + +// containerExitTimeout bounds the runsc commands that read one container exit. +// They run under the actor's lock, so a suspend or a terminate waits this long +// for each container if the sandbox is slow to answer. +const containerExitTimeout = 3 * time.Second + +// containerExitChecks is how many container exit checks may run at once on the +// worker. Each runs a runsc process in the worker's own memory, and many +// containers can exit together. +const containerExitChecks = 4 + +// containerStopped is the status `runsc state` gives a container whose first +// process exited. It gives the same status when the sandbox is gone. +const containerStopped = "stopped" + +// exitReader is the slice of *runsc that the container exit watch needs. +type exitReader interface { + cmdState(ctx context.Context, containerName string) (string, error) + cmdExitCode(ctx context.Context, containerName string) (int32, error) +} + +// startContainerLogs forwards an application container's output as +// StartJSONLogPipe does, and checks for the container's exit when the output +// ends. A blocked `runsc wait` for each container would cost one runsc process +// each, so the end of the output is the signal. +func (s *AteWorkerService) startContainerLogs(hosted *hostedActor, rcmd exitReader, containerName string) (*os.File, error) { + pr, pw, err := os.Pipe() + if err != nil { + return nil, err + } + go func() { + s.actorLogger.WrapContainerLogs(pr, hosted.attribution, containerName, "") + pr.Close() + s.containerOutputEnded(hosted, rcmd, containerName) + }() + return pw, nil +} + +// containerOutputEnded logs the container's exit if the container stopped while +// nothing was stopping the actor. The end of the output means only that each +// copy of the pipe's write end is closed: a container that closes its own +// stdout and stderr still runs, and `runsc state` tells the two apart. +func (s *AteWorkerService) containerOutputEnded(hosted *hostedActor, rcmd exitReader, containerName string) { + if s.shuttingDown.Load() { + return + } + attribution := hosted.attribution + // A suspend or a terminate holds the actor's lock while it closes the + // actor's pipes. Without this check, those pipes hold the slots until the + // lock is free, and a real exit on another actor waits for one. + if s.lookupActor(attribution.UID) != hosted || hosted.stopping.Load() { + return + } + // Taken before the actor's lock, so a burst of exits delays the exit + // records and not a suspend or a terminate. + s.exitChecks <- struct{}{} + defer func() { <-s.exitChecks }() + ctx := context.Background() + // The lock keeps `runsc delete` away until the exit code is read. It also + // makes an exit during a boot or a checkpoint wait for the result. + if !s.locks.Lock(ctx, attribution.UID) { + return + } + defer s.locks.Unlock(attribution.UID) + if s.lookupActor(attribution.UID) != hosted || hosted.stopping.Load() || s.shuttingDown.Load() { + return + } + // A dead sandbox closes each container's pipe. watchSandbox reports it. + if hosted.sandbox != nil && hosted.sandbox.hasExited() { + return + } + ctx, cancel := context.WithTimeout(ctx, containerExitTimeout) + defer cancel() + logAttrs := append(ateattr.ActorLogAttrs(attribution), slog.String("container", containerName)) + status, err := rcmd.cmdState(ctx, containerName) + if err != nil { + slog.LogAttrs(ctx, slog.LevelWarn, "Cannot tell if the container exited", append(logAttrs, slog.Any("err", err))...) + return + } + if status != containerStopped { + return + } + exit := actorlog.ContainerExit{Container: containerName} + // The sandbox keeps the exit status until `runsc delete`, so this returns + // at once. + code, err := rcmd.cmdExitCode(ctx, containerName) + if err != nil { + // A dying sandbox closes the pipes before its own exit shows, so the + // check above can miss it. With no pinned sandbox the failure cannot + // be told from a sandbox death, so that case has no record. + if hosted.sandbox == nil || hosted.sandbox.hasExited() { + return + } + slog.LogAttrs(ctx, slog.LevelWarn, "Cannot read the container's exit code", append(logAttrs, slog.Any("err", err))...) + } else { + exit.ExitCode = &code + } + s.actorLogger.EmitContainerExit(attribution, exit) +} diff --git a/cmd/ateworker-gvisor/containerexit_test.go b/cmd/ateworker-gvisor/containerexit_test.go new file mode 100644 index 0000000000..311edf5c77 --- /dev/null +++ b/cmd/ateworker-gvisor/containerexit_test.go @@ -0,0 +1,356 @@ +//go:build linux + +// Copyright 2026 The Agent Substrate 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" + "context" + "encoding/json" + "errors" + "io" + "os" + "os/exec" + "path/filepath" + "strconv" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "go.ate.dev/substrate/internal/actorlock" + "go.ate.dev/substrate/internal/actorlog" + "go.ate.dev/substrate/internal/ateattr" + "go.ate.dev/substrate/internal/ocispec" + "go.ate.dev/substrate/internal/proto/ateworkerpb" +) + +type fakeExitReader struct { + status string + stateErr error + code int32 + waitErr error + // hold, if set, blocks cmdState until it is closed. running counts the + // calls that wait on it. + hold chan struct{} + running atomic.Int32 +} + +func (f *fakeExitReader) cmdState(context.Context, string) (string, error) { + if f.hold != nil { + f.running.Add(1) + <-f.hold + f.running.Add(-1) + } + return f.status, f.stateErr +} + +func (f *fakeExitReader) cmdExitCode(context.Context, string) (int32, error) { + return f.code, f.waitErr +} + +// exitService hosts testActor on a service that logs to w. +func exitService(w io.Writer) (*AteWorkerService, *hostedActor) { + hosted := &hostedActor{attribution: testActor} + s := &AteWorkerService{ + locks: actorlock.New(), + actors: map[string]*hostedActor{testActor.UID: hosted}, + actorLogger: actorlog.NewActorLogger(w, false), + exitChecks: make(chan struct{}, containerExitChecks), + } + return s, hosted +} + +// liveSandbox pins a process that runs until the test ends as the actor's +// sandbox. +func liveSandbox(t *testing.T, h *hostedActor) { + t.Helper() + cmd := exec.Command("sleep", "600") + if err := cmd.Start(); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { + _ = cmd.Process.Kill() + _ = cmd.Wait() + }) + actorDirs := &ateworkerpb.ActorDirs{RootDir: t.TempDir()} + if err := os.MkdirAll(pidFileDir(actorDirs), 0o700); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(pidFilePath(actorDirs, ocispec.SandboxID), []byte(strconv.Itoa(cmd.Process.Pid)), 0o600); err != nil { + t.Fatal(err) + } + sandbox, err := openSandboxProcess(actorDirs) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sandbox.Close) + h.sandbox = sandbox +} + +// deadSandbox pins a process that has exited as the actor's sandbox. +func deadSandbox(t *testing.T, h *hostedActor) { + t.Helper() + sandbox, err := openSandboxProcess(exitingSandbox(t)) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sandbox.Close) + if err := sandbox.waitExited(context.Background(), sandboxExitTimeout); err != nil { + t.Fatal(err) + } + h.sandbox = sandbox +} + +func TestContainerOutputEndedLogsExit(t *testing.T) { + for _, tc := range []struct { + name string + rcmd *fakeExitReader + wantCode any // nil means the key is absent + }{ + {"exit code", &fakeExitReader{status: containerStopped, code: 137}, float64(137)}, + {"clean exit", &fakeExitReader{status: containerStopped}, float64(0)}, + {"no exit code", &fakeExitReader{status: containerStopped, waitErr: errors.New("wait failed")}, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + s, hosted := exitService(&buf) + liveSandbox(t, hosted) + s.containerOutputEnded(hosted, tc.rcmd, "app") + var record map[string]any + if err := json.Unmarshal(buf.Bytes(), &record); err != nil { + t.Fatalf("log = %q, want one exit record: %v", buf.String(), err) + } + if got := record["message"]; got != actorlog.ContainerExitedMessage { + t.Errorf("message = %v, want %q", got, actorlog.ContainerExitedMessage) + } + if got := record[string(ateattr.ActorExitedContainerNameKey)]; got != "app" { + t.Errorf("container = %v, want app", got) + } + if got := record[string(ateattr.ProcessExitCodeKey)]; got != tc.wantCode { + t.Errorf("exit code = %v, want %v", got, tc.wantCode) + } + }) + } +} + +func TestContainerOutputEndedIgnores(t *testing.T) { + stopped := &fakeExitReader{status: containerStopped} + for _, tc := range []struct { + name string + rcmd *fakeExitReader + setup func(*testing.T, *AteWorkerService, *hostedActor) + }{ + {"container closed its output and still runs", &fakeExitReader{status: "running"}, nil}, + {"state unknown", &fakeExitReader{status: containerStopped, stateErr: errors.New("no state")}, nil}, + {"stopped by ateworker", stopped, func(_ *testing.T, _ *AteWorkerService, h *hostedActor) { h.stopping.Store(true) }}, + {"worker shutting down", stopped, func(_ *testing.T, s *AteWorkerService, _ *hostedActor) { s.shuttingDown.Store(true) }}, + {"actor no longer hosted", stopped, func(_ *testing.T, s *AteWorkerService, _ *hostedActor) { delete(s.actors, testActor.UID) }}, + {"actor hosted again", stopped, func(_ *testing.T, s *AteWorkerService, _ *hostedActor) { + s.actors[testActor.UID] = &hostedActor{attribution: testActor} + }}, + {"sandbox died", stopped, func(t *testing.T, _ *AteWorkerService, h *hostedActor) { deadSandbox(t, h) }}, + {"wait failed and the sandbox is not pinned", &fakeExitReader{status: containerStopped, waitErr: errors.New("wait failed")}, nil}, + } { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + s, hosted := exitService(&buf) + if tc.setup != nil { + tc.setup(t, s, hosted) + } + s.containerOutputEnded(hosted, tc.rcmd, "app") + if buf.Len() != 0 { + t.Errorf("log = %q, want no record", buf.String()) + } + }) + } +} + +// recordWriter sends each record the logger writes on a channel. +type recordWriter chan map[string]any + +func (w recordWriter) Write(p []byte) (int, error) { + var record map[string]any + if err := json.Unmarshal(p, &record); err != nil { + return 0, err + } + w <- record + return len(p), nil +} + +// TestStartContainerLogsOrder pins that the exit record comes after the +// container's last line, including a line with no newline. +func TestStartContainerLogsOrder(t *testing.T) { + records := make(recordWriter, 2) + s, hosted := exitService(records) + pw, err := s.startContainerLogs(hosted, &fakeExitReader{status: containerStopped, code: 1}, "app") + if err != nil { + t.Fatal(err) + } + if _, err := pw.WriteString("fatal: out of cheese"); err != nil { + t.Fatal(err) + } + pw.Close() + for _, want := range []string{"fatal: out of cheese", actorlog.ContainerExitedMessage} { + select { + case record := <-records: + if got := record["message"]; got != want { + t.Errorf("record = %v, want %q", got, want) + } + case <-time.After(30 * time.Second): + t.Fatalf("no %q record", want) + } + } +} + +// TestContainerExitChecksAreCapped pins that the worker runs no more than +// containerExitChecks checks at once when the containers of many actors exit +// together. +func TestContainerExitChecksAreCapped(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s, _ := exitService(io.Discard) + rcmd := &fakeExitReader{status: "running", hold: make(chan struct{})} + // Each actor is hosted before a check starts: the checks read s.actors. + var hosted []*hostedActor + for i := range 3 * containerExitChecks { + attribution := testActor + attribution.UID = "actor-" + strconv.Itoa(i) + h := &hostedActor{attribution: attribution} + s.actors[attribution.UID] = h + hosted = append(hosted, h) + } + for _, h := range hosted { + go s.containerOutputEnded(h, rcmd, "app") + } + synctest.Wait() + if got := rcmd.running.Load(); got != containerExitChecks { + t.Errorf("checks that run at once = %d, want %d", got, containerExitChecks) + } + close(rcmd.hold) + synctest.Wait() + if got := len(s.exitChecks); got != 0 { + t.Errorf("slots held after the checks = %d, want 0", got) + } + }) +} + +// TestContainerExitNotBlockedBySuspends pins that the pipes that a suspend +// closes do not hold the exit-check slots. A checkpoint holds the actor's lock +// and sets stopping before it stops the sandbox, so each of its containers' +// output ends while the lock is held. +func TestContainerExitNotBlockedBySuspends(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var buf bytes.Buffer + s, crashed := exitService(&buf) + stopped := &fakeExitReader{status: containerStopped, code: 1} + ctx := context.Background() + + // containerExitChecks actors are in a checkpoint. Each is hosted + // before a check starts: the checks read s.actors. + var suspending []*hostedActor + for i := range containerExitChecks { + attribution := testActor + attribution.UID = "suspending-" + strconv.Itoa(i) + hosted := &hostedActor{attribution: attribution} + s.actors[attribution.UID] = hosted + if !s.locks.Lock(ctx, attribution.UID) { + t.Fatal("cannot take the actor's lock") + } + hosted.stopping.Store(true) + suspending = append(suspending, hosted) + } + // The output of each one's container ends. + for _, hosted := range suspending { + go s.containerOutputEnded(hosted, stopped, "app") + } + synctest.Wait() + + // A container of another actor exits. Nothing holds its lock. + go s.containerOutputEnded(crashed, stopped, "app") + synctest.Wait() + if buf.Len() == 0 { + t.Errorf("no exit record while %d other actors are in a checkpoint; exit-check slots held = %d", containerExitChecks, len(s.exitChecks)) + } + + for _, hosted := range suspending { + s.locks.Unlock(hosted.attribution.UID) + } + synctest.Wait() + }) +} + +// TestContainerExitChecksAgainUnderLock pins that a stop that starts while the +// check waits for the actor's lock gets no exit record. +func TestContainerExitChecksAgainUnderLock(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + var buf bytes.Buffer + s, hosted := exitService(&buf) + if !s.locks.Lock(context.Background(), testActor.UID) { + t.Fatal("cannot take the actor's lock") + } + go s.containerOutputEnded(hosted, &fakeExitReader{status: containerStopped}, "app") + synctest.Wait() + hosted.stopping.Store(true) + s.locks.Unlock(testActor.UID) + synctest.Wait() + if buf.Len() != 0 { + t.Errorf("log = %q, want no record", buf.String()) + } + }) +} + +// scriptRunsc is a runsc that prints output and exits with code. +func scriptRunsc(t *testing.T, output string, code int) *runsc { + t.Helper() + path := filepath.Join(t.TempDir(), "runsc") + script := "#!/bin/sh\ncat <<'EOF'\n" + output + "\nEOF\nexit " + strconv.Itoa(code) + "\n" + if err := os.WriteFile(path, []byte(script), 0o700); err != nil { + t.Fatal(err) + } + return &runsc{path: path, actorDirs: testActorDirs, flags: mustFlagStore(t)} +} + +func TestCmdState(t *testing.T) { + got, err := scriptRunsc(t, `{"ociVersion":"1.2.1","id":"app","status":"stopped","pid":0}`, 0).cmdState(context.Background(), "app") + if err != nil || got != containerStopped { + t.Errorf("cmdState = %q, %v, want %q", got, err, containerStopped) + } + if _, err := scriptRunsc(t, "not json", 0).cmdState(context.Background(), "app"); err == nil { + t.Error("cmdState took output that is not JSON") + } + if _, err := scriptRunsc(t, "", 1).cmdState(context.Background(), "app"); err == nil { + t.Error("cmdState took a failed command") + } +} + +func TestCmdExitCode(t *testing.T) { + got, err := scriptRunsc(t, `{"id":"app","exitStatus":137}`, 0).cmdExitCode(context.Background(), "app") + if err != nil || got != 137 { + t.Errorf("cmdExitCode = %d, %v, want 137", got, err) + } + got, err = scriptRunsc(t, `{"id":"app","exitStatus":0}`, 0).cmdExitCode(context.Background(), "app") + if err != nil || got != 0 { + t.Errorf("cmdExitCode = %d, %v, want 0", got, err) + } + for name, r := range map[string]*runsc{ + "no exit status": scriptRunsc(t, `{"id":"app"}`, 0), + "failed command": scriptRunsc(t, "", 1), + } { + if _, err := r.cmdExitCode(context.Background(), "app"); err == nil { + t.Errorf("cmdExitCode took %s", name) + } + } +} diff --git a/cmd/ateworker-gvisor/crash.go b/cmd/ateworker-gvisor/crash.go index 9447b530c7..25059a0a25 100644 --- a/cmd/ateworker-gvisor/crash.go +++ b/cmd/ateworker-gvisor/crash.go @@ -72,11 +72,15 @@ func (s *AteWorkerService) watchSandbox(ctx context.Context, hosted *hostedActor ours := s.lookupActor(attribution.UID) == hosted && !hosted.stopping.Load() if ours { slog.WarnContext(ctx, "Sandbox died", slog.String("actorUID", attribution.UID), slog.Int("pid", pid)) - if err := s.terminateWorkload(ctx, attribution.Ref, attribution.UID, runscPath, actorDirs, containers); err != nil { + terminate := s.terminateWorkload + if s.terminateDead != nil { + terminate = s.terminateDead + } + if err := s.endActivation(ctx, hosted, s.readDeadFinal, func() error { + return terminate(ctx, attribution.Ref, attribution.UID, runscPath, actorDirs, containers, false) + }); err != nil { slog.WarnContext(ctx, "Failed to tear down the dead sandbox", slog.String("actorUID", attribution.UID), slog.Any("err", err)) } - // not measured first: the sandbox, and its cgroup, are gone - s.recordFinalIfEnded(ctx, hosted) } s.locks.Unlock(attribution.UID) if !ours || s.crashReporter == nil { diff --git a/cmd/ateworker-gvisor/crash_test.go b/cmd/ateworker-gvisor/crash_test.go index 88cd0adc53..bb11458406 100644 --- a/cmd/ateworker-gvisor/crash_test.go +++ b/cmd/ateworker-gvisor/crash_test.go @@ -20,11 +20,15 @@ import ( "context" "os" "os/exec" + "path/filepath" "strconv" "testing" "time" + "go.opentelemetry.io/otel/attribute" + "go.ate.dev/substrate/internal/actorlock" + "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/ocispec" "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/resources" @@ -86,3 +90,123 @@ func TestWatchSandboxIgnoresExpectedExits(t *testing.T) { }) } } + +// crashFixture hosts testActor on a sweep-sampled cgroup fixture, then makes its +// sandbox die: the cgroup's CPU rises past the last sample and its memory drops +// to what a cgroup with no processes left holds. +func crashFixture(t *testing.T) (*AteWorkerService, *hostedActor, string) { + t.Helper() + s := newStatsService(t, healthyCgroup) + h := hostWithEpoch(s, time.Now(), true) + s.sweepUsage(context.Background()) + leaf := filepath.Join(s.cgroupRoot, ocispec.GVisorCgroupLeaf(testActor.UID, sandboxCgroupContainer)) + for name, content := range map[string]string{"cpu.stat": "usage_usec 2000000\n", "memory.current": "16384\n", "memory.stat": "", "cgroup.events": "populated 0\n"} { + if err := os.WriteFile(filepath.Join(leaf, name), []byte(content), 0o600); err != nil { + t.Fatal(err) + } + } + return s, h, leaf +} + +// TestSweepAfterDeathLeavesMemoryOut pins that a sweep reading the empty cgroup +// of a sandbox that died, before the crash path removes it, writes its CPU but +// no memory usage or working set, and stores no memory for the final record. +func TestSweepAfterDeathLeavesMemoryOut(t *testing.T) { + s, h, _ := crashFixture(t) + rec := withUsageRecorder(s) + s.sweepUsage(context.Background()) + if got := rec.Kinds(); len(got) != 1 || got[0] != ateattr.StatsKindPeriodic { + t.Fatalf("records = %v, want one periodic", got) + } + if got := rec.Value(0, string(ateattr.StatsCPUTimeKey)); got != "2" { + t.Errorf("periodic cpu.time = %q, want 2", got) + } + for _, key := range []attribute.Key{ateattr.StatsMemoryUsageKey, ateattr.StatsMemoryWorkingSetKey} { + if got := rec.Value(0, string(key)); got != "" { + t.Errorf("periodic %s = %q, want absent", key, got) + } + } + if got := h.usage.Latest(); !got.GetMemoryUnmeasured() || got.GetMemoryCurrentBytes() != 0 || got.GetMemoryWorkingSetBytes() != 0 { + t.Errorf("stored memory = %d/%d unmeasured=%v, want zero and unmeasured", got.GetMemoryCurrentBytes(), got.GetMemoryWorkingSetBytes(), got.GetMemoryUnmeasured()) + } +} + +func TestReadDeadFinal(t *testing.T) { + s, h, _ := crashFixture(t) + s.readDeadFinal(context.Background(), h) + got := h.usage.Latest() + if got.GetCpuUsageUsec() != 2000000 { + t.Errorf("CPU = %d, want the 2000000 read after the death", got.GetCpuUsageUsec()) + } + if !got.GetMemoryUnmeasured() || got.GetMemoryCurrentBytes() != 0 || got.GetMemoryWorkingSetBytes() != 0 { + t.Errorf("memory = %d/%d unmeasured=%v, want zero and unmeasured: not measured at the death", got.GetMemoryCurrentBytes(), got.GetMemoryWorkingSetBytes(), got.GetMemoryUnmeasured()) + } +} + +// TestWatchSandboxCrashWritesFinal drives the watcher through a sandbox that +// dies on its own: the actor is torn down after its cgroup is read, its final +// record carries the CPU and memory peak at death but no memory usage or +// working set, and the crash is reported. +func TestWatchSandboxCrashWritesFinal(t *testing.T) { + s, h, leaf := crashFixture(t) + rec := withUsageRecorder(s) + reporter := &fakeCrashReporter{reports: make(chan string, 1)} + s.crashReporter = reporter + actorDirs := exitingSandbox(t) + sandbox, err := openSandboxProcess(actorDirs) + if err != nil { + t.Fatal(err) + } + t.Cleanup(sandbox.Close) + h.sandbox = sandbox + s.terminateDead = func(context.Context, resources.ActorRef, string, string, *ateworkerpb.ActorDirs, []*ateworkerpb.Container, bool) error { + setHostedActor(s, nil) + return os.RemoveAll(leaf) // as runsc delete does + } + + s.watchSandbox(context.Background(), h, "", actorDirs, nil) + select { + case msg := <-reporter.reports: + if msg != "gVisor sandbox exited" { + t.Errorf("reported %q", msg) + } + case <-time.After(10 * time.Second): + t.Fatal("crash not reported") + } + if got := rec.Kinds(); len(got) != 1 || got[0] != ateattr.StatsKindFinal { + t.Fatalf("records = %v, want one final", got) + } + if got := rec.Value(0, string(ateattr.StatsCPUTimeKey)); got != "2" { + t.Errorf("final cpu.time = %q, want 2 (seconds) read after the death", got) + } + for _, key := range []attribute.Key{ateattr.StatsMemoryUsageKey, ateattr.StatsMemoryWorkingSetKey} { + if got := rec.Value(0, string(key)); got != "" { + t.Errorf("final %s = %q, want absent", key, got) + } + } + if got := rec.Value(0, string(ateattr.StatsMemoryPeakKey)); got == "" { + t.Error("final memory.peak absent, want the cgroup's high-water mark") + } +} + +// TestEndActivationLiveFinalKeepsMemory pins that a final record read while the +// sandbox runs, as Terminate's is, keeps every measurement. +func TestEndActivationLiveFinalKeepsMemory(t *testing.T) { + s := newStatsService(t, healthyCgroup) + rec := withUsageRecorder(s) + h := hostWithEpoch(s, time.Now(), true) + if err := s.endActivation(context.Background(), h, s.readFinal, func() error { + setHostedActor(s, nil) + return nil + }); err != nil { + t.Fatal(err) + } + if got := rec.Kinds(); len(got) != 1 || got[0] != ateattr.StatsKindFinal { + t.Fatalf("records = %v, want one final", got) + } + for _, key := range []attribute.Key{ateattr.StatsCPUTimeKey, ateattr.StatsMemoryUsageKey, ateattr.StatsMemoryWorkingSetKey, ateattr.StatsMemoryPeakKey} { + if rec.Value(0, string(key)) == "" { + t.Errorf("final %s absent, want it measured", key) + } + } +} diff --git a/cmd/ateworker-gvisor/flags.go b/cmd/ateworker-gvisor/flags.go index 432ef38d8a..4145541954 100644 --- a/cmd/ateworker-gvisor/flags.go +++ b/cmd/ateworker-gvisor/flags.go @@ -38,7 +38,7 @@ type commandFlags struct { // "--cpu-num-from-quota", "-allow-connected-on-save"). GlobalFlags []string `json:"globalFlags,omitempty"` // SubcommandFlags are passed after the command name (e.g. - // "-background", "-detach", "-force", "-quiet"). + // "-background", "-detach", "-force"). SubcommandFlags []string `json:"subcommandFlags,omitempty"` } diff --git a/cmd/ateworker-gvisor/hosted.go b/cmd/ateworker-gvisor/hosted.go index 7dff0694ca..280de16afb 100644 --- a/cmd/ateworker-gvisor/hosted.go +++ b/cmd/ateworker-gvisor/hosted.go @@ -37,7 +37,9 @@ import ( type hostedActor struct { // Attribution is available during boot. attribution resources.ActorAttribution - network *actornet.SandboxSession + // activationUID identifies this run or restore. Immutable after admission. + activationUID string + network *actornet.SandboxSession // Set once the containers exist. session *workloadSession // usage is this activation's epoch, CPU baseline, and latest sample. @@ -62,7 +64,7 @@ type hostedActor struct { // admitActor reserves capacity before network setup. An actor that is already // hosted keeps its slot; its old network is returned for the caller to close. -func (s *AteWorkerService) admitActor(attribution resources.ActorAttribution, memoryBytes int64) (*hostedActor, *actornet.SandboxSession, error) { +func (s *AteWorkerService) admitActor(attribution resources.ActorAttribution, activationUID string, memoryBytes int64) (*hostedActor, *actornet.SandboxSession, error) { s.actorsMu.Lock() defer s.actorsMu.Unlock() var stale *actornet.SandboxSession @@ -81,17 +83,18 @@ func (s *AteWorkerService) admitActor(attribution resources.ActorAttribution, me // The sandbox cgroup is new with every activation, so its counters start // at zero. ctx, cancel := context.WithCancel(context.Background()) - hosted := &hostedActor{attribution: attribution, usage: workerstats.NewActivation(time.Now(), false), ctx: ctx, cancel: cancel, memoryBytes: memoryBytes} + hosted := &hostedActor{attribution: attribution, activationUID: activationUID, usage: workerstats.NewActivation(time.Now(), false), ctx: ctx, cancel: cancel, memoryBytes: memoryBytes} s.actors[attribution.UID] = hosted + s.procs.resize(len(s.actors)) return hosted, stale, nil } // hostActor sets up the actor's network, replacing any stale one. memoryBytes // is what the actor books. -func (s *AteWorkerService) hostActor(ctx context.Context, attribution resources.ActorAttribution, actorDirs *ateworkerpb.ActorDirs, memoryBytes int64) (*hostedActor, error) { +func (s *AteWorkerService) hostActor(ctx context.Context, attribution resources.ActorAttribution, activationUID string, actorDirs *ateworkerpb.ActorDirs, memoryBytes int64) (*hostedActor, error) { uid := attribution.UID - hosted, stale, err := s.admitActor(attribution, memoryBytes) + hosted, stale, err := s.admitActor(attribution, activationUID, memoryBytes) if err != nil { return nil, err } @@ -100,6 +103,7 @@ func (s *AteWorkerService) hostActor(ctx context.Context, attribution resources. hosted.cancel() s.actorsMu.Lock() delete(s.actors, uid) + s.procs.resize(len(s.actors)) s.actorsMu.Unlock() } if stale != nil { @@ -114,6 +118,7 @@ func (s *AteWorkerService) hostActor(ctx context.Context, attribution resources. Veth: true, EgressPort: s.tunnel.EgressPort, DNSPolicy: s.tunnel.ActorEgressPolicy(attribution), + Families: s.families, }, s.tunnel.Egress, s.tunnel.DNSRelay) if err != nil { evict() @@ -131,6 +136,7 @@ func (s *AteWorkerService) unhostActor(ctx context.Context, actorUID string) err s.actorsMu.Lock() hosted, ok := s.actors[actorUID] delete(s.actors, actorUID) + s.procs.resize(len(s.actors)) if ok { // Retain capacity until network cleanup completes. s.draining++ diff --git a/cmd/ateworker-gvisor/hosted_test.go b/cmd/ateworker-gvisor/hosted_test.go index d34c44a385..ac003d3260 100644 --- a/cmd/ateworker-gvisor/hosted_test.go +++ b/cmd/ateworker-gvisor/hosted_test.go @@ -19,12 +19,14 @@ package main import ( "context" "fmt" + "io/fs" "sync" "testing" + "testing/synctest" "google.golang.org/grpc/codes" - "time" + "go.ate.dev/substrate/cmd/ateworker-gvisor/internal/cgroupstats" "go.ate.dev/substrate/internal/actorlock" "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/resources" @@ -43,7 +45,7 @@ func TestAdmitActorEnforcesTheCeilingConcurrently(t *testing.T) { wg.Add(1) go func() { defer wg.Done() - _, _, _ = s.admitActor(resources.ActorAttribution{UID: fmt.Sprintf("actor-%d", i)}, 0) + _, _, _ = s.admitActor(resources.ActorAttribution{UID: fmt.Sprintf("actor-%d", i)}, "", 0) }() } wg.Wait() @@ -56,20 +58,25 @@ func TestAdmitActorEnforcesTheCeilingConcurrently(t *testing.T) { // Re-admitting an actor that is already hosted keeps its slot, so it succeeds // on a full worker and a retry cannot lose its place to another actor. func TestAdmitActorKeepsAHostedActorsSlot(t *testing.T) { + const firstUID = "754f3dc4-2996-41c4-8e5a-a1b79e6678d5" + const nextUID = "a6ba5a75-ad36-48fc-ad2e-e845527a25b1" s := &AteWorkerService{actors: map[string]*hostedActor{}, maxActors: 1} - first, _, err := s.admitActor(resources.ActorAttribution{UID: "actor-a"}, 0) + first, _, err := s.admitActor(resources.ActorAttribution{UID: "actor-a"}, firstUID, 0) if err != nil { t.Fatal(err) } - again, _, err := s.admitActor(resources.ActorAttribution{UID: "actor-a"}, 0) + again, _, err := s.admitActor(resources.ActorAttribution{UID: "actor-a"}, nextUID, 0) if err != nil { t.Fatalf("re-admitting a hosted actor on a full worker: %v", err) } + if first.activationUID != firstUID || again.activationUID != nextUID { + t.Errorf("activation UIDs = %q, %q, want %q, %q", first.activationUID, again.activationUID, firstUID, nextUID) + } if again == first { t.Error("re-admission kept the old record; readers could not tell the incarnations apart") } // ResourceExhausted, so the control plane treats it as a capacity miss. - if _, _, err := s.admitActor(resources.ActorAttribution{UID: "actor-b"}, 0); apierror.Code(err) != codes.ResourceExhausted { + if _, _, err := s.admitActor(resources.ActorAttribution{UID: "actor-b"}, "", 0); apierror.Code(err) != codes.ResourceExhausted { t.Errorf("admitting past the ceiling: got %v, want ResourceExhausted", err) } if got := len(s.hostedActors()); got != 1 { @@ -85,69 +92,96 @@ func TestDrainingActorsStillCountAgainstTheCeiling(t *testing.T) { maxActors: 1, draining: 1, } - if _, err := s.hostActor(context.Background(), resources.ActorAttribution{UID: "actor-a"}, nil, 0); err == nil { + if _, err := s.hostActor(context.Background(), resources.ActorAttribution{UID: "actor-a"}, "", nil, 0); err == nil { t.Error("admitted an actor while a draining one still held the only place") } } -// TestGracefulShutdownWaitsForInFlightRPCs verifies checkpoints finish before shutdown. -func TestGracefulShutdownWaitsForInFlightRPCs(t *testing.T) { - s := &AteWorkerService{ - locks: actorlock.New(), - inFlight: actorlock.NewInFlight(), - actors: map[string]*hostedActor{}, - } - release := s.inFlight.Add("actor-a", rpcCheckpointWorkload, nil) +// TestGracefulShutdownStopsAnActorRestoredDuringTheWait checks that an actor +// whose restore finishes while shutdown waits still gets SIGTERM. +func TestGracefulShutdownStopsAnActorRestoredDuringTheWait(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s := &AteWorkerService{ + locks: actorlock.New(), + inFlight: actorlock.NewInFlight(), + actors: map[string]*hostedActor{}, + maxActors: 1, + readSandboxCgroup: func(string) (cgroupstats.Sample, error) { + return cgroupstats.Sample{}, fs.ErrNotExist + }, + } + release := s.inFlight.Add("actor-a", rpcRestoreWorkload) - returned := make(chan struct{}) - go func() { - defer close(returned) - s.gracefulShutdown(context.Background()) - }() + returned := make(chan struct{}) + go func() { + defer close(returned) + s.gracefulShutdown(context.Background()) + }() + synctest.Wait() - select { - case <-returned: - t.Fatal("gracefulShutdown returned while a checkpoint was still in flight") - case <-time.After(250 * time.Millisecond): - } + // The restore finishes. + if _, _, err := s.admitActor(resources.ActorAttribution{UID: "actor-a"}, "", 0); err != nil { + t.Fatal(err) + } + f := newFakeRunsc("app") + s.setSession("actor-a", &workloadSession{rcmd: f, containers: []string{"app"}}) + release() + <-returned - release() - select { - case <-returned: - case <-time.After(30 * time.Second): - t.Error("gracefulShutdown did not return after the checkpoint finished") - } + assertCalls(t, f, "kill app SIGTERM", "wait app") + }) } -func TestGracefulShutdownCancelsEveryStartup(t *testing.T) { - s := &AteWorkerService{ - locks: actorlock.New(), - inFlight: actorlock.NewInFlight(), - actors: map[string]*hostedActor{}, - } - canceled := make(chan string, 2) - for _, uid := range []string{"actor-a", "actor-b"} { - defer s.inFlight.Add(uid, rpcRunWorkload, func() { canceled <- uid })() - } +// TestGracefulShutdownLetsASuspendFinish checks that shutdown never signals an +// actor whose checkpoint is in flight. +func TestGracefulShutdownLetsASuspendFinish(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s := &AteWorkerService{ + locks: actorlock.New(), + inFlight: actorlock.NewInFlight(), + actors: map[string]*hostedActor{}, + maxActors: 1, + readSandboxCgroup: func(string) (cgroupstats.Sample, error) { + return cgroupstats.Sample{}, fs.ErrNotExist + }, + } + if _, _, err := s.admitActor(resources.ActorAttribution{UID: "actor-a"}, "", 0); err != nil { + t.Fatal(err) + } + f := newFakeRunsc("app") + s.setSession("actor-a", &workloadSession{rcmd: f, containers: []string{"app"}}) + release := s.inFlight.Add("actor-a", rpcCheckpointWorkload) - cancelStartups(context.Background(), s.inFlight) + returned := make(chan struct{}) + go func() { + defer close(returned) + s.gracefulShutdown(context.Background()) + }() + synctest.Wait() - seen := map[string]bool{} - for range 2 { select { - case uid := <-canceled: - seen[uid] = true - case <-time.After(5 * time.Second): - t.Fatalf("only %v were canceled", seen) + case <-returned: + t.Fatal("gracefulShutdown returned while the checkpoint was in flight") + default: } - } + assertCalls(t, f) + + // The checkpoint finishes and unhosts the actor. + if err := s.unhostActor(context.Background(), "actor-a"); err != nil { + t.Fatal(err) + } + release() + <-returned + + assertCalls(t, f) + }) } // TestBeginRPCRegistersBeforeCheckingForADrain checks registration and drain rejection. func TestBeginRPCRegistersBeforeCheckingForADrain(t *testing.T) { s := &AteWorkerService{locks: actorlock.New(), inFlight: actorlock.NewInFlight()} - release, err := s.beginRPC("actor-a", rpcRunWorkload, func() {}) + release, err := s.beginRPC("actor-a", rpcRunWorkload) if err != nil { t.Fatalf("beginRPC on a live ateworker: %v", err) } @@ -158,7 +192,7 @@ func TestBeginRPCRegistersBeforeCheckingForADrain(t *testing.T) { // Draining: refused, and nothing left behind for shutdown to wait on. s.shuttingDown.Store(true) - if _, err := s.beginRPC("actor-b", rpcRunWorkload, func() {}); err == nil { + if _, err := s.beginRPC("actor-b", rpcRunWorkload); err == nil { t.Error("beginRPC admitted an RPC while draining") } if got := s.inFlight.Names(); len(got) != 0 { diff --git a/cmd/ateworker-gvisor/kodata/internal_flags.json b/cmd/ateworker-gvisor/kodata/internal_flags.json index ac63d5178c..0c42ddb6fd 100644 --- a/cmd/ateworker-gvisor/kodata/internal_flags.json +++ b/cmd/ateworker-gvisor/kodata/internal_flags.json @@ -30,11 +30,6 @@ "subcommandFlags": [ "-force" ] - }, - "list": { - "subcommandFlags": [ - "-quiet" - ] } } } diff --git a/cmd/ateworker-gvisor/main.go b/cmd/ateworker-gvisor/main.go index d42598a5cd..c35f8ec8a6 100644 --- a/cmd/ateworker-gvisor/main.go +++ b/cmd/ateworker-gvisor/main.go @@ -59,6 +59,7 @@ import ( "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/resources" "go.ate.dev/substrate/internal/serverboot" + "go.ate.dev/substrate/internal/serverboot/pprofserver" "go.ate.dev/substrate/internal/sizing" "go.ate.dev/substrate/internal/snapshotcache" "go.ate.dev/substrate/internal/version" @@ -105,6 +106,7 @@ var ( podIPs = pflag.String("pod-ips", "", "The comma-separated IPs of the current pod") tunnelConfig = atunnel.RegisterFlags(pflag.CommandLine) + pprofCfg = pprofserver.RegisterFlags(pflag.CommandLine) readinessListenAddress = pflag.String("readiness-listen-address", "0.0.0.0:8080", "Address for the HTTP /readyz and /healthz probes") maxActors = pflag.Int("max-actors", 1000, "How many actors this worker will host at once") @@ -128,8 +130,14 @@ const minUsageSampleInterval = 50 * time.Second // kubelet SIGKILL of ateworker itself. const workloadGracePeriod = 30 * time.Minute +// workerMaxProcs caps GOMAXPROCS of the worker on hosts with more CPUs, so it +// holds few idle threads there (see pid1.Options). The worker waits for runsc +// and proxies its actors' traffic. Procs are later scaled as actors get +// created. +const workerMaxProcs = 16 + func main() { - pid1.RunIfPID1() + pid1.RunIfPID1(pid1.Options{MaxProcs: workerMaxProcs}) pflag.Parse() if *showVersion { fmt.Println(version.String()) @@ -153,9 +161,13 @@ func do(ctx context.Context) error { if err := serverboot.SetLogLevel(*logLevelFlag); err != nil { return err } - if err := preview.Init(*previewFlags...); err != nil { + previewGates, err := preview.New(*previewFlags...) + if err != nil { return fmt.Errorf("invalid --preview: %w", err) } + if err := pprofCfg.Validate(); err != nil { + return fmt.Errorf("invalid pprof configuration: %w", err) + } slog.InfoContext(ctx, "ateworker booting", slog.String("version", version.Version)) if *maxActors < 0 { @@ -208,6 +220,7 @@ func do(ctx context.Context) error { serverboot.Fatal(ctx, "Failed to initialize metrics", err) } defer serverboot.ShutdownProvider("MeterProvider", mp.Shutdown) + go pprofserver.Start(ctx, pprofCfg) lp, err := serverboot.InitLogging(ctx, serverboot.LoggingOptions{ ServiceName: serviceName, @@ -262,12 +275,18 @@ func do(ctx context.Context) error { return err } + workerPodIPs := register.ParsePodIPs(*podIPs) + ipv6ActorNetworking := previewGates.IsEnabled(preview.GateActorIPv6) + families, err := actornet.IPFamiliesForPodIPs(workerPodIPs, ipv6ActorNetworking) + if err != nil { + return err + } actorLogger := actorlog.NewActorLogger(syncedWriter, metadata.OnGCE()) - tunnel, err := atunnel.Start(ctx, *tunnelConfig, actornet.ActorHTTPUpstream) + tunnel, err := atunnel.Start(ctx, *tunnelConfig, actornet.ActorHTTPUpstream, mp.Meter(serviceName)) if err != nil { return err } - ateworkerService := NewService(tunnel, actorLogger, *maxActors, flags, bootID) + ateworkerService := NewService(tunnel, actorLogger, *maxActors, flags, bootID, families) ateworkerService.throttleMemory = cgroup.PSIEnabled(defaultCgroupRoot) if !ateworkerService.throttleMemory { slog.WarnContext(ctx, "Kernel has no cgroup memory pressure (PSI), so sandboxes keep memory.max and an OOM kill in one can restart the worker") @@ -291,8 +310,10 @@ func do(ctx context.Context) error { ) ateworkerpb.RegisterWorkerServer(svr, ateworkerService) reflection.Register(svr) + var sandboxRuntimes register.SandboxRuntimes readiness := &serverboot.Readiness{} readiness.AddCheck("registered", ateworkerService.epoch.Registered) + readiness.AddCheck("sandbox-runtimes", sandboxRuntimes.Reported) // Trap SIGTERM (sent by the kubelet at the start of the pod's termination // grace period) and propagate it into the sandbox so the actor can save its @@ -322,7 +343,7 @@ func do(ctx context.Context) error { TrustBundlePath: tunnelConfig.TrustBundle, AteletSPIFFEID: tunnelConfig.BrokerIdentity, Actors: *maxActors, - PodIPs: register.ParsePodIPs(*podIPs), + PodIPs: workerPodIPs, MemoryReservedBytes: memoryReservedBytes, SandboxClass: string(atev1.SandboxClassGvisor), RuntimesFile: nodepath.WorkerSandboxRuntimesPath(*podUID), @@ -333,7 +354,7 @@ func do(ctx context.Context) error { ateworkerService.crashReporter = reporter } go func() { - err := register.Report(ctx, reportConfig, &ateworkerService.epoch) + err := register.Report(ctx, reportConfig, &ateworkerService.epoch, &sandboxRuntimes) if err != nil && ctx.Err() == nil { serverboot.Fatal(ctx, "Failed to register worker", err) } @@ -358,7 +379,7 @@ const ( // in the sandbox, so the SIGTERM handler knows which containers to signal and // wait on during graceful shutdown. The sandbox runs one workload at a time. type workloadSession struct { - rcmd *runsc + rcmd containerRuntime containers []string } @@ -368,7 +389,7 @@ type AteWorkerService struct { // Serializes lifecycle RPCs per actor. locks *actorlock.Locks - // Tracks lifecycle RPCs for shutdown cancellation and draining. + // Tracks lifecycle RPCs so shutdown can wait for them. inFlight *actorlock.InFlight // crashReporter reports actors whose sandbox died. Nil if it could not be // set up. @@ -384,6 +405,8 @@ type AteWorkerService struct { // Actors undergoing network cleanup still count against capacity. draining int maxActors int + // procs resizes GOMAXPROCS. Nil if pid1 didn't cap it. + procs *procScaler actorLogger *actorlog.ActorLogger tunnel *atunnel.Tunnel @@ -413,13 +436,21 @@ type AteWorkerService struct { // micro-VM runtime. nil means the real read. readSandboxCgroup func(dir string) (cgroupstats.Sample, error) + // terminateDead overrides terminateWorkload for a sandbox that died, when + // set. Only tests set it: the real teardown needs the tunnel. nil means + // terminateWorkload. + terminateDead func(ctx context.Context, actorRef resources.ActorRef, actorUID, runscPath string, actorDirs *ateworkerpb.ActorDirs, containers []*ateworkerpb.Container, sandboxExited bool) error + // flags holds the watched JSON flag configuration. - flags *flagStore + flags *flagStore + families actornet.IPFamilies // checkpointWrites holds a slot per checkpoint writing its page cache, // which memoryReservedBytes budgets for. checkpointWrites chan struct{} - borrow *memborrow.Ledger + // exitChecks holds a slot per container exit check that runs. + exitChecks chan struct{} + borrow *memborrow.Ledger // enableCoreTags indicates whether the host kernel supports core tagging. enableCoreTags bool @@ -428,17 +459,20 @@ type AteWorkerService struct { var _ ateworkerpb.WorkerServer = (*AteWorkerService)(nil) // NewService creates a new AteWorkerService. -func NewService(tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, maxActors int, flags *flagStore, bootID string) *AteWorkerService { +func NewService(tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, maxActors int, flags *flagStore, bootID string, families actornet.IPFamilies) *AteWorkerService { s := &AteWorkerService{ locks: actorlock.New(), inFlight: actorlock.NewInFlight(), actors: map[string]*hostedActor{}, maxActors: maxActors, + procs: newProcScaler(), tunnel: tunnel, actorLogger: actorLogger, cgroupRoot: defaultCgroupRoot, flags: flags, + families: families, checkpointWrites: make(chan struct{}, checkpointWriteSlots), + exitChecks: make(chan struct{}, containerExitChecks), bootID: bootID, enableCoreTags: checkCoreTagsSupported(), } @@ -447,8 +481,8 @@ func NewService(tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, maxAc } // beginRPC registers before checking the drain flag so shutdown cannot miss it. -func (s *AteWorkerService) beginRPC(actorUID, name string, cancel context.CancelFunc) (func(), error) { - release := s.inFlight.Add(actorUID, name, cancel) +func (s *AteWorkerService) beginRPC(actorUID, name string) (func(), error) { + release := s.inFlight.Add(actorUID, name) if err := s.rejectIfDraining(); err != nil { release() return nil, err @@ -465,22 +499,10 @@ func (s *AteWorkerService) rejectIfDraining() error { return nil } -// cancelStartups cancels all boots and restores, leaving checkpoints running. -func cancelStartups(ctx context.Context, inFlight *actorlock.InFlight) { - for _, actorUID := range inFlight.CancelStartups() { - slog.InfoContext(ctx, "Cancelling in-progress workload startup RPC due to graceful shutdown", - slog.String("actorUID", actorUID)) - } -} - // gracefulShutdown propagates SIGTERM into the sandbox and waits for the application's // containers to exit. func (s *AteWorkerService) gracefulShutdown(ctx context.Context) { s.shuttingDown.Store(true) - // If there is an active run or restore RPC, try to cancel it. This is considered - // less disruptive than waiting for it to complete and then immediately sending - // a SIGTERM. - cancelStartups(ctx, s.inFlight) // One deadline covers the whole drain. Waiting for the lock and waiting out // SIGTERM below both run against it, so the two phases split a single grace @@ -489,7 +511,9 @@ func (s *AteWorkerService) gracefulShutdown(ctx context.Context) { // workloadGracePeriod however the time falls between them. deadline := time.Now().Add(workloadGracePeriod) - // Let checkpoints finish saving state before stopping containers. + // Let in-flight boots, restores and checkpoints finish before stopping + // containers. Canceling a boot or restore would crash an actor that has + // not served yet. waitCtx, waitCancel := context.WithDeadline(ctx, deadline) defer waitCancel() if !s.inFlight.WaitIdle(waitCtx) { @@ -514,7 +538,7 @@ func (s *AteWorkerService) gracefulShutdown(ctx context.Context) { for _, session := range sessions { for _, name := range session.containers { wg.Add(1) - go func(rcmd *runsc, containerName string) { + go func(rcmd containerRuntime, containerName string) { defer wg.Done() if err := killContainer(ctx, rcmd, containerName, deadline); err != nil { slog.WarnContext(ctx, "Failed to kill container during shutdown", slog.String("container", containerName), slog.Any("err", err)) @@ -542,9 +566,7 @@ var containerKillTimeout = 5 * time.Second type containerRuntime interface { cmdKill(ctx context.Context, containerName, signal string) error cmdWait(ctx context.Context, containerName string) error - cmdState(ctx context.Context, containerName string) error - cmdDelete(ctx context.Context, containerName string) error - cmdList(ctx context.Context) ([]string, error) + cmdDelete(ctx context.Context, containerNames ...string) error } // killContainer stops a container by sending SIGTERM, waiting until deadline, and @@ -670,17 +692,17 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run return nil, fmt.Errorf("gave up waiting for the actor's lock: %w", ctx.Err()) } defer s.locks.Unlock(req.GetActorUid()) - ctx, cancel := context.WithCancel(ctx) - defer cancel() - release, err := s.beginRPC(req.GetActorUid(), rpcRunWorkload, cancel) + release, err := s.beginRPC(req.GetActorUid(), rpcRunWorkload) if err != nil { return nil, err } defer release() - if err := resetRunscStateAndPidFileDirs(req.GetActorDirs()); err != nil { + // Kill a leftover sentry before resetting its records, so a failed kill + // leaves them for TerminateWorkload to delete the sandbox. + if err := s.removeStaleSandboxLeaf(ctx, req.GetActorUid()); err != nil { return nil, err } - if err := s.removeStaleSandboxLeaf(ctx, req.GetActorUid()); err != nil { + if err := resetRunscStateAndPidFileDirs(req.GetActorDirs()); err != nil { return nil, err } @@ -701,7 +723,7 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run return nil, err } // Publish attribution before boot so stats can include startup usage. - hosted, err := s.hostActor(ctx, attribution, req.GetActorDirs(), sizing.FromLimits(req.GetResources().GetLimits()).MemoryBytes) + hosted, err := s.hostActor(ctx, attribution, req.GetActivationUid(), req.GetActorDirs(), sizing.FromLimits(req.GetResources().GetLimits()).MemoryBytes) if err != nil { return nil, err } @@ -726,13 +748,10 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run if err := s.tunnel.Deactivate(cleanupCtx, workerstats.ActorAttributionFromRequest(req)); err != nil { slog.WarnContext(cleanupCtx, "Failed to deactivate actor networking after Run failure", slog.Any("err", err)) } - deleteContainers(cleanupCtx, rcmd, containersToDelete, "Run") - // Detach any bundle rootfs overlays a partially-completed setup - // mounted, mirroring the post-checkpoint cleanup — otherwise they - // linger in this namespace until atelet wipes the bundle dirs. - // Run before the network cleanup. - if err := imagecache.UnmountAllUnder(req.GetActorDirs().GetOciBundleDir()); err != nil { - slog.WarnContext(ctx, "Failed to unmount bundle rootfs overlays after Run failure", + if err := s.teardownContainers(cleanupCtx, req.GetActorUid(), req.GetActorDirs(), containerNames(req.GetSpec().GetContainers()), func() error { + return deleteContainers(cleanupCtx, rcmd, containersToDelete) + }); err != nil { + slog.WarnContext(cleanupCtx, "Failed to clean up runsc containers after Run failure", "actorUID", req.GetActorUid(), "err", err) } if err := s.unhostActor(cleanupCtx, req.GetActorUid()); err != nil { @@ -771,7 +790,7 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run // capabilities, so ateworker mounts it, and runsc's gofer resolves the // mount in this pod's mount namespace. for _, ac := range req.GetSpec().GetContainers() { - pw, err := s.actorLogger.StartJSONLogPipe(attribution, ac.GetName()) + pw, err := s.startContainerLogs(hosted, rcmd, ac.GetName()) if err != nil { return nil, fmt.Errorf("while starting json log pipe for %q: %w", ac.GetName(), err) } @@ -832,8 +851,7 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke ctx, cancel := ateworker.CheckpointContext(ctx) defer cancel() - // Not cancelable: a checkpoint is saving the actor's state. - defer s.inFlight.Add(req.GetActorUid(), rpcCheckpointWorkload, nil)() + defer s.inFlight.Add(req.GetActorUid(), rpcCheckpointWorkload)() // Per-phase timing, recorded on the way out so a failed checkpoint still // reports the phases it completed, and the failing step its elapsed time. @@ -852,7 +870,7 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke } s.actorLogger.EmitLifecycleLog(ctx, "Actor checkpointing", attribution) - // Read before the snapshot: a MEMORY checkpoint stops the sandbox, and its + // Read before the snapshot: a checkpoint stops the sandbox, and its // cgroup with it. The final record waits for the teardown. hosted := s.lookupActor(req.GetActorUid()) if hosted != nil { @@ -886,6 +904,7 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke containers := req.GetSpec().GetContainers() durablePaths := durableFSCheckpointPaths(containers) + var sandboxExited bool // Cleanup the containers after checkpointing. This also unhosts the actor, // before the snapshot listing below can fail. @@ -893,7 +912,7 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke terminate := func() error { cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) defer cancel() - err := s.terminateWorkload(cleanupCtx, attribution.Ref, attribution.UID, req.GetRunscPath(), req.GetActorDirs(), containers) + err := s.terminateWorkload(cleanupCtx, attribution.Ref, attribution.UID, req.GetRunscPath(), req.GetActorDirs(), containers, sandboxExited) if err != nil { slog.WarnContext(cleanupCtx, "failed to terminate workload after checkpoint", slog.String("actor", attribution.Ref.String()), @@ -906,6 +925,20 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke } fsPaths := slices.Concat(rootfsFSCheckpointPaths(containers), durablePaths) + var sandbox *sandboxProcess + if hosted != nil { + sandbox = hosted.sandbox + } + if sandbox == nil { + // never pinned: fall back to the pidfile, still better than + // cleaning up before the sandbox exits + var err error + if sandbox, err = openSandboxProcess(req.GetActorDirs()); err != nil { + slog.WarnContext(ctx, "Cannot watch the sandbox exit after checkpoint", slog.Any("err", err)) + } else { + defer sandbox.Close() + } + } var checkpointFn func(context.Context) error switch fidelity { case ateworkerpb.SnapshotFidelity_SNAPSHOT_FIDELITY_VOLUMES: @@ -913,20 +946,38 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke return nil, fmt.Errorf("no durable-dir volumes found for VOLUMES snapshot") } checkpointFn = func(ctx context.Context) error { + // Set before the checkpoint stops the sandbox, as for MEMORY. + if hosted != nil { + hosted.stopping.Store(true) + } err := rcmd.cmdFsCheckpoint(ctx, ocispec.SandboxID, checkpointPath, durablePaths) - timing.fsCheckpoint = lap(&tLast) if err != nil { + if hosted != nil { + hosted.stopping.Store(false) + } + timing.fsCheckpoint = lap(&tLast) return fmt.Errorf("while checkpointing durable-dir volumes: %w", err) } + sandboxExited = waitSandboxExited(ctx, sandbox) + timing.fsCheckpoint = lap(&tLast) return nil } case ateworkerpb.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS: checkpointFn = func(ctx context.Context) error { + // Set before the checkpoint stops the sandbox, as for MEMORY. + if hosted != nil { + hosted.stopping.Store(true) + } err := rcmd.cmdFsCheckpoint(ctx, ocispec.SandboxID, checkpointPath, fsPaths) - timing.fsCheckpoint = lap(&tLast) if err != nil { + if hosted != nil { + hosted.stopping.Store(false) + } + timing.fsCheckpoint = lap(&tLast) return fmt.Errorf("while checkpointing container filesystems: %w", err) } + sandboxExited = waitSandboxExited(ctx, sandbox) + timing.fsCheckpoint = lap(&tLast) return nil } case ateworkerpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY: @@ -934,20 +985,8 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke // rootfs bundle and durable-dir volumes into /fs when // present. checkpointFn = func(ctx context.Context) error { - var sandbox *sandboxProcess if hosted != nil { hosted.stopping.Store(true) - sandbox = hosted.sandbox - } - if sandbox == nil { - // never pinned: fall back to the pidfile, still better than - // cleaning up before the sandbox is reaped - var err error - if sandbox, err = openSandboxProcess(req.GetActorDirs()); err != nil { - slog.WarnContext(ctx, "Cannot watch the sandbox exit after checkpoint", slog.Any("err", err)) - } else { - defer sandbox.Close() - } } err := rcmd.cmdCheckpoint(ctx, ocispec.SandboxID, checkpointPath, fsPaths) if err != nil { @@ -959,12 +998,7 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke timing.checkpoint = lap(&tLast) return fmt.Errorf("while checkpointing the sandbox: %w", err) } - // the checkpoint stops the sandbox, runsc delete fails until it is reaped - if sandbox != nil { - if err := sandbox.waitGone(sandboxExitTimeout); err != nil { - slog.WarnContext(ctx, "Sandbox did not go away after checkpoint", slog.Any("err", err)) - } - } + sandboxExited = waitSandboxExited(ctx, sandbox) timing.checkpoint = lap(&tLast) return nil } @@ -1009,7 +1043,7 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke for i, f := range snapshotFiles { written[i] = filepath.Join(checkpointPath, f) } - if err := snapshotcache.StartWriteback(written, func() { s.borrow.Return(borrowed) }); err != nil { + if err := snapshotcache.StartWriteback(written, s.checkpointFlush(cacheHigh, borrowed), func() { s.borrow.Return(borrowed) }); err != nil { s.borrow.Return(borrowed) slog.WarnContext(ctx, "Failed to start checkpoint writeback", slog.String("actorUID", req.GetActorUid()), slog.Any("err", err)) } @@ -1024,6 +1058,18 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke return resp, nil } +// waitSandboxExited reports whether the checkpointed sandbox has exited. +func waitSandboxExited(ctx context.Context, sandbox *sandboxProcess) bool { + if sandbox == nil { + return false + } + if err := sandbox.waitExited(ctx, sandboxExitTimeout); err != nil { + slog.WarnContext(ctx, "Sandbox did not exit after checkpoint", slog.Any("err", err)) + return false + } + return true +} + // listSnapshotFiles returns the (relative) names of regular files directly under // dir, dir/fs, and dir/rootfs, which atelet ships to object storage as the // snapshot. @@ -1071,44 +1117,13 @@ func cleanupContainers(ctx context.Context, rcmd containerRuntime, containers [] } names = append(names, ocispec.SandboxID) - // Check state of all containers to mimic containerd. - // Without this, `runsc delete` occasionally throws an error. - present := make([]string, 0, len(names)) - for _, name := range names { - if err := rcmd.cmdState(ctx, name); err != nil { - err = fmt.Errorf("while checking state of %q container: %w", name, err) - gone, listErr := isContainerAlreadyGone(ctx, rcmd, name) - if listErr != nil { - return errors.Join(err, listErr) - } - if gone { - slog.InfoContext(ctx, "runsc container already destroyed, skipping its cleanup", slog.String("container", name)) - continue - } - return err - } - present = append(present, name) - } - - for _, name := range present { - if err := rcmd.cmdDelete(ctx, name); err != nil { - return fmt.Errorf("while deleting %q container: %w", name, err) - } + if err := rcmd.cmdDelete(ctx, names...); err != nil { + return fmt.Errorf("while deleting containers %q: %w", names, err) } return nil } -// isContainerAlreadyGone reports whether runsc no longer has a record of the -// container. -func isContainerAlreadyGone(ctx context.Context, rcmd containerRuntime, name string) (bool, error) { - ids, err := rcmd.cmdList(ctx) - if err != nil { - return false, err - } - return !slices.Contains(ids, name), nil -} - func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb.RestoreWorkloadRequest) (resp *ateworkerpb.RestoreWorkloadResponse, retErr error) { if err := ateworkervalidation.ValidateRestoreWorkloadRequest(ctx, req); err != nil { return nil, err @@ -1129,8 +1144,6 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb return nil, fmt.Errorf("gave up waiting for the actor's lock: %w", ctx.Err()) } defer s.locks.Unlock(req.GetActorUid()) - ctx, cancel := context.WithCancel(ctx) - defer cancel() // Per-phase timing, recorded on the way out so a failed restore still // reports the phases it completed, and the failing step its elapsed time. @@ -1148,15 +1161,16 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb slog.LogAttrs(ctx, slog.LevelInfo, "Restore timing breakdown", attrs...) }() - release, err := s.beginRPC(req.GetActorUid(), rpcRestoreWorkload, cancel) + release, err := s.beginRPC(req.GetActorUid(), rpcRestoreWorkload) if err != nil { return nil, err } defer release() - if err := resetRunscStateAndPidFileDirs(req.GetActorDirs()); err != nil { + // Same order as RunWorkload. + if err := s.removeStaleSandboxLeaf(ctx, req.GetActorUid()); err != nil { return nil, err } - if err := s.removeStaleSandboxLeaf(ctx, req.GetActorUid()); err != nil { + if err := resetRunscStateAndPidFileDirs(req.GetActorDirs()); err != nil { return nil, err } @@ -1179,7 +1193,7 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb if err != nil { return nil, err } - hosted, err := s.hostActor(ctx, attribution, req.GetActorDirs(), sizing.FromLimits(req.GetResources().GetLimits()).MemoryBytes) + hosted, err := s.hostActor(ctx, attribution, req.GetActivationUid(), req.GetActorDirs(), sizing.FromLimits(req.GetResources().GetLimits()).MemoryBytes) timing.netSetup = lap(&tLast) if err != nil { return nil, err @@ -1205,10 +1219,10 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb if err := s.tunnel.Deactivate(cleanupCtx, attribution); err != nil { slog.WarnContext(cleanupCtx, "Failed to deactivate actor networking after Restore failure", slog.Any("err", err)) } - deleteContainers(cleanupCtx, rcmd, containersToDelete, "Restore") - // Same overlay detach as the Run-failure path above. - if err := imagecache.UnmountAllUnder(req.GetActorDirs().GetOciBundleDir()); err != nil { - slog.WarnContext(ctx, "Failed to unmount bundle rootfs overlays after Restore failure", + if err := s.teardownContainers(cleanupCtx, req.GetActorUid(), req.GetActorDirs(), containerNames(containers), func() error { + return deleteContainers(cleanupCtx, rcmd, containersToDelete) + }); err != nil { + slog.WarnContext(cleanupCtx, "Failed to clean up runsc containers after Restore failure", "actorUID", req.GetActorUid(), "err", err) } if err := s.unhostActor(cleanupCtx, req.GetActorUid()); err != nil { @@ -1273,7 +1287,7 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb // every line is tagged with the originating container (ate.actor.container.name). // app_create includes starting that pipe. for _, ac := range containers { - pw, err := s.actorLogger.StartJSONLogPipe(attribution, ac.GetName()) + pw, err := s.startContainerLogs(hosted, rcmd, ac.GetName()) timing.appCreate += lap(&tLast) if err != nil { return nil, fmt.Errorf("while starting json log pipe for %q: %w", ac.GetName(), err) @@ -1355,12 +1369,9 @@ func (s *AteWorkerService) TerminateWorkload(ctx context.Context, req *ateworker attribution := workerstats.ActorAttributionFromRequest(req) - hosted := s.lookupActor(attribution.UID) - if hosted != nil { - s.readFinal(ctx, hosted) - } - err := s.terminateWorkload(ctx, attribution.Ref, attribution.UID, req.GetRunscPath(), req.GetActorDirs(), req.GetSpec().GetContainers()) - s.recordFinalIfEnded(ctx, hosted) + err := s.endActivation(ctx, s.lookupActor(attribution.UID), s.readFinal, func() error { + return s.terminateWorkload(ctx, attribution.Ref, attribution.UID, req.GetRunscPath(), req.GetActorDirs(), req.GetSpec().GetContainers(), false) + }) if err != nil { return nil, fmt.Errorf("failed to terminate workload: %w", err) } @@ -1370,7 +1381,7 @@ func (s *AteWorkerService) TerminateWorkload(ctx context.Context, req *ateworker return &ateworkerpb.TerminateWorkloadResponse{}, nil } -func (s *AteWorkerService) terminateWorkload(ctx context.Context, actorRef resources.ActorRef, actorUID, runscPath string, actorDirs *ateworkerpb.ActorDirs, containers []*ateworkerpb.Container) error { +func (s *AteWorkerService) terminateWorkload(ctx context.Context, actorRef resources.ActorRef, actorUID, runscPath string, actorDirs *ateworkerpb.ActorDirs, containers []*ateworkerpb.Container, sandboxExited bool) error { if hosted := s.lookupActor(actorUID); hosted != nil { hosted.stopping.Store(true) } @@ -1391,30 +1402,12 @@ func (s *AteWorkerService) terminateWorkload(ctx context.Context, actorRef resou // container without its record and the actor unrecoverable. cleanupCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), 30*time.Second) defer cancel() - // Stop the containers before deleting them, to avoid leaving a live container - // with no bundle on disk. Best-effort: if they are already stopped, the - // delete succeeds anyway. - stopContainers(cleanupCtx, rcmd, containers) - // Keep this as best-effort cleanup: atelet resets the bundle and checkpoint - // directories after uploading the snapshot. - if err := cleanupContainers(cleanupCtx, rcmd, containers); err != nil { + if err := s.teardownContainers(cleanupCtx, actorUID, actorDirs, containerNames(containers), func() error { + return terminateContainers(cleanupCtx, rcmd, containers, sandboxExited) + }); err != nil { errs = append(errs, fmt.Errorf("while cleaning up runsc containers: %w", err)) } - // The actor may resume on another worker, so this one may never see another - // Run or Restore for it. Reset files here to close the loop. - if err := resetRunscStateAndPidFileDirs(actorDirs); err != nil { - errs = append(errs, fmt.Errorf("while resetting runsc state and pid file dirs: %w", err)) - } - - // Detach the overlay rootfs mounts before atelet wipes the bundle dirs - // (deleting a bundle out from under a live mount in this namespace would - // leave the mount orphaned until the pod restarts). Best-effort, same as - // the container cleanup above. - if err := imagecache.UnmountAllUnder(actorDirs.GetOciBundleDir()); err != nil { - errs = append(errs, fmt.Errorf("while unmounting bundle rootfs overlays: %w", err)) - } - if err := s.unhostActor(ctx, actorUID); err != nil { errs = append(errs, fmt.Errorf("while cleaning up actor network: %w", err)) } @@ -1422,11 +1415,73 @@ func (s *AteWorkerService) terminateWorkload(ctx context.Context, actorRef resou return errors.Join(errs...) } -func deleteContainers(ctx context.Context, rcmd *runsc, containers []string, operation string) { +func terminateContainers(ctx context.Context, rcmd containerRuntime, containers []*ateworkerpb.Container, sandboxExited bool) error { + // Stop any live containers before their bundles can be removed. + if !sandboxExited { + stopContainers(ctx, rcmd, containers) + } + return cleanupContainers(ctx, rcmd, containers) +} + +// deleteContainers deletes the given runsc containers, last first, and +// returns every failure. +func deleteContainers(ctx context.Context, rcmd containerRuntime, containers []string) error { + var errs []error for _, container := range slices.Backward(containers) { if err := rcmd.cmdDelete(ctx, container); err != nil { - slog.WarnContext(ctx, "Failed to delete runsc container after failure", - "operation", operation, "container", container, "err", err) + errs = append(errs, fmt.Errorf("while deleting %q container: %w", container, err)) + } + } + return errors.Join(errs...) +} + +// teardownContainers deletes the actor's runsc containers with del. If that +// fails, it kills the sandbox instead. It then releases the containers, +// unless the kill failed too: the sentry may still run, so runsc's records +// and the overlays stay for a retried TerminateWorkload to delete it. +func (s *AteWorkerService) teardownContainers(ctx context.Context, actorUID string, actorDirs *ateworkerpb.ActorDirs, containers []string, del func() error) error { + if err := del(); err != nil { + slog.WarnContext(ctx, "Failed to delete runsc containers, killing the sandbox", + slog.String("actorUID", actorUID), slog.Any("err", err)) + if killErr := s.killSandbox(ctx, actorUID, containers); killErr != nil { + return errors.Join(err, killErr) + } + } + return releaseContainers(actorDirs) +} + +// killSandbox kills the sentry and removes the cgroup leaves of the sandbox +// and of the application containers, which runsc delete would have removed. +func (s *AteWorkerService) killSandbox(ctx context.Context, actorUID string, containers []string) error { + // A hung delete can use up ctx, and the kills still need to run. + ctx = context.WithoutCancel(ctx) + // During a checkpoint the sentry sits in the checkpoint cgroup. + // checkpointIsolated removes that cgroup once it is empty. + ckptCtx, cancel := context.WithTimeout(ctx, 10*time.Second) + defer cancel() + var errs []error + if err := cgroup.KillLeafUnder(ckptCtx, s.cgroupRoot, actorUID+checkpointCgroupSuffix); err != nil { + errs = append(errs, fmt.Errorf("while killing checkpoint cgroup: %w", err)) + } + for _, name := range slices.Concat([]string{sandboxCgroupContainer}, containers) { + if err := s.removeContainerLeaf(ctx, actorUID, name); err != nil { + errs = append(errs, err) } } + return errors.Join(errs...) +} + +// releaseContainers resets runsc's state and pid file dirs, since the actor +// may resume on another worker and this one may never see another Run or +// Restore for it. It detaches the rootfs overlays, which otherwise stay +// mounted in this namespace until atelet removes the bundle dir. +func releaseContainers(actorDirs *ateworkerpb.ActorDirs) error { + var errs []error + if err := resetRunscStateAndPidFileDirs(actorDirs); err != nil { + errs = append(errs, fmt.Errorf("while resetting runsc state and pid file dirs: %w", err)) + } + if err := imagecache.UnmountBundlesUnder(actorDirs.GetOciBundleDir()); err != nil { + errs = append(errs, fmt.Errorf("while unmounting bundle rootfs overlays: %w", err)) + } + return errors.Join(errs...) } diff --git a/cmd/ateworker-gvisor/main_test.go b/cmd/ateworker-gvisor/main_test.go index 7a0926052e..37dc8dc1cf 100644 --- a/cmd/ateworker-gvisor/main_test.go +++ b/cmd/ateworker-gvisor/main_test.go @@ -202,7 +202,7 @@ func TestSandboxLogAttribution(t *testing.T) { } const logTime = "2026-10-08T03:40:00Z" const jsonMessage = "container.go:123] cannot start container" - const jsonLine = `{"msg":"container.go:123] cannot start container","level":"warning","time":"2026-10-08T03:40:00Z","ate.actor.name":"forged"}` + const jsonLine = `{"msg":"container.go:123] cannot start container","level":"warning","time":"2026-10-08T03:40:00Z","ate.actor.name":"forged","log.iostream":"stdout"}` if _, err := fmt.Fprintln(pw, jsonLine); err != nil { t.Fatalf("write json line: %v", err) } @@ -235,6 +235,9 @@ func TestSandboxLogAttribution(t *testing.T) { actorName := string(ateattr.ActorNameKey) containerName := string(ateattr.ActorContainerNameKey) for name, record := range map[string]map[string]any{"json": jsonRecord, "plain": plainRecord} { + if v, ok := record["log.iostream"]; ok { + t.Errorf("%s record: log.iostream = %v, want absent for combined streams", name, v) + } labels, ok := record["labels"].(map[string]any) if !ok { t.Fatalf("%s record has no labels group: %v", name, record) diff --git a/cmd/ateworker-gvisor/memlimit.go b/cmd/ateworker-gvisor/memlimit.go index 5433b391a6..d5e731fbec 100644 --- a/cmd/ateworker-gvisor/memlimit.go +++ b/cmd/ateworker-gvisor/memlimit.go @@ -57,20 +57,30 @@ func (s *AteWorkerService) throttleSandboxMemory(ctx context.Context, hosted *ho // the host's RAM, and no watch. // https://github.com/google/gvisor/blob/0068142bdeb9de91fe72bf9794204de6dec92cb4/runsc/cgroup/cgroup_v2.go#L138-L153 func (s *AteWorkerService) removeStaleSandboxLeaf(ctx context.Context, actorUID string) error { - dir := s.sandboxLeaf(actorUID) + return s.removeContainerLeaf(ctx, actorUID, sandboxCgroupContainer) +} + +// removeContainerLeaf kills what is left in the cgroup leaf of one of the +// actor's runsc containers and removes the leaf. +func (s *AteWorkerService) removeContainerLeaf(ctx context.Context, actorUID, containerName string) error { + dir := s.containerLeaf(actorUID, containerName) killCtx, cancel := context.WithTimeout(ctx, 10*time.Second) defer cancel() if err := cgroup.KillLeafUnder(killCtx, s.cgroupRoot, filepath.Base(dir)); err != nil { - return fmt.Errorf("while clearing a leftover sandbox cgroup: %w", err) + return fmt.Errorf("while clearing leftover cgroup %q: %w", dir, err) } if err := os.Remove(dir); err != nil && !errors.Is(err, fs.ErrNotExist) { - return fmt.Errorf("while removing leftover sandbox cgroup %q: %w", dir, err) + return fmt.Errorf("while removing leftover cgroup %q: %w", dir, err) } return nil } func (s *AteWorkerService) sandboxLeaf(actorUID string) string { - return filepath.Join(s.cgroupRoot, ocispec.GVisorCgroupLeaf(actorUID, sandboxCgroupContainer)) + return s.containerLeaf(actorUID, sandboxCgroupContainer) +} + +func (s *AteWorkerService) containerLeaf(actorUID, containerName string) string { + return filepath.Join(s.cgroupRoot, ocispec.GVisorCgroupLeaf(actorUID, containerName)) } // swapMemoryMaxForHigh returns the limit it moved, or 0 if the leaf has none. diff --git a/cmd/ateworker-gvisor/memory.go b/cmd/ateworker-gvisor/memory.go index 942741133a..cef55b6c5b 100644 --- a/cmd/ateworker-gvisor/memory.go +++ b/cmd/ateworker-gvisor/memory.go @@ -70,3 +70,15 @@ func (s *AteWorkerService) checkpointCacheLimit(hosted *hostedActor, actorUID st } return max(checkpointWriteHeadroom, booked-used) + borrowed, borrowed } + +// checkpointFlush returns the flush func for a checkpoint's writeback, given +// what checkpointCacheLimit returned. When the pod lent the whole write, +// write-out waits until memory is tight. When it lent part or none, write-out +// starts right away: the rest of the write isn't in the ledger, and terminate +// has released the actor's booking. +func (s *AteWorkerService) checkpointFlush(cacheHigh, borrowed int64) func() (bool, <-chan struct{}) { + if cacheHigh != 0 || borrowed <= 0 { + return nil + } + return s.borrow.Tight +} diff --git a/cmd/ateworker-gvisor/memory_test.go b/cmd/ateworker-gvisor/memory_test.go new file mode 100644 index 0000000000..a74965ba68 --- /dev/null +++ b/cmd/ateworker-gvisor/memory_test.go @@ -0,0 +1,53 @@ +//go:build linux + +// Copyright 2026 The Agent Substrate 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" + + "go.ate.dev/substrate/internal/ateworker/memborrow" +) + +func TestCheckpointFlush(t *testing.T) { + // a pod with room to spare, so Tight reports false + s := &AteWorkerService{borrow: &memborrow.Ledger{ + Unbooked: func(int64) int64 { return 3 << 30 }, + PodMemory: func() (int64, int64, error) { return 4 << 30, 1 << 30, nil }, + }} + for _, tc := range []struct { + name string + cacheHigh, borrowed int64 + // wantNow is whether write-out starts right away. + wantNow bool + }{ + {name: "whole write lent", cacheHigh: 0, borrowed: 512 << 20, wantNow: false}, + {name: "partial loan", cacheHigh: 528 << 20, borrowed: 256 << 20, wantNow: true}, + {name: "sandbox memory reads 0", cacheHigh: 0, borrowed: 0, wantNow: true}, + } { + t.Run(tc.name, func(t *testing.T) { + flush := s.checkpointFlush(tc.cacheHigh, tc.borrowed) + // StartWriteback starts write-out right away for a nil flush. + now := flush == nil + if !now { + now, _ = flush() + } + if now != tc.wantNow { + t.Errorf("checkpointFlush(%d, %d) starts write-out right away = %v, want %v", tc.cacheHigh, tc.borrowed, now, tc.wantNow) + } + }) + } +} diff --git a/cmd/ateworker-gvisor/procs.go b/cmd/ateworker-gvisor/procs.go new file mode 100644 index 0000000000..9732859678 --- /dev/null +++ b/cmd/ateworker-gvisor/procs.go @@ -0,0 +1,65 @@ +//go:build linux + +// Copyright 2026 The Agent Substrate 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 ( + "runtime" + + "go.ate.dev/substrate/internal/ateworker/pid1" +) + +// actorsPerProc is how many hosted actors it takes for the worker to add 1 +// proc. +const actorsPerProc = 2 + +// procStep is the multiple that the added procs are rounded up to. +// Changing GOMAXPROCS causes a stop-the-world in the Go runtime, +// so it must change sparingly. +const procStep = 8 + +// procScaler grows GOMAXPROCS with the number of running actors on a host. +// This ensures that idle workers don't have many idle threads. +type procScaler struct { + // base is GOMAXPROCS with zero actors running. + base int + // limit is GOMAXPROCS as the Go runtime would have set it by default. + limit int +} + +// newProcScaler returns a procScaler, or nil if GOMAXPROCS isn't capped. +func newProcScaler() *procScaler { + base, limit := runtime.GOMAXPROCS(0), pid1.HostProcs() + if limit <= base { + return nil + } + return &procScaler{base: base, limit: limit} +} + +// procs returns GOMAXPROCS for a worker that hosts currentActors. +func (p *procScaler) procs(currentActors int) int { + added := (currentActors/actorsPerProc + procStep - 1) / procStep * procStep + return min(p.limit, p.base+added) +} + +// resize sets GOMAXPROCS for the given number of running actors. +// This causes a stop-the-world if GOMAXPROCS's value does change. +func (p *procScaler) resize(currentActors int) { + if p == nil { + return + } + runtime.GOMAXPROCS(p.procs(currentActors)) +} diff --git a/cmd/ateworker-gvisor/procs_test.go b/cmd/ateworker-gvisor/procs_test.go new file mode 100644 index 0000000000..4a8481f86a --- /dev/null +++ b/cmd/ateworker-gvisor/procs_test.go @@ -0,0 +1,77 @@ +//go:build linux + +// Copyright 2026 The Agent Substrate 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 ( + "context" + "fmt" + "runtime" + "testing" + + "go.ate.dev/substrate/internal/resources" +) + +func TestProcScalerProcs(t *testing.T) { + p := &procScaler{base: 16, limit: 192} + tests := []struct { + name string + actors int + want int + }{ + {name: "no actor", actors: 0, want: 16}, + {name: "fewer actors than one proc takes", actors: actorsPerProc - 1, want: 16}, + {name: "one more proc is rounded up to a step", actors: actorsPerProc, want: 16 + procStep}, + {name: "a full step", actors: actorsPerProc * procStep, want: 16 + procStep}, + {name: "one proc past a step", actors: actorsPerProc * (procStep + 1), want: 16 + 2*procStep}, + {name: "more actors than the host has procs for", actors: 1000, want: 192}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if got := p.procs(tc.actors); got != tc.want { + t.Errorf("procs(%d) = %d, want %d", tc.actors, got, tc.want) + } + }) + } +} + +func TestHostingAnActorResizesProcs(t *testing.T) { + old := runtime.GOMAXPROCS(1) + t.Cleanup(func() { runtime.GOMAXPROCS(old) }) + s := &AteWorkerService{ + actors: map[string]*hostedActor{}, + maxActors: actorsPerProc, + procs: &procScaler{base: 1, limit: 1 + procStep}, + } + + for i := range actorsPerProc { + if got := runtime.GOMAXPROCS(0); got != 1 { + t.Errorf("GOMAXPROCS with %d actors hosted = %d, want 1", i, got) + } + if _, _, err := s.admitActor(resources.ActorAttribution{UID: fmt.Sprintf("actor-%d", i)}, "", 0); err != nil { + t.Fatal(err) + } + } + if got, want := runtime.GOMAXPROCS(0), 1+procStep; got != want { + t.Errorf("GOMAXPROCS with %d actors hosted = %d, want %d", actorsPerProc, got, want) + } + if err := s.unhostActor(context.Background(), "actor-0"); err != nil { + t.Fatal(err) + } + if got := runtime.GOMAXPROCS(0); got != 1 { + t.Errorf("GOMAXPROCS with %d actors hosted = %d, want 1", actorsPerProc-1, got) + } +} diff --git a/cmd/ateworker-gvisor/runsc.go b/cmd/ateworker-gvisor/runsc.go index 0cef2a156b..850a3cba84 100644 --- a/cmd/ateworker-gvisor/runsc.go +++ b/cmd/ateworker-gvisor/runsc.go @@ -17,8 +17,8 @@ package main import ( - "bytes" "context" + "encoding/json" "fmt" "io" "log/slog" @@ -75,6 +75,16 @@ func (r *runsc) buildArgs(command, containerName string, extraArgs ...string) [] return args } +// command returns a command object that executes runsc with args. +func (r *runsc) command(ctx context.Context, args []string) *exec.Cmd { + cmd := exec.CommandContext(ctx, r.path, args...) + env := slices.DeleteFunc(os.Environ(), func(e string) bool { + return strings.HasPrefix(e, "GOMAXPROCS=") + }) + cmd.Env = append(env, "GOMAXPROCS=2") + return cmd +} + // durableVolumeNames returns the sorted, deduplicated durable-dir volume names // mounted by workload containers. func durableVolumeNames(spec *ateworkerpb.WorkloadSpec) []string { @@ -143,7 +153,7 @@ func (r *runsc) cmdCreate(ctx context.Context, out io.Writer, containerName stri return fmt.Errorf("while writing the OCI spec for %q: %w", containerName, err) } - cmd := exec.CommandContext(ctx, r.path, r.createArgs(containerName, additionalArgs)...) + cmd := r.command(ctx, r.createArgs(containerName, additionalArgs)) cmd.Stdout = out cmd.Stderr = out @@ -158,7 +168,7 @@ func (r *runsc) cmdCreate(ctx context.Context, out io.Writer, containerName stri func (r *runsc) cmdStart(ctx context.Context, out io.Writer, containerName string) error { slog.InfoContext(ctx, "About to run runsc start", slog.String("container", containerName)) - cmd := exec.CommandContext(ctx, r.path, r.buildArgs("start", containerName)...) + cmd := r.command(ctx, r.buildArgs("start", containerName)) cmd.Stdout = out cmd.Stderr = out @@ -184,7 +194,7 @@ func (r *runsc) checkpointArgs(containerName, checkpointPath string, fsCheckpoin func (r *runsc) cmdCheckpoint(ctx context.Context, containerName, checkpointPath string, fsCheckpointPaths []string) error { slog.InfoContext(ctx, "About to run runsc checkpoint", slog.String("container", containerName)) - cmd := exec.CommandContext(ctx, r.path, r.checkpointArgs(containerName, checkpointPath, fsCheckpointPaths)...) + cmd := r.command(ctx, r.checkpointArgs(containerName, checkpointPath, fsCheckpointPaths)) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() @@ -209,7 +219,7 @@ func (r *runsc) fsCheckpointArgs(containerName, checkpointPath string, fsCheckpo func (r *runsc) cmdFsCheckpoint(ctx context.Context, containerName, checkpointPath string, fsCheckpointPaths []string) error { slog.InfoContext(ctx, "About to run runsc fscheckpoint", slog.String("container", containerName)) - cmd := exec.CommandContext(ctx, r.path, r.fsCheckpointArgs(containerName, checkpointPath, fsCheckpointPaths)...) + cmd := r.command(ctx, r.fsCheckpointArgs(containerName, checkpointPath, fsCheckpointPaths)) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() @@ -239,7 +249,7 @@ func (r *runsc) cmdRestore(ctx context.Context, out io.Writer, containerName, ch return fmt.Errorf("while writing the OCI spec for %q: %w", containerName, err) } - cmd := exec.CommandContext(ctx, r.path, r.restoreArgs(containerName, checkpointPath)...) + cmd := r.command(ctx, r.restoreArgs(containerName, checkpointPath)) cmd.Stdout = out cmd.Stderr = out if err := cmd.Run(); err != nil { @@ -248,12 +258,10 @@ func (r *runsc) cmdRestore(ctx context.Context, out io.Writer, containerName, ch return nil } -func (r *runsc) cmdDelete(ctx context.Context, containerName string) error { - cmd := exec.CommandContext( - ctx, - r.path, - r.buildArgs("delete", containerName)..., - ) +// cmdDelete deletes the containers in the given order with one runsc +// execution. runsc stops at the first container it fails to delete. +func (r *runsc) cmdDelete(ctx context.Context, containerNames ...string) error { + cmd := r.command(ctx, r.buildArgs("delete", "", containerNames...)) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr err := cmd.Run() @@ -263,42 +271,12 @@ func (r *runsc) cmdDelete(ctx context.Context, containerName string) error { return nil } -func (r *runsc) cmdState(ctx context.Context, containerName string) error { - cmd := exec.CommandContext( - ctx, - r.path, - r.buildArgs("state", containerName)..., - ) - cmd.Stdout = os.Stdout - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - return fmt.Errorf("while running `runsc state`: %w", err) - } - return nil -} - -// cmdList returns the container IDs runsc has a record of. -func (r *runsc) cmdList(ctx context.Context) ([]string, error) { - cmd := exec.CommandContext( - ctx, - r.path, - r.buildArgs("list", "")..., - ) - var out bytes.Buffer - cmd.Stdout = &out - cmd.Stderr = os.Stderr - if err := cmd.Run(); err != nil { - return nil, fmt.Errorf("while running `runsc list`: %w", err) - } - return strings.Fields(out.String()), nil -} - // cmdKill sends signal to the given container's process(es) inside the gVisor // sandbox. Used during graceful shutdown to propagate SIGTERM to the actor. func (r *runsc) cmdKill(ctx context.Context, containerName, signal string) error { slog.InfoContext(ctx, "About to run runsc kill", slog.String("container", containerName), slog.String("signal", signal)) - cmd := exec.CommandContext(ctx, r.path, r.buildArgs("kill", "", containerName, signal)...) + cmd := r.command(ctx, r.buildArgs("kill", "", containerName, signal)) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { @@ -310,7 +288,7 @@ func (r *runsc) cmdKill(ctx context.Context, containerName, signal string) error // runWait runs `runsc wait [extraArgs...] ` and blocks until the // waited-on condition completes. func (r *runsc) runWait(ctx context.Context, containerName string, extraArgs ...string) error { - cmd := exec.CommandContext(ctx, r.path, r.buildArgs("wait", containerName, extraArgs...)...) + cmd := r.command(ctx, r.buildArgs("wait", containerName, extraArgs...)) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { @@ -326,6 +304,46 @@ func (r *runsc) cmdWait(ctx context.Context, containerName string) error { return r.runWait(ctx, containerName) } +// cmdState returns the container's status, as `runsc state` prints it: +// running while the first process lives, stopped after it exits or when the +// sandbox is gone. +func (r *runsc) cmdState(ctx context.Context, containerName string) (string, error) { + cmd := r.command(ctx, r.buildArgs("state", containerName)) + cmd.Stderr = os.Stderr + out, err := cmd.Output() + if err != nil { + return "", fmt.Errorf("while running `runsc state`: %w", err) + } + var state struct { + Status string `json:"status"` + } + if err := json.Unmarshal(out, &state); err != nil { + return "", fmt.Errorf("while parsing `runsc state` output: %w", err) + } + return state.Status, nil +} + +// cmdExitCode returns the exit code `runsc wait` prints for the container. It +// blocks while the container runs. +func (r *runsc) cmdExitCode(ctx context.Context, containerName string) (int32, error) { + cmd := r.command(ctx, r.buildArgs("wait", containerName)) + cmd.Stderr = os.Stderr + out, err := cmd.Output() + if err != nil { + return 0, fmt.Errorf("while running `runsc wait`: %w", err) + } + var result struct { + ExitStatus *int32 `json:"exitStatus"` + } + if err := json.Unmarshal(out, &result); err != nil { + return 0, fmt.Errorf("while parsing `runsc wait` output: %w", err) + } + if result.ExitStatus == nil { + return 0, fmt.Errorf("`runsc wait` printed no exit status: %q", out) + } + return *result.ExitStatus, nil +} + // cmdWaitRestore blocks until background page loading from `runsc restore -background` completes. func (r *runsc) cmdWaitRestore(ctx context.Context, containerName string) error { return r.runWait(ctx, containerName, "-restore") diff --git a/cmd/ateworker-gvisor/runsc_test.go b/cmd/ateworker-gvisor/runsc_test.go index 9791c31992..2f90cc0770 100644 --- a/cmd/ateworker-gvisor/runsc_test.go +++ b/cmd/ateworker-gvisor/runsc_test.go @@ -209,6 +209,31 @@ func TestBuildArgs(t *testing.T) { } } +// Verify that GOMAXPROCS is stripped out from runsc's env. +func TestCommandCapsGOMAXPROCS(t *testing.T) { + t.Setenv("GOMAXPROCS", "64") + t.Setenv("ATE_TEST_INHERITED", "1") + + r := &runsc{path: "/usr/local/bin/runsc"} + cmd := r.command(context.Background(), []string{"state", "app"}) + + if want := []string{"/usr/local/bin/runsc", "state", "app"}; !slices.Equal(cmd.Args, want) { + t.Errorf("command args = %v, want %v", cmd.Args, want) + } + var maxProcs []string + for _, e := range cmd.Env { + if strings.HasPrefix(e, "GOMAXPROCS=") { + maxProcs = append(maxProcs, e) + } + } + if want := []string{"GOMAXPROCS=2"}; !slices.Equal(maxProcs, want) { + t.Errorf("command environment has %v, want %v", maxProcs, want) + } + if !slices.Contains(cmd.Env, "ATE_TEST_INHERITED=1") { + t.Error("command environment lost the worker's other variables") + } +} + func TestBuildArgsEnableCoreTags(t *testing.T) { r := &runsc{ path: "/usr/bin/runsc", diff --git a/cmd/ateworker-gvisor/sandboxexit.go b/cmd/ateworker-gvisor/sandboxexit.go index d5276a7181..e800f8e0eb 100644 --- a/cmd/ateworker-gvisor/sandboxexit.go +++ b/cmd/ateworker-gvisor/sandboxexit.go @@ -17,6 +17,7 @@ package main import ( + "context" "fmt" "os" "strconv" @@ -31,12 +32,13 @@ import ( "go.ate.dev/substrate/internal/proto/ateworkerpb" ) -// sandboxExitTimeout bounds the wait for a checkpointed sandbox to go away. +// sandboxExitTimeout bounds the wait for a checkpointed sandbox to exit. const sandboxExitTimeout = 10 * time.Second -// sandboxProcess is the runsc sandbox across a MEMORY checkpoint, which stops -// it. runsc treats a sandbox as live while its pid exists, zombie included, so -// a delete issued before the sandbox is reaped fails. +// sandboxProcess is the runsc sandbox across a checkpoint, which stops it. +// Since gvisor/gvisor@f80859d424 (release-20260921.0) runsc treats an exited +// sandbox as stopped, zombie included, so once it exits cleanup can skip +// stopping its containers. type sandboxProcess struct { pid int pidfd int @@ -75,28 +77,30 @@ func (p *sandboxProcess) exited() (<-chan struct{}, error) { return pidfd.ExitedFD(p.pidfd) } +// hasExited reports if the sandbox has exited, and does not block. +func (p *sandboxProcess) hasExited() bool { + n, _ := unix.Poll([]unix.PollFd{{Fd: int32(p.pidfd), Events: unix.POLLIN}}, 0) + return n > 0 +} + func (p *sandboxProcess) Close() { _ = unix.Close(p.pidfd) } -// waitGone blocks until the sandbox has exited and been reaped. -func (p *sandboxProcess) waitGone(timeout time.Duration) error { - deadline := time.Now().Add(timeout) - // usually gone within a few milliseconds of the checkpoint returning - backoff := time.Millisecond - for { - // ESRCH only once the process is reaped. EPERM still means it exists. - err := unix.PidfdSendSignal(p.pidfd, 0, nil, 0) - if err == unix.ESRCH { - return nil - } - if err != nil && err != unix.EPERM { - return fmt.Errorf("signaling sandbox %d: %w", p.pid, err) - } - if time.Now().After(deadline) { - return fmt.Errorf("sandbox %d still present after %v", p.pid, timeout) - } - time.Sleep(backoff) - backoff = min(backoff*2, 50*time.Millisecond) +// waitExited blocks until the sandbox has exited. +func (p *sandboxProcess) waitExited(ctx context.Context, timeout time.Duration) error { + exited, err := p.exited() + if err != nil { + return fmt.Errorf("watching sandbox %d: %w", p.pid, err) + } + timer := time.NewTimer(timeout) + defer timer.Stop() + select { + case <-exited: + return nil + case <-timer.C: + return fmt.Errorf("sandbox %d still running after %v", p.pid, timeout) + case <-ctx.Done(): + return fmt.Errorf("waiting for sandbox %d to exit: %w", p.pid, ctx.Err()) } } diff --git a/cmd/ateworker-gvisor/sandboxexit_test.go b/cmd/ateworker-gvisor/sandboxexit_test.go index 64eb689390..6cbbae6518 100644 --- a/cmd/ateworker-gvisor/sandboxexit_test.go +++ b/cmd/ateworker-gvisor/sandboxexit_test.go @@ -17,6 +17,8 @@ package main import ( + "context" + "math" "os" "os/exec" "strconv" @@ -56,30 +58,61 @@ func startFakeSandbox(t *testing.T) (*exec.Cmd, *sandboxProcess) { return cmd, p } -func TestSandboxWaitGoneAfterReap(t *testing.T) { - cmd, p := startFakeSandbox(t) - _ = cmd.Process.Kill() - go func() { _, _ = cmd.Process.Wait() }() - if err := p.waitGone(5 * time.Second); err != nil { - t.Fatalf("waitGone = %v, want nil", err) +func TestWaitSandboxExitedReturnsFalseWhenExitUnconfirmed(t *testing.T) { + tests := []struct { + name string + sandbox *sandboxProcess + }{ + {name: "missing sandbox"}, + // no process can have this descriptor open + {name: "invalid pidfd", sandbox: &sandboxProcess{pidfd: math.MaxInt32}}, } -} - -func TestSandboxWaitGoneWaitsForReap(t *testing.T) { - cmd, p := startFakeSandbox(t) - // a zombie: killed, but nothing reaps it until cleanup - _ = cmd.Process.Kill() - err := p.waitGone(100 * time.Millisecond) - if err == nil || !strings.Contains(err.Error(), "still present") { - t.Fatalf("waitGone = %v, want a still present error", err) + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + if waitSandboxExited(t.Context(), tc.sandbox) { + t.Fatal("waitSandboxExited = true, want false") + } + }) } } -func TestSandboxWaitGoneTimesOutWhileRunning(t *testing.T) { - _, p := startFakeSandbox(t) - err := p.waitGone(10 * time.Millisecond) - if err == nil || !strings.Contains(err.Error(), "still present") { - t.Fatalf("waitGone = %v, want a still present error", err) +func TestSandboxWaitExited(t *testing.T) { + for _, tc := range []struct { + name string + kill bool + reap bool + canceled bool + timeout time.Duration + wantErr string + }{ + {name: "reaped", kill: true, reap: true, timeout: 5 * time.Second}, + // nothing reaps it until cleanup + {name: "zombie", kill: true, timeout: 5 * time.Second}, + {name: "running", timeout: 10 * time.Millisecond, wantErr: "still running"}, + {name: "canceled", canceled: true, timeout: 5 * time.Second, wantErr: "context canceled"}, + } { + t.Run(tc.name, func(t *testing.T) { + cmd, p := startFakeSandbox(t) + if tc.kill { + _ = cmd.Process.Kill() + } + if tc.reap { + _, _ = cmd.Process.Wait() + } + ctx, cancel := context.WithCancel(t.Context()) + defer cancel() + if tc.canceled { + cancel() + } + err := p.waitExited(ctx, tc.timeout) + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("waitExited = %v, want an error containing %q", err, tc.wantErr) + } + } else if err != nil { + t.Fatalf("waitExited = %v, want nil", err) + } + }) } } @@ -101,8 +134,7 @@ func TestSandboxExited(t *testing.T) { t.Fatal("not closed after the sandbox exited") } // the watch uses its own copy, so the sandbox's pidfd still works - go func() { _, _ = cmd.Process.Wait() }() - if err := p.waitGone(5 * time.Second); err != nil { - t.Fatalf("waitGone after the watch = %v", err) + if err := p.waitExited(t.Context(), 5*time.Second); err != nil { + t.Fatalf("waitExited after the watch = %v", err) } } diff --git a/cmd/ateworker-gvisor/stats.go b/cmd/ateworker-gvisor/stats.go index b5d7712e65..95ffa03952 100644 --- a/cmd/ateworker-gvisor/stats.go +++ b/cmd/ateworker-gvisor/stats.go @@ -206,6 +206,35 @@ func (s *AteWorkerService) readFinal(ctx context.Context, h *hostedActor) { } } +// readDeadFinal reads the cgroup of h's sandbox, which has died, for the final +// record. The cgroup keeps its CPU counter and memory peak until the teardown +// removes it, but the memory went with the processes, so memory usage and +// working set are left unset: no one measured them at the death. measure does +// the same for any empty cgroup; this also covers a kernel that does not +// report cgroup.events. A failed read leaves the newest sample to stand in, as +// in readFinal. +func (s *AteWorkerService) readDeadFinal(ctx context.Context, h *hostedActor) { + sample, _, err := s.measure(ctx, h) + if err != nil { + return + } + markMemoryUnmeasured(sample) + h.usage.Store(sample) +} + +// endActivation reads h's final usage with read, tears the activation down, +// and writes its final record, in that order: the reading needs the sandbox's +// cgroup, which the teardown removes. h is nil for an actor not hosted. It +// returns the teardown's error. +func (s *AteWorkerService) endActivation(ctx context.Context, h *hostedActor, read func(context.Context, *hostedActor), teardown func() error) error { + if h != nil { + read(ctx, h) + } + err := teardown() + s.recordFinalIfEnded(ctx, h) + return err +} + // recordFinalIfEnded writes h's final record if a checkpoint or terminate tore // its activation down, which unhosts the actor even when a later step fails. // The caller holds the actor's lock. @@ -254,9 +283,21 @@ func (s *AteWorkerService) measure(ctx context.Context, h *hostedActor) (*atewor raw = r return sample, nil, err }) + if err == nil && raw.Empty { + // No process is left in the cgroup, as after the sandbox died: its + // memory went with them, so none was measured. The CPU counter stays. + markMemoryUnmeasured(sample) + } return sample, raw, err } +// markMemoryUnmeasured says s carries no memory usage or working set. +func markMemoryUnmeasured(s *ateworkerpb.WorkloadStatsSample) { + s.MemoryCurrentBytes = 0 + s.MemoryWorkingSetBytes = 0 + s.MemoryUnmeasured = true +} + // sampleSandbox reads the sandbox cgroup and builds the sample attributed to // active, returning the raw reading alongside it. Errors come back raw -- // notably fs.ErrNotExist for a cgroup that is not there yet -- because the diff --git a/cmd/ateworker-microvm/checkpoint.go b/cmd/ateworker-microvm/checkpoint.go index e774f03f3f..3f0e81e1c1 100644 --- a/cmd/ateworker-microvm/checkpoint.go +++ b/cmd/ateworker-microvm/checkpoint.go @@ -23,6 +23,7 @@ import ( "log/slog" "os" "path/filepath" + "slices" "time" "go.ate.dev/substrate/internal/apierror" @@ -90,7 +91,7 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke ctx, cancel := ateworker.CheckpointContext(ctx) defer cancel() - defer s.inFlight.Add(req.GetActorUid(), rpcCheckpointWorkload, nil)() + defer s.inFlight.Add(req.GetActorUid(), rpcCheckpointWorkload)() // Per-phase timing, recorded on the way out so a failed checkpoint still // reports the phases it completed, and the failing step its elapsed time. @@ -114,10 +115,6 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke }) }() - if err := s.tunnel.Deactivate(ctx, attribution); err != nil { - return nil, err - } - actorUID := req.GetActorUid() actorDirs := req.GetActorDirs() @@ -157,8 +154,16 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke chSocket = ra.apiSocket } client := ch.NewClient(chSocket) + // Reach the VMM before deactivating the actor's networking, so a failed + // wait leaves the actor serving and the checkpoint can be retried. if _, err := client.WaitReady(ctx, 10*time.Second); err != nil { - return nil, fmt.Errorf("while waiting for CH api-socket: %w", err) + return nil, checkpointWaitReadyError(ctx, ra, err) + } + if ra != nil { + ra.checkpointWaitReadyFailures = 0 + } + if err := s.tunnel.Deactivate(ctx, attribution); err != nil { + return nil, err } // Read before the pause: a paused guest cannot answer. if hosted != nil { @@ -199,15 +204,22 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke // VOLUMES the workload cold-starts on restore, discarding rootfs state. shipsRootfs := includesRootfs(scope) var durableFiles []string + var snapshotRelease func() + defer func() { + if snapshotRelease != nil { + snapshotRelease() + } + }() g, gctx := errgroup.WithContext(ctx) if scope == ateworkerpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY { g.Go(func() error { t := time.Now() - d, err := s.snapshotVMState(gctx, client, ra, actorUID, checkpointDir) + d, release, err := s.snapshotVMState(gctx, client, ra, actorUID, checkpointDir) if err != nil { d = time.Since(t) } dSnapshot = d + snapshotRelease = release return err }) } @@ -242,7 +254,9 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke } // Tear down: the actor returns to "available". Best-effort; the snapshot is - // already on disk for atelet to ship. + // already on disk for atelet to ship. Teardown removes the leaf, so there is + // no memory.high or memory watch to put back. + snapshotRelease = nil tTeardown := time.Now() if err := s.terminateWorkload(ctx, attribution, actorDirs); err != nil { slog.WarnContext(ctx, "failed to terminate workload after checkpoint", @@ -269,10 +283,48 @@ func (s *AteWorkerService) CheckpointWorkload(ctx context.Context, req *ateworke return resp, nil } +// maxConsecutiveCheckpointWaitReadyFailures is the number of consecutive +// unanswered CH api-socket waits on a live VMM at which CheckpointWorkload +// gives up and returns Internal so the control plane crashes the actor. +const maxConsecutiveCheckpointWaitReadyFailures = 3 + +// checkpointWaitReadyError reports CheckpointWorkload's failure to reach the +// CH api-socket. A live VMM that does not answer returns Unavailable until it +// hits maxConsecutiveCheckpointWaitReadyFailures in a row, then resets the +// count and returns Internal. A VMM that exited stays Internal, since watchVM +// reports that crash. If the checkpoint deadline passes, the wrapped error +// keeps DeadlineExceeded. +func checkpointWaitReadyError(ctx context.Context, ra *runningActor, err error) error { + if ctx.Err() == nil && errors.Is(err, ch.ErrNotReady) && vmmRunning(ra) { + ra.checkpointWaitReadyFailures++ + if ra.checkpointWaitReadyFailures < maxConsecutiveCheckpointWaitReadyFailures { + return apierror.Unavailable("while waiting for CH api-socket: %w", err) + } + n := ra.checkpointWaitReadyFailures + ra.checkpointWaitReadyFailures = 0 + return apierror.Internal("CH api-socket did not answer %d times in a row, giving up: %w", n, err) + } + return fmt.Errorf("while waiting for CH api-socket: %w", err) +} + +// vmmRunning reports whether ra's cloud-hypervisor process is still running. +func vmmRunning(ra *runningActor) bool { + if ra == nil || ra.chProc == nil { + return false + } + select { + case <-ra.chProc.Done(): + return false + default: + return true + } +} + // snapshotVMState captures the paused guest into checkpointDir: the CH snapshot // (config.json + state.json + memory-ranges) plus the base-id the restore side -// needs, and returns how long the snapshot itself took. -func (s *AteWorkerService) snapshotVMState(ctx context.Context, client *ch.Client, ra *runningActor, actorUID, checkpointDir string) (time.Duration, error) { +// needs, and returns how long the snapshot itself took and writeSnapshot's +// release func. +func (s *AteWorkerService) snapshotVMState(ctx context.Context, client *ch.Client, ra *runningActor, actorUID, checkpointDir string) (time.Duration, func(), error) { // Record the FROZEN base id (the id the guest's virtio-fs find-paths are pinned // to, /rootfs). For a cold-run actor this is its own id; for a restored // actor it is the golden id propagated via ra.baseID (set from the snapshot we @@ -285,14 +337,14 @@ func (s *AteWorkerService) snapshotVMState(ctx context.Context, client *ch.Clien baseID = ra.baseID } if err := os.WriteFile(filepath.Join(checkpointDir, baseIDFile), []byte(baseID), 0o600); err != nil { - return 0, fmt.Errorf("while writing %s: %w", baseIDFile, err) + return 0, nil, fmt.Errorf("while writing %s: %w", baseIDFile, err) } slog.InfoContext(ctx, "Snapshotting guest", slog.String("id", actorUID), slog.String("dir", checkpointDir)) tSnapshot := time.Now() - borrowed, err := s.writeSnapshot(ctx, client, ra, actorUID, checkpointDir) + borrowed, release, err := s.writeSnapshot(ctx, client, ra, actorUID, checkpointDir) if err != nil { - return 0, err + return 0, nil, err } dSnapshot := time.Since(tSnapshot) @@ -312,7 +364,8 @@ func (s *AteWorkerService) snapshotVMState(ctx context.Context, client *ch.Clien tMerge := time.Now() if err := mergeOnDemandDelta(ctx, ra.restoreSourceDir, checkpointDir, ra.preserveRestoreSource); err != nil { s.writeBackSnapshot(ctx, actorUID, checkpointDir, borrowed) - return 0, fmt.Errorf("while merging OnDemand delta into restore source: %w", err) + release() + return 0, nil, fmt.Errorf("while merging OnDemand delta into restore source: %w", err) } slog.InfoContext(ctx, "Merged OnDemand delta into base (complete snapshot)", slog.String("id", actorUID), slog.Duration("merge", time.Since(tMerge))) @@ -325,7 +378,7 @@ func (s *AteWorkerService) snapshotVMState(ctx context.Context, client *ch.Clien // The RO lower never ships (reconstructed from the OCI image at restore). // The disk-backed upper ships as its own tar from CheckpointWorkload; a - return dSnapshot, nil + return dSnapshot, release, nil } // snapshotWriteHeadroom is how far the actor's cgroup may grow past the paused @@ -346,20 +399,29 @@ const ( // kernel throttles CH to the disk past that. // // It returns what it borrowed, for the caller to Return once the snapshot is on -// disk. On error the loan comes back once whatever CH wrote is on disk or -// removed. -func (s *AteWorkerService) writeSnapshot(ctx context.Context, client *ch.Client, ra *runningActor, actorUID, checkpointDir string) (int64, error) { +// disk, and a func that puts the leaf's memory.high and memory watch back, for +// when the guest keeps running. Putting memory.high back while the paused guest +// still holds its memory makes the kernel reclaim the snapshot CH just wrote. +// On error the loan comes back once whatever CH wrote is on disk or removed. +func (s *AteWorkerService) writeSnapshot(ctx context.Context, client *ch.Client, ra *runningActor, actorUID, checkpointDir string) (int64, func(), error) { if s.snapshotWrites != nil { select { case s.snapshotWrites <- struct{}{}: defer func() { <-s.snapshotWrites }() case <-ctx.Done(): - return 0, fmt.Errorf("while waiting to snapshot: %w", ctx.Err()) + return 0, nil, fmt.Errorf("while waiting to snapshot: %w", ctx.Err()) + } + } + var releases []func() + releaseAll := func() { + for _, release := range slices.Backward(releases) { + release() } } // the page cache the write adds isn't the actor running away if ra != nil { - defer ra.memory.Resume(ra.memory.Pause()) + limit := ra.memory.Pause() + releases = append(releases, func() { ra.memory.Resume(limit) }) } var borrowed int64 // the write caches about as much as the guest has populated, which is @@ -375,7 +437,7 @@ func (s *AteWorkerService) writeSnapshot(ctx context.Context, client *ch.Client, if err != nil { slog.WarnContext(ctx, "Snapshotting under the actor's memory limit", slog.String("id", actorUID), slog.Any("err", err)) } else { - defer release() + releases = append(releases, release) } } if err != nil || borrowed < current { @@ -387,14 +449,15 @@ func (s *AteWorkerService) writeSnapshot(ctx context.Context, client *ch.Client, if err != nil { slog.WarnContext(ctx, "Snapshotting without a page cache limit", slog.String("id", actorUID), slog.Any("err", err)) } else { - defer release() + releases = append(releases, release) } } if err := client.Snapshot(ctx, checkpointDir); err != nil { s.writeBackSnapshot(ctx, actorUID, checkpointDir, borrowed) - return 0, fmt.Errorf("while snapshotting guest: %w", err) + releaseAll() + return 0, nil, fmt.Errorf("while snapshotting guest: %w", err) } - return borrowed, nil + return borrowed, releaseAll, nil } // writeBackSnapshot returns borrowed once the snapshot files in checkpointDir @@ -407,7 +470,9 @@ func (s *AteWorkerService) writeBackSnapshot(ctx context.Context, actorUID, chec written = append(written, p) } } - if err := snapshotcache.StartWriteback(written, func() { s.borrow.Return(borrowed) }); err != nil { + // Pass nil for flush so write-out starts right away. Left dirty, the + // snapshot slows the next one's write. + if err := snapshotcache.StartWriteback(written, nil, func() { s.borrow.Return(borrowed) }); err != nil { s.borrow.Return(borrowed) slog.WarnContext(ctx, "Failed to start snapshot writeback", slog.String("id", actorUID), slog.Any("err", err)) } @@ -454,10 +519,10 @@ func (s *AteWorkerService) teardownActor(ctx context.Context, id string, actorDi var errs []error if ra != nil { - // Close the kata-agent client kept open for stdout/stderr forwarding. This - // fails the forwarding goroutines' in-flight ReadStdout/ReadStderr calls, so - // they return io.EOF and exit (no goroutine leak). Guarded so a second - // teardown / a never-forwarded actor is a no-op. + // Close the kata-agent connection kept open for stdout/stderr forwarding + // and the container exit watch. This fails their in-flight calls and + // waits for the goroutines to exit. Guarded so a second teardown + // or a never-forwarded actor is a no-op. s.actorsMu.Lock() agent := ra.guestAgent ra.guestAgent = nil @@ -492,7 +557,7 @@ func (s *AteWorkerService) teardownActor(ctx context.Context, id string, actorDi // Detach the bundle rootfs overlays composed in buildActorContainers, so // atelet's bundle wipe doesn't strand live mounts in this namespace. - if err := imagecache.UnmountAllUnder(actorDirs.GetOciBundleDir()); err != nil { + if err := imagecache.UnmountBundlesUnder(actorDirs.GetOciBundleDir()); err != nil { if !errors.Is(err, os.ErrNotExist) { errs = append(errs, fmt.Errorf("while unmounting bundle rootfs overlays: %w", err)) } diff --git a/cmd/ateworker-microvm/checkpoint_test.go b/cmd/ateworker-microvm/checkpoint_test.go new file mode 100644 index 0000000000..34bc55de4f --- /dev/null +++ b/cmd/ateworker-microvm/checkpoint_test.go @@ -0,0 +1,347 @@ +//go:build linux + +// Copyright 2026 The Agent Substrate 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 ( + "context" + "errors" + "io" + "net" + "net/http" + "net/url" + "os" + "os/exec" + "path/filepath" + "strings" + "testing" + "testing/synctest" + "time" + + "google.golang.org/grpc/codes" + + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/ch" + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/child" + "go.ate.dev/substrate/internal/actorlock" + "go.ate.dev/substrate/internal/actorlog" + "go.ate.dev/substrate/internal/apierror" + "go.ate.dev/substrate/internal/atunnel" + "go.ate.dev/substrate/internal/atunnel/egress" + "go.ate.dev/substrate/internal/atunnel/ingress" + "go.ate.dev/substrate/internal/linuxsys" + "go.ate.dev/substrate/internal/localca" + "go.ate.dev/substrate/internal/proto/ateworkerpb" +) + +// shortSocketPath returns a unix socket path short enough for sun_path. +func shortSocketPath(t *testing.T) string { + t.Helper() + dir, err := os.MkdirTemp("", "ch-") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + return filepath.Join(dir, "api.sock") +} + +// notReadyErr is a real WaitReady deadline error from a socket nobody serves. +func notReadyErr(t *testing.T) error { + t.Helper() + _, err := ch.NewClient(shortSocketPath(t)).WaitReady(t.Context(), 20*time.Millisecond) + if !errors.Is(err, ch.ErrNotReady) { + t.Fatalf("WaitReady on a dead socket = %v, want ch.ErrNotReady", err) + } + return err +} + +// liveVM is a running actor whose VMM runs until the test ends. +func liveVM(t *testing.T) *runningActor { + t.Helper() + chProc, err := child.Start(exec.Command("sleep", "30")) + if err != nil { + t.Fatal(err) + } + t.Cleanup(chProc.Stop) + return &runningActor{chProc: chProc} +} + +func TestCheckpointWaitReadyError(t *testing.T) { + notReady := notReadyErr(t) + expired, cancel := context.WithDeadline(t.Context(), time.Now().Add(-time.Second)) + defer cancel() + exitedVM := func(t *testing.T) *runningActor { + ra := fakeVM(t) + <-ra.chProc.Done() + return ra + } + for _, tc := range []struct { + name string + ctx context.Context + ra func(*testing.T) *runningActor + err error + want codes.Code + }{ + {"live VMM not answering", t.Context(), liveVM, notReady, codes.Unavailable}, + {"VMM exited", t.Context(), exitedVM, notReady, codes.Internal}, + {"no tracked VMM", t.Context(), func(*testing.T) *runningActor { return nil }, notReady, codes.Internal}, + {"checkpoint deadline passed", expired, liveVM, context.DeadlineExceeded, codes.DeadlineExceeded}, + {"other error", t.Context(), liveVM, errors.New("permission denied"), codes.Internal}, + } { + t.Run(tc.name, func(t *testing.T) { + err := checkpointWaitReadyError(tc.ctx, tc.ra(t), tc.err) + if got := apierror.Code(err); got != tc.want { + t.Errorf("apierror.Code(err) = %v, want %v (err: %v)", got, tc.want, err) + } + if !errors.Is(err, tc.err) { + t.Errorf("err = %v, want it to wrap %v", err, tc.err) + } + }) + } +} + +// serveVMMPing serves a VMM api-socket that answers vmm.ping. +func serveVMMPing(t *testing.T) string { + t.Helper() + sock := shortSocketPath(t) + lis, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + srv := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/api/v1/vmm.ping" { + http.NotFound(w, r) + return + } + _, _ = io.WriteString(w, `{"version":"53.0.0"}`) + })} + go func() { _ = srv.Serve(lis) }() + t.Cleanup(func() { srv.Close() }) + return sock +} + +// testTunnel is an unstarted tunnel that tracks actor activations. +func testTunnel(t *testing.T) *atunnel.Tunnel { + t.Helper() + ca, err := localca.GenerateCA("test", localca.KeyTypeECDSAP256, time.Hour) + if err != nil { + t.Fatal(err) + } + certPEM, err := ca.TLSCertificateChainPEM() + if err != nil { + t.Fatal(err) + } + keyPEM, err := ca.TLSPrivateKeyPEM() + if err != nil { + t.Fatal(err) + } + dir := t.TempDir() + bundle := filepath.Join(dir, "bundle.pem") + trust := filepath.Join(dir, "trust.pem") + if err := os.WriteFile(bundle, append(certPEM, keyPEM...), 0o600); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(trust, certPEM, 0o600); err != nil { + t.Fatal(err) + } + in, err := ingress.NewServer(ingress.Config{ + CredentialBundlePath: bundle, + TrustBundlePath: trust, + AllowedClientID: "spiffe://cluster.local/ns/ate-system/sa/atenet-router", + Upstream: &url.URL{Scheme: "http", Host: "127.0.0.1"}, + }) + if err != nil { + t.Fatal(err) + } + eg, err := egress.New(linuxsys.TCPOriginalDestination) + if err != nil { + t.Fatal(err) + } + return &atunnel.Tunnel{Ingress: in, Egress: eg} +} + +// A checkpoint that can't reach the VMM fails before it deactivates the +// actor's networking, so the actor keeps serving. Activating the actor's +// ingress again succeeds only if the checkpoint deactivated it. +func TestCheckpointReachesVMMBeforeDeactivating(t *testing.T) { + for _, tc := range []struct { + name string + socket func(*testing.T) string + fakeTime bool + wantDeactivated bool + }{ + // Fake time runs the full WaitReady deadline instantly. + {"VMM not answering", shortSocketPath, true, false}, + {"VMM answering", serveVMMPing, false, true}, + } { + t.Run(tc.name, func(t *testing.T) { + // Started outside the bubble: child.Start's wait goroutine blocks + // in a syscall. + ra := liveVM(t) + ra.apiSocket = tc.socket(t) + run := func(t *testing.T) { + tun := testTunnel(t) + s := &AteWorkerService{ + locks: actorlock.New(), + inFlight: actorlock.NewInFlight(), + actors: map[string]*hostedActor{testActor.UID: {attribution: testActor, usage: testActivation()}}, + tunnel: tun, + actorLogger: actorlog.NewActorLogger(io.Discard, false), + } + s.setRunningVM(testActor.UID, ra) + req := &ateworkerpb.CheckpointWorkloadRequest{ + Atespace: testActor.Ref.Atespace, + ActorName: testActor.Ref.Name, + ActorUid: testActor.UID, + Spec: testSpec(), + ActorDirs: testDirs(), + Fidelity: ateworkerpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + } + + dial := func(context.Context, string, string) (net.Conn, error) { + return nil, errors.New("no sandbox") + } + if err := tun.ActivateIngress(testActor, dial); err != nil { + t.Fatal(err) + } + + _, err := s.CheckpointWorkload(t.Context(), req) + reactivateErr := tun.ActivateIngress(testActor, dial) + if reactivateErr != nil && !strings.Contains(reactivateErr.Error(), "already active") { + t.Fatalf("ActivateIngress after the checkpoint = %v, want nil or already active", reactivateErr) + } + if deactivated := reactivateErr == nil; deactivated != tc.wantDeactivated { + t.Fatalf("deactivated = %v, want %v (err: %v)", deactivated, tc.wantDeactivated, err) + } + if tc.wantDeactivated { + if err == nil || !strings.Contains(err.Error(), "while pausing guest") { + t.Errorf("CheckpointWorkload = %v, want the pause to fail", err) + } + } else { + if got := apierror.Code(err); got != codes.Unavailable { + t.Errorf("apierror.Code(err) = %v, want %v (err: %v)", got, codes.Unavailable, err) + } + if err == nil || !strings.Contains(err.Error(), "while waiting for CH api-socket") { + t.Errorf("CheckpointWorkload = %v, want the api-socket wait to fail", err) + } + } + if s.runningVM(testActor.UID) == nil { + t.Error("the failed checkpoint unhosted the actor") + } + } + if tc.fakeTime { + synctest.Test(t, run) + } else { + run(t) + } + }) + } +} + +func TestCheckpointWaitReadyCap(t *testing.T) { + exitedVM := func(t *testing.T) *runningActor { + t.Helper() + ra := fakeVM(t) + <-ra.chProc.Done() + return ra + } + newService := func(t *testing.T, ra *runningActor) (*AteWorkerService, *ateworkerpb.CheckpointWorkloadRequest) { + t.Helper() + s := &AteWorkerService{ + locks: actorlock.New(), + inFlight: actorlock.NewInFlight(), + actors: map[string]*hostedActor{testActor.UID: {attribution: testActor, usage: testActivation()}}, + tunnel: testTunnel(t), + actorLogger: actorlog.NewActorLogger(io.Discard, false), + } + s.setRunningVM(testActor.UID, ra) + req := &ateworkerpb.CheckpointWorkloadRequest{ + Atespace: testActor.Ref.Atespace, + ActorName: testActor.Ref.Name, + ActorUid: testActor.UID, + Spec: testSpec(), + ActorDirs: testDirs(), + Fidelity: ateworkerpb.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + } + return s, req + } + + type step struct { + answering bool + wantCode codes.Code + wantMsg string + } + for _, tc := range []struct { + name string + vm func(*testing.T) *runningActor + steps []step + }{ + { + name: "gives up on third unanswered wait", + vm: liveVM, + steps: []step{ + {wantCode: codes.Unavailable, wantMsg: "while waiting for CH api-socket"}, + {wantCode: codes.Unavailable, wantMsg: "while waiting for CH api-socket"}, + {wantCode: codes.Internal, wantMsg: "3 times in a row"}, + // Giving up resets the count. + {wantCode: codes.Unavailable, wantMsg: "while waiting for CH api-socket"}, + }, + }, + { + name: "answering VMM resets count", + vm: liveVM, + steps: []step{ + {wantCode: codes.Unavailable, wantMsg: "while waiting for CH api-socket"}, + {wantCode: codes.Unavailable, wantMsg: "while waiting for CH api-socket"}, + // WaitReady succeeds and resets the count; Pause fails on the ping-only server. + {answering: true, wantCode: codes.Internal, wantMsg: "while pausing guest"}, + {wantCode: codes.Unavailable, wantMsg: "while waiting for CH api-socket"}, + {wantCode: codes.Unavailable, wantMsg: "while waiting for CH api-socket"}, + {wantCode: codes.Internal, wantMsg: "3 times in a row"}, + }, + }, + { + name: "exited VMM fails immediately", + vm: exitedVM, + steps: []step{ + {wantCode: codes.Internal, wantMsg: "while waiting for CH api-socket"}, + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + deadSock := shortSocketPath(t) + liveSock := serveVMMPing(t) + ra := tc.vm(t) + + synctest.Test(t, func(t *testing.T) { + s, req := newService(t, ra) + for i, st := range tc.steps { + if st.answering { + ra.apiSocket = liveSock + } else { + ra.apiSocket = deadSock + } + _, err := s.CheckpointWorkload(t.Context(), req) + if got := apierror.Code(err); got != st.wantCode { + t.Fatalf("attempt %d: code = %v, want %v (err: %v)", i+1, got, st.wantCode, err) + } + if err == nil || !strings.Contains(err.Error(), st.wantMsg) { + t.Fatalf("attempt %d: err = %v, want substring %q", i+1, err, st.wantMsg) + } + } + }) + }) + } +} diff --git a/cmd/ateworker-microvm/containerexit.go b/cmd/ateworker-microvm/containerexit.go new file mode 100644 index 0000000000..f1de90dcfb --- /dev/null +++ b/cmd/ateworker-microvm/containerexit.go @@ -0,0 +1,103 @@ +//go:build linux + +// Copyright 2026 The Agent Substrate 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 ( + "context" + "errors" + "io" + "log/slog" + "sync" + + "github.com/containerd/ttrpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/kata" + "go.ate.dev/substrate/internal/actorlog" + "go.ate.dev/substrate/internal/ateattr" + "go.ate.dev/substrate/internal/resources" +) + +// processWaiter is the slice of *kata.AgentClient that the container exit +// watch needs. +type processWaiter interface { + WaitProcess(ctx context.Context, containerID, execID string) (int32, error) +} + +// watchContainer forwards the container's stdout and stderr to the pod's log +// through the actor logger, and logs the container's exit if it exits while +// the microVM stays up. +// +// The calls on ac have no deadline, so they outlive the RPC that started them. +// They end when the container has exited and its output has ended, or when ac +// is closed (by teardownActor, or on a failed boot or restore). Close waits +// for them. +func (s *AteWorkerService) watchContainer(ac *agentConn, a resources.ActorAttribution, containerID, containerName string) { + ctx := context.Background() + stdout := kata.NewStdioReader(ctx, ac.AgentClient, containerID, containerID, false) + stderr := kata.NewStdioReader(ctx, ac.AgentClient, containerID, containerID, true) + s.watchStreams(&ac.logWG, stdout, stderr, ac, a, containerID, containerName) +} + +// watchStreams forwards the container's two output streams, and logs the +// container's exit after both end. The streams end when the container's +// processes have closed them or exited. wg counts the two goroutines. +func (s *AteWorkerService) watchStreams(wg *sync.WaitGroup, stdout, stderr io.Reader, agent processWaiter, a resources.ActorAttribution, containerID, containerName string) { + stderrEnded := make(chan struct{}) + wg.Go(func() { + defer close(stderrEnded) + s.actorLogger.WrapContainerLogs(stderr, a, containerName, ateattr.LogIostreamStderr) + }) + wg.Go(func() { + s.actorLogger.WrapContainerLogs(stdout, a, containerName, ateattr.LogIostreamStdout) + <-stderrEnded + s.logContainerExit(agent, a, containerID, containerName) + }) +} + +// logContainerExit logs the container's exit. Call it after the container's +// output ends: the guest agent drops the output that is still in the pipes +// when a wait collects the exit, so a wait that is in progress at the exit +// cuts the container's last lines. +func (s *AteWorkerService) logContainerExit(agent processWaiter, a resources.ActorAttribution, containerID, containerName string) { + // The agent keeps the exit status until a wait collects it, so this + // returns at once for a process that exited. It blocks for a container + // that closed its own stdout and stderr and still runs. + code, err := agent.WaitProcess(context.Background(), containerID, containerID) + switch { + case err == nil: + case errors.Is(err, ttrpc.ErrClosed): + // A teardown, or the microVM died, which watchVM reports. + return + case status.Code(err) == codes.NotFound: + // An earlier wait collected the exit: this watch before a suspend, + // or the graceful shutdown. + return + default: + slog.LogAttrs(context.Background(), slog.LevelWarn, "Cannot tell if the container exited", + append(ateattr.ActorLogAttrs(a), slog.String("container", containerName), slog.Any("err", err))...) + return + } + // A wait that succeeds is an exit of the container itself. A suspend or a + // terminate sends no signal into the guest: it closes the connection, + // which fails the wait. Only the graceful shutdown stops the workloads. + if s.shuttingDown.Load() { + return + } + s.actorLogger.EmitContainerExit(a, actorlog.ContainerExit{Container: containerName, ExitCode: &code}) +} diff --git a/cmd/ateworker-microvm/containerexit_test.go b/cmd/ateworker-microvm/containerexit_test.go new file mode 100644 index 0000000000..4fdbcbb8f8 --- /dev/null +++ b/cmd/ateworker-microvm/containerexit_test.go @@ -0,0 +1,276 @@ +//go:build linux + +// Copyright 2026 The Agent Substrate 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" + "context" + "encoding/json" + "fmt" + "io" + "log/slog" + "strconv" + "strings" + "sync" + "sync/atomic" + "testing" + "testing/synctest" + "time" + + "github.com/containerd/ttrpc" + specs "github.com/opencontainers/runtime-spec/specs-go" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/third_party/kata/agentpb" + "go.ate.dev/substrate/internal/actorlog" + "go.ate.dev/substrate/internal/ateattr" + "go.ate.dev/substrate/internal/ateworker/actornet" +) + +// fakeWaiter is a guest process that exited with code, or a wait that fails +// with err. It counts the waits and keeps the ids of the last one. +type fakeWaiter struct { + code int32 + err error + + waits atomic.Int32 + containerID, execID string +} + +func (f *fakeWaiter) WaitProcess(_ context.Context, containerID, execID string) (int32, error) { + f.containerID, f.execID = containerID, execID + f.waits.Add(1) + return f.code, f.err +} + +// lockedBuffer is the actor log of a test. The two forwarders and the exit +// record write to it from different goroutines. +type lockedBuffer struct { + mu sync.Mutex + buf bytes.Buffer +} + +func (b *lockedBuffer) Write(p []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.Write(p) +} + +func (b *lockedBuffer) String() string { + b.mu.Lock() + defer b.mu.Unlock() + return b.buf.String() +} + +// captureWarnings routes the default logger to a buffer for the test. +func captureWarnings(t *testing.T) *lockedBuffer { + t.Helper() + buf := &lockedBuffer{} + prev := slog.Default() + slog.SetDefault(slog.New(slog.NewJSONHandler(buf, &slog.HandlerOptions{Level: slog.LevelWarn}))) + t.Cleanup(func() { slog.SetDefault(prev) }) + return buf +} + +// exitService is a service whose actor log is the returned buffer. +func exitService() (*AteWorkerService, *lockedBuffer) { + buf := &lockedBuffer{} + return &AteWorkerService{actorLogger: actorlog.NewActorLogger(buf, false)}, buf +} + +func TestLogContainerExit(t *testing.T) { + for _, code := range []int32{0, 1, 137} { + t.Run(strconv.Itoa(int(code)), func(t *testing.T) { + s, log := exitService() + agent := &fakeWaiter{code: code} + s.logContainerExit(agent, testActor, "ctr-id", "app") + // The agent keys a container's first process by the container id. + if agent.containerID != "ctr-id" || agent.execID != "ctr-id" { + t.Errorf("waited on container %q exec %q, want both ctr-id", agent.containerID, agent.execID) + } + var record map[string]any + if err := json.Unmarshal([]byte(log.String()), &record); err != nil { + t.Fatalf("log = %q, want one exit record: %v", log.String(), err) + } + if got := record["message"]; got != actorlog.ContainerExitedMessage { + t.Errorf("message = %v, want %q", got, actorlog.ContainerExitedMessage) + } + if got := record[string(ateattr.ActorExitedContainerNameKey)]; got != "app" { + t.Errorf("container = %v, want app", got) + } + if got := record[string(ateattr.ProcessExitCodeKey)]; got != float64(code) { + t.Errorf("exit code = %v, want %d", got, code) + } + }) + } +} + +// TestLogContainerExitIgnores pins the waits that give no exit record, and +// that only an unexpected error gives a warning. +func TestLogContainerExitIgnores(t *testing.T) { + // The errors are wrapped as the agent client wraps them. + wrapped := func(err error) error { return fmt.Errorf("agent WaitProcess: %w", err) } + for _, tc := range []struct { + name string + err error + shuttingDown bool + wantWarning bool + }{ + {name: "connection closed", err: wrapped(ttrpc.ErrClosed)}, + {name: "exit collected by an earlier wait", err: wrapped(status.Error(codes.NotFound, "InvalidExecId"))}, + {name: "wait failed", err: wrapped(status.Error(codes.Internal, "Failed to receive exit code")), wantWarning: true}, + {name: "worker shutting down", shuttingDown: true}, + } { + t.Run(tc.name, func(t *testing.T) { + warnings := captureWarnings(t) + s, log := exitService() + s.shuttingDown.Store(tc.shuttingDown) + s.logContainerExit(&fakeWaiter{code: 1, err: tc.err}, testActor, "ctr-id", "app") + if got := log.String(); got != "" { + t.Errorf("actor log = %q, want no record", got) + } + if got := strings.Contains(warnings.String(), "Cannot tell if the container exited"); got != tc.wantWarning { + t.Errorf("worker warning = %t, want %t: %q", got, tc.wantWarning, warnings.String()) + } + }) + } +} + +// TestWatchStreams pins that both streams are forwarded, that the wait starts +// only after both end, and that the exit record comes after the container's +// last lines. A wait that is in progress at the exit makes the guest agent +// drop the output that is still in the pipes. +func TestWatchStreams(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s, log := exitService() + agent := &fakeWaiter{code: 3} + stdout, stdoutW := io.Pipe() + stderr, stderrW := io.Pipe() + var wg sync.WaitGroup + s.watchStreams(&wg, stdout, stderr, agent, testActor, "ctr-id", "app") + + go func() { + _, _ = io.WriteString(stdoutW, "last stdout line") + stdoutW.Close() + }() + synctest.Wait() + if got := agent.waits.Load(); got != 0 { + t.Errorf("waits = %d while stderr is open, want 0", got) + } + go func() { + _, _ = io.WriteString(stderrW, "last stderr line") + stderrW.Close() + }() + synctest.Wait() + + lines := strings.Split(strings.TrimSpace(log.String()), "\n") + if len(lines) != 3 { + t.Fatalf("actor log has %d lines, want two output lines and the exit record: %q", len(lines), log.String()) + } + for i, want := range []string{"last stdout line", "last stderr line", actorlog.ContainerExitedMessage} { + var record map[string]any + if err := json.Unmarshal([]byte(lines[i]), &record); err != nil { + t.Fatal(err) + } + if got := record["message"]; got != want { + t.Errorf("line %d message = %v, want %q", i, got, want) + } + } + if got := agent.waits.Load(); got != 1 { + t.Errorf("waits = %d, want 1", got) + } + }) +} + +// blockingWaiter is a wait that returns code when release is closed. +type blockingWaiter struct { + release chan struct{} + code int32 +} + +func (b *blockingWaiter) WaitProcess(context.Context, string, string) (int32, error) { + <-b.release + return b.code, nil +} + +// TestLogContainerExitShutdownDuringWait pins that the shutdown is checked +// after the wait returns. A container that closed its own output is in the +// wait when the drain signals it. +func TestLogContainerExitShutdownDuringWait(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + s, log := exitService() + agent := &blockingWaiter{release: make(chan struct{}), code: 143} + go s.logContainerExit(agent, testActor, "ctr-id", "app") + synctest.Wait() + s.shuttingDown.Store(true) + close(agent.release) + synctest.Wait() + if got := log.String(); got != "" { + t.Errorf("actor log = %q, want no record for an exit after the shutdown started", got) + } + }) +} + +// TestCloseEndsAWaitInProgress pins that agentConn.Close returns while the +// exit watch has a wait in progress, for a container that closed its own +// output and still runs. teardownActor calls Close under the actor's lock. +func TestCloseEndsAWaitInProgress(t *testing.T) { + warnings := captureWarnings(t) + waitEntered := make(chan struct{}) + ended := func(_ context.Context, unmarshal func(interface{}) error) (interface{}, error) { + if err := unmarshal(&agentpb.ReadStreamRequest{}); err != nil { + return nil, err + } + return &agentpb.ReadStreamResponse{}, nil + } + ac, vsockPath := startFakeKataAgent(t, map[string]ttrpc.Method{ + "ReadStdout": ended, + "ReadStderr": ended, + "WaitProcess": func(ctx context.Context, unmarshal func(interface{}) error) (interface{}, error) { + if err := unmarshal(&agentpb.WaitProcessRequest{}); err != nil { + return nil, err + } + close(waitEntered) + <-ctx.Done() + return nil, ctx.Err() + }, + }) + log := &lockedBuffer{} + svc := NewService("pod-1", "cloud-hypervisor", false, 10, nil, actorlog.NewActorLogger(log, false), "boot-1", actornet.IPv4) + ctr := actorContainer{name: "app", id: "c_app", spec: &specs.Spec{Hostname: "actor"}} + if err := svc.startRootfsContainer(t.Context(), ac, testActor, vsockPath, ctr); err != nil { + t.Fatal(err) + } + <-waitEntered + closed := make(chan error, 1) + go func() { closed <- ac.Close() }() + select { + case err := <-closed: + if err != nil { + t.Fatalf("Close: %v", err) + } + case <-time.After(30 * time.Second): + t.Fatal("Close did not return while a wait was in progress") + } + if got := log.String(); got != "" { + t.Errorf("actor log = %q, want no record", got) + } + if got := warnings.String(); strings.Contains(got, "Cannot tell if the container exited") { + t.Errorf("worker warning = %q, want none", got) + } +} diff --git a/cmd/ateworker-microvm/hosted.go b/cmd/ateworker-microvm/hosted.go index b7576810ab..411f3446b8 100644 --- a/cmd/ateworker-microvm/hosted.go +++ b/cmd/ateworker-microvm/hosted.go @@ -94,6 +94,7 @@ func (s *AteWorkerService) hostActor(ctx context.Context, attribution resources. ActorUID: uid, EgressPort: s.tunnel.EgressPort, DNSPolicy: s.tunnel.ActorEgressPolicy(attribution), + Families: s.families, }, s.tunnel.Egress, s.tunnel.DNSRelay) if err != nil { s.actorsMu.Lock() diff --git a/cmd/ateworker-microvm/internal/ch/ch.go b/cmd/ateworker-microvm/internal/ch/ch.go index 25ecd9520c..83ad8d9788 100644 --- a/cmd/ateworker-microvm/internal/ch/ch.go +++ b/cmd/ateworker-microvm/internal/ch/ch.go @@ -26,11 +26,28 @@ package ch import ( "context" + "errors" "fmt" "os" "time" ) +// ErrNotReady matches the error WaitReady returns when the api-socket did not +// answer before its deadline. +var ErrNotReady = errors.New("cloud-hypervisor api socket not ready") + +// notReadyError is WaitReady's deadline error. It matches ErrNotReady. +type notReadyError struct { + apiSocket string + deadline time.Duration +} + +func (e *notReadyError) Error() string { + return fmt.Sprintf("cloud-hypervisor api socket %q not ready after %s", e.apiSocket, e.deadline) +} + +func (e *notReadyError) Is(target error) bool { return target == ErrNotReady } + // Client talks to one cloud-hypervisor VMM over its unix api-socket. type Client struct { apiSocket string @@ -80,7 +97,7 @@ func (c *Client) WaitReady(ctx context.Context, deadline time.Duration) (VMMInfo return info, nil } if !time.Now().Before(end) { - return VMMInfo{}, fmt.Errorf("cloud-hypervisor api socket %q not ready after %s", c.apiSocket, deadline) + return VMMInfo{}, ¬ReadyError{apiSocket: c.apiSocket, deadline: deadline} } select { case <-ctx.Done(): diff --git a/cmd/ateworker-microvm/internal/ch/ch_test.go b/cmd/ateworker-microvm/internal/ch/ch_test.go index 2181c29530..7b68531878 100644 --- a/cmd/ateworker-microvm/internal/ch/ch_test.go +++ b/cmd/ateworker-microvm/internal/ch/ch_test.go @@ -17,6 +17,7 @@ package ch import ( "context" "encoding/json" + "errors" "io" "net" "net/http" @@ -145,4 +146,7 @@ func TestWaitReadyTimesOut(t *testing.T) { if err == nil { t.Fatal("WaitReady returned nil for a dead socket, want timeout error") } + if !errors.Is(err, ErrNotReady) { + t.Errorf("WaitReady error = %v, want it to match ErrNotReady", err) + } } diff --git a/cmd/ateworker-microvm/internal/kata/agentclient.go b/cmd/ateworker-microvm/internal/kata/agentclient.go index ad8eed991f..59d1fd68b3 100644 --- a/cmd/ateworker-microvm/internal/kata/agentclient.go +++ b/cmd/ateworker-microvm/internal/kata/agentclient.go @@ -146,6 +146,16 @@ func (a *AgentClient) CreateContainer(ctx context.Context, req *agentpb.CreateCo return nil } +// CloseStdin closes the agent's write end of a process's stdin pipe, so the +// process reads EOF from stdin. Mirrors grpc.AgentService/CloseStdin. +func (a *AgentClient) CloseStdin(ctx context.Context, containerID, execID string) error { + req := &agentpb.CloseStdinRequest{ContainerId: containerID, ExecId: execID} + if err := a.client.Call(ctx, "grpc.AgentService", "CloseStdin", req, &emptypb.Empty{}); err != nil { + return fmt.Errorf("agent CloseStdin %q: %w", containerID, err) + } + return nil +} + // ReseedRandomDev feeds fresh entropy into the guest's random device: the agent // writes data into /dev/random and reseeds the kernel CRNG. This is how a restored // or cloned guest diverges from the entropy state frozen in its snapshot. Mirrors @@ -229,9 +239,9 @@ func (a *AgentClient) SignalProcess(ctx context.Context, containerID, execID str } // WaitProcess blocks until the identified guest process exits and returns its -// exit status (mimics waitpid(2)). Used during graceful shutdown to confirm the -// actor has stopped before ateworker tears the VM down. Mirrors -// grpc.AgentService/WaitProcess. +// exit status (mimics waitpid(2)). The graceful shutdown uses it to confirm the +// actor has stopped before ateworker tears the VM down, and the container exit +// watch uses it to read the exit code. Mirrors grpc.AgentService/WaitProcess. func (a *AgentClient) WaitProcess(ctx context.Context, containerID, execID string) (int32, error) { resp := &agentpb.WaitProcessResponse{} req := &agentpb.WaitProcessRequest{ContainerId: containerID, ExecId: execID} @@ -242,10 +252,9 @@ func (a *AgentClient) WaitProcess(ctx context.Context, containerID, execID strin } // ReadStdout reads up to max bytes from the container process's stdout. It is a -// unary RPC (NOT a server stream): each call returns whatever bytes the agent has -// buffered (up to max), so callers loop until it returns an error — the agent -// returns an error/EOF-like status once the stream ends (container exit / connection -// close). Mirrors grpc.AgentService/ReadStdout. The kata-agent keys the stream by +// unary RPC (NOT a server stream): each call returns whatever bytes the agent +// has buffered (up to max), and returns empty data once the stream reaches EOF. +// Mirrors grpc.AgentService/ReadStdout. The kata-agent keys the stream by // ExecId, which ateworker sets equal to ContainerId. func (a *AgentClient) ReadStdout(ctx context.Context, containerID, execID string, max uint32) ([]byte, error) { resp := &agentpb.ReadStreamResponse{} @@ -257,8 +266,7 @@ func (a *AgentClient) ReadStdout(ctx context.Context, containerID, execID string } // ReadStderr reads up to max bytes from the container process's stderr. Same -// semantics as ReadStdout (unary, loop-until-error). Mirrors -// grpc.AgentService/ReadStderr. +// semantics as ReadStdout. Mirrors grpc.AgentService/ReadStderr. func (a *AgentClient) ReadStderr(ctx context.Context, containerID, execID string, max uint32) ([]byte, error) { resp := &agentpb.ReadStreamResponse{} req := &agentpb.ReadStreamRequest{ContainerId: containerID, ExecId: execID, Len: max} @@ -292,13 +300,9 @@ func (a *AgentClient) StatsContainer(ctx context.Context, containerID string) (* return resp.GetCgroupStats(), nil } -// StreamReader adapts the agent's repeated ReadStdout/ReadStderr unary calls into -// an io.Reader, so the consumer can pump the container's output through the shared -// actorlog forwarder like any other stream. Each Read issues one RPC with Len set -// to len(p); on RPC error (the agent signals EOF/container-exit via an error -// status) it returns io.EOF so the consuming goroutine terminates cleanly. The -// reader stops when its context is cancelled OR the underlying ttrpc connection is -// closed (both surface as RPC errors), so it never outlives the AgentClient. +// StreamReader adapts ReadStdout/ReadStderr unary calls into an io.Reader for +// actorlog. It returns io.EOF when kata-agent returns empty data on container +// stdio EOF or when an RPC errors (context cancellation or connection close). type StreamReader struct { ctx context.Context ac *AgentClient @@ -314,10 +318,15 @@ func NewStdioReader(ctx context.Context, ac *AgentClient, containerID, execID st return &StreamReader{ctx: ctx, ac: ac, containerID: containerID, execID: execID, stderr: stderr} } -// Read issues a single ReadStdout/ReadStderr RPC for up to len(p) bytes, copying -// the returned data into p. It returns io.EOF on any RPC error so the consumer -// stops cleanly when the container exits or the connection closes. +// Read issues one ReadStdout or ReadStderr RPC for up to len(p) bytes. kata-agent +// answers with empty data at stdio EOF (its agent.proto doesn't document this, but +// kata's own runtime treats it the same way in virtcontainers readProcessStream), +// so an empty response returns io.EOF, as does an RPC error. A zero-length p +// returns without an RPC, since that request would also come back empty. func (r *StreamReader) Read(p []byte) (int, error) { + if len(p) == 0 { + return 0, nil + } var ( data []byte err error @@ -330,6 +339,9 @@ func (r *StreamReader) Read(p []byte) (int, error) { if err != nil { return 0, io.EOF } + if len(data) == 0 { + return 0, io.EOF + } n := copy(p, data) return n, nil } diff --git a/cmd/ateworker-microvm/internal/kata/agentclient_linux_test.go b/cmd/ateworker-microvm/internal/kata/agentclient_linux_test.go index 0facc787f3..2429970a7b 100644 --- a/cmd/ateworker-microvm/internal/kata/agentclient_linux_test.go +++ b/cmd/ateworker-microvm/internal/kata/agentclient_linux_test.go @@ -20,12 +20,16 @@ import ( "bytes" "context" "errors" + "io" "net" "path/filepath" + "slices" + "sync" "testing" "time" "github.com/containerd/ttrpc" + specs "github.com/opencontainers/runtime-spec/specs-go" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/third_party/kata/agentpb" "google.golang.org/protobuf/types/known/emptypb" ) @@ -34,16 +38,7 @@ import ( // a client connected to it. func startFakeAgent(t *testing.T, handle func(*agentpb.ReseedRandomDevRequest) error) *AgentClient { t.Helper() - sock := filepath.Join(t.TempDir(), "agent.sock") - l, err := net.Listen("unix", sock) - if err != nil { - t.Fatalf("listen: %v", err) - } - srv, err := ttrpc.NewServer() - if err != nil { - t.Fatalf("ttrpc.NewServer: %v", err) - } - srv.Register("grpc.AgentService", map[string]ttrpc.Method{ + return serveFakeAgent(t, map[string]ttrpc.Method{ "ReseedRandomDev": func(_ context.Context, unmarshal func(interface{}) error) (interface{}, error) { var req agentpb.ReseedRandomDevRequest if err := unmarshal(&req); err != nil { @@ -55,8 +50,30 @@ func startFakeAgent(t *testing.T, handle func(*agentpb.ReseedRandomDevRequest) e return &emptypb.Empty{}, nil }, }) - go func() { _ = srv.Serve(context.Background(), l) }() - t.Cleanup(func() { _ = srv.Close() }) +} + +// serveFakeAgent serves methods as grpc.AgentService and returns a client +// connected to it. +func serveFakeAgent(t *testing.T, methods map[string]ttrpc.Method) *AgentClient { + t.Helper() + sock := filepath.Join(t.TempDir(), "agent.sock") + l, err := net.Listen("unix", sock) + if err != nil { + t.Fatalf("listen: %v", err) + } + srv, err := ttrpc.NewServer() + if err != nil { + t.Fatalf("ttrpc.NewServer: %v", err) + } + srv.Register("grpc.AgentService", methods) + serveErr := make(chan error, 1) + go func() { serveErr <- srv.Serve(context.Background(), l) }() + t.Cleanup(func() { + _ = srv.Close() + if err := <-serveErr; err != nil && !errors.Is(err, ttrpc.ErrServerClosed) { + t.Logf("fake kata-agent server: %v", err) + } + }) conn, err := net.Dial("unix", sock) if err != nil { @@ -103,3 +120,127 @@ func TestReseedRandomDevReturnsAgentError(t *testing.T) { t.Fatal("ReseedRandomDev returned nil for an agent error, want the error") } } + +func TestStartRootfsContainerClosesStdin(t *testing.T) { + tests := []struct { + name string + closeStdinErr error + wantErr bool + wantCalls []string + }{{ + name: "closes stdin before starting", + wantCalls: []string{"CreateContainer", "CloseStdin", "StartContainer"}, + }, { + name: "does not start when CloseStdin fails", + closeStdinErr: errors.New("close refused"), + wantErr: true, + wantCalls: []string{"CreateContainer", "CloseStdin"}, + }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var ( + mu sync.Mutex + calls []string + ) + // record decodes the request into req, records the call, and + // fails it with reply if reply is not nil. + record := func(name string, req any, reply error) ttrpc.Method { + return func(_ context.Context, unmarshal func(any) error) (any, error) { + mu.Lock() + defer mu.Unlock() + if err := unmarshal(req); err != nil { + return nil, err + } + calls = append(calls, name) + if reply != nil { + return nil, reply + } + return &emptypb.Empty{}, nil + } + } + closeReq := &agentpb.CloseStdinRequest{} + ac := serveFakeAgent(t, map[string]ttrpc.Method{ + "CreateContainer": record("CreateContainer", &agentpb.CreateContainerRequest{}, nil), + "CloseStdin": record("CloseStdin", closeReq, tt.closeStdinErr), + "StartContainer": record("StartContainer", &agentpb.StartContainerRequest{}, nil), + }) + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + err := ac.StartRootfsContainer(ctx, "c1", &specs.Spec{}) + if (err != nil) != tt.wantErr { + t.Fatalf("StartRootfsContainer() = %v, want error: %t", err, tt.wantErr) + } + mu.Lock() + defer mu.Unlock() + if !slices.Equal(calls, tt.wantCalls) { + t.Errorf("agent calls = %v, want %v", calls, tt.wantCalls) + } + if closeReq.GetContainerId() != "c1" || closeReq.GetExecId() != "c1" { + t.Errorf("CloseStdin got container %q exec %q, want both %q", closeReq.GetContainerId(), closeReq.GetExecId(), "c1") + } + }) + } +} + +// kata-agent's do_read_stream signals stdio pipe EOF after container exit by +// returning an empty ReadStreamResponse with a nil error. StreamReader.Read +// must translate that into io.EOF on the first empty response. +func TestStreamReaderEmptyDataReturnsEOF(t *testing.T) { + for _, tc := range []struct { + name string + method string + stderr bool + }{ + {name: "stdout", method: "ReadStdout", stderr: false}, + {name: "stderr", method: "ReadStderr", stderr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + chunks := [][]byte{[]byte("line 1\n"), []byte("line 2\n")} + var calls int + ac := serveFakeAgent(t, map[string]ttrpc.Method{ + tc.method: func(_ context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.ReadStreamRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + if req.GetContainerId() != "c_main" || req.GetExecId() != "c_main" { + t.Errorf("got container=%q exec=%q, want c_main/c_main", req.GetContainerId(), req.GetExecId()) + } + i := calls + calls++ + if i < len(chunks) { + return &agentpb.ReadStreamResponse{Data: chunks[i]}, nil + } + if i == len(chunks) { + return &agentpb.ReadStreamResponse{}, nil + } + t.Errorf("Read called again after the empty EOF response") + return nil, errors.New("unexpected Read after EOF") + }, + }) + + r := NewStdioReader(t.Context(), ac, "c_main", "c_main", tc.stderr) + got, err := io.ReadAll(r) + if err != nil { + t.Fatalf("io.ReadAll: %v", err) + } + if want := "line 1\nline 2\n"; string(got) != want { + t.Errorf("got %q, want %q", got, want) + } + wantCalls := len(chunks) + 1 + if calls != wantCalls { + t.Errorf("RPC calls = %d, want %d (must stop on first empty response)", calls, wantCalls) + } + + // A zero-length read buffer must not be treated as stream EOF or issue an RPC. + n, err := r.Read(nil) + if n != 0 || err != nil { + t.Errorf("Read(nil) = (%d, %v), want (0, nil)", n, err) + } + if calls != wantCalls { + t.Errorf("RPC calls after Read(nil) = %d, want %d (no extra RPC)", calls, wantCalls) + } + }) + } +} diff --git a/cmd/ateworker-microvm/internal/kata/overlay_linux.go b/cmd/ateworker-microvm/internal/kata/overlay_linux.go index 7537d149fa..fa7d03efec 100644 --- a/cmd/ateworker-microvm/internal/kata/overlay_linux.go +++ b/cmd/ateworker-microvm/internal/kata/overlay_linux.go @@ -137,7 +137,9 @@ func virtiofsdArgs(o VirtiofsdOptions) []string { // which cannot produce decodable file handles. "--inode-file-handles=never", "--cache=auto", - "--thread-pool-size=1", + // No thread pool: the queue thread serves each request under the vring + // lock, so a snapshot's GET_VRING_BASE waits for the request in flight. + "--thread-pool-size=0", "--announce-submounts", "--migration-mode", "find-paths", // The default (abort) makes a snapshot unrestorable if the guest still @@ -465,6 +467,12 @@ func (a *AgentClient) StartRootfsContainer(ctx context.Context, cid string, spec }); err != nil { return fmt.Errorf("creating rootfs container %q: %w", cid, err) } + // The agent gives every non-tty process a stdin pipe and keeps the write end + // open, so a read from stdin would block forever. Close it so the workload + // reads EOF, as it does from /dev/null on gVisor. + if err := a.CloseStdin(ctx, cid, cid); err != nil { + return fmt.Errorf("closing stdin of rootfs container %q: %w", cid, err) + } if err := a.StartContainer(ctx, cid); err != nil { return fmt.Errorf("starting rootfs container %q: %w", cid, err) } diff --git a/cmd/ateworker-microvm/internal/third_party/kata/PROVENANCE.md b/cmd/ateworker-microvm/internal/third_party/kata/PROVENANCE.md index 23a3cc902f..fcba07b142 100644 --- a/cmd/ateworker-microvm/internal/third_party/kata/PROVENANCE.md +++ b/cmd/ateworker-microvm/internal/third_party/kata/PROVENANCE.md @@ -42,7 +42,8 @@ the message types are needed. ### RPCs actually used ateworker drives a small subset of `AgentService`: -`CreateSandbox`, `CreateContainer`, `StartContainer`, `UpdateInterface`, `UpdateRoutes`, +`CreateSandbox`, `CreateContainer`, `CloseStdin`, `StartContainer`, `SignalProcess`, +`WaitProcess`, `StatsContainer`, `ReseedRandomDev`, `UpdateInterface`, `UpdateRoutes`, `AddARPNeighbors`, `ReadStdout`, `ReadStderr`. ### Regenerating diff --git a/cmd/ateworker-microvm/main.go b/cmd/ateworker-microvm/main.go index 845f26d006..11cd6d41db 100644 --- a/cmd/ateworker-microvm/main.go +++ b/cmd/ateworker-microvm/main.go @@ -50,12 +50,15 @@ import ( "go.ate.dev/substrate/internal/ateworker/register" "go.ate.dev/substrate/internal/atunnel" "go.ate.dev/substrate/internal/bootid" + "go.ate.dev/substrate/internal/hardware" "go.ate.dev/substrate/internal/nodepath" "go.ate.dev/substrate/internal/otlprelay" "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/resources" + "go.ate.dev/substrate/internal/sandboxruntimes" "go.ate.dev/substrate/internal/serverboot" + "go.ate.dev/substrate/internal/serverboot/pprofserver" "go.ate.dev/substrate/internal/version" "go.ate.dev/substrate/internal/workerstats" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" @@ -78,6 +81,7 @@ var ( "Unix socket of atelet's OTLP relay to export telemetry through, keeping it off the pod network. Empty, or absent at startup, exports directly to OTEL_EXPORTER_OTLP_ENDPOINT instead.") tunnelConfig = atunnel.RegisterFlags(pflag.CommandLine) + pprofCfg = pprofserver.RegisterFlags(pflag.CommandLine) readinessListenAddress = pflag.String("readiness-listen-address", "0.0.0.0:8080", "Address for the HTTP /readyz and /healthz probes") maxActors = pflag.Int("max-actors", 1000, "How many actors this worker will host at once") @@ -89,7 +93,7 @@ var ( const minUsageSampleInterval = 50 * time.Second func main() { - pid1.RunIfPID1() + pid1.RunIfPID1(pid1.Options{}) pflag.Parse() if *showVersion { fmt.Println(version.String()) @@ -115,9 +119,13 @@ func do(ctx context.Context) error { if err := serverboot.SetLogLevel(*logLevelFlag); err != nil { return err } - if err := preview.Init(*previewFlags...); err != nil { + previewGates, err := preview.New(*previewFlags...) + if err != nil { return fmt.Errorf("invalid --preview: %w", err) } + if err := pprofCfg.Validate(); err != nil { + return fmt.Errorf("invalid pprof configuration: %w", err) + } slog.InfoContext(ctx, "ateworker-microvm booting", slog.String("version", version.Version)) if *maxActors < 0 { return fmt.Errorf("--max-actors must not be negative, got %d", *maxActors) @@ -169,6 +177,7 @@ func do(ctx context.Context) error { serverboot.Fatal(ctx, "Failed to initialize metrics", err) } defer serverboot.ShutdownProvider("MeterProvider", mp.Shutdown) + go pprofserver.Start(ctx, pprofCfg) lp, err := serverboot.InitLogging(ctx, serverboot.LoggingOptions{ ServiceName: serviceName, @@ -234,11 +243,17 @@ func do(ctx context.Context) error { return fmt.Errorf("while delegating the worker cgroup: %w", err) } - tunnel, err := atunnel.Start(ctx, *tunnelConfig, actornet.ActorHTTPUpstream) + workerPodIPs := register.ParsePodIPs(*podIPs) + ipv6ActorNetworking := previewGates.IsEnabled(preview.GateActorIPv6) + families, err := actornet.IPFamiliesForPodIPs(workerPodIPs, ipv6ActorNetworking) + if err != nil { + return err + } + tunnel, err := atunnel.Start(ctx, *tunnelConfig, actornet.ActorHTTPUpstream, mp.Meter(serviceName)) if err != nil { return err } - ateworkerService := NewService(*podUID, *chBinary, *guestDebug, *maxActors, tunnel, actorLogger, bootID) + ateworkerService := NewService(*podUID, *chBinary, *guestDebug, *maxActors, tunnel, actorLogger, bootID, families) ateworkerService.throttleMemory = cgroup.PSIEnabled(cgroup.Root) if !ateworkerService.throttleMemory { slog.WarnContext(ctx, "Kernel has no cgroup memory pressure (PSI), so actor cgroups get no memory limit and an actor over its booking can restart the worker") @@ -262,8 +277,10 @@ func do(ctx context.Context) error { ) ateworkerpb.RegisterWorkerServer(svr, ateworkerService) reflection.Register(svr) + var sandboxRuntimes register.SandboxRuntimes readiness := &serverboot.Readiness{} readiness.AddCheck("registered", ateworkerService.epoch.Registered) + readiness.AddCheck("sandbox-runtimes", sandboxRuntimes.Reported) // Trap SIGTERM (sent by the kubelet at the start of the pod's termination grace // period) and propagate it into the guest so the actor can save its state and @@ -291,15 +308,20 @@ func do(ctx context.Context) error { // Report retries every failure it can outlast, including the window before // the Worker record exists; anything that reaches here is a misconfiguration // no restart-in-place will fix. + var runtimeAttributes sandboxruntimes.Attributes + if families.Has(actornet.IPv6) { + runtimeAttributes = sandboxruntimes.Attributes{hardware.AttrActorIPFamilies: families.String()} + } reportConfig := register.ReportConfig{ SocketPath: nodepath.WorkerSupportSocket, CredentialBundlePath: tunnelConfig.CredentialBundle, TrustBundlePath: tunnelConfig.TrustBundle, AteletSPIFFEID: tunnelConfig.BrokerIdentity, Actors: *maxActors, - PodIPs: register.ParsePodIPs(*podIPs), + PodIPs: workerPodIPs, MemoryReservedBytes: memoryReservedBytes, ActorOverhead: actorOverhead, + RuntimeAttributes: runtimeAttributes, SandboxClass: string(atev1.SandboxClassMicroVM), RuntimesFile: nodepath.WorkerSandboxRuntimesPath(*podUID), } @@ -309,7 +331,7 @@ func do(ctx context.Context) error { ateworkerService.crashReporter = reporter } go func() { - err := register.Report(ctx, reportConfig, &ateworkerService.epoch) + err := register.Report(ctx, reportConfig, &ateworkerService.epoch, &sandboxRuntimes) if err != nil && ctx.Err() == nil { serverboot.Fatal(ctx, "Failed to register worker", err) } @@ -364,7 +386,7 @@ type AteWorkerService struct { // Serializes lifecycle RPCs per actor. locks *actorlock.Locks - // Tracks lifecycle RPCs for shutdown cancellation and draining. + // Tracks lifecycle RPCs so shutdown can wait for them. inFlight *actorlock.InFlight // crashReporter reports actors whose micro-VM died. Nil if it could not // be set up. @@ -388,6 +410,7 @@ type AteWorkerService struct { podUID string chBinary string guestDebug bool + families actornet.IPFamilies // snapshotWrites holds a slot per CH snapshot write in flight, whose page // cache memoryReservedBytes budgets for. @@ -420,7 +443,7 @@ type AteWorkerService struct { var _ ateworkerpb.WorkerServer = (*AteWorkerService)(nil) // NewService creates a new AteWorkerService. -func NewService(podUID, chBinary string, guestDebug bool, maxActors int, tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, bootID string) *AteWorkerService { +func NewService(podUID, chBinary string, guestDebug bool, maxActors int, tunnel *atunnel.Tunnel, actorLogger *actorlog.ActorLogger, bootID string, families actornet.IPFamilies) *AteWorkerService { s := &AteWorkerService{ locks: actorlock.New(), inFlight: actorlock.NewInFlight(), @@ -430,6 +453,7 @@ func NewService(podUID, chBinary string, guestDebug bool, maxActors int, tunnel podUID: podUID, chBinary: chBinary, guestDebug: guestDebug, + families: families, snapshotWrites: make(chan struct{}, snapshotWriteSlots), tunnel: tunnel, actorLogger: actorLogger, @@ -440,8 +464,8 @@ func NewService(podUID, chBinary string, guestDebug bool, maxActors int, tunnel } // beginRPC registers before checking the drain flag so shutdown cannot miss it. -func (s *AteWorkerService) beginRPC(actorUID, name string, cancel context.CancelFunc) (func(), error) { - release := s.inFlight.Add(actorUID, name, cancel) +func (s *AteWorkerService) beginRPC(actorUID, name string) (func(), error) { + release := s.inFlight.Add(actorUID, name) if err := s.rejectIfDraining(); err != nil { release() return nil, err @@ -489,11 +513,3 @@ func (s *AteWorkerService) rejectIfDraining() error { } return nil } - -// cancelStartups cancels all boots and restores, leaving checkpoints running. -func (s *AteWorkerService) cancelStartups(ctx context.Context) { - for _, actorUID := range s.inFlight.CancelStartups() { - slog.InfoContext(ctx, "Cancelling in-progress workload startup RPC due to graceful shutdown", - slog.String("actorUID", actorUID)) - } -} diff --git a/cmd/ateworker-microvm/net.go b/cmd/ateworker-microvm/net.go index bd95abad45..c65e04330b 100644 --- a/cmd/ateworker-microvm/net.go +++ b/cmd/ateworker-microvm/net.go @@ -47,11 +47,14 @@ const ( actorTapMTU = 1500 ) -var gatewayHWAddr = actornet.MustParseMAC(gatewayMAC) +var ( + gatewayHWAddr = actornet.MustParseMAC(gatewayMAC) + actorGuestHWAddr = actornet.MustParseMAC(actorGuestMAC) +) // setupActorTap creates the guest's tap with a fixed gateway address and MAC. // Returns the FDs cloud-hypervisor adopts on boot or restore. -func setupActorTap(ctx context.Context, actorNetNS netns.Handle, name string, queuePairs int) ([]*os.File, error) { +func setupActorTap(ctx context.Context, actorNetNS netns.Handle, name string, queuePairs int, families actornet.IPFamilies) ([]*os.File, error) { var fds []*os.File err := netns.Do(ctx, actorNetNS, func(ctx context.Context) error { if old, lerr := netlink.LinkByName(name); lerr == nil { @@ -81,11 +84,28 @@ func setupActorTap(ctx context.Context, actorNetNS netns.Handle, name string, qu return fmt.Errorf("setting the gateway MAC on tap %q: %w", name, err) } if err := netlink.AddrReplace(link, actornet.HostVethAddr); err != nil { - return fmt.Errorf("assigning the gateway address to tap %q: %w", name, err) + return fmt.Errorf("assigning the IPv4 gateway address to tap %q: %w", name, err) + } + if families.Has(actornet.IPv6) { + if err := netlink.AddrReplace(link, actornet.HostVethIPv6Addr); err != nil { + return fmt.Errorf("assigning the IPv6 gateway address to tap %q: %w", name, err) + } } if err := netlink.LinkSetUp(link); err != nil { return fmt.Errorf("bringing up tap %q: %w", name, err) } + guestNeighbors := []*netlink.Neigh{{Family: netlink.FAMILY_V4, IP: actornet.ActorVethAddr.IP}} + if families.Has(actornet.IPv6) { + guestNeighbors = append(guestNeighbors, &netlink.Neigh{Family: netlink.FAMILY_V6, IP: actornet.ActorVethIPv6Addr.IP}) + } + for _, neighbor := range guestNeighbors { + neighbor.LinkIndex = link.Attrs().Index + neighbor.State = netlink.NUD_PERMANENT + neighbor.HardwareAddr = actorGuestHWAddr + if err := netlink.NeighSet(neighbor); err != nil { + return fmt.Errorf("setting guest neighbor %s on tap %q: %w", neighbor.IP, name, err) + } + } return nil }) if err != nil { diff --git a/cmd/ateworker-microvm/net_linux_test.go b/cmd/ateworker-microvm/net_linux_test.go index becf6e78d1..51e2ded392 100644 --- a/cmd/ateworker-microvm/net_linux_test.go +++ b/cmd/ateworker-microvm/net_linux_test.go @@ -89,7 +89,7 @@ func TestSetupActorTap(t *testing.T) { ctx := context.Background() ns := tapNetNS(t, "microvm-tap-test") - fds, err := setupActorTap(ctx, ns, "tap0_kata", 1) + fds, err := setupActorTap(ctx, ns, "tap0_kata", 1, actornet.IPv4|actornet.IPv6) if err != nil { t.Fatalf("setupActorTap: %v", err) } @@ -116,18 +116,33 @@ func TestSetupActorTap(t *testing.T) { if got := link.Attrs().MTU; got != actorTapMTU { t.Errorf("tap MTU = %d, want %d, the value the guest was snapshotted against", got, actorTapMTU) } - addrs, err := netlink.AddrList(link, netlink.FAMILY_V4) + addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL) if err != nil { return err } - var found bool + found := map[string]struct{}{} for _, a := range addrs { - if a.IPNet.String() == actornet.HostVethAddr.IPNet.String() { - found = true + found[a.IPNet.String()] = struct{}{} + } + for _, want := range []*netlink.Addr{actornet.HostVethAddr, actornet.HostVethIPv6Addr} { + if _, ok := found[want.IPNet.String()]; !ok { + t.Errorf("tap addresses = %v, want gateway %s", addrs, want) } } - if !found { - t.Errorf("tap addresses = %v, want the gateway %s the guest routes to", addrs, actornet.HostVethAddr) + neighbors, err := netlink.NeighList(link.Attrs().Index, netlink.FAMILY_ALL) + if err != nil { + return err + } + foundNeighbors := map[string]bool{} + for _, neighbor := range neighbors { + if neighbor.HardwareAddr.String() == actorGuestMAC && neighbor.State == netlink.NUD_PERMANENT { + foundNeighbors[neighbor.IP.String()] = true + } + } + for _, want := range []string{actornet.ActorVethIP, actornet.ActorVethIPv6} { + if !foundNeighbors[want] { + t.Errorf("tap neighbors = %v, want %s at %s permanent", neighbors, want, actorGuestMAC) + } } return nil }); err != nil { @@ -147,7 +162,7 @@ func TestSetupActorTapReplacesALeftover(t *testing.T) { ctx := context.Background() ns := tapNetNS(t, "microvm-tap-replace") - first, err := setupActorTap(ctx, ns, "tap0_kata", 1) + first, err := setupActorTap(ctx, ns, "tap0_kata", 1, actornet.IPv4) if err != nil { t.Fatalf("first setupActorTap: %v", err) } @@ -155,7 +170,7 @@ func TestSetupActorTapReplacesALeftover(t *testing.T) { defer f.Close() } - second, err := setupActorTap(ctx, ns, "tap0_kata", 2) + second, err := setupActorTap(ctx, ns, "tap0_kata", 2, actornet.IPv4) if err != nil { t.Fatalf("second setupActorTap over a leftover: %v", err) } diff --git a/cmd/ateworker-microvm/restore.go b/cmd/ateworker-microvm/restore.go index 33e718a657..7720c5a70f 100644 --- a/cmd/ateworker-microvm/restore.go +++ b/cmd/ateworker-microvm/restore.go @@ -22,20 +22,22 @@ import ( "encoding/json" "errors" "fmt" + "io" "log/slog" "os" "path/filepath" "strings" + "syscall" "time" "go.ate.dev/substrate/internal/apierror" - "go.ate.dev/substrate/internal/ateworker/phaselog" - "go.ate.dev/substrate/internal/workerstats" - "go.ate.dev/substrate/internal/ateworker/actornet" "go.ate.dev/substrate/internal/ateworker/cgroup" + "go.ate.dev/substrate/internal/ateworker/phaselog" + "go.ate.dev/substrate/internal/workerstats" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/ch" + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/child" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/kata" "go.ate.dev/substrate/internal/ateworkervalidation" "go.ate.dev/substrate/internal/imagecache" @@ -136,10 +138,7 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb } defer s.locks.Unlock(req.GetActorUid()) - ctx, cancel := context.WithCancel(ctx) - defer cancel() - // Register for startup cancellation before checking for shutdown. - release, err := s.beginRPC(req.GetActorUid(), rpcRestoreWorkload, cancel) + release, err := s.beginRPC(req.GetActorUid(), rpcRestoreWorkload) if err != nil { return nil, err } @@ -150,6 +149,7 @@ func (s *AteWorkerService) RestoreWorkload(ctx context.Context, req *ateworkerpb } p := actorBootParams{ + activationUID: req.GetActivationUid(), actorRef: resources.ActorRef{Atespace: req.GetAtespace(), Name: req.GetActorName()}, actorUID: req.GetActorUid(), actorDirs: req.GetActorDirs(), @@ -377,7 +377,7 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo } }() for i, nd := range netDevs { - files, terr := setupActorTap(ctx, s.sandboxNetNS(actorUID), fmt.Sprintf("tap%d_kata", i), nd.QueuePairs) + files, terr := setupActorTap(ctx, s.sandboxNetNS(actorUID), fmt.Sprintf("tap%d_kata", i), nd.QueuePairs, s.families) if terr != nil { return fmt.Errorf("while building restore tap for %s: %w", nd.ID, terr) } @@ -397,7 +397,7 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo SysProcAttr: leaf.SysProcAttr(), }) if err != nil { - return fmt.Errorf("while launching VMM for restore: %w", err) + return restoreVMMError(ctx, "launching VMM for restore", err) } defer func() { if retErr != nil { @@ -419,7 +419,7 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo slog.InfoContext(ctx, "restoring guest memory", slog.String("mode", memMode), slog.String("vmm_version", client.Info().Version)) if err := client.RestoreWithNetFDs(ctx, restoreDir, restoredNets, memMode); err != nil { - return fmt.Errorf("while restoring VM with net FDs: %w", err) + return restoreVMMRunningError(ctx, chProc, "restoring VM with net FDs", err) } tVMRestore := time.Now() // An eager restore has read the whole snapshot into guest memory, and nothing @@ -480,6 +480,14 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo } tReseeded := time.Now() + // Re-attach stdout/stderr forwarding and the exit watch after CRNG reseed + // (the last retryable step) and before the wakeup probe so pre-probe logs + // are captured. + attribution := p.actorAttribution() + for _, c := range ctrs { + s.watchContainer(guestAC, attribution, c.id, c.name) + } + // Block until every wakeup-probe-enabled container reports 200. if err := wakeupprobe.WaitAll(ctx, containers, actornet.ActorVethIP, wakeupprobe.DialFunc(s.sandboxDialer(actorUID))); err != nil { return fmt.Errorf("while waiting for container wakeup probe: %w", err) @@ -523,7 +531,8 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo }) ra := &runningActor{ - chProc: chProc, vfsdProc: vfsdProc, + activationUID: p.activationUID, + chProc: chProc, vfsdProc: vfsdProc, apiSocket: apiSocket, memoryBytes: p.size.MemoryBytes, baseID: srcID, restoreSourceDir: restoreDir, preserveRestoreSource: preserveRestoreDir, snapshotIsSelfContained: memMode == ch.MemRestoreEager, @@ -533,14 +542,6 @@ func (s *AteWorkerService) restoreMemoryFidelity(ctx context.Context, p actorBoo guestAgent: guestAC, } - // Re-attach stdout/stderr forwarding for each container over the agent - // connection dialed after resume: the restored guest's containers are alive, so - // ReadStdout/ReadStderr pick up where they left off. - attribution := p.actorAttribution() - for _, c := range ctrs { - s.startActorLogForwarding(guestAC, attribution, c.id, c.name) - } - if err := s.tunnel.ActivateIngress(p.attribution(), s.sandboxDialer(p.actorUID)); err != nil { return err } @@ -585,7 +586,7 @@ func (s *AteWorkerService) cleanupFailedRestoreRootfs(ctx context.Context, actor if err := os.RemoveAll(rootfsUpperDir(actorDirs)); err != nil { slog.WarnContext(ctx, "Failed to remove rootfs upper dir after Restore failure", slog.String("actorUID", actorUID), slog.Any("err", err)) } - if err := imagecache.UnmountAllUnder(actorDirs.GetOciBundleDir()); err != nil { + if err := imagecache.UnmountBundlesUnder(actorDirs.GetOciBundleDir()); err != nil { slog.WarnContext(ctx, "Failed to unmount bundle rootfs overlays after Restore failure", slog.String("actorUID", actorUID), slog.Any("err", err)) } } @@ -629,6 +630,54 @@ func restoreGuestReadyError(ctx context.Context, step string, err error) error { return apierror.Unavailable("while %s: %w", step, err) } +// restoreVMMError classifies a failure to launch the restore VMM or to issue +// vm.restore to it. When the VMM did not answer or its api-socket failed, the +// snapshot has only been read and the restoreMemoryFidelity and +// RestoreWorkload defers stop the VMM and undo the host state, so the failure +// is Unavailable and safe to retry. An error CH itself returned, such as a +// corrupt snapshot, would fail the same way again and stays an internal error. +// As in restoreGuestReadyError, the caller's context ending is reported as +// such. +func restoreVMMError(ctx context.Context, step string, err error) error { + if !isVMMTransportError(err) { + return fmt.Errorf("while %s: %w", step, err) + } + if ctx.Err() != nil { + return fmt.Errorf("while %s: %v: %w", step, err, ctx.Err()) + } + return apierror.Unavailable("while %s: %w", step, err) +} + +// restoreVMMRunningError is restoreVMMError for a VMM that was already +// running. If chProc has exited, CH crashed, and the error stays internal. +func restoreVMMRunningError(ctx context.Context, chProc *child.Process, step string, err error) error { + if chProc != nil { + select { + case <-chProc.Done(): + return fmt.Errorf("while %s: %w", step, err) + default: + } + } + return restoreVMMError(ctx, step, err) +} + +// isVMMTransportError reports whether err is the VMM not answering its +// api-socket in time, or a failure of the socket itself. +func isVMMTransportError(err error) bool { + if errors.Is(err, ch.ErrNotReady) { + return true + } + for _, target := range []error{ + os.ErrDeadlineExceeded, io.EOF, io.ErrUnexpectedEOF, + syscall.ECONNREFUSED, syscall.ECONNRESET, syscall.EPIPE, + } { + if errors.Is(err, target) { + return true + } + } + return false +} + // rewriteSnapshotPaths repoints the snapshot config.json's per-actor paths from // the source actor's to the restoring actor's. The file is CH's own: at // snapshot time it serializes the config the VM booted with, and at restore diff --git a/cmd/ateworker-microvm/restore_linux_test.go b/cmd/ateworker-microvm/restore_linux_test.go index 20665004a9..1f422ffcd0 100644 --- a/cmd/ateworker-microvm/restore_linux_test.go +++ b/cmd/ateworker-microvm/restore_linux_test.go @@ -59,7 +59,7 @@ func failedRestoreRootfs(t *testing.T, actorUID string, overlays bool) *ateworke } // Detach the overlays even if the cleanup under test leaves them, so // t.TempDir can remove the bundle. - t.Cleanup(func() { _ = imagecache.UnmountAllUnder(dirs.GetOciBundleDir()) }) + t.Cleanup(func() { _ = imagecache.UnmountBundlesUnder(dirs.GetOciBundleDir()) }) } if _, err := (&AteWorkerService{}).buildActorContainers(actorUID, dirs, containers); err != nil { t.Fatalf("buildActorContainers: %v", err) diff --git a/cmd/ateworker-microvm/restore_test.go b/cmd/ateworker-microvm/restore_test.go index de72a6a2a4..3002ab0f4f 100644 --- a/cmd/ateworker-microvm/restore_test.go +++ b/cmd/ateworker-microvm/restore_test.go @@ -23,6 +23,8 @@ import ( "errors" "fmt" "io/fs" + "net" + "net/http" "os" "path/filepath" "strings" @@ -33,6 +35,7 @@ import ( "google.golang.org/grpc/codes" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/ch" + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/child" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/kata" "go.ate.dev/substrate/internal/actorlock" "go.ate.dev/substrate/internal/apierror" @@ -588,6 +591,126 @@ func TestRestoreGuestReadyError(t *testing.T) { }) } +// restoreErrFrom issues vm.restore to a socket served by serve, or to a stale +// socket file with no listener when serve is nil, and returns its error. +func restoreErrFrom(t *testing.T, serve func(net.Listener)) error { + t.Helper() + sock := shortSocketPath(t) + if serve == nil { + lis, err := net.ListenUnix("unix", &net.UnixAddr{Name: sock, Net: "unix"}) + if err != nil { + t.Fatal(err) + } + lis.SetUnlinkOnClose(false) + lis.Close() + } else { + lis, err := net.Listen("unix", sock) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { lis.Close() }) + go serve(lis) + } + ctx, cancel := context.WithTimeout(t.Context(), 5*time.Second) + defer cancel() + return ch.NewClient(sock).RestoreWithNetFDs(ctx, t.TempDir(), nil, "") +} + +func TestRestoreVMMError(t *testing.T) { + closesConn := func(lis net.Listener) { + for { + c, err := lis.Accept() + if err != nil { + return + } + c.Close() + } + } + refuses := func(lis net.Listener) { + _ = http.Serve(lis, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "Error restoring VM: corrupt snapshot", http.StatusInternalServerError) + })) + } + for _, tc := range []struct { + name string + step string + err func(*testing.T) error + retryable bool + }{ + {"VMM api-socket not ready after launch", "launching VMM for restore", + func(t *testing.T) error { return fmt.Errorf("while waiting for VMM api-socket: %w", notReadyErr(t)) }, true}, + {"nobody on the socket", "restoring VM with net FDs", + func(t *testing.T) error { return restoreErrFrom(t, nil) }, true}, + {"VMM closes the connection", "restoring VM with net FDs", + func(t *testing.T) error { return restoreErrFrom(t, closesConn) }, true}, + {"socket error that would repeat", "restoring VM with net FDs", + func(*testing.T) error { return &net.OpError{Op: "dial", Net: "unix", Err: syscall.EINVAL} }, false}, + {"CH refuses the snapshot", "restoring VM with net FDs", + func(t *testing.T) error { return restoreErrFrom(t, refuses) }, false}, + {"cloud-hypervisor fails to start", "launching VMM for restore", + func(*testing.T) error { + return fmt.Errorf("while starting cloud-hypervisor: %w", &os.PathError{Op: "fork/exec", Path: "/nope", Err: os.ErrNotExist}) + }, false}, + } { + t.Run(tc.name, func(t *testing.T) { + cause := tc.err(t) + if cause == nil { + t.Fatal("scenario produced no error") + } + want := codes.Internal + if tc.retryable { + want = codes.Unavailable + } + err := restoreVMMError(t.Context(), tc.step, cause) + if got := apierror.Code(err); got != want { + t.Errorf("apierror.Code(err) = %v, want %v (err: %v)", got, want, err) + } + if !errors.Is(err, cause) { + t.Errorf("err = %v, want it to wrap %v", err, cause) + } + + ended, cancel := context.WithCancel(t.Context()) + cancel() + if got := apierror.Code(restoreVMMError(ended, tc.step, cause)); tc.retryable && got != codes.Canceled { + t.Errorf("caller gone: apierror.Code(err) = %v, want %v", got, codes.Canceled) + } + }) + } +} + +func TestRestoreVMMRunningError(t *testing.T) { + closes := restoreErrFrom(t, func(lis net.Listener) { + for { + c, err := lis.Accept() + if err != nil { + return + } + c.Close() + } + }) + exited := fakeVM(t) + <-exited.chProc.Done() + for _, tc := range []struct { + name string + chProc *child.Process + want codes.Code + }{ + {"VMM exited", exited.chProc, codes.Internal}, + {"VMM running", liveVM(t).chProc, codes.Unavailable}, + {"no VMM", nil, codes.Unavailable}, + } { + t.Run(tc.name, func(t *testing.T) { + err := restoreVMMRunningError(t.Context(), tc.chProc, "restoring VM with net FDs", closes) + if got := apierror.Code(err); got != tc.want { + t.Errorf("apierror.Code(err) = %v, want %v (err: %v)", got, tc.want, err) + } + if !errors.Is(err, closes) { + t.Errorf("err = %v, want it to wrap %v", err, closes) + } + }) + } +} + func TestRPCsRejectUntrustedRuntimeAssetPaths(t *testing.T) { s := &AteWorkerService{} s.epoch.Store(1) diff --git a/cmd/ateworker-microvm/run.go b/cmd/ateworker-microvm/run.go index 058849dd20..7b796348bc 100644 --- a/cmd/ateworker-microvm/run.go +++ b/cmd/ateworker-microvm/run.go @@ -25,6 +25,7 @@ import ( "os" "path/filepath" "runtime" + "sync" "sync/atomic" "syscall" "time" @@ -54,6 +55,9 @@ import ( // cloud-hypervisor process directly (booted by RunWorkload or relaunched by // RestoreWorkload), so it tracks that process and its api-socket for teardown. type runningActor struct { + // activationUID identifies this run or restore. Immutable once published. + activationUID string + // baseID is the FROZEN base sandbox id propagated across this actor's restore // lineage. For a cold-run actor this is the actor's own id; for a restored // actor it is the id read from the snapshot's base-id file (the golden id, @@ -95,21 +99,26 @@ type runningActor struct { // there is no delta to overlay onto restoreSourceDir. snapshotIsSelfContained bool - // guestAgent is the kata-agent ttrpc client retained past boot. Two things - // share it: the stdout/stderr forwarding goroutines (they pump the + // guestAgent is the kata-agent ttrpc connection retained past boot. Three + // things share it: the stdout/stderr forwarding goroutines (they pump the // container's output via ReadStdout/ReadStderr on this connection for the - // actor's lifetime) and GetWorkloadStats (via the hosted actor's guest - // stats target, which points at this same client). It is NOT closed when - // RunWorkload / RestoreWorkload return — teardownActor closes it, which - // makes the in-flight ReadStdout/ReadStderr calls fail and the forwarding - // goroutines exit (io.EOF). Both boot and restore fail if they cannot dial - // the agent, so a running actor always has one; nil only once teardown has - // closed it. - guestAgent *kata.AgentClient + // actor's lifetime), the container exit watch, and GetWorkloadStats (via + // the hosted actor's guest stats target, which points at this same + // client). It is NOT closed when RunWorkload / RestoreWorkload return; + // teardownActor closes it, which makes the in-flight calls fail and waits + // for those goroutines to exit. Both boot and restore fail if they cannot + // dial the agent, so a running actor always has one; nil only once + // teardown has closed it. + guestAgent *agentConn // workloadIDs are the guest container ids of this actor's workloads, for the // SIGTERM the graceful shutdown propagates into the guest (see shutdown.go). workloadIDs []string + + // checkpointWaitReadyFailures counts consecutive CheckpointWorkload calls + // where the VMM stayed alive and its api-socket did not answer. Guarded by + // AteWorkerService.locks for this actor. + checkpointWaitReadyFailures int } // baseIDFile is a tiny snapshot file (under the checkpoint/restore dir) holding @@ -246,10 +255,7 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run return nil, fmt.Errorf("gave up waiting for the actor's lock: %w", ctx.Err()) } defer s.locks.Unlock(req.GetActorUid()) - ctx, cancel := context.WithCancel(ctx) - defer cancel() - // Register for startup cancellation before checking for shutdown. - release, err := s.beginRPC(req.GetActorUid(), rpcRunWorkload, cancel) + release, err := s.beginRPC(req.GetActorUid(), rpcRunWorkload) if err != nil { return nil, err } @@ -260,6 +266,7 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run } p := actorBootParams{ + activationUID: req.GetActivationUid(), actorRef: resources.ActorRef{Atespace: req.GetAtespace(), Name: req.GetActorName()}, actorUID: req.GetActorUid(), actorDirs: req.GetActorDirs(), @@ -305,6 +312,7 @@ func (s *AteWorkerService) RunWorkload(ctx context.Context, req *ateworkerpb.Run // request, or from a Restore request whose snapshot fidelity covers only the // durable-dir volumes (the workload itself cold-starts). type actorBootParams struct { + activationUID string actorRef resources.ActorRef actorUID string actorDirs *ateworkerpb.ActorDirs @@ -415,7 +423,7 @@ func (s *AteWorkerService) coldBootActor(ctx context.Context, p actorBootParams) } // Detach any bundle rootfs overlays mounted by buildActorContainers // before the failure, mirroring teardownActor's cleanup. - if err := imagecache.UnmountAllUnder(p.actorDirs.GetOciBundleDir()); err != nil { + if err := imagecache.UnmountBundlesUnder(p.actorDirs.GetOciBundleDir()); err != nil { slog.WarnContext(ctx, "Failed to unmount bundle rootfs overlays after Run failure", slog.Any("err", err)) } } @@ -541,7 +549,7 @@ func (s *AteWorkerService) coldBootActor(ctx context.Context, p actorBootParams) // Network device: build the actor's tap and add a virtio-net to the created // (pre-boot) VM with its FDs (SCM_RIGHTS). - tapFiles, err := setupActorTap(ctx, s.sandboxNetNS(actorUID), "tap0_kata", 1) + tapFiles, err := setupActorTap(ctx, s.sandboxNetNS(actorUID), "tap0_kata", 1, s.families) if err != nil { return fmt.Errorf("while building tap: %w", err) } @@ -580,18 +588,20 @@ func (s *AteWorkerService) coldBootActor(ctx context.Context, p actorBootParams) return fmt.Errorf("while dialing kata-agent: %w", err) } tDialed := time.Now() - // The agent client must stay open past this RPC: the stdout/stderr forwarding - // goroutines (started below) read over it for the actor's lifetime. It is stored - // on the runningActor and closed by teardownActor. Close it here only if Run - // fails after this point (no runningActor recorded). + // The agent connection must stay open past this RPC: the stdout/stderr + // forwarding goroutines (started below) read over it for the actor's + // lifetime. It is stored on the runningActor and closed by teardownActor. + // Close it here only if Run fails after this point (no runningActor + // recorded). defer func() { if retErr != nil { _ = ac.Close() } }() + attribution := p.actorAttribution() // Post-boot kata-agent setup: sandbox, guest networking, start each container. - if err := s.startActorContainers(ctx, ac, actorUID, vsockPath, ctrs); err != nil { + if err := s.startActorContainers(ctx, ac, attribution, vsockPath, ctrs); err != nil { return err } tContainers := time.Now() @@ -610,7 +620,7 @@ func (s *AteWorkerService) coldBootActor(ctx context.Context, p actorBootParams) slog.Duration("wakeup_probe", time.Since(tContainers)), slog.Duration("since_boot", time.Since(tBooted))) - ra := &runningActor{chProc: chProc, vfsdProc: vfsdProc, apiSocket: apiSocket, memoryBytes: p.size.MemoryBytes, baseID: actorUID, guestAgent: ac, workloadIDs: workloadIDs(ctrs)} + ra := &runningActor{activationUID: p.activationUID, chProc: chProc, vfsdProc: vfsdProc, apiSocket: apiSocket, memoryBytes: p.size.MemoryBytes, baseID: actorUID, guestAgent: ac, workloadIDs: workloadIDs(ctrs)} if err := s.tunnel.ActivateIngress(p.attribution(), s.sandboxDialer(p.actorUID)); err != nil { return err } @@ -618,22 +628,12 @@ func (s *AteWorkerService) coldBootActor(ctx context.Context, p actorBootParams) s.setRunningVM(actorUID, ra) go s.watchVM(p.attribution(), p.actorDirs, ra) - // Forward each container's stdout/stderr into the pod logs, keyed by the - // container id (see StartRootfsContainer). The goroutines read over ac for - // the actor's lifetime and exit (io.EOF) when teardownActor closes ac. - workloadIDs := make([]string, 0, len(ctrs)) - attribution := p.actorAttribution() - for _, c := range ctrs { - s.startActorLogForwarding(ac, attribution, c.id, c.name) - workloadIDs = append(workloadIDs, c.id) - } - // Publish the guest to GetWorkloadStats, past every error return above: a // failing attempt closes ac on its way out (and coldBootActorRetrying may // then try the whole boot again), so a target published earlier would leave // the handler polling a connection nobody owns. Same client the forwarding // above reads over — ttrpc multiplexes, and teardownActor ends both. - s.setGuestStats(actorUID, &guestStatsTarget{actorUID: actorUID, agent: ac, workloadIDs: workloadIDs}) + s.setGuestStats(actorUID, &guestStatsTarget{actorUID: actorUID, agent: ac, workloadIDs: ra.workloadIDs}) // Looked up while the caller holds the actor's lock, so it is this // activation even if the read below outlives the RPC. if hosted := s.lookupActor(actorUID); hosted != nil { @@ -857,7 +857,8 @@ func buildFsConfigs(id string) []ch.FsConfig { // does at boot: establish the sandbox once (mounting the kataShared virtio-fs base), // configure guest networking (eth0 IP/MAC/MTU + routes) once, then start each // container on its own overlay rootfs. On failure it dumps guest diagnostics. -func (s *AteWorkerService) startActorContainers(ctx context.Context, ac *kata.AgentClient, id, vsockPath string, ctrs []actorContainer) error { +func (s *AteWorkerService) startActorContainers(ctx context.Context, ac *agentConn, attribution resources.ActorAttribution, vsockPath string, ctrs []actorContainer) error { + id := attribution.UID // Establish the agent sandbox + the kataShared virtio-fs mount (every // container's merged rootfs, durable volumes, CSI volumes, and system-info // volumes). All containers share it, so use the first container's hostname. @@ -876,7 +877,7 @@ func (s *AteWorkerService) startActorContainers(ctx context.Context, ac *kata.Ag // Configure guest networking (the shim's job): eth0 IP/MAC/MTU, routes, ARP. mtu := uint64(actorTapMTUOf(ctx, s.sandboxNetNS(id), "tap0_kata")) netCtx, netCancel := context.WithTimeout(ctx, 20*time.Second) - err = s.configureGuestNetwork(netCtx, ac, mtu) + err = s.configureGuestNetwork(netCtx, ac.AgentClient, mtu) netCancel() if err != nil { if s.guestDebug { @@ -889,7 +890,7 @@ func (s *AteWorkerService) startActorContainers(ctx context.Context, ac *kata.Ag tNetwork := time.Now() for _, c := range ctrs { - if err := s.startRootfsContainer(ctx, ac, vsockPath, c); err != nil { + if err := s.startRootfsContainer(ctx, ac, attribution, vsockPath, c); err != nil { return err } } @@ -902,11 +903,12 @@ func (s *AteWorkerService) startActorContainers(ctx context.Context, ac *kata.Ag } // startRootfsContainer brings up one container on its host-merged rootfs (the -// stock kata flow: create + start against shared//rootfs). On failure it +// stock kata flow: create + start against shared//rootfs) and starts +// forwarding its stdout and stderr and watching for its exit. On failure it // dumps the guest's view of the shared tree. // // Its spec binds every declared volume at its mount path. -func (s *AteWorkerService) startRootfsContainer(ctx context.Context, ac *kata.AgentClient, vsockPath string, c actorContainer) error { +func (s *AteWorkerService) startRootfsContainer(ctx context.Context, ac *agentConn, attribution resources.ActorAttribution, vsockPath string, c actorContainer) error { cCtx, cancel := context.WithTimeout(ctx, 30*time.Second) err := ac.StartRootfsContainer(cCtx, c.id, c.spec) cancel() @@ -920,26 +922,30 @@ func (s *AteWorkerService) startRootfsContainer(ctx context.Context, ac *kata.Ag } return fmt.Errorf("while starting rootfs container %q: %w", c.name, err) } + s.watchContainer(ac, attribution, c.id, c.name) return nil } -// startActorLogForwarding spawns two goroutines that pump the actor container's -// stdout and stderr (read over the kata-agent ttrpc client ac via repeated -// ReadStdout/ReadStderr) through the shared actorlog forwarder, which annotates -// each line with the actor's ate.dev/* labels and writes it to the pod's stdout. -// -// The streams are keyed by streamID == the kata containerID==execID (the overlay -// workload id); lines are tagged with actorName + containerName -// (ate.actor.container.name) so a multi-container actor demultiplexes. -// The reader contexts are context.Background() — the goroutines are NOT bound to the -// RPC that started them; they terminate when ac is closed (by teardownActor), which -// makes the in-flight ReadStdout/ReadStderr fail and the StreamReader return io.EOF, -// ending WrapContainerLogs. This keeps the agent connection (which ttrpc allows -// concurrent Calls on) alive for forwarding while guaranteeing no goroutine outlives -// the connection. -func (s *AteWorkerService) startActorLogForwarding(ac *kata.AgentClient, a resources.ActorAttribution, streamID, containerName string) { - go s.actorLogger.WrapContainerLogs(kata.NewStdioReader(context.Background(), ac, streamID, streamID, false), a, containerName) - go s.actorLogger.WrapContainerLogs(kata.NewStdioReader(context.Background(), ac, streamID, streamID, true), a, containerName) +// agentConn pairs a guest's *kata.AgentClient with the WaitGroup for the +// goroutines that forward and watch its containers over it (see +// watchContainer). Close shuts the client and waits for those goroutines to +// exit. Nothing starts a watch after Close begins: both run on the RPC +// goroutine or under the actor's lock. +type agentConn struct { + *kata.AgentClient + logWG sync.WaitGroup +} + +func newAgentConn(ac *kata.AgentClient) *agentConn { + return &agentConn{AgentClient: ac} +} + +// Close shuts the underlying AgentClient to unblock live stream reads and waits +// for the forwarding goroutines to exit. Safe to call more than once. +func (c *agentConn) Close() error { + err := c.AgentClient.Close() + c.logWG.Wait() + return err } // errGuestStopped reports that the micro-VM stopped before the kata-agent @@ -973,7 +979,7 @@ const ( // unlinks it when the VM stops (virtio-vsock device shutdown), so a socket that // has gone missing means the guest died. Polling on would only spend the rest // of the timeout to report a bare "no such file or directory". -func dialAgentRetry(ctx context.Context, vsockPath string, timeout time.Duration) (*kata.AgentClient, error) { +func dialAgentRetry(ctx context.Context, vsockPath string, timeout time.Duration) (*agentConn, error) { deadline := time.Now().Add(timeout) start := time.Now() var lastErr error @@ -984,7 +990,7 @@ func dialAgentRetry(ctx context.Context, vsockPath string, timeout time.Duration if err == nil { slog.InfoContext(ctx, "kata-agent answered", slog.Int("attempts", attempt), slog.Duration("elapsed", time.Since(start))) - return ac, nil + return newAgentConn(ac), nil } if errors.Is(err, fs.ErrNotExist) { return nil, fmt.Errorf("%w (cloud-hypervisor removed %q): %w", errGuestStopped, vsockPath, err) @@ -1040,32 +1046,55 @@ func tailString(s string, n int) string { // configureGuestNetwork replicates the kata shim's guest network setup over the // agent: configure eth0 (IP/MAC/MTU), install the connected + default routes, and -// pin the gateway's ARP entry to its fixed MAC (so a restored guest's frozen -// neighbor entry stays valid). +// pin the gateway's neighbor entry to its fixed MAC (so a restored guest's +// frozen entry stays valid). func (s *AteWorkerService) configureGuestNetwork(ctx context.Context, ac *kata.AgentClient, mtu uint64) error { - if err := ac.UpdateInterface(ctx, &agentpb.Interface{ - Device: actornet.ActorVethName, - Name: actornet.ActorVethName, - HwAddr: actorGuestMAC, - Mtu: mtu, - IPAddresses: []*agentpb.IPAddress{ - {Family: agentpb.IPFamily_v4, Address: actornet.ActorVethIP, Mask: "30"}, + addresses := []*agentpb.IPAddress{{Family: agentpb.IPFamily_v4, Address: actornet.ActorVethIP, Mask: "30"}} + routes := []*agentpb.Route{ + {Dest: actornet.ActorVethSubnet, Device: actornet.ActorVethName, Scope: uint32(unix.RT_SCOPE_LINK), Family: agentpb.IPFamily_v4}, + {Dest: "", Gateway: actornet.ActorVethGateway, Device: actornet.ActorVethName, Family: agentpb.IPFamily_v4}, + } + neighbors := []*agentpb.ARPNeighbor{ + { + ToIPAddress: &agentpb.IPAddress{Family: agentpb.IPFamily_v4, Address: actornet.ActorVethGateway}, + Device: actornet.ActorVethName, Lladdr: gatewayMAC, State: unix.NUD_PERMANENT, }, - }); err != nil { + } + if s.families.Has(actornet.IPv6) { + addresses = append(addresses, &agentpb.IPAddress{Family: agentpb.IPFamily_v6, Address: actornet.ActorVethIPv6, Mask: "126"}) + routes = append(routes, + &agentpb.Route{Dest: actornet.ActorVethIPv6Subnet, Device: actornet.ActorVethName, Scope: uint32(unix.RT_SCOPE_LINK), Family: agentpb.IPFamily_v6}, + &agentpb.Route{Dest: "", Gateway: actornet.ActorVethIPv6Gateway, Device: actornet.ActorVethName, Family: agentpb.IPFamily_v6}, + ) + neighbors = append(neighbors, &agentpb.ARPNeighbor{ + ToIPAddress: &agentpb.IPAddress{Family: agentpb.IPFamily_v6, Address: actornet.ActorVethIPv6Gateway}, + Device: actornet.ActorVethName, Lladdr: gatewayMAC, State: unix.NUD_PERMANENT, + }) + } + iface := &agentpb.Interface{ + Device: actornet.ActorVethName, + Name: actornet.ActorVethName, + HwAddr: actorGuestMAC, + Mtu: mtu, + IPAddresses: addresses, + } + if s.families.Has(actornet.IPv6) { + // The point-to-point link uses permanent neighbors, so NOARP also avoids + // freezing a tentative IPv6 address into the golden snapshot during DAD. + iface.RawFlags = unix.IFF_NOARP + if err := ac.UpdateInterface(ctx, &agentpb.Interface{ + Device: iface.Device, Name: iface.Name, HwAddr: iface.HwAddr, Mtu: iface.Mtu, RawFlags: iface.RawFlags, + }); err != nil { + return err + } + } + if err := ac.UpdateInterface(ctx, iface); err != nil { return err } - if err := ac.UpdateRoutes(ctx, []*agentpb.Route{ - {Dest: actornet.ActorVethSubnet, Device: actornet.ActorVethName, Scope: uint32(unix.RT_SCOPE_LINK), Family: agentpb.IPFamily_v4}, - {Dest: "", Gateway: actornet.ActorVethGateway, Device: actornet.ActorVethName, Family: agentpb.IPFamily_v4}, - }); err != nil { + if err := ac.UpdateRoutes(ctx, routes); err != nil { return err } - return ac.AddARPNeighbors(ctx, []*agentpb.ARPNeighbor{{ - ToIPAddress: &agentpb.IPAddress{Family: agentpb.IPFamily_v4, Address: actornet.ActorVethGateway}, - Device: actornet.ActorVethName, - Lladdr: gatewayMAC, - State: 0x80, // NUD_PERMANENT - }}) + return ac.AddARPNeighbors(ctx, neighbors) } // waitForFile polls for path to exist, up to d. Used to wait for the kata-agent diff --git a/cmd/ateworker-microvm/run_test.go b/cmd/ateworker-microvm/run_test.go index 5863175d5d..ac284d3aa5 100644 --- a/cmd/ateworker-microvm/run_test.go +++ b/cmd/ateworker-microvm/run_test.go @@ -17,20 +17,31 @@ package main import ( + "bufio" + "bytes" "context" "encoding/json" "errors" + "fmt" "net" "os" "path/filepath" "runtime" "slices" "strings" + "sync" "testing" "time" + "github.com/containerd/ttrpc" + specs "github.com/opencontainers/runtime-spec/specs-go" "go.ate.dev/substrate/cmd/ateworker-microvm/internal/kata" + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/third_party/kata/agentpb" + "go.ate.dev/substrate/internal/actorlog" + "go.ate.dev/substrate/internal/ateworker/actornet" "go.ate.dev/substrate/internal/proto/ateworkerpb" + "go.ate.dev/substrate/internal/resources" + "google.golang.org/protobuf/types/known/emptypb" ) // A vsock socket that has gone missing means cloud-hypervisor stopped the VM @@ -241,3 +252,357 @@ func TestBuildVMConfigBalloon(t *testing.T) { t.Errorf("VmConfig JSON = %s, %v; want the balloon section cloud-hypervisor expects", b, err) } } + +// hybridVsockListener speaks cloud-hypervisor's hybrid-vsock text handshake +// ("CONNECT \n" -> "OK \n") on each accepted Unix connection before +// handing the stream to the ttrpc server, matching kata.DialAgent. +type hybridVsockListener struct { + net.Listener +} + +type bufferedConn struct { + net.Conn + r *bufio.Reader +} + +func (c *bufferedConn) Read(p []byte) (int, error) { + return c.r.Read(p) +} + +func (l hybridVsockListener) Accept() (net.Conn, error) { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + br := bufio.NewReader(conn) + line, err := br.ReadString('\n') + if err != nil { + _ = conn.Close() + return nil, err + } + if !strings.HasPrefix(line, "CONNECT ") { + _ = conn.Close() + return nil, fmt.Errorf("unexpected handshake %q", line) + } + if _, err := fmt.Fprint(conn, "OK 1024\n"); err != nil { + _ = conn.Close() + return nil, err + } + return &bufferedConn{Conn: conn, r: br}, nil +} + +func startFakeKataAgent(t *testing.T, overrides map[string]ttrpc.Method) (*agentConn, string) { + t.Helper() + vsockPath := filepath.Join(t.TempDir(), "clh.sock") + rawLis, err := net.Listen("unix", vsockPath) + if err != nil { + t.Fatalf("listen: %v", err) + } + srv, err := ttrpc.NewServer() + if err != nil { + t.Fatalf("ttrpc.NewServer: %v", err) + } + emptyOK := func(_ context.Context, unmarshal func(interface{}) error) (interface{}, error) { + if err := unmarshal(&emptypb.Empty{}); err != nil { + return nil, err + } + return &emptypb.Empty{}, nil + } + methods := map[string]ttrpc.Method{ + "CreateContainer": emptyOK, + "CloseStdin": emptyOK, + "StartContainer": emptyOK, + } + for k, v := range overrides { + methods[k] = v + } + srv.Register("grpc.AgentService", methods) + serveErr := make(chan error, 1) + go func() { serveErr <- srv.Serve(context.Background(), hybridVsockListener{Listener: rawLis}) }() + t.Cleanup(func() { + _ = srv.Close() + if err := <-serveErr; err != nil && !errors.Is(err, ttrpc.ErrServerClosed) { + t.Logf("fake kata-agent server: %v", err) + } + }) + + ac, err := kata.DialAgent(t.Context(), vsockPath) + if err != nil { + t.Fatalf("DialAgent: %v", err) + } + conn := newAgentConn(ac) + t.Cleanup(func() { _ = conn.Close() }) + return conn, vsockPath +} + +type blockingLogWriter struct { + mu sync.Mutex + buf bytes.Buffer + writeEntered chan struct{} + enterOnce sync.Once + unblockWrite <-chan struct{} + closeReturned <-chan struct{} + closedEarly bool +} + +func (w *blockingLogWriter) Write(p []byte) (int, error) { + w.enterOnce.Do(func() { close(w.writeEntered) }) + <-w.unblockWrite + w.mu.Lock() + defer w.mu.Unlock() + select { + case <-w.closeReturned: + w.closedEarly = true + default: + } + return w.buf.Write(p) +} + +// Container logs must start forwarding in startRootfsContainer as soon as +// each container starts, rather than waiting for wakeupprobe.WaitAll to pass. +func TestStartRootfsContainerForwardsLogs(t *testing.T) { + attr := resources.ActorAttribution{ + Ref: resources.ActorRef{Atespace: "ns-1", Name: "actor-1"}, + UID: "uid-1", + TemplateAtespace: "ns-1", + TemplateName: "tmpl-1", + } + + t.Run("crash output from first container is drained when second container fails to start", func(t *testing.T) { + var stdoutCalls, stderrCalls int + var mu sync.Mutex + ac, vsockPath := startFakeKataAgent(t, map[string]ttrpc.Method{ + "StartContainer": func(_ context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.StartContainerRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + if req.GetContainerId() == "c_second" { + return nil, errors.New("oci runtime start failed") + } + return &emptypb.Empty{}, nil + }, + "ReadStdout": func(_ context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.ReadStreamRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + if req.GetContainerId() != "c_first" { + t.Errorf("ReadStdout for container %q, want c_first", req.GetContainerId()) + return nil, errors.New("unexpected container") + } + mu.Lock() + defer mu.Unlock() + stdoutCalls++ + if stdoutCalls == 1 { + return &agentpb.ReadStreamResponse{Data: []byte("first container booting\n")}, nil + } + return &agentpb.ReadStreamResponse{}, nil + }, + "ReadStderr": func(_ context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.ReadStreamRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + if req.GetContainerId() != "c_first" { + t.Errorf("ReadStderr for container %q, want c_first", req.GetContainerId()) + return nil, errors.New("unexpected container") + } + mu.Lock() + defer mu.Unlock() + stderrCalls++ + if stderrCalls == 1 { + return &agentpb.ReadStreamResponse{Data: []byte("fatal: missing config\n")}, nil + } + return &agentpb.ReadStreamResponse{}, nil + }, + // The exit watch waits for the first container after both of + // its streams end. + "WaitProcess": func(_ context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.WaitProcessRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + if req.GetContainerId() != "c_first" || req.GetExecId() != "c_first" { + t.Errorf("WaitProcess for container %q exec %q, want c_first for both", req.GetContainerId(), req.GetExecId()) + } + return &agentpb.WaitProcessResponse{Status: 2}, nil + }, + }) + + var buf bytes.Buffer + svc := NewService("pod-1", "cloud-hypervisor", false, 10, nil, actorlog.NewActorLogger(actorlog.NewSyncedWriter(&buf), false), "boot-1", actornet.IPv4) + ctrs := []actorContainer{ + {name: "first", id: "c_first", spec: &specs.Spec{Hostname: "actor"}}, + {name: "second", id: "c_second", spec: &specs.Spec{Hostname: "actor"}}, + } + + if err := svc.startRootfsContainer(t.Context(), ac, attr, vsockPath, ctrs[0]); err != nil { + t.Fatalf("startRootfsContainer(first): %v", err) + } + if err := svc.startRootfsContainer(t.Context(), ac, attr, vsockPath, ctrs[1]); err == nil { + t.Fatal("startRootfsContainer(second) succeeded, want error") + } + // Both streams return empty data after their first chunk, so the + // forwarders reach EOF on their own before the failure path closes ac. + ac.logWG.Wait() + if err := ac.Close(); err != nil { + t.Fatalf("ac.Close: %v", err) + } + + got := buf.String() + for _, want := range []string{ + "first container booting", + "fatal: missing config", + `"ate.actor.container.name":"first"`, + `"ate.actor.uid":"uid-1"`, + } { + if !strings.Contains(got, want) { + t.Errorf("forwarded logs = %s, missing %q", got, want) + } + } + // The exit record of the crashed container comes after its output. + exit := strings.Index(got, actorlog.ContainerExitedMessage) + if exit < strings.Index(got, "first container booting") || exit < strings.Index(got, "fatal: missing config") { + t.Errorf("forwarded logs = %s, want the exit record after the container's output", got) + } + for _, want := range []string{`"ate.actor.exited_container.name":"first"`, `"process.exit.code":2`} { + if !strings.Contains(got, want) { + t.Errorf("forwarded logs = %s, missing %q", got, want) + } + } + }) + + t.Run("live container streams before probe and unblocks on failure close", func(t *testing.T) { + firstLineWritten := make(chan struct{}) + var stdoutCalls int + var mu sync.Mutex + ac, vsockPath := startFakeKataAgent(t, map[string]ttrpc.Method{ + "ReadStdout": func(ctx context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.ReadStreamRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + mu.Lock() + stdoutCalls++ + call := stdoutCalls + mu.Unlock() + if call == 1 { + return &agentpb.ReadStreamResponse{Data: []byte("listening on wrong port\n")}, nil + } + if call == 2 { + close(firstLineWritten) + } + // Simulate a still-running container whose stdout blocks while + // wakeupprobe.WaitAll times out and fails. + <-ctx.Done() + return nil, ctx.Err() + }, + "ReadStderr": func(ctx context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.ReadStreamRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + <-ctx.Done() + return nil, ctx.Err() + }, + }) + + var buf bytes.Buffer + svc := NewService("pod-1", "cloud-hypervisor", false, 10, nil, actorlog.NewActorLogger(actorlog.NewSyncedWriter(&buf), false), "boot-1", actornet.IPv4) + ctr := actorContainer{name: "app", id: "c_app", spec: &specs.Spec{Hostname: "actor"}} + + if err := svc.startRootfsContainer(t.Context(), ac, attr, vsockPath, ctr); err != nil { + t.Fatalf("startRootfsContainer: %v", err) + } + + // Before any wakeup probe completes, the first log line has already been + // read and the forwarder has issued the next ReadStdout call. + <-firstLineWritten + + // Simulate wakeupprobe.WaitAll failing and the defer closing the agent. + if err := ac.Close(); err != nil { + t.Fatalf("ac.Close: %v", err) + } + + if got := buf.String(); !strings.Contains(got, "listening on wrong port") { + t.Errorf("forwarded logs = %s, want startup log before probe failure", got) + } + }) + + t.Run("Close waits for forwarders to finish writing and is idempotent", func(t *testing.T) { + stderrBlocked := make(chan struct{}) + clientClosed := make(chan struct{}) + var stderrOnce, closedOnce sync.Once + var stdoutCalls int + var mu sync.Mutex + ac, vsockPath := startFakeKataAgent(t, map[string]ttrpc.Method{ + "ReadStdout": func(ctx context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.ReadStreamRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + mu.Lock() + stdoutCalls++ + call := stdoutCalls + mu.Unlock() + if call == 1 { + return &agentpb.ReadStreamResponse{Data: []byte("flushed before close returns\n")}, nil + } + <-ctx.Done() + return nil, ctx.Err() + }, + "ReadStderr": func(ctx context.Context, unmarshal func(interface{}) error) (interface{}, error) { + var req agentpb.ReadStreamRequest + if err := unmarshal(&req); err != nil { + return nil, err + } + stderrOnce.Do(func() { close(stderrBlocked) }) + <-ctx.Done() + closedOnce.Do(func() { close(clientClosed) }) + return nil, ctx.Err() + }, + }) + + closeReturned := make(chan struct{}) + closeErr := make(chan error, 1) + w := &blockingLogWriter{ + writeEntered: make(chan struct{}), + unblockWrite: clientClosed, + closeReturned: closeReturned, + } + svc := NewService("pod-1", "cloud-hypervisor", false, 10, nil, actorlog.NewActorLogger(w, false), "boot-1", actornet.IPv4) + ctr := actorContainer{name: "app", id: "c_app", spec: &specs.Spec{Hostname: "actor"}} + + if err := svc.startRootfsContainer(t.Context(), ac, attr, vsockPath, ctr); err != nil { + t.Fatalf("startRootfsContainer: %v", err) + } + + <-w.writeEntered + <-stderrBlocked + + go func() { + closeErr <- ac.Close() + close(closeReturned) + }() + + if err := <-closeErr; err != nil { + t.Fatalf("first ac.Close: %v", err) + } + <-closeReturned + + w.mu.Lock() + closedEarly := w.closedEarly + got := w.buf.String() + w.mu.Unlock() + if closedEarly { + t.Fatal("ac.Close returned before the log forwarder finished writing") + } + if !strings.Contains(got, "flushed before close returns") { + t.Errorf("forwarded logs = %s, want log written before Close returned", got) + } + if err := ac.Close(); err != nil { + t.Fatalf("second ac.Close: %v", err) + } + }) +} diff --git a/cmd/ateworker-microvm/shutdown.go b/cmd/ateworker-microvm/shutdown.go index 074926633c..864874e4ee 100644 --- a/cmd/ateworker-microvm/shutdown.go +++ b/cmd/ateworker-microvm/shutdown.go @@ -31,6 +31,9 @@ import ( "syscall" "time" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/kata" ) @@ -69,10 +72,6 @@ func (s *AteWorkerService) gracefulShutdown(ctx context.Context) { // Set this first so an RPC that arrives while we drain is turned away. s.shuttingDown.Store(true) - // Cancel an in-flight run or restore. Waiting for a cold boot to finish only to - // SIGTERM the guest it just produced is strictly worse than aborting it. - s.cancelStartups(ctx) - // One deadline covers the whole drain. Waiting for the lock and waiting out // SIGTERM below both run against it, so the two phases split a single grace // period rather than each getting one: an RPC that burns most of the budget @@ -80,7 +79,9 @@ func (s *AteWorkerService) gracefulShutdown(ctx context.Context) { // workloadGracePeriod however the time falls between them. deadline := time.Now().Add(workloadGracePeriod) - // Let checkpoints finish saving state before stopping guests. + // Let in-flight boots, restores and checkpoints finish before stopping + // guests. Canceling a boot or restore would crash an actor that has not + // served yet. waitCtx, waitCancel := context.WithDeadline(ctx, deadline) defer waitCancel() if !s.inFlight.WaitIdle(waitCtx) { @@ -136,7 +137,7 @@ func (s *AteWorkerService) gracefulShutdown(ctx context.Context) { // down has no workload left for this path to stop. type drainTarget struct { id string - agent *kata.AgentClient + agent *agentConn workloadIDs []string // hosted is the activation the drain ends, for its final record. hosted *hostedActor @@ -156,11 +157,11 @@ type guestAgent interface { func gracefullyStopActor(ctx context.Context, t drainTarget, deadline time.Time) { id := t.id - // Obtain a kata-agent client to signal the guest: reuse the log-forwarding + // Obtain a kata-agent client to signal the guest: reuse the actor's retained // connection if it's open, else dial a fresh one (best-effort). A dial we open - // here is closed here; the snapshotted client belongs to the log forwarder. + // here is closed here; the snapshotted client belongs to the running actor. agent := t.agent - var dialed *kata.AgentClient + var dialed *agentConn if agent == nil { a, err := dialAgentRetry(ctx, kata.VsockSocketPath(id), 15*time.Second) if err != nil { @@ -200,6 +201,12 @@ func stopGuestWorkload(ctx context.Context, agent guestAgent, id, wid string, de // An actor that installed no handler terminates immediately. slog.InfoContext(ctx, "Sending SIGTERM to guest workload", slog.String("id", id), slog.String("workload", wid)) if err := signalWorkload(ctx, agent, wid, syscall.SIGTERM); err != nil { + // The agent drops a process when a wait collects its exit, which the + // container exit watch does. The workload has stopped. + if status.Code(err) == codes.NotFound { + slog.InfoContext(ctx, "Guest workload exited before the shutdown", slog.String("id", id), slog.String("workload", wid), slog.Any("err", err)) + return nil + } return fmt.Errorf("while propagating SIGTERM to workload %q: %w", wid, err) } @@ -213,6 +220,11 @@ func stopGuestWorkload(ctx context.Context, agent guestAgent, id, wid string, de done := make(chan error, 1) go func() { _, err := agent.WaitProcess(waitCtx, wid, wid) + // The container exit watch collected the exit first. The workload + // has stopped. + if status.Code(err) == codes.NotFound { + err = nil + } done <- err }() diff --git a/cmd/ateworker-microvm/shutdown_test.go b/cmd/ateworker-microvm/shutdown_test.go index 5b9506970a..c5e798b146 100644 --- a/cmd/ateworker-microvm/shutdown_test.go +++ b/cmd/ateworker-microvm/shutdown_test.go @@ -19,12 +19,16 @@ package main import ( "context" "errors" + "fmt" "reflect" "strings" "sync" "syscall" "testing" "time" + + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) // fakeGuestAgent stands in for *kata.AgentClient. It records the signals @@ -121,6 +125,33 @@ func TestStopGuestWorkload(t *testing.T) { wantSignals: []syscall.Signal{syscall.SIGTERM, syscall.SIGKILL}, wantErr: "failed to exit even after SIGKILL", }, + { + // The container exit watch collected the exit, so the agent has + // no record of the process. The error is wrapped as the agent + // client wraps it. + name: "workload that exited before the shutdown is not an error", + signalErr: map[syscall.Signal]error{syscall.SIGTERM: fmt.Errorf("agent SignalProcess: %w", status.Error(codes.NotFound, "InvalidExecId"))}, + deadlineIn: time.Minute, + wantSignals: []syscall.Signal{syscall.SIGTERM}, + }, + { + // The workload exits on SIGTERM, and the container exit watch + // collects the exit before this wait reaches the agent. + name: "exit collected before the wait is not an error", + exitOn: syscall.SIGTERM, + waitErr: fmt.Errorf("agent WaitProcess: %w", status.Error(codes.NotFound, "InvalidExecId")), + deadlineIn: time.Minute, + wantSignals: []syscall.Signal{syscall.SIGTERM}, + }, + { + // The agent gives InvalidArgument for a container id it does not + // know, which is not an exit. + name: "unknown container is an error", + signalErr: map[syscall.Signal]error{syscall.SIGTERM: fmt.Errorf("agent SignalProcess: %w", status.Error(codes.InvalidArgument, "InvalidContainerId"))}, + deadlineIn: time.Minute, + wantSignals: []syscall.Signal{syscall.SIGTERM}, + wantErr: "while propagating SIGTERM to workload", + }, { name: "undeliverable SIGTERM does not escalate", signalErr: map[syscall.Signal]error{syscall.SIGTERM: errors.New("ttrpc closed")}, diff --git a/cmd/ateworker-microvm/snapshotborrow.go b/cmd/ateworker-microvm/snapshotborrow.go index e312a54d92..c0b9dbdb89 100644 --- a/cmd/ateworker-microvm/snapshotborrow.go +++ b/cmd/ateworker-microvm/snapshotborrow.go @@ -71,7 +71,7 @@ func (s *AteWorkerService) archiveDir(ctx context.Context, tarPath, srcDir strin s.borrow.Return(size) return err } - if err := snapshotcache.StartWriteback([]string{tarPath}, func() { s.borrow.Return(size) }); err != nil { + if err := snapshotcache.StartWriteback([]string{tarPath}, nil, func() { s.borrow.Return(size) }); err != nil { s.borrow.Return(size) slog.WarnContext(ctx, "Failed to start archive writeback", slog.String("path", tarPath), slog.Any("err", err)) } diff --git a/cmd/ateworker-microvm/snapshotborrow_test.go b/cmd/ateworker-microvm/snapshotborrow_test.go index 69abd9496a..b73456db32 100644 --- a/cmd/ateworker-microvm/snapshotborrow_test.go +++ b/cmd/ateworker-microvm/snapshotborrow_test.go @@ -17,10 +17,13 @@ package main import ( + "net" + "net/http" "os" "path/filepath" "testing" + "go.ate.dev/substrate/cmd/ateworker-microvm/internal/ch" "go.ate.dev/substrate/internal/ateworker/memborrow" ) @@ -67,3 +70,65 @@ func TestArchiveDirReturnsTheLoanOnError(t *testing.T) { t.Errorf("Take() after a failed archiveDir = %d, want all %d back", got, int64(1<<30)) } } + +func startTestSnapshotCH(t *testing.T, status int) *ch.Client { + t.Helper() + sockPath := filepath.Join(t.TempDir(), "ch.sock") + lis, err := net.Listen("unix", sockPath) + if err != nil { + t.Fatalf("listen unix: %v", err) + } + mux := http.NewServeMux() + mux.HandleFunc("/api/v1/vm.snapshot", func(w http.ResponseWriter, _ *http.Request) { + w.WriteHeader(status) + }) + srv := &http.Server{Handler: mux} + go srv.Serve(lis) + t.Cleanup(func() { _ = srv.Close() }) + return ch.NewClient(sockPath) +} + +func TestWriteSnapshotDefersReleaseUntilCallerInvokesIt(t *testing.T) { + client := startTestSnapshotCH(t, http.StatusNoContent) + s := &AteWorkerService{} + ra := &runningActor{} + const limit = 1 << 30 + ra.memory.Resume(limit) + + _, release, err := s.writeSnapshot(t.Context(), client, ra, "actor-a", t.TempDir()) + if err != nil { + t.Fatalf("writeSnapshot() unexpected error: %v", err) + } + if release == nil { + t.Fatal("writeSnapshot() returned nil release func") + } + // While the paused guest still exists alongside the newly written snapshot + // page cache, writeSnapshot must NOT have resumed the guard (or restored + // memory.high) yet. + if got := ra.memory.Pause(); got != 0 { + t.Fatalf("ra.memory limit before release() = %d, want 0 (still paused)", got) + } + release() + if got := ra.memory.Pause(); got != limit { + t.Errorf("ra.memory limit after release() = %d, want %d", got, uint64(limit)) + } +} + +func TestWriteSnapshotRestoresGuardOnSnapshotError(t *testing.T) { + client := startTestSnapshotCH(t, http.StatusInternalServerError) + s := &AteWorkerService{} + ra := &runningActor{} + const limit = 1 << 30 + ra.memory.Resume(limit) + + _, release, err := s.writeSnapshot(t.Context(), client, ra, "actor-a", t.TempDir()) + if err == nil { + t.Fatal("writeSnapshot() succeeded on 500 response, want error") + } + if release != nil { + t.Errorf("writeSnapshot() returned non-nil release func on error") + } + if got := ra.memory.Pause(); got != limit { + t.Errorf("ra.memory limit after failed writeSnapshot() = %d, want %d", got, uint64(limit)) + } +} diff --git a/cmd/benchmarking/egress/internal/cmd/actor/stats_test.go b/cmd/benchmarking/egress/internal/cmd/actor/stats_test.go index bc725b2523..2b2677f428 100644 --- a/cmd/benchmarking/egress/internal/cmd/actor/stats_test.go +++ b/cmd/benchmarking/egress/internal/cmd/actor/stats_test.go @@ -16,17 +16,14 @@ package actor import ( "encoding/json" - "flag" - "os" - "path/filepath" "reflect" "regexp" "strings" "testing" "time" -) -var updateGolden = flag.Bool("update", false, "rewrite testdata goldens") + "go.ate.dev/substrate/internal/testgolden" +) // numberList matches an indented JSON array of numbers, so a golden can keep // each Point's bounds and counts on one line. @@ -99,25 +96,13 @@ func TestStatsGolden(t *testing.T) { if err != nil { t.Fatal(err) } - path := filepath.Join("testdata", "collect.json") - if *updateGolden { - if err := os.WriteFile(path, got, 0o644); err != nil { - t.Fatal(err) - } - } - want, err := os.ReadFile(path) - if err != nil { - t.Fatal(err) - } - if string(got) != string(want) { - t.Errorf("Stats JSON differs from %s (run with -update to accept):\n%s", path, got) - } + want := testgolden.Check(t, "collect.json", got) var back Stats if err := json.Unmarshal(want, &back); err != nil { - t.Fatalf("decoding %s: %v", path, err) + t.Fatalf("decoding golden: %v", err) } if !reflect.DeepEqual(back, in) { - t.Errorf("%s decodes to\n%+v\nwant\n%+v", path, back, in) + t.Errorf("golden decodes to\n%+v\nwant\n%+v", back, in) } } diff --git a/cmd/benchmarking/isolate/fake-atelet/main.go b/cmd/benchmarking/isolate/fake-atelet/main.go index 58d524057c..ab9118c130 100644 --- a/cmd/benchmarking/isolate/fake-atelet/main.go +++ b/cmd/benchmarking/isolate/fake-atelet/main.go @@ -92,7 +92,7 @@ func main() { if err := serverboot.SetLogLevel(*logLevelFlag); err != nil { serverboot.Fatal(ctx, "Invalid --log-level", err) } - if err := preview.Init(*previewFlags...); err != nil { + if _, err := preview.New(*previewFlags...); err != nil { serverboot.Fatal(ctx, "Invalid --preview", err) } if err := applyTuningEnv(pflag.CommandLine, os.LookupEnv); err != nil { diff --git a/cmd/benchmarking/isolate/fake-workersync/main.go b/cmd/benchmarking/isolate/fake-workersync/main.go index d41479e6af..cdf41200e9 100644 --- a/cmd/benchmarking/isolate/fake-workersync/main.go +++ b/cmd/benchmarking/isolate/fake-workersync/main.go @@ -96,7 +96,7 @@ func main() { if err := serverboot.SetLogLevel(*logLevelFlag); err != nil { serverboot.Fatal(ctx, "Invalid --log-level", err) } - if err := preview.Init(*previewFlags...); err != nil { + if _, err := preview.New(*previewFlags...); err != nil { serverboot.Fatal(ctx, "Invalid --preview", err) } if err := fakeworker.ValidateRun(*run); err != nil { diff --git a/cmd/credential-provider/kubernetes-secrets/kubeprovider.go b/cmd/credential-provider/kubernetes-secrets/kubeprovider.go index 190e383d58..1b6ccc9032 100644 --- a/cmd/credential-provider/kubernetes-secrets/kubeprovider.go +++ b/cmd/credential-provider/kubernetes-secrets/kubeprovider.go @@ -14,8 +14,8 @@ // This file implements the CredentialProvider plugin API backed by Kubernetes // Secrets. It resolves ate-secret:// URIs of the provider "k8s.io" to a Secret -// value read straight from the Kubernetes API — so Substrate never stores the -// secret, it only brokers a read the provider is authorized to perform. +// value read from the Kubernetes API. Substrate never stores the secret at +// rest, and the provider reuses each Secret it reads for --secret-cache-ttl. package main import ( @@ -24,9 +24,12 @@ import ( "log/slog" "net/url" "strings" + "time" + "golang.org/x/sync/singleflight" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/util/cache" "k8s.io/apimachinery/pkg/util/validation" "k8s.io/client-go/kubernetes" @@ -43,6 +46,14 @@ const ProviderName = "k8s.io" // uriScheme is the only scheme a credential URI may carry. const uriScheme = "ate-secret" +// maxURILength matches the API's cap on CredentialHeader.credential_uri. +const maxURILength = 1024 + +// secretFetchTimeout caps one Secret read. The read runs detached from the +// caller's context, so it needs a deadline of its own. It matches +// injectionTimeout in atenet-egress, which caps the whole fetch. +const secretFetchTimeout = 4 * time.Second + // LocalLocator is the reserved leading path segment naming the local Kubernetes // API server the provider runs in — the only cluster served today. const LocalLocator = "default" @@ -66,6 +77,9 @@ type SecretRef struct { // ParseURI parses an ate-secret:// URI of the k8s.io provider. It // rejects any other scheme or provider name. func ParseURI(raw string) (SecretRef, error) { + if len(raw) > maxURILength { + return SecretRef{}, fmt.Errorf("credential URI is %d characters, more than %d", len(raw), maxURILength) + } u, err := url.Parse(raw) if err != nil { return SecretRef{}, fmt.Errorf("parsing credential URI %q: %w", raw, err) @@ -76,11 +90,14 @@ func ParseURI(raw string) (SecretRef, error) { if u.Host != ProviderName { return SecretRef{}, fmt.Errorf("credential URI %q: provider is %q, this provider serves %q", raw, u.Host, ProviderName) } + if u.User != nil { + return SecretRef{}, fmt.Errorf("credential URI %q: userinfo is not allowed", raw) + } // The grammar is scheme/host/path only; a query or fragment means the caller // assumed a syntax this provider does not honor, so reject it rather than // silently ignore it. - if u.User != nil || u.RawQuery != "" || u.ForceQuery || strings.Contains(raw, "#") { - return SecretRef{}, fmt.Errorf("credential URI %q: user info, query, and fragment components are not allowed", raw) + if u.RawQuery != "" || u.ForceQuery || u.Fragment != "" { + return SecretRef{}, fmt.Errorf("credential URI %q: query and fragment components are not allowed", raw) } // Reject percent-encoding in the path of secret uri. if u.EscapedPath() != u.Path { @@ -89,8 +106,11 @@ func ParseURI(raw string) (SecretRef, error) { segments := strings.Split(strings.TrimPrefix(u.Path, "/"), "/") for i, s := range segments { - if s == "" { + switch s { + case "": return SecretRef{}, fmt.Errorf("credential URI %q: empty path segment %d", raw, i) + case ".", "..": + return SecretRef{}, fmt.Errorf("credential URI %q: dot segment %d is not allowed", raw, i) } } @@ -120,16 +140,37 @@ type Server struct { client kubernetes.Interface // nsAuth restricts which namespaces an atespace may resolve secrets from. nsAuth *NamespaceAuthorizer + + // ttl is how long a Secret read is reused. 0 disables caching. + ttl time.Duration + // secrets maps "namespace/name" to a cachedSecret until ttl passes. + secrets *cache.Expiring + // flight collapses concurrent reads of one Secret into a single Get. + flight singleflight.Group +} + +// cachedSecret is the part of a Secret that FetchSecret uses. +type cachedSecret struct { + labels map[string]string + data map[string][]byte } // NewServer builds a Kubernetes credential provider with a default-deny policy. -func NewServer(client kubernetes.Interface, nsAuth *NamespaceAuthorizer) *Server { - return &Server{client: client, nsAuth: nsAuth} +// Each Secret read is reused for ttl; 0 reads on every call. +func NewServer(client kubernetes.Interface, nsAuth *NamespaceAuthorizer, ttl time.Duration) *Server { + return &Server{client: client, nsAuth: nsAuth, ttl: ttl, secrets: cache.NewExpiring()} } // Grants exposes the enforced atespace→namespace policy for /statusz. func (s *Server) Grants() map[string][]string { return s.nsAuth.Grants() } +// GrantDetails exposes each grant and its secretSelector labels for /statusz. +func (s *Server) GrantDetails() map[string][]NamespaceGrant { return s.nsAuth.GrantDetails() } + +// PolicyError reports why the policy file failed to load while an older +// policy stays in force, for /statusz. +func (s *Server) PolicyError() error { return s.nsAuth.LoadError() } + // FetchSecret resolves one ate-secret:// URI to its Secret value. func (s *Server) FetchSecret(ctx context.Context, req *credprovider.FetchSecretRequest) (*credprovider.FetchSecretResponse, error) { ref, err := ParseURI(req.GetUri()) @@ -149,7 +190,7 @@ func (s *Server) FetchSecret(ctx context.Context, req *credprovider.FetchSecretR slog.String("actor", req.GetActorSpiffeId()), ) - secret, err := s.client.CoreV1().Secrets(ref.Namespace).Get(ctx, ref.Name, metav1.GetOptions{}) + secret, err := s.getSecret(ctx, ref.Namespace, ref.Name) if err != nil { if k8serrors.IsNotFound(err) { // Authorization is enforced, so a missing Secret must look the @@ -166,7 +207,7 @@ func (s *Server) FetchSecret(ctx context.Context, req *credprovider.FetchSecretR // Step 3: the Secret is in hand, so a grant narrowed by label can finally // be settled. This refusal and the NotFound above give the same code and // message, so a caller learns nothing from the difference. - if !s.nsAuth.AllowedSecret(atespace, ref.Namespace, secret.GetLabels()) { + if !s.nsAuth.AllowedSecret(atespace, ref.Namespace, secret.labels) { slog.WarnContext(ctx, "credential request denied: secret does not match the grant", slog.String("atespace", atespace), slog.String("namespace", ref.Namespace), @@ -175,13 +216,58 @@ func (s *Server) FetchSecret(ctx context.Context, req *credprovider.FetchSecretR return nil, status.Errorf(codes.PermissionDenied, "atespace %q is not permitted to resolve secret %s/%s", atespace, ref.Namespace, ref.Name) } - value, err := selectKey(secret.Data, ref.Key) + value, err := selectKey(secret.data, ref.Key) if err != nil { return nil, status.Errorf(codes.NotFound, "secret %s/%s: %v", ref.Namespace, ref.Name, err) } return &credprovider.FetchSecretResponse{OpaqueBytes: value}, nil } +// getSecret returns the Secret namespace/name, reading it from Kubernetes when +// there is no live cache entry. +func (s *Server) getSecret(ctx context.Context, namespace, name string) (cachedSecret, error) { + key := namespace + "/" + name + if secret, ok := s.cached(key); ok { + return secret, nil + } + + // The read outlives the caller: the leader of a flight going away must + // not fail the callers that joined it. + ch := s.flight.DoChan(key, func() (any, error) { + // A flight that finished between the miss above and DoChan has + // already stored a fresh entry. + if secret, ok := s.cached(key); ok { + return secret, nil + } + getCtx, cancel := context.WithTimeout(context.WithoutCancel(ctx), secretFetchTimeout) + defer cancel() + secret, err := s.client.CoreV1().Secrets(namespace).Get(getCtx, name, metav1.GetOptions{}) + if err != nil { + return nil, err + } + entry := cachedSecret{labels: secret.GetLabels(), data: secret.Data} + if s.ttl > 0 { + s.secrets.Set(key, entry, s.ttl) + } + return entry, nil + }) + select { + case <-ctx.Done(): + return cachedSecret{}, ctx.Err() + case res := <-ch: + if res.Err != nil { + return cachedSecret{}, res.Err + } + return res.Val.(cachedSecret), nil + } +} + +func (s *Server) cached(key string) (cachedSecret, bool) { + v, ok := s.secrets.Get(key) + secret, _ := v.(cachedSecret) + return secret, ok +} + // authorize checks the actor identity and its namespace grant before reading // from Kubernetes. FetchSecret then checks the Secret against any label selector. func (s *Server) authorize(ctx context.Context, actorSpiffeID, namespace string) (string, error) { diff --git a/cmd/credential-provider/kubernetes-secrets/kubeprovider_test.go b/cmd/credential-provider/kubernetes-secrets/kubeprovider_test.go index 24800d752a..5cb86b6533 100644 --- a/cmd/credential-provider/kubernetes-secrets/kubeprovider_test.go +++ b/cmd/credential-provider/kubernetes-secrets/kubeprovider_test.go @@ -17,17 +17,24 @@ package main import ( "context" "errors" + "fmt" "os" "path/filepath" "strings" + "sync" + "sync/atomic" "testing" + "testing/synctest" + "time" corev1 "k8s.io/api/core/v1" k8serrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" "k8s.io/apimachinery/pkg/runtime" "k8s.io/apimachinery/pkg/runtime/schema" + "k8s.io/client-go/kubernetes" "k8s.io/client-go/kubernetes/fake" + typedcorev1 "k8s.io/client-go/kubernetes/typed/core/v1" k8stesting "k8s.io/client-go/testing" "sigs.k8s.io/yaml" @@ -49,6 +56,24 @@ func TestParseURI(t *testing.T) { uri: "ate-secret://k8s.io/default/ns1/example-api/token", want: SecretRef{Namespace: "ns1", Name: "example-api", Key: "token"}, }, + { + // Stored policies may still use these, so they keep resolving. + name: "uppercase scheme", + uri: "ATE-SECRET://k8s.io/default/ns1/example-api/token", + want: SecretRef{Namespace: "ns1", Name: "example-api", Key: "token"}, + }, + { + name: "empty fragment", + uri: "ate-secret://k8s.io/default/ns1/example-api/token#", + want: SecretRef{Namespace: "ns1", Name: "example-api", Key: "token"}, + }, + {name: "empty query", uri: "ate-secret://k8s.io/default/ns1/example-api/token?", wantErr: true}, + {name: "dot segment", uri: "ate-secret://k8s.io/default/../example-api/token", wantErr: true}, + {name: "dot key", uri: "ate-secret://k8s.io/default/ns1/example-api/.", wantErr: true}, + {name: "trailing slash", uri: "ate-secret://k8s.io/default/ns1/example-api/token/", wantErr: true}, + {name: "extra leading slash", uri: "ate-secret://k8s.io//default/ns1/example-api/token", wantErr: true}, + {name: "userinfo", uri: "ate-secret://user@k8s.io/default/ns1/example-api/token", wantErr: true}, + {name: "too long", uri: "ate-secret://k8s.io/default/ns1/example-api/" + strings.Repeat("k", 1000), wantErr: true}, {name: "key required", uri: "ate-secret://k8s.io/default/ns1/example-api", wantErr: true}, {name: "wrong scheme", uri: "https://k8s.io/default/ns1/example-api/token", wantErr: true}, {name: "wrong provider", uri: "ate-secret://vault.io/default/ns1/example-api/token", wantErr: true}, @@ -61,14 +86,8 @@ func TestParseURI(t *testing.T) { {name: "percent-encoded separator", uri: "ate-secret://k8s.io/default/ns1/example-api/tok%2Fen", wantErr: true}, {name: "percent-encoding of any kind", uri: "ate-secret://k8s.io/default/ns1/example-api/tok%2Den", wantErr: true}, {name: "space in path", uri: "ate-secret://k8s.io/default/ns1/example-api/tok en", wantErr: true}, - - {name: "user info", uri: "ate-secret://user@k8s.io/default/ns1/api/token", wantErr: true}, - {name: "empty query", uri: "ate-secret://k8s.io/default/ns1/api/token?", wantErr: true}, - {name: "empty fragment", uri: "ate-secret://k8s.io/default/ns1/api/token#", wantErr: true}, - {name: "trailing slash", uri: "ate-secret://k8s.io/default/ns1/api/token/", wantErr: true}, {name: "empty namespace", uri: "ate-secret://k8s.io/default//api/token", wantErr: true}, {name: "invalid namespace", uri: "ate-secret://k8s.io/default/NS/api/token", wantErr: true}, - {name: "path traversal", uri: "ate-secret://k8s.io/default/ns1/../token", wantErr: true}, {name: "unparseable", uri: "://://", wantErr: true}, } for _, tc := range tests { @@ -187,7 +206,7 @@ func TestFetchSecretAuthorization(t *testing.T) { for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { client := fake.NewSimpleClientset(secret) - srv := NewServer(client, authz) + srv := NewServer(client, authz, 0) resp, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{Uri: tc.uri, ActorSpiffeId: tc.actorSpiffeID}) if tc.wantCode != codes.OK { if len(client.Actions()) != 0 { @@ -209,7 +228,7 @@ func TestFetchSecretAuthorization(t *testing.T) { // A missing authorizer must fail closed. t.Run("nil authorizer denies", func(t *testing.T) { - srv := NewServer(fake.NewSimpleClientset(secret), nil) + srv := NewServer(fake.NewSimpleClientset(secret), nil, 0) if _, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{ Uri: "ate-secret://k8s.io/default/ns1/example-api/token", ActorSpiffeId: teamAURI, @@ -265,16 +284,21 @@ func TestFetchSecret(t *testing.T) { uri: "ate-secret://k8s.io/default/ns1/absent/token", wantCode: codes.PermissionDenied, }, + { + name: "remote form rejected", + uri: "ate-secret://k8s.io/cluster/remote-east/ns1/example-api/token", + wantCode: codes.InvalidArgument, + }, { name: "bad uri", - uri: "ate-secret://vault.io/ns1/example-api", + uri: "ate-secret://vault.io/default/ns1/example-api", wantCode: codes.InvalidArgument, }, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { client := fake.NewSimpleClientset(secret, multiKey) - srv := NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}}) + srv := NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}}, 0) resp, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{Uri: tc.uri, ActorSpiffeId: "spiffe://substrate-actor.local/actor/team-a/my-actor"}) if tc.wantCode != codes.OK { if status.Code(err) != tc.wantCode { @@ -336,7 +360,7 @@ func TestFetchSecretKubernetesErrors(t *testing.T) { t.Run(tc.name, func(t *testing.T) { client := fake.NewSimpleClientset() client.PrependReactor("get", "secrets", func(k8stesting.Action) (bool, runtime.Object, error) { return true, nil, tc.err }) - srv := NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}}) + srv := NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}}, 0) _, err := srv.FetchSecret(t.Context(), &credprovider.FetchSecretRequest{ Uri: "ate-secret://k8s.io/default/ns1/api/token", ActorSpiffeId: "spiffe://substrate-actor.local/actor/team-a/a", }) @@ -353,7 +377,7 @@ func TestFetchSecretKubernetesErrors(t *testing.T) { func TestFetchSecretObservesRotation(t *testing.T) { secret := &corev1.Secret{ObjectMeta: metav1.ObjectMeta{Name: "api", Namespace: "ns1"}, Data: map[string][]byte{"token": []byte("first")}} client := fake.NewSimpleClientset(secret) - srv := NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}}) + srv := NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}}, 0) req := &credprovider.FetchSecretRequest{Uri: "ate-secret://k8s.io/default/ns1/api/token", ActorSpiffeId: "spiffe://substrate-actor.local/actor/team-a/a"} first, err := srv.FetchSecret(t.Context(), req) if err != nil || string(first.GetOpaqueBytes()) != "first" { @@ -369,6 +393,182 @@ func TestFetchSecretObservesRotation(t *testing.T) { } } +// Fetches of one Secret within the TTL share a single read, whichever key they +// ask for. Authorization still runs on a cached Secret, a failed read is not +// cached, and an expired entry is read again. +func TestFetchSecretCache(t *testing.T) { + // team-a may read any Secret in ns1; team-b only labeled ones. + authz, err := newNamespaceAuthorizer(namespacePolicyFile{Policies: []atespaceNamespacePolicy{ + {Atespace: "team-a", AllowedNamespaces: []string{"ns1"}}, + { + Atespace: "team-b", AllowedNamespaces: []string{"ns1"}, + SecretSelector: &secretSelector{MatchLabels: map[string]string{"example.com/credential": "true"}}, + }, + }}) + if err != nil { + t.Fatalf("newNamespaceAuthorizer: %v", err) + } + const teamA = "spiffe://substrate-actor.local/actor/team-a/my-actor" + const teamB = "spiffe://substrate-actor.local/actor/team-b/my-actor" + + type fetch struct { + // wait is how long to sleep before this fetch, on synctest's clock. + wait time.Duration + actor string + key string + wantCode codes.Code + } + tests := []struct { + name string + ttl time.Duration + // createAfter is how many fetches run before the Secret exists. + createAfter int + fetches []fetch + wantGets int + }{ + { + name: "keys share a read", + ttl: time.Hour, + fetches: []fetch{{actor: teamA, key: "token"}, {actor: teamA, key: "user"}}, + wantGets: 1, + }, + { + name: "zero ttl reads every time", + fetches: []fetch{{actor: teamA, key: "token"}, {actor: teamA, key: "user"}}, + wantGets: 2, + }, + { + name: "cached secret still checked against labels", + ttl: time.Hour, + fetches: []fetch{{actor: teamA, key: "token"}, {actor: teamB, key: "token", wantCode: codes.PermissionDenied}}, + wantGets: 1, + }, + { + name: "missing secret not cached", + ttl: time.Hour, + createAfter: 1, + fetches: []fetch{{actor: teamA, key: "token", wantCode: codes.PermissionDenied}, {actor: teamA, key: "token"}}, + wantGets: 2, + }, + { + name: "expired entry read again", + ttl: 10 * time.Second, + fetches: []fetch{{actor: teamA, key: "token"}, {wait: 10 * time.Second, actor: teamA, key: "token"}}, + wantGets: 2, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + client := fake.NewSimpleClientset() + srv := NewServer(client, authz, tc.ttl) + for i, f := range tc.fetches { + if i == tc.createAfter { + if err := client.Tracker().Add(&corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "example-api", Namespace: "ns1"}, + Data: map[string][]byte{"token": []byte("s3cr3t"), "user": []byte("bob")}, + }); err != nil { + t.Fatalf("adding Secret: %v", err) + } + } + time.Sleep(f.wait) + _, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{ + Uri: "ate-secret://k8s.io/default/ns1/example-api/" + f.key, + ActorSpiffeId: f.actor, + }) + if status.Code(err) != f.wantCode { + t.Fatalf("fetch %d: code = %v, want %v (err=%v)", i, status.Code(err), f.wantCode, err) + } + } + gets := 0 + for _, a := range client.Actions() { + if a.Matches("get", "secrets") { + gets++ + } + } + if gets != tc.wantGets { + t.Errorf("Secret Gets = %d, want %d", gets, tc.wantGets) + } + }) + }) + } +} + +// gatedSecrets counts Secret Gets and holds each one until gate closes. The +// fake clientset runs reactors under a mutex, so a blocking reactor would +// serialize the callers instead. +type gatedSecrets struct { + kubernetes.Interface + gate chan struct{} + gets atomic.Int32 +} + +func (g *gatedSecrets) CoreV1() typedcorev1.CoreV1Interface { + return gatedCoreV1{g.Interface.CoreV1(), g} +} + +type gatedCoreV1 struct { + typedcorev1.CoreV1Interface + g *gatedSecrets +} + +func (c gatedCoreV1) Secrets(namespace string) typedcorev1.SecretInterface { + return gatedSecretClient{c.CoreV1Interface.Secrets(namespace), c.g} +} + +type gatedSecretClient struct { + typedcorev1.SecretInterface + g *gatedSecrets +} + +func (s gatedSecretClient) Get(ctx context.Context, name string, opts metav1.GetOptions) (*corev1.Secret, error) { + s.g.gets.Add(1) + <-s.g.gate + return s.SecretInterface.Get(ctx, name, opts) +} + +// Concurrent fetches of one Secret share a single read, even with the cache +// disabled. +func TestFetchSecretCollapsesConcurrentReads(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + client := &gatedSecrets{ + Interface: fake.NewSimpleClientset(&corev1.Secret{ + ObjectMeta: metav1.ObjectMeta{Name: "example-api", Namespace: "ns1"}, + Data: map[string][]byte{"token": []byte("s3cr3t")}, + }), + gate: make(chan struct{}), + } + srv := NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}}, 0) + + const callers = 8 + var wg sync.WaitGroup + errs := make(chan error, callers) + for range callers { + wg.Go(func() { + _, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{ + Uri: "ate-secret://k8s.io/default/ns1/example-api/token", + ActorSpiffeId: "spiffe://substrate-actor.local/actor/team-a/my-actor", + }) + errs <- err + }) + } + // Every caller is now parked on the read or on the flight, so none + // can arrive after the read completes and start its own. + synctest.Wait() + close(client.gate) + wg.Wait() + close(errs) + for err := range errs { + if err != nil { + t.Errorf("FetchSecret: %v", err) + } + } + if gets := client.gets.Load(); gets != 1 { + t.Errorf("Secret Gets = %d, want 1 for %d concurrent callers", gets, callers) + } + }) +} + // A grant narrowed by label admits only Secrets carrying those labels. A grant // with no selector keeps admitting every Secret in the namespace, which is // what every policy written before the field existed already means. @@ -417,7 +617,7 @@ func TestFetchSecretSecretNarrowing(t *testing.T) { if err != nil { t.Fatalf("newNamespaceAuthorizer: %v", err) } - srv := NewServer(fake.NewSimpleClientset(model, caPool), authz) + srv := NewServer(fake.NewSimpleClientset(model, caPool), authz, 0) resp, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{ Uri: "ate-secret://k8s.io/default/ns1/" + tc.secret + "/token", ActorSpiffeId: actorURI, @@ -570,6 +770,105 @@ func TestLoadNamespaceAuthorizerRejectsUnknownFields(t *testing.T) { } } +// The provider rereads its policy when the file changes, and keeps the last +// good policy while the file fails to load. +func TestLoadNamespaceAuthorizerReloads(t *testing.T) { + dir := t.TempDir() + path := filepath.Join(dir, "policy.yaml") + dataLink := filepath.Join(dir, "..data") + // path resolves through the ..data symlink, and each step swaps that + // symlink to a new directory, the way the kubelet updates a ConfigMap + // volume. + if err := os.Symlink(filepath.Join("..data", "policy.yaml"), path); err != nil { + t.Fatalf("link policy: %v", err) + } + version := 0 + replace := func(t *testing.T, content string) { + t.Helper() + version++ + target := fmt.Sprintf("..v%d", version) + if err := os.Mkdir(filepath.Join(dir, target), 0o700); err != nil { + t.Fatalf("create policy dir: %v", err) + } + if err := os.WriteFile(filepath.Join(dir, target, "policy.yaml"), []byte(content), 0o600); err != nil { + t.Fatalf("write policy: %v", err) + } + tmp := filepath.Join(dir, "..data_tmp") + if err := os.Symlink(target, tmp); err != nil { + t.Fatalf("link policy dir: %v", err) + } + if err := os.Rename(tmp, dataLink); err != nil { + t.Fatalf("swap policy dir: %v", err) + } + } + replace(t, "policies:\n- atespace: team-a\n allowedNamespaces: [ns1]\n") + authz, err := LoadNamespaceAuthorizer(path) + if err != nil { + t.Fatalf("LoadNamespaceAuthorizer: %v", err) + } + + steps := []struct { + name string + // content replaces the file; empty removes it. + content string + wantAllowed []string + wantRefused []string + wantErr bool + }{ + { + name: "grant moves to another namespace", + content: "policies:\n- atespace: team-a\n allowedNamespaces: [ns2]\n", + wantAllowed: []string{"ns2"}, + wantRefused: []string{"ns1"}, + }, + { + name: "malformed file keeps the previous policy", + content: "policies:\n- atespace: team-a\n allowedNamespace: [ns3]\n", + wantAllowed: []string{"ns2"}, + wantRefused: []string{"ns3"}, + wantErr: true, + }, + { + name: "fixed file loads", + content: "policies:\n- atespace: team-a\n allowedNamespaces: [ns3]\n", + wantAllowed: []string{"ns3"}, + wantRefused: []string{"ns2"}, + }, + { + name: "missing file keeps the previous policy", + wantAllowed: []string{"ns3"}, + wantErr: true, + }, + { + name: "file comes back", + content: "policies: []\n", + wantRefused: []string{"ns3"}, + }, + } + for _, step := range steps { + if step.content == "" { + if err := os.Remove(dataLink); err != nil { + t.Fatalf("%s: remove policy: %v", step.name, err) + } + } else { + replace(t, step.content) + } + for _, ns := range step.wantAllowed { + if !authz.Allowed("team-a", ns) || !authz.AllowedSecret("team-a", ns, nil) { + t.Errorf("%s: team-a/%s refused, want allowed", step.name, ns) + } + } + for _, ns := range step.wantRefused { + if authz.Allowed("team-a", ns) || authz.AllowedSecret("team-a", ns, nil) { + t.Errorf("%s: team-a/%s allowed, want refused", step.name, ns) + } + } + if err := authz.LoadError(); (err != nil) != step.wantErr { + t.Errorf("%s: LoadError() = %v, want error %v", step.name, err, step.wantErr) + } + } +} + // Each policy is its own grant and they are OR-ed. Merging them into one would // let a narrow policy take away what a broad one granted, and would AND the // selectors of separate policies together. @@ -640,7 +939,7 @@ func TestFetchSecretLabelGrantHidesExistence(t *testing.T) { srv := NewServer(fake.NewSimpleClientset(&corev1.Secret{ ObjectMeta: metav1.ObjectMeta{Name: "actor-id-ca-pool", Namespace: "ns1"}, Data: map[string][]byte{"token": []byte("private")}, - }), authz) + }), authz, 0) ask := func(name string) (codes.Code, string) { _, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{ @@ -674,7 +973,7 @@ func TestFetchSecretMissingSecretIsPermissionDeniedWhenEnforced(t *testing.T) { if err != nil { t.Fatalf("newNamespaceAuthorizer: %v", err) } - srv := NewServer(fake.NewSimpleClientset(), authz) + srv := NewServer(fake.NewSimpleClientset(), authz, 0) if _, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{ Uri: "ate-secret://k8s.io/default/ns1/no-such-secret/token", ActorSpiffeId: "spiffe://substrate-actor.local/actor/team-a/my-actor", diff --git a/cmd/credential-provider/kubernetes-secrets/main.go b/cmd/credential-provider/kubernetes-secrets/main.go index 2e8209f2aa..f9111a5fe8 100644 --- a/cmd/credential-provider/kubernetes-secrets/main.go +++ b/cmd/credential-provider/kubernetes-secrets/main.go @@ -67,6 +67,7 @@ var ( drainGrace = pflag.Duration("drain-grace", 5*time.Second, "how long to wait for in-flight RPCs on shutdown before a hard stop") kubeAPIQPS = pflag.Float32("kube-api-qps", 50, "Sustained queries per second allowed against the Kubernetes API.") kubeAPIBurst = pflag.Int("kube-api-burst", 100, "Burst queries allowed against the Kubernetes API.") + secretCacheTTL = pflag.Duration("secret-cache-ttl", 10*time.Second, "How long a Secret read from Kubernetes is reused before reading it again, which bounds how long a rotated or relabeled Secret keeps serving its old value. 0 disables the cache (concurrent fetches of one Secret still share a read)") previewFlags = pflag.StringSlice("preview", nil, "Preview gates to enable.") ) @@ -78,7 +79,7 @@ func main() { if err := serverboot.SetLogLevel(*logLevel); err != nil { serverboot.Fatal(ctx, "invalid --log-level", err) } - if err := preview.Init(*previewFlags...); err != nil { + if _, err := preview.New(*previewFlags...); err != nil { serverboot.Fatal(ctx, "invalid --preview", err) } @@ -98,6 +99,10 @@ func run(ctx context.Context) error { go serverboot.StartMetricsServer(ctx, *metricsAddr) + if *secretCacheTTL < 0 { + return fmt.Errorf("--secret-cache-ttl must not be negative, got %s (0 disables the cache)", *secretCacheTTL) + } + client, err := newKubeClient() if err != nil { return fmt.Errorf("kubernetes client: %w", err) @@ -112,7 +117,6 @@ func run(ctx context.Context) error { if err != nil { return fmt.Errorf("namespace policy: %w", err) } - slog.InfoContext(ctx, "loaded namespace authorization policy", slog.String("file", *nsPolicyFile)) creds, err := buildServerCreds(ctx) if err != nil { @@ -124,7 +128,7 @@ func run(ctx context.Context) error { grpc.Creds(creds), ) reflection.Register(srv) - provider := NewServer(client, nsAuth) + provider := NewServer(client, nsAuth, *secretCacheTTL) credprovider.RegisterCredentialProviderServer(srv, provider) lis, err := (&net.ListenConfig{}).Listen(ctx, "tcp", *listenAddr) diff --git a/cmd/credential-provider/kubernetes-secrets/main_test.go b/cmd/credential-provider/kubernetes-secrets/main_test.go index e6c9af74e6..39426f7435 100644 --- a/cmd/credential-provider/kubernetes-secrets/main_test.go +++ b/cmd/credential-provider/kubernetes-secrets/main_test.go @@ -337,7 +337,7 @@ func TestProviderMTLS(t *testing.T) { ObjectMeta: metav1.ObjectMeta{Name: "api", Namespace: "ns1"}, Data: map[string][]byte{"token": []byte("credential")}, }) srv := grpc.NewServer(grpc.Creds(creds)) - credprovider.RegisterCredentialProviderServer(srv, NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}})) + credprovider.RegisterCredentialProviderServer(srv, NewServer(client, &NamespaceAuthorizer{allowed: map[string]map[string][]grant{"team-a": {"ns1": {{}}}}}, 0)) lis, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) diff --git a/cmd/credential-provider/kubernetes-secrets/nsauthz.go b/cmd/credential-provider/kubernetes-secrets/nsauthz.go index 9bf7f56188..885a4734bd 100644 --- a/cmd/credential-provider/kubernetes-secrets/nsauthz.go +++ b/cmd/credential-provider/kubernetes-secrets/nsauthz.go @@ -16,11 +16,15 @@ package main import ( "fmt" + "log/slog" + "maps" "os" + "slices" "sort" + "sync" "go.ate.dev/substrate/internal/resources" - "k8s.io/apimachinery/pkg/util/validation" + "k8s.io/apimachinery/pkg/api/validate/content" "sigs.k8s.io/yaml" ) @@ -70,8 +74,20 @@ type grant struct { // NamespaceAuthorizer decides whether an atespace may resolve secrets in a given // Kubernetes namespace. It is default-deny: an atespace absent from the mapping -// can resolve nothing. +// can resolve nothing. One loaded from a file rereads the file when it changes. type NamespaceAuthorizer struct { + // path is the policy file; empty when the authorizer was built from an + // already parsed policy and never reloads. + path string + + mu sync.Mutex + // fi is the stat of path taken before its last parse, successful or not, + // so a file that fails to parse is read and logged once rather than per + // request. Nil when path could not be stat'ed, so the next call retries. + fi os.FileInfo + // loadErr is why the file as it is now failed to load; allowed then holds + // the last policy that loaded. + loadErr error // allowed maps atespace -> namespace -> the grants that apply there. Each // policy contributes its own grant and they are OR-ed: a Secret is admitted // when any one of them admits it. Within a grant the criteria are AND-ed, @@ -80,8 +96,19 @@ type NamespaceAuthorizer struct { } // LoadNamespaceAuthorizer reads the YAML policy file at path and builds an -// authorizer, so a malformed file fails startup rather than the first request. +// authorizer that rereads the file whenever it changes. A malformed file fails +// here, at startup; once running, a file that fails to load leaves the last +// good policy in force. func LoadNamespaceAuthorizer(path string) (*NamespaceAuthorizer, error) { + a := &NamespaceAuthorizer{path: path} + if _, err := a.policy(); err != nil { + return nil, err + } + return a, nil +} + +// readNamespacePolicy parses the YAML policy file at path. +func readNamespacePolicy(path string) (*NamespaceAuthorizer, error) { data, err := os.ReadFile(path) if err != nil { return nil, fmt.Errorf("reading namespace policy file %q: %w", path, err) @@ -106,10 +133,10 @@ func newNamespaceAuthorizer(file namespacePolicyFile) (*NamespaceAuthorizer, err // nothing and look like the policy was simply ignored. Fail loading // instead. for k, v := range p.SecretSelector.labels() { - if len(validation.IsQualifiedName(k)) != 0 { + if len(content.IsLabelKey(k)) != 0 { return nil, fmt.Errorf("namespace policy %d: invalid label key %q", i, k) } - if len(validation.IsValidLabelValue(v)) != 0 { + if len(content.IsLabelValue(v)) != 0 { return nil, fmt.Errorf("namespace policy %d: invalid label value %q for key %q", i, v, k) } } @@ -126,7 +153,7 @@ func newNamespaceAuthorizer(file namespacePolicyFile) (*NamespaceAuthorizer, err g.labels[k] = v } for _, ns := range p.AllowedNamespaces { - if len(validation.IsDNS1123Label(ns)) != 0 { + if len(content.IsDNS1123Label(ns)) != 0 { return nil, fmt.Errorf("namespace policy %d: invalid namespace %q", i, ns) } set[ns] = append(set[ns], g) @@ -135,13 +162,63 @@ func newNamespaceAuthorizer(file namespacePolicyFile) (*NamespaceAuthorizer, err return &NamespaceAuthorizer{allowed: allowed}, nil } +// policy returns the grants in force, first rereading the policy file if its +// stat no longer matches the last one parsed. The kubelet updates a ConfigMap +// volume by swapping in a new file, so the stat changes even when the size +// does not. The error is why the file as it is now failed to load. +func (a *NamespaceAuthorizer) policy() (map[string]map[string][]grant, error) { + a.mu.Lock() + defer a.mu.Unlock() + if a.path == "" { + return a.allowed, nil + } + fi, err := os.Stat(a.path) + if err != nil { + a.fi = nil + return a.allowed, a.loadFailed(fmt.Errorf("reading namespace policy file %q: %w", a.path, err)) + } + if a.fi != nil && os.SameFile(a.fi, fi) && fi.ModTime().Equal(a.fi.ModTime()) && fi.Size() == a.fi.Size() { + return a.allowed, a.loadErr + } + a.fi = fi + next, err := readNamespacePolicy(a.path) + if err != nil { + return a.allowed, a.loadFailed(err) + } + a.allowed, a.loadErr = next.allowed, nil + slog.Info("loaded namespace authorization policy", slog.String("file", a.path)) + return a.allowed, nil +} + +// loadFailed records err as the load error and returns it. It logs err unless +// it repeats the last one or no policy has loaded yet, when +// LoadNamespaceAuthorizer returns it instead. The caller holds a.mu. +func (a *NamespaceAuthorizer) loadFailed(err error) error { + if a.allowed != nil && (a.loadErr == nil || a.loadErr.Error() != err.Error()) { + slog.Error("namespace policy file failed to load, keeping the last policy that loaded", slog.String("file", a.path), slog.Any("err", err)) + } + a.loadErr = err + return err +} + +// LoadError reports why the policy file failed to load, or nil when the +// policy in force is the file's current content. +func (a *NamespaceAuthorizer) LoadError() error { + if a == nil { + return nil + } + _, err := a.policy() + return err +} + // Grants returns the loaded policy as atespace → sorted namespaces func (a *NamespaceAuthorizer) Grants() map[string][]string { if a == nil { return nil } - out := make(map[string][]string, len(a.allowed)) - for atespace, namespaces := range a.allowed { + allowed, _ := a.policy() + out := make(map[string][]string, len(allowed)) + for atespace, namespaces := range allowed { list := make([]string, 0, len(namespaces)) for ns := range namespaces { list = append(list, ns) @@ -152,6 +229,38 @@ func (a *NamespaceAuthorizer) Grants() map[string][]string { return out } +// NamespaceGrant describes one grant allowing an atespace to resolve Secrets +// in Namespace. MatchLabels is nil when the grant admits every Secret there. +type NamespaceGrant struct { + Namespace string `json:"namespace"` + MatchLabels map[string]string `json:"match_labels,omitempty"` +} + +// GrantDetails returns the policy in force per atespace, sorted by namespace and +// preserving each grant's secretSelector labels. +func (a *NamespaceAuthorizer) GrantDetails() map[string][]NamespaceGrant { + if a == nil { + return nil + } + allowed, _ := a.policy() + out := make(map[string][]NamespaceGrant, len(allowed)) + for atespace, namespaces := range allowed { + names := slices.Sorted(maps.Keys(namespaces)) + list := make([]NamespaceGrant, 0, len(names)) + for _, ns := range names { + for _, g := range namespaces[ns] { + var labels map[string]string + if len(g.labels) > 0 { + labels = maps.Clone(g.labels) + } + list = append(list, NamespaceGrant{Namespace: ns, MatchLabels: labels}) + } + } + out[atespace] = list + } + return out +} + // Allowed reports whether atespace may resolve secrets in namespace. Default // deny: an atespace absent from the mapping, or a namespace not in its list, is // refused. @@ -159,7 +268,8 @@ func (a *NamespaceAuthorizer) Allowed(atespace, namespace string) bool { if a == nil { return false } - set, ok := a.allowed[atespace] + allowed, _ := a.policy() + set, ok := allowed[atespace] if !ok { return false } @@ -169,9 +279,11 @@ func (a *NamespaceAuthorizer) Allowed(atespace, namespace string) bool { // AllowedSecret reports whether atespace may resolve a Secret with these // labels in namespace. A grant without a label selector admits every Secret, // including one that does not exist: pass nil labels to ask that question -// before reading anything from Kubernetes. +// before reading anything from Kubernetes. The namespace grant is checked again +// here, so a request that straddles a reload is settled by the newer policy. func (a *NamespaceAuthorizer) AllowedSecret(atespace, namespace string, labels map[string]string) bool { - for _, g := range a.allowed[atespace][namespace] { + allowed, _ := a.policy() + for _, g := range allowed[atespace][namespace] { if len(g.labels) == 0 { return true } diff --git a/cmd/credential-provider/kubernetes-secrets/statusz.go b/cmd/credential-provider/kubernetes-secrets/statusz.go index 2428cfb8e1..45d03c7697 100644 --- a/cmd/credential-provider/kubernetes-secrets/statusz.go +++ b/cmd/credential-provider/kubernetes-secrets/statusz.go @@ -15,9 +15,9 @@ // The provider's /statusz page, mirroring the atenet router's: one handler // serving an HTML dashboard by default and JSON under ?format=json (or // Accept: application/json). It shows the provider's configuration as the -// running process holds it — notably the authorization policy loaded at -// startup, which the ConfigMap on disk may have since drifted from. Names -// and configuration only, never secret values. +// running process holds it — notably the authorization policy in force, which +// stays at the last version that loaded while the file on disk fails to parse. +// Names and configuration only, never secret values. package main import ( @@ -35,12 +35,14 @@ import ( // statusContext is the /statusz payload; the JSON form is the contract tests // and tooling read, the HTML form renders the same data. type statusContext struct { - Version string `json:"version"` - ProviderName string `json:"provider_name"` - Args string `json:"args"` - Flags map[string]string `json:"flags"` - InjectorSAN string `json:"injector_san"` - PolicyGrants map[string][]string `json:"policy_grants"` + Version string `json:"version"` + ProviderName string `json:"provider_name"` + Args string `json:"args"` + Flags map[string]string `json:"flags"` + InjectorSAN string `json:"injector_san"` + PolicyGrants map[string][]string `json:"policy_grants"` + PolicyGrantDetails map[string][]NamespaceGrant `json:"policy_grant_details"` + PolicyError string `json:"policy_error,omitempty"` } // newStatuszHandler serves /statusz over the provider's state. @@ -50,12 +52,16 @@ func newStatuszHandler(srv *Server) http.HandlerFunc { pflag.VisitAll(func(f *pflag.Flag) { flags[f.Name] = f.Value.String() }) data := statusContext{ - Version: version.String(), - ProviderName: ProviderName, - Args: strings.Join(os.Args, " "), - Flags: flags, - InjectorSAN: *injectorIdentity, - PolicyGrants: srv.Grants(), + Version: version.String(), + ProviderName: ProviderName, + Args: strings.Join(os.Args, " "), + Flags: flags, + InjectorSAN: *injectorIdentity, + PolicyGrants: srv.Grants(), + PolicyGrantDetails: srv.GrantDetails(), + } + if err := srv.PolicyError(); err != nil { + data.PolicyError = err.Error() } if strings.Contains(req.Header.Get("Accept"), "application/json") || req.URL.Query().Get("format") == "json" { @@ -88,12 +94,15 @@ provider: {{.ProviderName}}
required caller SAN: {{.InjectorSAN}}
args: {{.Args}}

-

Namespace policy (as loaded at startup)

-{{if .PolicyGrants}} +

Namespace policy

+{{if .PolicyError}}

policy file failed to load, previous policy in force: {{.PolicyError}}

{{end}} +{{if .PolicyGrantDetails}} - -{{range $atespace, $namespaces := .PolicyGrants}} - + +{{range $atespace, $grants := .PolicyGrantDetails}} +{{range $grants}} + +{{end}} {{end}}
atespaceallowed namespaces
{{$atespace}}{{range $namespaces}}{{.}} {{end}}
atespacenamespacesecret selector
{{$atespace}}{{.Namespace}}{{if .MatchLabels}}{{range $k, $v := .MatchLabels}}{{$k}}={{$v}} {{end}}{{else}}*{{end}}
{{else}} diff --git a/cmd/credential-provider/kubernetes-secrets/statusz_test.go b/cmd/credential-provider/kubernetes-secrets/statusz_test.go index 9586c54cf9..0deaf0176f 100644 --- a/cmd/credential-provider/kubernetes-secrets/statusz_test.go +++ b/cmd/credential-provider/kubernetes-secrets/statusz_test.go @@ -34,7 +34,8 @@ func TestGrants(t *testing.T) { authz, err := newNamespaceAuthorizer(namespacePolicyFile{ Policies: []atespaceNamespacePolicy{ {Atespace: "team-a", AllowedNamespaces: []string{"ns2", "ns1"}}, - {Atespace: "team-b", AllowedNamespaces: []string{"ns3"}}, + {Atespace: "team-b", AllowedNamespaces: []string{"ns3"}, + SecretSelector: &secretSelector{MatchLabels: map[string]string{"env": "prod"}}}, }, }) if err != nil { @@ -48,28 +49,55 @@ func TestGrants(t *testing.T) { t.Errorf("Grants() = %v, want %v", got, want) } + wantDetails := map[string][]NamespaceGrant{ + "team-a": {{Namespace: "ns1"}, {Namespace: "ns2"}}, + "team-b": {{Namespace: "ns3", MatchLabels: map[string]string{"env": "prod"}}}, + } + gotDetails := authz.GrantDetails() + if !reflect.DeepEqual(gotDetails, wantDetails) { + t.Fatalf("GrantDetails() = %+v, want %+v", gotDetails, wantDetails) + } + gotDetails["team-b"][0].MatchLabels["env"] = "dev" + if !authz.AllowedSecret("team-b", "ns3", map[string]string{"env": "prod"}) { + t.Error("mutating GrantDetails() output altered AllowedSecret()") + } + var disabled *NamespaceAuthorizer if got := disabled.Grants(); got != nil { t.Errorf("nil authorizer Grants() = %v, want nil", got) } + if got := disabled.GrantDetails(); got != nil { + t.Errorf("nil authorizer GrantDetails() = %v, want nil", got) + } } -// statuszServer builds a provider that has resolved a secret, so the tests -// can assert the value never surfaces on the page. +// statuszServer builds a provider that has resolved a labeled secret, so the +// tests can assert policy selectors appear while secret data and non-policy +// secret metadata stay hidden. func statuszServer(t *testing.T) (*Server, string) { t.Helper() const secretValue = "statusz-must-never-show-this" secret := &corev1.Secret{ - ObjectMeta: metav1.ObjectMeta{Name: "example-api", Namespace: "ns1"}, - Data: map[string][]byte{"token": []byte(secretValue)}, + ObjectMeta: metav1.ObjectMeta{ + Name: "example-api", + Namespace: "ns1", + Labels: map[string]string{"env": "prod", "app": "web", "unreferenced": "secret-only-label"}, + }, + Data: map[string][]byte{"token": []byte(secretValue)}, } authz, err := newNamespaceAuthorizer(namespacePolicyFile{ - Policies: []atespaceNamespacePolicy{{Atespace: "team-a", AllowedNamespaces: []string{"ns1"}}}, + Policies: []atespaceNamespacePolicy{ + {Atespace: "team-a", AllowedNamespaces: []string{"ns1"}, + SecretSelector: &secretSelector{MatchLabels: map[string]string{"env": "prod", "app": "web"}}}, + {Atespace: "team-a", AllowedNamespaces: []string{"ns1"}, + SecretSelector: &secretSelector{MatchLabels: map[string]string{"team": "x"}}}, + {Atespace: "team-b", AllowedNamespaces: []string{"ns2"}}, + }, }) if err != nil { t.Fatalf("newNamespaceAuthorizer: %v", err) } - srv := NewServer(fake.NewSimpleClientset(secret), authz) + srv := NewServer(fake.NewSimpleClientset(secret), authz, 0) if _, err := srv.FetchSecret(context.Background(), &credprovider.FetchSecretRequest{ Uri: "ate-secret://k8s.io/default/ns1/example-api/token", @@ -93,8 +121,19 @@ func TestStatuszJSON(t *testing.T) { if err := json.Unmarshal(rec.Body.Bytes(), &data); err != nil { t.Fatalf("decoding statusz JSON: %v (body %q)", err, rec.Body.String()) } - if !reflect.DeepEqual(data.PolicyGrants, map[string][]string{"team-a": {"ns1"}}) { - t.Errorf("policy_grants = %v, want team-a → ns1", data.PolicyGrants) + wantGrants := map[string][]string{"team-a": {"ns1"}, "team-b": {"ns2"}} + if !reflect.DeepEqual(data.PolicyGrants, wantGrants) { + t.Errorf("policy_grants = %v, want %v", data.PolicyGrants, wantGrants) + } + wantDetails := map[string][]NamespaceGrant{ + "team-a": { + {Namespace: "ns1", MatchLabels: map[string]string{"env": "prod", "app": "web"}}, + {Namespace: "ns1", MatchLabels: map[string]string{"team": "x"}}, + }, + "team-b": {{Namespace: "ns2"}}, + } + if !reflect.DeepEqual(data.PolicyGrantDetails, wantDetails) { + t.Errorf("policy_grant_details = %+v, want %+v", data.PolicyGrantDetails, wantDetails) } if data.InjectorSAN != *injectorIdentity { t.Errorf("injector_san = %q, want %q", data.InjectorSAN, *injectorIdentity) @@ -106,6 +145,9 @@ func TestStatuszJSON(t *testing.T) { if strings.Contains(rec.Body.String(), secretValue) { t.Fatal("statusz JSON contains the secret value") } + if strings.Contains(rec.Body.String(), "secret-only-label") { + t.Fatal("statusz JSON leaked a label from a Kubernetes Secret rather than the policy") + } } // The page shows configuration only; a resolved secret value appearing in @@ -122,10 +164,20 @@ func TestStatuszHTMLNeverShowsSecret(t *testing.T) { if !strings.Contains(rec.Header().Get("Content-Type"), "text/html") { t.Errorf("Content-Type = %q, want text/html", rec.Header().Get("Content-Type")) } - if !strings.Contains(body, "team-a") { - t.Errorf("HTML page is missing the policy grants") + wantRows := []string{ + "team-ans1app=web env=prod ", + "team-ans1team=x ", + "team-bns2*", + } + for _, want := range wantRows { + if !strings.Contains(body, want) { + t.Errorf("HTML page is missing row %q:\n%s", want, body) + } } if strings.Contains(body, secretValue) { t.Fatal("statusz HTML contains the secret value") } + if strings.Contains(body, "secret-only-label") { + t.Fatal("statusz HTML leaked a label from a Kubernetes Secret rather than the policy") + } } diff --git a/cmd/dataplane/envoy/Dockerfile b/cmd/dataplane/envoy/Dockerfile index 29f6f5cd15..5bc10bf61b 100644 --- a/cmd/dataplane/envoy/Dockerfile +++ b/cmd/dataplane/envoy/Dockerfile @@ -47,17 +47,19 @@ RUN arch="$(cat /target-arch)" \ fi \ && cargo build --release --locked --target "${arch}-unknown-linux-gnu" \ && mkdir -p target/release \ - && cp "target/${arch}-unknown-linux-gnu/release/libenvoy_substrate_egress_policy.so" target/release/ + && cp "target/${arch}-unknown-linux-gnu/release/libenvoy_substrate_egress_policy.so" \ + "target/${arch}-unknown-linux-gnu/release/libenvoy_substrate_ingress_cache.so" target/release/ # Stage 2: Create the runtime image containing Envoy and the built dynamic module shared libraries # When changing Envoy version, the version of SDK in the Cargo.toml files SHOULD match. # Pin the multi-platform image index, not one platform's manifest, so that the # --platform the installer passes (the host architecture on kind, linux/amd64 # otherwise) selects a matching Envoy binary. -FROM envoyproxy/envoy:v1.39.5@sha256:8fc594a5d85eb76dca24155cfb9208882406873932b20cf33649a0a611194c43 +FROM envoyproxy/envoy:v1.40.0@sha256:459f2a6404c340fe6afccd69d85527012d47f3c036765493e6f8f3113fa384de -# Copy the built dynamic module shared library from the builder stage +# Copy the built dynamic module shared libraries from the builder stage COPY --from=builder /usr/src/dynamic-modules/target/release/libenvoy_substrate_egress_policy.so /usr/local/lib/libenvoy_substrate_egress_policy.so +COPY --from=builder /usr/src/dynamic-modules/target/release/libenvoy_substrate_ingress_cache.so /usr/local/lib/libenvoy_substrate_ingress_cache.so # Set default search path for Envoy dynamic modules ENV ENVOY_DYNAMIC_MODULES_SEARCH_PATH=/usr/local/lib diff --git a/cmd/dataplane/envoy/README.md b/cmd/dataplane/envoy/README.md index 29730d1043..27e63c7e71 100644 --- a/cmd/dataplane/envoy/README.md +++ b/cmd/dataplane/envoy/README.md @@ -14,7 +14,7 @@ cmd/dataplane/envoy/ - **`Dockerfile`**: Multi-stage container build that: 1. Compiles the Rust dynamic module (`envoy-substrate-egress-policy`) into a shared library (`libenvoy_substrate_egress_policy.so`) in a `rust:bookworm` builder stage. - 2. Packages the compiled `.so` into the `envoyproxy/envoy:v1.39.5` runtime image under `/usr/local/lib/libenvoy_substrate_egress_policy.so` and sets `ENVOY_DYNAMIC_MODULES_SEARCH_PATH=/usr/local/lib`. + 2. Packages the compiled `.so` into the `envoyproxy/envoy:v1.40.0` runtime image under `/usr/local/lib/libenvoy_substrate_egress_policy.so` and sets `ENVOY_DYNAMIC_MODULES_SEARCH_PATH=/usr/local/lib`. - **`dynamic-modules/egress-policy/`**: A Rust crate using the Envoy Dynamic Modules SDK (`envoy-proxy-dynamic-modules-rust-sdk`) that implements a custom Envoy listener filter for Substrate egress policy evaluation. See [`dynamic-modules/egress-policy/README.md`](dynamic-modules/egress-policy/README.md) for module-specific build, test, and Envoy configuration details. ## Building and Deployment diff --git a/cmd/dataplane/envoy/dynamic-modules/Cargo.lock b/cmd/dataplane/envoy/dynamic-modules/Cargo.lock index 088375f4d7..7ae6578531 100644 --- a/cmd/dataplane/envoy/dynamic-modules/Cargo.lock +++ b/cmd/dataplane/envoy/dynamic-modules/Cargo.lock @@ -19,14 +19,13 @@ checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" [[package]] name = "bindgen" -version = "0.70.1" +version = "0.73.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f" +checksum = "787ef8ef523575546b106a58213d6e6b06198a05c2f757258c68a74273670cfa" dependencies = [ "bitflags", "cexpr", "clang-sys", - "itertools", "log", "prettyplease", "proc-macro2", @@ -39,9 +38,9 @@ dependencies = [ [[package]] name = "bitflags" -version = "2.13.1" +version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b588b76d00fde79687d7646a9b5bdf3cc0f655e0bbd080335a95d7e96f3587da" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" [[package]] name = "cexpr" @@ -54,9 +53,9 @@ dependencies = [ [[package]] name = "cfg-if" -version = "1.0.4" +version = "1.0.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" [[package]] name = "clang-sys" @@ -75,19 +74,14 @@ version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1435fa1053d8b2fbbe9be7e97eca7f33d37b28409959813daefc1446a14247f1" -[[package]] -name = "either" -version = "1.18.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "252afb9ae5eaa683babdc6a068b3f5726eb19e05070c731f9b2a23a7c3e8ed34" - [[package]] name = "envoy-proxy-dynamic-modules-rust-sdk" version = "0.1.0" -source = "git+https://github.com/envoyproxy/envoy?rev=b579d07d3ad7ee11d32b105e91a5a39ad24718d7#b579d07d3ad7ee11d32b105e91a5a39ad24718d7" +source = "git+https://github.com/envoyproxy/envoy?rev=9e5580933739775e8bce696a57a2e1bc99368f23#9e5580933739775e8bce696a57a2e1bc99368f23" dependencies = [ "bindgen", "mockall", + "smallvec", ] [[package]] @@ -111,15 +105,6 @@ version = "0.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" -[[package]] -name = "itertools" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" -dependencies = [ - "either", -] - [[package]] name = "itoa" version = "1.0.18" @@ -128,9 +113,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "libc" -version = "0.2.189" +version = "0.2.190" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2" +checksum = "ce5d3ddc6d3fa000eb1536d85e147bfe31aacaba692ed6a876f95cb7c855be78" [[package]] name = "libloading" @@ -162,9 +147,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" [[package]] name = "mockall" -version = "0.13.1" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "39a6bfcc6c8c7eed5ee98b9c3e33adc726054389233e201c95dab2d41a3839d2" +checksum = "1a6ceddfe3ce334925e96bf420fdb2dcee5bed6c632a168ece622676dadeaf8a" dependencies = [ "cfg-if", "downcast", @@ -176,9 +161,9 @@ dependencies = [ [[package]] name = "mockall_derive" -version = "0.13.1" +version = "0.15.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "25ca3004c2efe9011bd4e461bd8256445052b9615405b4f7ea43fc8ca5c20898" +checksum = "9cfe16fbe8a314aeec0b861ac24e60b1e123e97634bab045475b9d6a18416fd8" dependencies = [ "cfg-if", "proc-macro2", @@ -290,9 +275,9 @@ checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" [[package]] name = "rustc-hash" -version = "1.1.0" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustversion" @@ -345,9 +330,15 @@ dependencies = [ [[package]] name = "shlex" -version = "1.3.0" +version = "2.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" [[package]] name = "substrate-envoy-egress-policy" @@ -360,6 +351,15 @@ dependencies = [ "thread_local", ] +[[package]] +name = "substrate-envoy-ingress-cache" +version = "0.1.0" +dependencies = [ + "envoy-proxy-dynamic-modules-rust-sdk", + "serde", + "serde_json", +] + [[package]] name = "syn" version = "2.0.119" @@ -399,9 +399,9 @@ dependencies = [ [[package]] name = "unicode-ident" -version = "1.0.24" +version = "1.0.26" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75" +checksum = "d245f478577f809a851594d02313b640fb437e0bb33866753cff937863096954" [[package]] name = "windows-link" diff --git a/cmd/dataplane/envoy/dynamic-modules/Cargo.toml b/cmd/dataplane/envoy/dynamic-modules/Cargo.toml index 19f8b02218..b7d72fe3bc 100644 --- a/cmd/dataplane/envoy/dynamic-modules/Cargo.toml +++ b/cmd/dataplane/envoy/dynamic-modules/Cargo.toml @@ -16,6 +16,7 @@ resolver = "3" members = [ "egress-policy", + "ingress-cache", ] [workspace.package] @@ -23,11 +24,11 @@ version = "0.1.0" edition = "2024" [workspace.dependencies] -# Pin to v1.39.1 commit SHA +# Pin to v1.40.0 commit SHA # When changing the SDK version, the version of Envoy in the cmd/dataplane/envoy/Dockerfile SHOULD match. # SDK version SHOULD NOT be newer than Envoy's in the dataplane image, as extensions will not load if they use # APIs not supported by the Envoy binary in the image. -envoy-proxy-dynamic-modules-rust-sdk = { git = "https://github.com/envoyproxy/envoy", rev = "b579d07d3ad7ee11d32b105e91a5a39ad24718d7" } +envoy-proxy-dynamic-modules-rust-sdk = { git = "https://github.com/envoyproxy/envoy", rev = "9e5580933739775e8bce696a57a2e1bc99368f23" } rapidhash = "4.5.1" serde = { version = "1.0", features = ["derive"] } serde_json = "1.0" diff --git a/cmd/dataplane/envoy/dynamic-modules/egress-policy/Cargo.toml b/cmd/dataplane/envoy/dynamic-modules/egress-policy/Cargo.toml index bae4077ba5..64b3a40ec7 100644 --- a/cmd/dataplane/envoy/dynamic-modules/egress-policy/Cargo.toml +++ b/cmd/dataplane/envoy/dynamic-modules/egress-policy/Cargo.toml @@ -27,3 +27,6 @@ rapidhash.workspace = true serde.workspace = true serde_json.workspace = true thread_local.workspace = true + +[dev-dependencies] +envoy-proxy-dynamic-modules-rust-sdk = { workspace = true, features = ["mock"] } diff --git a/cmd/dataplane/envoy/dynamic-modules/egress-policy/src/egress_policy_store.rs b/cmd/dataplane/envoy/dynamic-modules/egress-policy/src/egress_policy_store.rs index 922a80d07b..382d862995 100644 --- a/cmd/dataplane/envoy/dynamic-modules/egress-policy/src/egress_policy_store.rs +++ b/cmd/dataplane/envoy/dynamic-modules/egress-policy/src/egress_policy_store.rs @@ -59,6 +59,16 @@ impl EgressPolicyStore { pub fn remove(&mut self, key: u64) -> Option> { self.policies.remove(&key) } + + /// Removes the policy under `key` when the store holds the only remaining + /// reference, returning whether it was removed. + pub fn remove_if_unused(&mut self, key: u64) -> bool { + if self.policies.get(&key).is_some_and(|p| Rc::strong_count(p) == 1) { + self.policies.remove(&key); + return true; + } + false + } } /// Global store for egress policies holding a thread-local [`EgressPolicyStore`]. @@ -118,4 +128,27 @@ mod tests { assert_eq!(GlobalEgressPolicyStore::get_local_store().lookup(policy.hash), None); assert_eq!(GlobalEgressPolicyStore::get_local_store().remove(policy.hash), None); } + + #[test] + fn test_remove_if_unused() { + let policy = Rc::new(EgressPolicy { + rules: vec![SniRule { + pattern: "unused.example.com".to_string(), + mode: "mitm".to_string(), + }], + hash: 42, + }); + let mut store = EgressPolicyStore::new(); + store.store(policy.hash, &policy); + // External Rc still exists (strong_count == 2), so entry stays. + assert!(!store.remove_if_unused(policy.hash)); + assert!(store.lookup(policy.hash).is_some()); + + let hash = policy.hash; + drop(policy); + // Store holds the only reference (strong_count == 1), so entry is removed. + assert!(store.remove_if_unused(hash)); + assert!(store.lookup(hash).is_none()); + assert!(!store.remove_if_unused(hash)); + } } diff --git a/cmd/dataplane/envoy/dynamic-modules/egress-policy/src/policy_store_filter.rs b/cmd/dataplane/envoy/dynamic-modules/egress-policy/src/policy_store_filter.rs index 49d10b97af..7bec54140c 100644 --- a/cmd/dataplane/envoy/dynamic-modules/egress-policy/src/policy_store_filter.rs +++ b/cmd/dataplane/envoy/dynamic-modules/egress-policy/src/policy_store_filter.rs @@ -14,6 +14,7 @@ //! HTTP filter implementation for storing the egress policy. +use std::cell::RefCell; use std::rc::Rc; use envoy_proxy_dynamic_modules_rust_sdk::{ @@ -48,7 +49,7 @@ pub struct EgressPolicyStoreFilterConfig { impl HttpFilterConfig for EgressPolicyStoreFilterConfig { fn new_http_filter(&self, _envoy: &mut EHF) -> Box> { Box::new(EgressPolicyStoreFilter { - policy: Rc::default(), + policy: RefCell::new(None), store_size: self.store_size, parse_errors: self.parse_errors, policy_shared: self.policy_shared, @@ -58,7 +59,7 @@ impl HttpFilterConfig for EgressPolicyStoreFilterConf /// Per-stream HTTP filter instance for egress-policy-store. pub struct EgressPolicyStoreFilter { - pub policy: Rc, + pub policy: RefCell>>, pub store_size: EnvoyGaugeId, pub parse_errors: EnvoyCounterId, pub policy_shared: EnvoyCounterId, @@ -67,7 +68,7 @@ pub struct EgressPolicyStoreFilter { impl Default for EgressPolicyStoreFilter { fn default() -> Self { Self { - policy: Rc::default(), + policy: RefCell::new(None), store_size: EnvoyGaugeId(0), parse_errors: EnvoyCounterId(0), policy_shared: EnvoyCounterId(0), @@ -77,7 +78,7 @@ impl Default for EgressPolicyStoreFilter { impl HttpFilter for EgressPolicyStoreFilter { fn on_request_headers( - &mut self, + &self, envoy_filter: &mut EHF, _end_of_stream: bool, ) -> envoy_dynamic_module_type_on_http_filter_request_headers_status { @@ -87,8 +88,9 @@ impl HttpFilter for EgressPolicyStoreFilter { return envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue; }; envoy_log_trace!("egress policy store: policy={:?}", policy); + let hash = policy.hash; let mut local_store = GlobalEgressPolicyStore::get_local_store(); - if let Some(existing_policy) = local_store.lookup(policy.hash) { + if let Some(existing_policy) = local_store.lookup(hash) { // Sanity check that the policy is the same and fail closed on hash collisions. if existing_policy != policy { envoy_filter.send_response(400, &[], Some(b"hash collision"), Some("hash_collision")); @@ -96,11 +98,11 @@ impl HttpFilter for EgressPolicyStoreFilter { } let _ = envoy_filter.increment_counter(self.policy_shared, 1); // Use the policy that was alredy in the store. - self.policy = existing_policy; + *self.policy.borrow_mut() = Some(existing_policy); } else { - local_store.store(policy.hash, &policy); + local_store.store(hash, &policy); let _ = envoy_filter.increase_gauge(self.store_size, 1); - self.policy = policy; + *self.policy.borrow_mut() = Some(policy); } // Dynamic module API does not yet support writing filter state values // that are shared with the upstream (will be available in Envoy v1.40). @@ -109,21 +111,21 @@ impl HttpFilter for EgressPolicyStoreFilter { // TODO(yanavlasov): remove this workaround after Envoy v1.40 is released. envoy_filter.set_filter_state_bytes( ATE_POLICY_EGRESS_HASH_NOT_SHARED, - self.policy.hash.to_string().as_bytes(), + hash.to_string().as_bytes(), ); envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue } - // on_stream_complete is called right before the filter object is dropped - // This is the last callback that still has valid filter ref. - fn on_stream_complete(&mut self, envoy_filter: &mut EHF) { - // Reference count 2 for the policy object means that it is held by the policy - // store table and this filter that is about to be dropped. - // To avoid leaking the policy in the store, remove it from the store. When on_stream_complete - // callback finishes and and filter is dropped, the only remaining reference to the policy is - // decremented and the policy object will be dropped as well. - if Rc::strong_count(&self.policy) == 2 { - GlobalEgressPolicyStore::get_local_store().remove(self.policy.hash); + fn on_stream_complete(&self, envoy_filter: &mut EHF) { + // Release this filter's reference immediately. Envoy 1.40 defers filter + // destruction until later in the event loop, so multiple streams sharing a + // policy can run on_stream_complete before any filter is dropped. + let Some(policy) = self.policy.borrow_mut().take() else { + return; + }; + let hash = policy.hash; + drop(policy); + if GlobalEgressPolicyStore::get_local_store().remove_if_unused(hash) { let _ = envoy_filter.decrease_gauge(self.store_size, 1); } } @@ -170,8 +172,8 @@ mod tests { parse_errors: EnvoyCounterId(2), policy_shared: EnvoyCounterId(3), }; - let mut filter = EgressPolicyStoreFilter { - policy: Rc::default(), + let filter = EgressPolicyStoreFilter { + policy: RefCell::new(None), store_size: config.store_size, parse_errors: config.parse_errors, policy_shared: config.policy_shared, @@ -218,8 +220,9 @@ mod tests { filter.on_request_headers(&mut mock_filter, false), envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue ); + let stored_policy = filter.policy.borrow().clone().unwrap(); assert_eq!( - filter.policy.rules, + stored_policy.rules, vec![ SniRule { pattern: "api.example.com".to_string(), @@ -231,19 +234,19 @@ mod tests { }, ] ); - assert_ne!(filter.policy.hash, 0); + assert_ne!(stored_policy.hash, 0); - let hash = filter.policy.hash; + let hash = stored_policy.hash; assert!(Rc::ptr_eq( &GlobalEgressPolicyStore::get_local_store() .lookup(hash) .unwrap(), - &filter.policy + &stored_policy )); // A second filter receiving the same policy reuses the stored Rc without incrementing store_size. - let mut second_filter = EgressPolicyStoreFilter { - policy: Rc::default(), + let second_filter = EgressPolicyStoreFilter { + policy: RefCell::new(None), store_size: config.store_size, parse_errors: config.parse_errors, policy_shared: config.policy_shared, @@ -286,31 +289,37 @@ mod tests { second_filter.on_request_headers(&mut mock_filter, false), envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue ); - assert!(Rc::ptr_eq(&second_filter.policy, &filter.policy)); + assert!(Rc::ptr_eq( + second_filter.policy.borrow().as_ref().unwrap(), + &stored_policy + )); + drop(stored_policy); - // Completing and dropping the first filter keeps the policy in the local store while the second filter holds it. + // Completing both filters before either is dropped (Envoy 1.40 deferred + // destruction) removes the entry and decrements store_size on the second + // on_stream_complete rather than leaking it. filter.on_stream_complete(&mut mock_filter); - drop(filter); assert!(GlobalEgressPolicyStore::get_local_store() .lookup(hash) .is_some()); - // Completing and dropping the last filter holding the policy decrements store_size and removes it from the local store. mock_filter .expect_decrease_gauge() .withf(|id, value| *id == EnvoyGaugeId(1) && *value == 1) .returning(|_, _| Ok(())) .once(); second_filter.on_stream_complete(&mut mock_filter); - drop(second_filter); assert!(GlobalEgressPolicyStore::get_local_store() .lookup(hash) .is_none()); + + drop(filter); + drop(second_filter); } #[test] fn test_on_request_headers_missing_or_invalid_policy() { - let mut filter = EgressPolicyStoreFilter { + let filter = EgressPolicyStoreFilter { parse_errors: EnvoyCounterId(2), ..Default::default() }; @@ -334,7 +343,7 @@ mod tests { filter.on_request_headers(&mut mock_filter, false), envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue ); - assert_eq!(filter.policy, Rc::default()); + assert!(filter.policy.borrow().is_none()); mock_filter .expect_get_metadata_string() @@ -355,7 +364,7 @@ mod tests { filter.on_request_headers(&mut mock_filter, false), envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue ); - assert_eq!(filter.policy, Rc::default()); + assert!(filter.policy.borrow().is_none()); } #[test] @@ -386,7 +395,7 @@ mod tests { }); GlobalEgressPolicyStore::get_local_store().store(colliding_hash, &existing_policy); - let mut filter = EgressPolicyStoreFilter::default(); + let filter = EgressPolicyStoreFilter::default(); let mut mock_filter = MockEnvoyHttpFilter::default(); mock_filter .expect_get_metadata_string() @@ -423,7 +432,7 @@ mod tests { filter.on_request_headers(&mut mock_filter, false), envoy_dynamic_module_type_on_http_filter_request_headers_status::StopIteration ); - assert_eq!(filter.policy, Rc::default()); + assert!(filter.policy.borrow().is_none()); GlobalEgressPolicyStore::get_local_store().remove(colliding_hash); } diff --git a/cmd/dataplane/envoy/dynamic-modules/ingress-cache/Cargo.toml b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/Cargo.toml new file mode 100644 index 0000000000..d012bf012b --- /dev/null +++ b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/Cargo.toml @@ -0,0 +1,30 @@ +# Copyright 2026 The Agent Substrate 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] +name = "substrate-envoy-ingress-cache" +version.workspace = true +edition.workspace = true + +[lib] +name = "envoy_substrate_ingress_cache" +crate-type = ["cdylib"] + +[dependencies] +envoy-proxy-dynamic-modules-rust-sdk.workspace = true +serde.workspace = true +serde_json.workspace = true + +[dev-dependencies] +envoy-proxy-dynamic-modules-rust-sdk = { workspace = true, features = ["mock"] } diff --git a/cmd/dataplane/envoy/dynamic-modules/ingress-cache/README.md b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/README.md new file mode 100644 index 0000000000..8e18b6b1b0 --- /dev/null +++ b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/README.md @@ -0,0 +1,166 @@ +# Envoy Substrate Ingress Cache - Rust Dynamic Module + +An Envoy dynamic module, written in Rust, that runs as an HTTP filter ahead of +`ext_proc` on the ingress router and caches `/` to worker IP +bindings. With upstream CONNECT (the default), the same library also provides +the `tunnel_watcher` network filter on the router's `actor_connect` +internal listener, which marks cache entries from what happens to the tunnels +they route to. + +The cache is per Envoy worker thread. Each thread learns bindings on its own, +which costs more misses than a shared cache but keeps the network filter's +marks on the thread, and in the cache, that the request was routed from. + +The cache is a preview feature and is **disabled by default**. Read the +caveats below before enabling it. + +## Enabling + +The cache is controlled by the `IngressCache` preview gate on `atenet-router` +and is only implemented by the Envoy dataplane (`--atenet-dataplane=envoy`, the +default). Enable it at install time with: + +```bash +ATE_PREVIEW=IngressCache go run ./cmd/ate-setup deploy ate-system +``` + +or pass `--preview=IngressCache` to the `atenet-router` container directly. + +With the gate off, the router installs neither these filters nor the cached +routes that skip `ext_proc`, so every request is resolved through `ext_proc`. + +`atenet-router` sets the filter config from `--ingress-cache-ttl` (default 5s) +and `--ingress-cache-max-cached-actors` (default 10,000 per Envoy worker +thread). + +## Caveats + +- **Stale routing for up to the TTL.** A cache hit skips `ext_proc` and so does + not observe suspends, migrations, or reassignments made in the last + `cache_ttl_seconds` (default 5s). A request to the old worker evicts the + entry and, when that is safe, is replayed through `ext_proc`, as described + below. +- **Only bodiless requests use the cache.** A request with a body, including + every gRPC call, always goes through `ext_proc`: if it hit a stale entry, the + router couldn't replay it. Its response still refreshes the cache. +- **Clients must retry some failures.** Only bodiless requests that failed + before reaching the actor are replayed by the router. One interrupted + mid-flight returns the error to the client after evicting the entry; the + client's retry is resolved through `ext_proc`. +- **No replays while an entry is spoiled.** If an actor is suspended while a + request is in flight on an established tunnel, before it responded, its entry + is marked spoiled and no request on it is replayed, including one refused at + the same moment. Suspends follow an idle signal, so this is rare, and those + clients get a `503` rather than risk running a request twice. +- **Partial response headers.** If an actor writes only part of its response + headers and then dies or is suspended, the network filter treats the request + as answered and doesn't spoil the entry. The router returns `503 UC`, which + can then be replayed although the actor ran the request, if another request's + refusal marked the entry stale. A 1xx followed by a drop isn't replayed: the + router reports it as `upstream_reset_after_response_started`. +- **Each thread caches at most `max_cached_actors` actors** (10,000 by + default). A full thread cache drops expired bindings before it caches another + actor. If none had expired, the new actor isn't cached and its requests keep + going through `ext_proc`. + +## How it works + +- **Cache hit (`on_request_headers`)**: When an unexpired binding exists for the + target actor, the filter writes the `ORIGINAL_DST` dynamic metadata + (`envoy.filters.listener.original_dst`), sets the `x-ate-target-port` and + `ate-target-actor` request headers that `ext_proc` would otherwise set, sets + the `ate.ingress_cache` `hit` dynamic metadata to select the route with + `ext_proc` disabled, and clears the route cache. Clients can't set dynamic + metadata, so they can't select that route. The two headers are sent to + `atunnel` on the worker, so their names are `atunnel`'s + (`internal/atunnel/ingress`, `internal/atenet`). +- **Cache miss (`on_request_headers` / `on_response_headers`)**: The request + proceeds through `ext_proc`, which resolves or resumes the actor and populates + the `ORIGINAL_DST` dynamic metadata. On response headers, the filter records + the worker IP in the cache for `cache_ttl_seconds`. +- **Request with a body (`on_request_headers`)**: The filter skips the cache + lookup and the request proceeds through `ext_proc`, then is learned from like a + miss. A request counts as having a body unless it ends with its headers or has + `content-length: 0`. Envoy delivers a bodiless HTTP/1 request's headers that + way, so this sends chunked or HTTP/2 GETs and upgrades such as WebSocket + through `ext_proc`. +- **gRPC `UNAVAILABLE` (`on_response_headers` / `on_response_trailers`)**: A + response with gRPC status `14` is not learned from. If the status arrives in + the trailers, after the headers were learned from, the actor's binding is + removed. +- **Stale binding eviction (`on_response_headers`)**: If a fast-path request + fails with `421 Misdirected Request` (with `x-ate-assignment-stale: true`, + the response header `atunnel` adds to its own refusals), or `503 Service + Unavailable` with upstream transport failure response flags (`UF`, `UH`, + `UC`, `UR`), the filter immediately evicts the cached binding so subsequent + requests resolve through `ext_proc`. +- **Tunnel marks (`tunnel_watcher`)**: On each `actor_connect` + connection, the network filter reads the actor and worker from the tunnel + filter state (`dev.ate.tunnel.actor`, `dev.ate.tunnel.worker`) and notes + whether request bytes went upstream without response bytes coming back; it + never parses them. When the connection closes: + - with `UF`, the tunnel was never established (refused CONNECT, failed dial, + or connect timeout), so it marks every live entry for that actor and worker + **stale** and removes the current binding; + - after being established with a request outstanding, it marks them + **spoiled**, since that request may have reached the actor. + The marks are in place before the router reports the `503`: the close + callback runs inside `tcp_proxy`'s close, and the router sees the close on the + next event-loop iteration. A request routed from the cache holds its entry + until it ends, so marks reach it even after a newer binding replaces it. +- **Stream replay (`recreate_stream`)**: To prevent duplicate execution of requests + with side effects, automatic replay is only performed when failure is + guaranteed to have occurred before the request reached the upstream actor + (only bodiless requests are served from the cache): + - `421 Misdirected Request` with `x-ate-assignment-stale: true` (rejected by + worker `atunnel` prior to forwarding). + - `503 Service Unavailable` with zero-byte upstream failure response flags: + `UF` (upstream connection failure / connection refused before connection + establishment) or `UH` (no healthy upstream host in cluster). + - `503 Service Unavailable` with `UC` (upstream connection termination) when + the entry the request was routed from is stale and not spoiled, and the + response code details start with `upstream_reset_before_response_started`. + On the CONNECT path a refused tunnel reaches the router as `503 UC`, and + stale-but-not-spoiled means no request on the entry was cut off after + reaching the actor. The details rule out a 1xx, which the router doesn't + forward and the network filter counts as an answer. + Other `503 UC` and `503 UR` responses evict the entry but are not replayed, + leaving retries to the client. Eviction removes the binding only if it is + still the one the request used, so a newer binding learned by another request + stays. + +## Filter configuration + +The filter accepts an optional JSON configuration object in `filter_config` +(an empty config defaults to `{}`): + +| Field | Type | Default | Description | +|---|---|---|---| +| `cache_ttl_seconds` | `u64` | `5` | Time-to-live in seconds for cached actor -> worker bindings | +| `atunnel_port` | `u16` | `443` | Port `atunnel` listens on at the worker | +| `target_port_header` | `String` | `"x-ate-target-port"` | Request header carrying the actor's target port to `atunnel` | +| `max_cached_actors` | `usize` | `10000` | Most actors cached per Envoy worker thread | + +## Metrics + +| Counter name | Description | +|---|---| +| `ate_ingress_cache.hit` | Incremented when an unexpired actor -> worker binding is served from cache | +| `ate_ingress_cache.miss` | Incremented when a bodiless request finds no unexpired binding in the cache | +| `ate_ingress_cache.bypass` | Incremented when a request with a body skips the cache lookup and is routed through `ext_proc` | +| `ate_ingress_cache.eviction` | Incremented when an expired or stale cache entry is evicted | +| `ate_ingress_cache.replay` | Incremented when a stale fast-path request is replayed via `recreate_stream` | +| `ate_ingress_cache.marked_stale` | Incremented when a tunnel closes with `UF` and marks at least one live entry stale (`tunnel_watcher`) | +| `ate_ingress_cache.marked_spoiled` | Incremented when an established tunnel closes with a request outstanding and marks at least one live entry spoiled (`tunnel_watcher`) | + +`hit`, `miss`, and `bypass` partition the requests the filter resolves an actor +for, so the hit rate among cacheable requests is `hit / (hit + miss)`. Envoy's +Prometheus endpoint exports the counters with `.` replaced by `_`, e.g. +`ate_ingress_cache_bypass`. + +## Building and testing + +```bash +hack/test-dynamic-modules.sh +``` + diff --git a/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/cache.rs b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/cache.rs new file mode 100644 index 0000000000..d7ec1c3e42 --- /dev/null +++ b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/cache.rs @@ -0,0 +1,360 @@ +// Copyright 2026 The Agent Substrate 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. + +//! Per-thread actor -> worker binding cache. +//! +//! Each Envoy worker thread has its own cache. The HTTP filter and the +//! `tunnel_watcher` network filter for a request run on the same thread +//! (the internal listener connection is accepted on the thread that opened it), +//! and so do Envoy's connection pools, so the network filter's marks always land +//! in the cache the request was routed from. +//! +//! A request routed from the cache holds an [`Rc`] to its [`Entry`] until the +//! request ends. The cache keeps two maps: +//! +//! * current bindings, `actor key -> Rc`, which new requests look up; +//! * live entries, `(actor key, worker IP) -> [Weak]`, which the network +//! filter marks. An entry stays reachable here while any request holds it, +//! even after it leaves the current bindings. + +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::rc::{Rc, Weak}; +use std::time::{Duration, Instant}; + +/// A resolved actor -> worker binding. +#[derive(Debug)] +pub struct Entry { + pub worker_ip: String, + pub worker_spiffe_id: Option, + pub expires_at: Instant, + /// Set when a tunnel for this binding was refused before it was established. + stale: Cell, + /// Set when an established tunnel for this binding closed while a request was + /// waiting for its response, so that request may have reached the actor. + spoiled: Cell, +} + +impl Entry { + pub fn is_stale(&self) -> bool { + self.stale.get() + } + + pub fn is_spoiled(&self) -> bool { + self.spoiled.get() + } + + /// Reports whether a request routed from this entry whose connection ended + /// before a response can be replayed: a tunnel for the binding was refused, + /// and no request on it may have reached the actor. + pub fn refused_and_unspoiled(&self) -> bool { + self.is_stale() && !self.is_spoiled() + } +} + +/// The result of looking up an actor in the cache. +pub enum Lookup { + /// An unexpired binding. + Hit(Rc), + /// A binding that had expired and has been removed. + Expired, + /// No binding. + Miss, +} + +/// How often a full cache may scan for expired bindings, so a cache full of +/// unexpired bindings doesn't rescan on every miss. +const FULL_SWEEP_INTERVAL: Duration = Duration::from_secs(1); + +#[derive(Default)] +struct Cache { + bindings: HashMap>, + live: HashMap<(String, String), Vec>>, + last_full_sweep: Option, +} + +impl Cache { + /// Reports whether `key` can be bound under `max_actors`: it already is, or + /// there's room, possibly after dropping expired bindings. + fn has_room_for(&mut self, key: &str, now: Instant, max_actors: usize) -> bool { + if self.bindings.len() < max_actors || self.bindings.contains_key(key) { + return true; + } + if self + .last_full_sweep + .is_some_and(|last| now < last + FULL_SWEEP_INTERVAL) + { + return false; + } + self.last_full_sweep = Some(now); + self.bindings.retain(|_, entry| entry.expires_at > now); + self.bindings.len() < max_actors + } + + /// Drops live-entry slots whose entries have been freed. Runs a full sweep + /// only when dead slots may outnumber live bindings, so the cost is amortized. + fn maybe_sweep(&mut self) { + if self.live.len() <= 2 * self.bindings.len() + 64 { + return; + } + self.live.retain(|_, entries| { + entries.retain(|e| e.strong_count() > 0); + !entries.is_empty() + }); + } + + /// Applies `mark` to every live entry for `(actor, worker_ip)` and returns how + /// many entries it marked. + fn mark(&mut self, actor: &str, worker_ip: &str, mark: impl Fn(&Entry)) -> usize { + let Some(entries) = self.live.get_mut(&(actor.to_string(), worker_ip.to_string())) else { + return 0; + }; + let mut marked = 0; + entries.retain(|weak| match weak.upgrade() { + Some(entry) => { + mark(&entry); + marked += 1; + true + } + None => false, + }); + marked + } +} + +thread_local! { + static CACHE: RefCell = RefCell::default(); +} + +/// Looks up the current binding for `key`, removing it if it expired by `now`. +pub fn lookup(key: &str, now: Instant) -> Lookup { + CACHE.with_borrow_mut(|cache| match cache.bindings.get(key) { + Some(entry) if entry.expires_at > now => Lookup::Hit(Rc::clone(entry)), + Some(_) => { + cache.bindings.remove(key); + Lookup::Expired + } + None => Lookup::Miss, + }) +} + +/// Returns the current binding for `key`, expired or not. +pub fn current(key: &str) -> Option> { + CACHE.with_borrow(|cache| cache.bindings.get(key).cloned()) +} + +/// Makes a new binding for `key` current, replacing any previous one, and returns it. +/// If the cache already binds `max_actors` unexpired actors, the entry isn't cached. +pub fn insert( + key: String, + worker_ip: String, + worker_spiffe_id: Option, + ttl: Duration, + max_actors: usize, +) -> Rc { + let now = Instant::now(); + let entry = Rc::new(Entry { + worker_ip, + worker_spiffe_id, + expires_at: now + ttl, + stale: Cell::new(false), + spoiled: Cell::new(false), + }); + CACHE.with_borrow_mut(|cache| { + if !cache.has_room_for(&key, now, max_actors) { + return; + } + let slot = cache + .live + .entry((key.clone(), entry.worker_ip.clone())) + .or_default(); + slot.retain(|e| e.strong_count() > 0); + slot.push(Rc::downgrade(&entry)); + cache.bindings.insert(key, Rc::clone(&entry)); + cache.maybe_sweep(); + }); + entry +} + +/// Removes the current binding for `key` if it is `entry`, so a newer binding +/// learned by another request is left alone. Reports whether it removed it. +pub fn remove_if_current(key: &str, entry: &Rc) -> bool { + CACHE.with_borrow_mut(|cache| { + if cache + .bindings + .get(key) + .is_some_and(|current| Rc::ptr_eq(current, entry)) + { + cache.bindings.remove(key); + true + } else { + false + } + }) +} + +/// Marks every live entry for `(actor, worker_ip)` stale and removes the current +/// binding if it points at that worker, so new requests resolve through +/// `ext_proc`. Returns how many entries it marked. +pub fn mark_stale(actor: &str, worker_ip: &str) -> usize { + CACHE.with_borrow_mut(|cache| { + let marked = cache.mark(actor, worker_ip, |e| e.stale.set(true)); + if cache + .bindings + .get(actor) + .is_some_and(|current| current.worker_ip == worker_ip) + { + cache.bindings.remove(actor); + } + marked + }) +} + +/// Marks every live entry for `(actor, worker_ip)` spoiled. Returns how many +/// entries it marked. +pub fn mark_spoiled(actor: &str, worker_ip: &str) -> usize { + CACHE.with_borrow_mut(|cache| cache.mark(actor, worker_ip, |e| e.spoiled.set(true))) +} + +// ========================================== +// Tests +// ========================================== + +#[cfg(test)] +mod tests { + use super::*; + + // Each Rust test runs on its own thread, so each test starts with an empty cache. + + const MAX: usize = 100; + + #[test] + fn test_insert_lookup_and_remove() { + let entry = insert( + "ns/a".to_string(), + "10.244.0.42".to_string(), + Some("spiffe://cluster.local/ns/default/sa/worker-pool-1".to_string()), + Duration::from_secs(5), + MAX, + ); + match lookup("ns/a", Instant::now()) { + Lookup::Hit(hit) => assert!(Rc::ptr_eq(&hit, &entry)), + _ => panic!("expected a hit"), + } + assert!(remove_if_current("ns/a", &entry)); + assert!(matches!(lookup("ns/a", Instant::now()), Lookup::Miss)); + } + + #[test] + fn test_lookup_removes_expired_binding() { + insert("ns/a".to_string(), "10.0.0.1".to_string(), None, Duration::ZERO, MAX); + assert!(matches!( + lookup("ns/a", Instant::now() + Duration::from_millis(1)), + Lookup::Expired + )); + assert!(current("ns/a").is_none()); + } + + #[test] + fn test_remove_if_current_keeps_newer_binding() { + let old = insert("ns/a".to_string(), "10.0.0.1".to_string(), None, Duration::from_secs(5), MAX); + let new = insert("ns/a".to_string(), "10.0.0.2".to_string(), None, Duration::from_secs(5), MAX); + assert!(!remove_if_current("ns/a", &old)); + assert!(Rc::ptr_eq(¤t("ns/a").unwrap(), &new)); + } + + #[test] + fn test_mark_stale_marks_held_entry_and_removes_binding() { + let held = insert("ns/a".to_string(), "10.0.0.1".to_string(), None, Duration::from_secs(5), MAX); + assert_eq!(mark_stale("ns/a", "10.0.0.1"), 1); + assert!(held.is_stale()); + assert!(!held.is_spoiled()); + assert!(held.refused_and_unspoiled()); + assert!(current("ns/a").is_none()); + } + + #[test] + fn test_mark_stale_ignores_other_worker() { + let on_a = insert("ns/a".to_string(), "10.0.0.1".to_string(), None, Duration::from_secs(5), MAX); + assert_eq!(mark_stale("ns/a", "10.0.0.2"), 0); + assert!(!on_a.is_stale()); + assert!(current("ns/a").is_some()); + } + + #[test] + fn test_marks_reach_entry_held_after_newer_binding_replaces_it() { + // A request still holds the worker-A entry after ext_proc learned worker B. + let old = insert("ns/a".to_string(), "10.0.0.1".to_string(), None, Duration::from_secs(5), MAX); + let new = insert("ns/a".to_string(), "10.0.0.2".to_string(), None, Duration::from_secs(5), MAX); + assert_eq!(mark_spoiled("ns/a", "10.0.0.1"), 1); + assert!(old.is_spoiled()); + assert!(!new.is_spoiled()); + // The current binding points at worker B, so a stale mark for A keeps it. + assert_eq!(mark_stale("ns/a", "10.0.0.1"), 1); + assert!(Rc::ptr_eq(¤t("ns/a").unwrap(), &new)); + } + + #[test] + fn test_marks_reach_every_live_entry_for_the_same_worker() { + // The actor moved away from worker A and back while a request held the old entry. + let first = insert("ns/a".to_string(), "10.0.0.1".to_string(), None, Duration::from_secs(5), MAX); + let second = insert("ns/a".to_string(), "10.0.0.1".to_string(), None, Duration::from_secs(5), MAX); + assert_eq!(mark_spoiled("ns/a", "10.0.0.1"), 2); + assert!(first.is_spoiled()); + assert!(second.is_spoiled()); + } + + #[test] + fn test_freed_entries_are_not_marked() { + let entry = insert("ns/a".to_string(), "10.0.0.1".to_string(), None, Duration::from_secs(5), MAX); + assert!(remove_if_current("ns/a", &entry)); + drop(entry); + assert_eq!(mark_stale("ns/a", "10.0.0.1"), 0); + } + + #[test] + fn test_sweep_drops_dead_live_slots() { + for i in 0..200 { + let key = format!("ns/actor-{i}"); + let entry = insert(key.clone(), "10.0.0.1".to_string(), None, Duration::from_secs(5), MAX); + remove_if_current(&key, &entry); + } + let live = CACHE.with_borrow(|cache| cache.live.len()); + assert!(live <= 65, "dead live slots were not swept: {live}"); + } + + fn fill(ttl: Duration) { + for i in 0..MAX { + insert(format!("ns/actor-{i}"), "10.0.0.1".to_string(), None, ttl, MAX); + } + } + + #[test] + fn test_full_cache_skips_new_actor_but_rebinds_known_ones() { + fill(Duration::from_secs(5)); + insert("ns/new".to_string(), "10.0.0.2".to_string(), None, Duration::from_secs(5), MAX); + assert!(current("ns/new").is_none()); + let rebound = insert("ns/actor-0".to_string(), "10.0.0.2".to_string(), None, Duration::from_secs(5), MAX); + assert!(Rc::ptr_eq(¤t("ns/actor-0").unwrap(), &rebound)); + assert_eq!(CACHE.with_borrow(|cache| cache.bindings.len()), MAX); + } + + #[test] + fn test_full_cache_drops_expired_bindings_to_make_room() { + fill(Duration::ZERO); + let entry = insert("ns/new".to_string(), "10.0.0.2".to_string(), None, Duration::from_secs(5), MAX); + assert!(Rc::ptr_eq(¤t("ns/new").unwrap(), &entry)); + assert_eq!(CACHE.with_borrow(|cache| cache.bindings.len()), 1); + } +} diff --git a/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/config.rs b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/config.rs new file mode 100644 index 0000000000..747d8cac09 --- /dev/null +++ b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/config.rs @@ -0,0 +1,128 @@ +// Copyright 2026 The Agent Substrate 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. + +//! Configuration types for the ingress-cache HTTP filter. + +use std::cell::RefCell; + +use envoy_proxy_dynamic_modules_rust_sdk::{ + EnvoyCounterId, EnvoyHttpFilter, HttpFilter, HttpFilterConfig, +}; +use serde::Deserialize; + +use crate::filter::{CacheFilter, CacheFilterState}; + +/// Default TTL in seconds for cached actor -> worker bindings. +pub const DEFAULT_CACHE_TTL_SECONDS: u64 = 5; + +/// Default port `atunnel` listens on at the worker. +pub const DEFAULT_ATUNNEL_PORT: u16 = 443; + +/// Default request header carrying the actor's target port to `atunnel`. +pub const DEFAULT_TARGET_PORT_HEADER: &str = "x-ate-target-port"; + +/// Default for the most actors each Envoy worker thread's cache binds. +pub const DEFAULT_MAX_CACHED_ACTORS: usize = 10_000; + +/// Filter configuration supplied as JSON in the Envoy HTTP filter config. +#[derive(Deserialize, Clone, Debug, PartialEq, Eq)] +#[serde(default)] +pub struct Config { + /// How long an actor -> worker binding may be served from cache. + pub cache_ttl_seconds: u64, + /// The port `atunnel` listens on at the worker. + pub atunnel_port: u16, + /// Header carrying the actor's target port to `atunnel`. + pub target_port_header: String, + /// The most actors cached per Envoy worker thread. Each thread has its own cache. + pub max_cached_actors: usize, +} + +impl Default for Config { + fn default() -> Self { + Self { + cache_ttl_seconds: DEFAULT_CACHE_TTL_SECONDS, + atunnel_port: DEFAULT_ATUNNEL_PORT, + target_port_header: DEFAULT_TARGET_PORT_HEADER.to_string(), + max_cached_actors: DEFAULT_MAX_CACHED_ACTORS, + } + } +} + +impl Config { + /// Parses filter configuration from raw JSON bytes, returning defaults when + /// the slice is empty or whitespace-only. + pub fn from_config(filter_config: &[u8]) -> Result { + let raw = std::str::from_utf8(filter_config).unwrap_or(""); + let json_str = if raw.trim().is_empty() { "{}" } else { raw }; + serde_json::from_str(json_str) + } +} + +/// Per-filter-chain configuration pairing parsed [`Config`] settings with +/// Envoy counter IDs registered at config creation time. +pub struct FilterConfig { + pub settings: Config, + pub cache_hit: Option, + pub cache_miss: Option, + pub cache_bypass: Option, + pub cache_eviction: Option, + pub cache_replay: Option, +} + +impl HttpFilterConfig for FilterConfig { + fn new_http_filter(&self, _envoy: &mut EHF) -> Box> { + Box::new(CacheFilter { + config: self.settings.clone(), + cache_hit: self.cache_hit, + cache_miss: self.cache_miss, + cache_bypass: self.cache_bypass, + cache_eviction: self.cache_eviction, + cache_replay: self.cache_replay, + state: RefCell::new(CacheFilterState::default()), + }) + } +} + +// ========================================== +// Tests +// ========================================== + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_config_defaults_and_overrides() { + assert_eq!(Config::from_config(b"").unwrap(), Config::default()); + assert_eq!(Config::from_config(b" ").unwrap(), Config::default()); + assert_eq!(Config::from_config(b"{}").unwrap(), Config::default()); + + let custom = Config::from_config( + br#"{"cache_ttl_seconds": 10, "atunnel_port": 8443, "target_port_header": "x-custom-port", "max_cached_actors": 500}"#, + ) + .unwrap(); + assert_eq!( + custom, + Config { + cache_ttl_seconds: 10, + atunnel_port: 8443, + target_port_header: "x-custom-port".to_string(), + max_cached_actors: 500, + } + ); + + assert!(Config::from_config(b"not-json").is_err()); + } +} diff --git a/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/filter.rs b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/filter.rs new file mode 100644 index 0000000000..8e7afc7084 --- /dev/null +++ b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/filter.rs @@ -0,0 +1,1497 @@ +// Copyright 2026 The Agent Substrate 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. + +//! HTTP filter implementation for the ingress-cache dynamic module. + +use std::cell::RefCell; +use std::net::SocketAddr; +use std::rc::Rc; +use std::time::{Duration, Instant}; + +use envoy_proxy_dynamic_modules_rust_sdk::{ + EnvoyCounterId, EnvoyHttpFilter, EnvoyHttpFilterConfig, HttpFilter, HttpFilterConfig, + abi::{ + envoy_dynamic_module_type_attribute_id, envoy_dynamic_module_type_metadata_source, + envoy_dynamic_module_type_on_http_filter_request_headers_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status, + envoy_dynamic_module_type_on_http_filter_response_trailers_status, + }, + envoy_log_error, envoy_log_trace, +}; + +use crate::cache::{self, Entry, Lookup}; +use crate::config::{Config, FilterConfig}; +use crate::routing::{ + CACHE_HIT_METADATA_KEY, CACHE_HIT_METADATA_NAMESPACE, CACHE_HIT_METADATA_VALUE, + GRPC_STATUS_HEADER, ORIGINAL_DST_ADDRESS_KEY, ORIGINAL_DST_NAMESPACE, STALE_ASSIGNMENT_HEADER, + TARGET_ACTOR_HEADER, WORKER_SPIFFE_ID_KEY, is_grpc_unavailable, request_header_str, + response_header_str, response_trailer_str, +}; + +/// Counter incremented when an unexpired actor -> worker binding is served from cache. +pub const CACHE_HIT_COUNTER: &str = "ate_ingress_cache.hit"; + +/// Counter incremented when no valid cached binding exists for the target actor. +pub const CACHE_MISS_COUNTER: &str = "ate_ingress_cache.miss"; + +/// Counter incremented when a request with a body skips the cache lookup and is +/// routed through `ext_proc`. +pub const CACHE_BYPASS_COUNTER: &str = "ate_ingress_cache.bypass"; + +/// Counter incremented when an expired or stale cache entry is evicted. +pub const CACHE_EVICTION_COUNTER: &str = "ate_ingress_cache.eviction"; + +/// Counter incremented when a stale fast-path request is replayed via `recreate_stream`. +pub const CACHE_REPLAY_COUNTER: &str = "ate_ingress_cache.replay"; + +/// Envoy core response flag: No healthy upstream (UH = 1 << 1). +pub const RESPONSE_FLAG_UH: i64 = 1 << 1; + +/// Envoy core response flag: Upstream remote reset (UR = 1 << 4). +pub const RESPONSE_FLAG_UR: i64 = 1 << 4; + +/// Envoy core response flag: Upstream connection failure (UF = 1 << 5). +pub const RESPONSE_FLAG_UF: i64 = 1 << 5; + +/// Envoy core response flag: Upstream connection termination (UC = 1 << 6). +pub const RESPONSE_FLAG_UC: i64 = 1 << 6; + +/// Mask of upstream flags that indicate a failure communicating with the upstream worker, +/// warranting cache eviction. +pub const UPSTREAM_FAILURE_RESPONSE_FLAGS: i64 = + RESPONSE_FLAG_UF | RESPONSE_FLAG_UH | RESPONSE_FLAG_UC | RESPONSE_FLAG_UR; + + +/// Mask of response flags that guarantee zero bytes reached the actor, +/// making replay safe for bodiless requests. +pub const ZERO_BYTE_FAILURE_RESPONSE_FLAGS: i64 = RESPONSE_FLAG_UF | RESPONSE_FLAG_UH; + +/// Prefix of the response code details Envoy's router sets when the upstream reset before +/// any response. After a 1xx it uses `upstream_reset_after_response_started`. +pub const EARLY_UPSTREAM_RESET_DETAILS: &str = "upstream_reset_before_response_started"; + + + +/// Creates a new HTTP filter configuration for the `ingress-cache` dynamic module. +pub fn new_http_filter_config_fn( + envoy_filter_config: &mut EC, + _filter_name: &str, + filter_config: &[u8], +) -> Option>> { + let config = Config::from_config(filter_config) + .map_err(|e| { + envoy_log_error!("ingress_cache: invalid filter config: {}", e); + }) + .ok()?; + + envoy_log_trace!("ingress_cache: ttl={}s", config.cache_ttl_seconds); + + Some(Box::new(FilterConfig { + cache_hit: envoy_filter_config.define_counter(CACHE_HIT_COUNTER).ok(), + cache_miss: envoy_filter_config.define_counter(CACHE_MISS_COUNTER).ok(), + cache_bypass: envoy_filter_config.define_counter(CACHE_BYPASS_COUNTER).ok(), + cache_eviction: envoy_filter_config + .define_counter(CACHE_EVICTION_COUNTER) + .ok(), + cache_replay: envoy_filter_config + .define_counter(CACHE_REPLAY_COUNTER) + .ok(), + settings: config, + })) +} + +/// Per-stream HTTP filter sitting ahead of `ext_proc` in the ingress filter chain. +/// +/// * **On a hit**: publishes dynamic metadata for `ORIGINAL_DST` / `actor_connect`, +/// sets the [`CACHE_HIT_METADATA_NAMESPACE`] dynamic metadata to select the route +/// with `ext_proc` disabled, and clears the route cache. +/// * **On a miss**: lets `ext_proc` run normally, then learns the resolved worker IP +/// from dynamic metadata in `on_response_headers`. +/// * **On a request with a body**: skips the cache lookup and routes through `ext_proc`, +/// since a stale hit couldn't be replayed. Learns from the response like a miss. +/// * **On upstream stale rejection (`421` or `503` on a cache hit)**: evicts the +/// stale cache entry and calls `recreate_stream` (if replay-safe). The recreated +/// stream starts without this stream's dynamic metadata, so it replays through +/// `ext_proc`. +/// A `503` from a connection that ended before a response is replay-safe only if +/// the `tunnel_watcher` network filter marked the entry stale and not spoiled. +/// * **On gRPC UNAVAILABLE (`grpc-status: 14`)**: does not learn the binding, and removes +/// it if it was learned from this response's headers. gRPC requests always have a body, +/// so they never use the cache. + +/// Per-stream mutable state of [`CacheFilter`], stored behind a [`RefCell`] +/// because Envoy 1.40's [`HttpFilter`] callbacks take `&self`. +#[derive(Default)] +pub struct CacheFilterState { + pub learn_key: Option, + pub actor_key: Option, + pub was_cache_hit: bool, + pub has_request_body: bool, + /// The entry this request was routed from on a cache hit. Holding it keeps the + /// entry, and the network filter's marks on it, alive until the request ends. + pub entry: Option>, + /// The entry this request's response added to the cache, if any. + pub learned: Option>, +} + +pub struct CacheFilter { + pub config: Config, + /// Counts bodiless requests served from an unexpired cache entry, skipping ext_proc. + pub cache_hit: Option, + /// Counts bodiless requests with no unexpired cache entry, resolved through ext_proc. + pub cache_miss: Option, + /// Counts requests with a body, which skip the cache lookup and go through ext_proc. + pub cache_bypass: Option, + /// Counts cache entries removed because they expired or a cache hit found them stale. + pub cache_eviction: Option, + /// Counts stale cache hits replayed through ext_proc with `recreate_stream`. + pub cache_replay: Option, + pub state: RefCell, +} + +impl CacheFilter { + /// Evicts the binding this request used or learned, if it is still current, and if this + /// stream was a cache hit, increments the eviction counter and clears the cache hit flag. + fn handle_eviction(&self, envoy_filter: &mut EHF) { + let was_cache_hit = { + let mut state = self.state.borrow_mut(); + if let (Some(key), Some(entry)) = ( + &state.actor_key, + state.entry.as_ref().or(state.learned.as_ref()), + ) { + cache::remove_if_current(key, entry); + } + let hit = state.was_cache_hit; + state.was_cache_hit = false; + hit + }; + if was_cache_hit { + increment_counter(envoy_filter, self.cache_eviction); + } + } + + #[cfg(test)] + pub(crate) fn new_test_filter(config: Config) -> Self { + Self { + config, + cache_hit: None, + cache_miss: None, + cache_bypass: None, + cache_eviction: None, + cache_replay: None, + state: RefCell::new(CacheFilterState::default()), + } + } +} + +/// Increments an optional Envoy counter by 1. +fn increment_counter(envoy_filter: &EHF, counter: Option) { + if let Some(id) = counter { + let _ = envoy_filter.increment_counter(id, 1); + } +} + +/// Reports whether the upstream response indicates a stale actor assignment or upstream failure. +fn is_stale_rejection( + envoy_filter: &EHF, + status: Option<&str>, + response_flags: i64, +) -> bool { + match status { + Some("421") => response_header_str(envoy_filter, STALE_ASSIGNMENT_HEADER) + .is_some_and(|val| val.eq_ignore_ascii_case("true")), + // With --upstream-connect enabled, atunnel's 421 CONNECT rejection or + // deactivated tunnel closure is surfaced by Envoy's internal tcp_proxy + // as an HTTP 503 response with upstream response flags (UF, UH, UC, or UR). + // An application 503 emitted directly by the actor has response_flags == 0. + Some("503") => (response_flags & UPSTREAM_FAILURE_RESPONSE_FLAGS) != 0, + _ => false, + } +} + +/// Reports whether a request that encountered a stale rejection can be safely replayed. +/// +/// Replay is safe if: +/// 1. The request has no body (`!state.has_request_body`). We do not buffer request +/// bodies in Envoy, so replaying a request with a body would drop or corrupt the payload. +/// Requests with a body skip the cache, so this is a defensive check. +/// 2. For 503 errors, response flags guarantee zero bytes reached the upstream worker (`UF` or `UH`), +/// or the connection ended before any response (`UC`, with early-reset details) and the +/// entry the request was routed from is stale and not spoiled. Stale means a tunnel for the +/// binding was refused; not spoiled means no request on it was cut off after reaching the +/// actor. A 1xx counts as a response: the actor got the request. +/// 3. For 421 errors (with stale header), atunnel rejected the request before forwarding to +/// the actor, so bodiless requests are safe to replay. +fn is_replay_safe( + envoy_filter: &EHF, + state: &CacheFilterState, + status: Option<&str>, + response_flags: i64, +) -> bool { + if state.has_request_body { + return false; + } + match status { + Some("503") => { + (response_flags & ZERO_BYTE_FAILURE_RESPONSE_FLAGS) != 0 + // On the CONNECT path a refused tunnel reaches the router as a connection + // termination (`UC`), like a tunnel cut off mid-request. The network filter's + // marks tell them apart. + || ((response_flags & RESPONSE_FLAG_UC) != 0 + && state.entry.as_ref().is_some_and(|e| e.refused_and_unspoiled()) + && envoy_filter + .get_attribute_string(envoy_dynamic_module_type_attribute_id::ResponseCodeDetails) + .is_some_and(|d| d.as_slice().starts_with(EARLY_UPSTREAM_RESET_DETAILS.as_bytes()))) + } + Some("421") => true, + _ => false, + } +} + +/// Extracts the resolved worker IP and optional SPIFFE ID from the `ORIGINAL_DST` +/// dynamic metadata published by `ext_proc`. +fn read_learned_binding( + envoy_filter: &EHF, +) -> Option<(String, Option)> { + let buf = envoy_filter.get_metadata_string( + envoy_dynamic_module_type_metadata_source::Dynamic, + ORIGINAL_DST_NAMESPACE, + ORIGINAL_DST_ADDRESS_KEY, + )?; + let addr = std::str::from_utf8(buf.as_slice()).ok()?; + let ip = addr.parse::().ok()?.ip().to_string(); + + let spiffe_id = envoy_filter + .get_metadata_string( + envoy_dynamic_module_type_metadata_source::Dynamic, + ORIGINAL_DST_NAMESPACE, + WORKER_SPIFFE_ID_KEY, + ) + .and_then(|b| { + let s = std::str::from_utf8(b.as_slice()).ok()?; + (!s.is_empty()).then(|| s.to_string()) + }); + + Some((ip, spiffe_id)) +} + +/// Reports whether the request may have a body, which a replay can't resend because Envoy +/// doesn't buffer it. A request is bodiless only if it ends with its headers or has +/// `content-length: 0`, so chunked requests and WS upgrades still count as having a body. +fn request_has_body(envoy_filter: &EHF, end_of_stream: bool) -> bool { + if end_of_stream { + return false; + } + request_header_str(envoy_filter, "content-length") + .map_or(true, |len| len.trim().parse::() != Ok(0)) +} + +impl HttpFilter for CacheFilter { + fn on_request_headers( + &self, + envoy_filter: &mut EHF, + end_of_stream: bool, + ) -> envoy_dynamic_module_type_on_http_filter_request_headers_status { + let has_request_body = request_has_body(envoy_filter, end_of_stream); + self.state.borrow_mut().has_request_body = has_request_body; + + let Some(actor) = self.config.resolve_actor_ref(envoy_filter) else { + return envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue; + }; + + let key = actor.cache_key(); + self.state.borrow_mut().actor_key = Some(key.clone()); + + // A stale hit can't be replayed for a request with a body, so the cache isn't worth + // the risk: route it through ext_proc. Its response still refreshes the cache. + if has_request_body { + increment_counter(envoy_filter, self.cache_bypass); + let mut state = self.state.borrow_mut(); + state.was_cache_hit = false; + state.learn_key = Some(key); + return envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue; + } + + match cache::lookup(&key, Instant::now()) { + Lookup::Hit(entry) => { + increment_counter(envoy_filter, self.cache_hit); + self.config.route_to( + envoy_filter, + &actor, + &entry.worker_ip, + entry.worker_spiffe_id.as_deref(), + ); + envoy_filter.set_dynamic_metadata_string( + CACHE_HIT_METADATA_NAMESPACE, + CACHE_HIT_METADATA_KEY, + CACHE_HIT_METADATA_VALUE, + ); + envoy_filter.clear_route_cache(); + let mut state = self.state.borrow_mut(); + state.was_cache_hit = true; + state.entry = Some(entry); + return envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue; + } + Lookup::Expired => increment_counter(envoy_filter, self.cache_eviction), + Lookup::Miss => {} + } + + increment_counter(envoy_filter, self.cache_miss); + let mut state = self.state.borrow_mut(); + state.was_cache_hit = false; + state.learn_key = Some(key); + envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue + } + + fn on_response_headers( + &self, + envoy_filter: &mut EHF, + _end_of_stream: bool, + ) -> envoy_dynamic_module_type_on_http_filter_response_headers_status { + let status_str = response_header_str(envoy_filter, ":status"); + let response_flags = envoy_filter + .get_attribute_int(envoy_dynamic_module_type_attribute_id::ResponseFlags) + .unwrap_or(0); + let stale_rejection = is_stale_rejection(envoy_filter, status_str.as_deref(), response_flags); + let grpc_unavailable = status_str.as_deref() == Some("200") + && response_header_str(envoy_filter, GRPC_STATUS_HEADER) + .as_deref() + .is_some_and(is_grpc_unavailable); + + if stale_rejection || grpc_unavailable { + let should_replay = { + let state = self.state.borrow(); + state.was_cache_hit + && stale_rejection + && is_replay_safe(envoy_filter, &state, status_str.as_deref(), response_flags) + }; + + self.handle_eviction(envoy_filter); + + // Only stale HTTP rejections (421 or 503 UF/UH/UC/UR) are replayed; gRPC UNAVAILABLE + // is returned directly to the client since gRPC clients handle retries. + if should_replay { + let actor_key = self.state.borrow().actor_key.clone(); + if let Some(key) = actor_key { + // Upstream route mutations strip TARGET_ACTOR_HEADER before forwarding to + // the actor tunnel. Re-inject it so the recreated stream passes the valid + // actor reference to ext_proc on replay. + envoy_filter.set_request_header(TARGET_ACTOR_HEADER, key.as_bytes()); + } + increment_counter(envoy_filter, self.cache_replay); + if envoy_filter.recreate_stream(None) { + return envoy_dynamic_module_type_on_http_filter_response_headers_status::StopIteration; + } + } + } + + // On a cache miss that succeeded upstream, learn from the metadata ext_proc published. + let learn_key = if !stale_rejection && !grpc_unavailable { + self.state.borrow_mut().learn_key.take() + } else { + None + }; + if let Some(key) = learn_key + && let Some((worker_ip, worker_spiffe_id)) = read_learned_binding(envoy_filter) + { + self.state.borrow_mut().learned = Some(cache::insert( + key, + worker_ip, + worker_spiffe_id, + Duration::from_secs(self.config.cache_ttl_seconds), + self.config.max_cached_actors, + )); + } + + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + } + + fn on_response_trailers( + &self, + envoy_filter: &mut EHF, + ) -> envoy_dynamic_module_type_on_http_filter_response_trailers_status { + if response_trailer_str(envoy_filter, GRPC_STATUS_HEADER) + .as_deref() + .is_some_and(is_grpc_unavailable) + { + self.handle_eviction(envoy_filter); + } + + envoy_dynamic_module_type_on_http_filter_response_trailers_status::Continue + } +} + +// ========================================== +// Tests +// ========================================== + +#[cfg(test)] +mod tests { + use super::*; + use crate::config::DEFAULT_MAX_CACHED_ACTORS; + use crate::routing::{ + ActorRef, CONNECT_AUTHORITY_FILTER_STATE_KEY, ORIGINAL_DST_PORT_KEY, + TARGET_ACTOR_FILTER_STATE_KEY, TARGET_ACTOR_HEADER, + }; + use envoy_proxy_dynamic_modules_rust_sdk::{EnvoyBuffer, MockEnvoyHttpFilter}; + + #[test] + fn test_cache_miss_and_learn_on_response() { + let config = Config::default(); + let filter = CacheFilter::new_test_filter(config.clone()); + + let target_actor = b"team-b/actor-2"; + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == TARGET_ACTOR_FILTER_STATE_KEY) + .returning(move |_| Some(EnvoyBuffer::new(target_actor))); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == CONNECT_AUTHORITY_FILTER_STATE_KEY) + .returning(|_| None); + mock + .expect_get_request_header_value() + .withf(|key| key == ":method") + .returning(|_| Some(EnvoyBuffer::new(b"GET"))); + mock + .expect_get_request_header_value() + .withf(|key| key == "content-length") + .returning(|_| None); + + let status = filter.on_request_headers(&mut mock, false); + assert_eq!( + status, + envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue + ); + assert_eq!(filter.state.borrow().learn_key.as_deref(), Some("team-b/actor-2")); + assert!(!filter.state.borrow().was_cache_hit); + + // Response headers arrive: learning worker address from dynamic metadata + let metadata_local = b"10.244.1.50:443"; + let metadata_spiffe = b"spiffe://cluster.local/ns/default/sa/worker-pool-1"; + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"200"))); + mock + .expect_get_response_header_value() + .withf(|key| key == GRPC_STATUS_HEADER) + .returning(|_| None); + mock.expect_get_attribute_int().returning(|_| None); + mock + .expect_get_metadata_string() + .withf(|src, ns, key| { + *src == envoy_dynamic_module_type_metadata_source::Dynamic + && ns == ORIGINAL_DST_NAMESPACE + && key == ORIGINAL_DST_ADDRESS_KEY + }) + .returning(move |_, _, _| Some(EnvoyBuffer::new(metadata_local))); + mock + .expect_get_metadata_string() + .withf(|src, ns, key| { + *src == envoy_dynamic_module_type_metadata_source::Dynamic + && ns == ORIGINAL_DST_NAMESPACE + && key == WORKER_SPIFFE_ID_KEY + }) + .returning(move |_, _, _| Some(EnvoyBuffer::new(metadata_spiffe))); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + + // Verify entry is now in cache + let entry = cache::current("team-b/actor-2").expect("should be in cache"); + assert_eq!(entry.worker_ip, "10.244.1.50"); + assert_eq!( + entry.worker_spiffe_id.as_deref(), + Some("spiffe://cluster.local/ns/default/sa/worker-pool-1") + ); + } + + #[test] + fn test_request_with_body_bypasses_cache_and_learns() { + let key = "team-b/actor-body"; + let _entry = cache::insert(key.to_string(), "10.244.9.1".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let mut filter = CacheFilter::new_test_filter(Config::default()); + let bypass_id = EnvoyCounterId(7); + filter.cache_bypass = Some(bypass_id); + + // The mock panics on any unexpected call, so a cache hit (route_to setting metadata + // and headers) would fail the test. + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_filter_state_bytes() + .withf(|k| k == TARGET_ACTOR_FILTER_STATE_KEY) + .returning(move |_| Some(EnvoyBuffer::new(key.as_bytes()))); + mock + .expect_get_filter_state_bytes() + .withf(|k| k == CONNECT_AUTHORITY_FILTER_STATE_KEY) + .returning(|_| None); + mock + .expect_get_request_header_value() + .withf(|k| k == ":method") + .returning(|_| Some(EnvoyBuffer::new(b"POST"))); + mock + .expect_get_request_header_value() + .withf(|k| k == "content-length") + .returning(|_| Some(EnvoyBuffer::new(b"12"))); + mock + .expect_increment_counter() + .withf(move |id, val| *id == bypass_id && *val == 1) + .times(1) + .returning(|_, _| Ok(())); + + let status = filter.on_request_headers(&mut mock, false); + assert_eq!( + status, + envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue + ); + assert!(filter.state.borrow().has_request_body); + assert!(!filter.state.borrow().was_cache_hit); + assert_eq!(filter.state.borrow().learn_key.as_deref(), Some(key)); + + // ext_proc resolved a different worker: the response refreshes the cached binding. + mock + .expect_get_response_header_value() + .withf(|k| k == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"200"))); + mock + .expect_get_response_header_value() + .withf(|k| k == GRPC_STATUS_HEADER) + .returning(|_| None); + mock.expect_get_attribute_int().returning(|_| None); + mock + .expect_get_metadata_string() + .withf(|src, ns, k| { + *src == envoy_dynamic_module_type_metadata_source::Dynamic + && ns == ORIGINAL_DST_NAMESPACE + && k == ORIGINAL_DST_ADDRESS_KEY + }) + .returning(|_, _, _| Some(EnvoyBuffer::new(b"10.244.9.2:443"))); + mock + .expect_get_metadata_string() + .withf(|src, ns, k| { + *src == envoy_dynamic_module_type_metadata_source::Dynamic + && ns == ORIGINAL_DST_NAMESPACE + && k == WORKER_SPIFFE_ID_KEY + }) + .returning(|_, _, _| None); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert_eq!(cache::current(key).expect("should be cached").worker_ip, "10.244.9.2"); + } + + #[test] + fn test_cache_hit_populates_metadata_and_skips_extproc() { + let config = Config::default(); + let _entry = cache::insert("team-c/actor-3".to_string(), "10.244.2.100".to_string(), Some("spiffe://cluster.local/ns/default/sa/worker-pool-2".to_string()), Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + + let target_actor = b"team-c/actor-3"; + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == TARGET_ACTOR_FILTER_STATE_KEY) + .returning(|_| None); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == CONNECT_AUTHORITY_FILTER_STATE_KEY) + .returning(|_| None); + mock + .expect_get_request_header_values() + .withf(|key| key == TARGET_ACTOR_HEADER) + .returning(move |_| vec![EnvoyBuffer::new(target_actor)]); + mock + .expect_get_request_header_value() + .withf(|key| key == ":method") + .returning(|_| Some(EnvoyBuffer::new(b"GET"))); + mock + .expect_get_request_header_value() + .withf(|key| key == "content-length") + .returning(|_| None); + + mock + .expect_set_dynamic_metadata_string() + .withf(|ns, key, val| { + ns == ORIGINAL_DST_NAMESPACE && key == ORIGINAL_DST_ADDRESS_KEY && val == "10.244.2.100:443" + }) + .returning(|_, _, _| ()); + mock + .expect_set_dynamic_metadata_string() + .withf(|ns, key, val| { + ns == ORIGINAL_DST_NAMESPACE && key == ORIGINAL_DST_PORT_KEY && val == "80" + }) + .returning(|_, _, _| ()); + mock + .expect_set_dynamic_metadata_string() + .withf(|ns, key, val| { + ns == ORIGINAL_DST_NAMESPACE + && key == WORKER_SPIFFE_ID_KEY + && val == "spiffe://cluster.local/ns/default/sa/worker-pool-2" + }) + .returning(|_, _, _| ()); + mock + .expect_set_request_header() + .withf(|key, val| key == "x-ate-target-port" && val == b"80") + .returning(|_, _| true); + mock + .expect_set_request_header() + .withf(|key, val| key == TARGET_ACTOR_HEADER && val == b"team-c/actor-3") + .returning(|_, _| true); + mock + .expect_set_dynamic_metadata_string() + .withf(|ns, key, val| { + ns == CACHE_HIT_METADATA_NAMESPACE + && key == CACHE_HIT_METADATA_KEY + && val == CACHE_HIT_METADATA_VALUE + }) + .times(1) + .returning(|_, _, _| ()); + mock.expect_clear_route_cache().returning(|| ()); + + let status = filter.on_request_headers(&mut mock, true); + assert_eq!( + status, + envoy_dynamic_module_type_on_http_filter_request_headers_status::Continue + ); + assert!(filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_421_recreates_stream_on_cache_hit() { + let config = Config::default(); + let entry = cache::insert("team-d/actor-4".to_string(), "10.244.3.40".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-d/actor-4".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"421"))); + mock + .expect_get_response_header_value() + .withf(|key| key == STALE_ASSIGNMENT_HEADER) + .returning(|_| Some(EnvoyBuffer::new(b"true"))); + mock.expect_get_attribute_int().returning(|_| None); + mock + .expect_set_request_header() + .withf(|key, val| key == TARGET_ACTOR_HEADER && val == b"team-d/actor-4") + .returning(|_, _| true); + mock.expect_recreate_stream().returning(|_| true); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::StopIteration + ); + + assert!(cache::current("team-d/actor-4").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_503_recreates_stream_on_cache_hit() { + let config = Config::default(); + let entry = cache::insert("team-d/actor-4-503".to_string(), "10.244.3.41".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-d/actor-4-503".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + mock + .expect_get_attribute_int() + .returning(|_| Some(RESPONSE_FLAG_UF)); + mock + .expect_set_request_header() + .withf(|key, val| key == TARGET_ACTOR_HEADER && val == b"team-d/actor-4-503") + .returning(|_, _| true); + mock.expect_recreate_stream().returning(|_| true); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::StopIteration + ); + + assert!(cache::current("team-d/actor-4-503").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_421_does_not_loop_on_cache_miss() { + let config = Config::default(); + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().learn_key = Some("team-e/actor-5".to_string()); + filter.state.borrow_mut().actor_key = Some("team-e/actor-5".to_string()); + filter.state.borrow_mut().was_cache_hit = false; + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"421"))); + mock + .expect_get_response_header_value() + .withf(|key| key == STALE_ASSIGNMENT_HEADER) + .returning(|_| Some(EnvoyBuffer::new(b"true"))); + mock.expect_get_attribute_int().returning(|_| None); + + // recreate_stream and metadata learning should NOT be called on a 421 cache miss! + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-e/actor-5").is_none()); + } + + #[test] + fn test_upstream_421_without_stale_header_is_not_treated_as_stale() { + let config = Config::default(); + let entry = cache::insert("team-h/actor-8".to_string(), "10.244.5.10".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-h/actor-8".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"421"))); + // No STALE_ASSIGNMENT_HEADER on the response (e.g. actor application returned 421). + mock + .expect_get_response_header_value() + .withf(|key| key == STALE_ASSIGNMENT_HEADER) + .returning(|_| None); + mock.expect_get_attribute_int().returning(|_| None); + + // recreate_stream must NOT be called, and cache must NOT be evicted. + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-h/actor-8").is_some()); + assert!(filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_421_with_false_stale_header_is_not_treated_as_stale() { + let config = Config::default(); + let entry = cache::insert("team-h/actor-9".to_string(), "10.244.5.11".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-h/actor-9".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"421"))); + mock + .expect_get_response_header_value() + .withf(|key| key == STALE_ASSIGNMENT_HEADER) + .returning(|_| Some(EnvoyBuffer::new(b"false"))); + mock.expect_get_attribute_int().returning(|_| None); + + // recreate_stream must NOT be called, and cache must NOT be evicted. + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-h/actor-9").is_some()); + assert!(filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_421_with_case_insensitive_true_stale_header() { + let config = Config::default(); + let entry = cache::insert("team-h/actor-10".to_string(), "10.244.5.12".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-h/actor-10".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"421"))); + mock + .expect_get_response_header_value() + .withf(|key| key == STALE_ASSIGNMENT_HEADER) + .returning(|_| Some(EnvoyBuffer::new(b"TRUE"))); + mock.expect_get_attribute_int().returning(|_| None); + mock + .expect_set_request_header() + .withf(|key, val| key == TARGET_ACTOR_HEADER && val == b"team-h/actor-10") + .returning(|_, _| true); + mock.expect_recreate_stream().returning(|_| true); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::StopIteration + ); + assert!(cache::current("team-h/actor-10").is_none()); + } + + #[test] + fn test_upstream_503_from_actor_is_not_treated_as_stale() { + let config = Config::default(); + let entry = cache::insert("team-j/actor-11".to_string(), "10.244.6.1".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-j/actor-11".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + // Actor's own 503 has no upstream connection flags set (flags == 0). + mock.expect_get_attribute_int().returning(|_| Some(0)); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + // Cache entry must remain intact, and hit status must not be cleared. + assert!(cache::current("team-j/actor-11").is_some()); + assert!(filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_503_with_uh_recreates_stream_for_bodiless_get() { + let config = Config::default(); + let entry = cache::insert("team-j/actor-12".to_string(), "10.244.6.2".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-j/actor-12".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + filter.state.borrow_mut().has_request_body = false; + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + // No healthy upstream (UH) flag set by Envoy. Zero bytes were sent. + mock + .expect_get_attribute_int() + .returning(|_| Some(RESPONSE_FLAG_UH)); + mock + .expect_set_request_header() + .withf(|key, val| key == TARGET_ACTOR_HEADER && val == b"team-j/actor-12") + .returning(|_, _| true); + mock.expect_recreate_stream().returning(|_| true); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::StopIteration + ); + assert!(cache::current("team-j/actor-12").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + /// Sets up a bodiless cache hit on `key` -> `ip` and returns the filter and the entry it was + /// routed from. + fn hit_with_503(key: &str, ip: &str) -> (CacheFilter, Rc) { + let entry = cache::insert(key.to_string(), ip.to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + let filter = CacheFilter::new_test_filter(Config::default()); + filter.state.borrow_mut().actor_key = Some(key.to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + (filter, entry) + } + + fn mock_503(flags: i64) -> MockEnvoyHttpFilter { + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + mock.expect_get_attribute_int().returning(move |_| Some(flags)); + mock + } + + fn expect_code_details(mock: &mut MockEnvoyHttpFilter, details: &'static [u8]) { + mock + .expect_get_attribute_string() + .withf(|id| *id == envoy_dynamic_module_type_attribute_id::ResponseCodeDetails) + .returning(move |_| Some(EnvoyBuffer::new(details))); + } + + #[test] + fn test_upstream_503_uc_replays_when_entry_is_stale_and_unspoiled() { + let (filter, entry) = hit_with_503("team-k/actor-1", "10.244.7.1"); + // The network filter saw a tunnel for this binding refused. + assert_eq!(cache::mark_stale("team-k/actor-1", "10.244.7.1"), 1); + + let mut mock = mock_503(RESPONSE_FLAG_UC); + expect_code_details( + &mut mock, + b"upstream_reset_before_response_started{connection_termination}", + ); + mock + .expect_set_request_header() + .withf(|key, val| key == TARGET_ACTOR_HEADER && val == b"team-k/actor-1") + .returning(|_, _| true); + mock.expect_recreate_stream().times(1).returning(|_| true); + + let status = filter.on_response_headers(&mut mock, false); + assert_eq!( + status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::StopIteration + ); + assert!(entry.is_stale()); + assert!(cache::current("team-k/actor-1").is_none()); + } + + #[test] + fn test_upstream_503_uc_does_not_replay_after_a_1xx() { + // The actor sent a 1xx, so it got the request, but its connection doesn't spoil the entry. + let (filter, _entry) = hit_with_503("team-k/actor-6", "10.244.7.6"); + cache::mark_stale("team-k/actor-6", "10.244.7.6"); + + let mut mock = mock_503(RESPONSE_FLAG_UC); + expect_code_details( + &mut mock, + b"upstream_reset_after_response_started{connection_termination}", + ); + let status = filter.on_response_headers(&mut mock, false); + assert_eq!( + status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + } + + #[test] + fn test_upstream_503_ur_does_not_replay_even_when_entry_is_stale() { + // UR can follow response bytes the network filter counted as an answer, so only UC + // replays on the network filter's marks. + let (filter, _entry) = hit_with_503("team-k/actor-2", "10.244.7.2"); + cache::mark_stale("team-k/actor-2", "10.244.7.2"); + + let mut mock = mock_503(RESPONSE_FLAG_UR); + let status = filter.on_response_headers(&mut mock, false); + assert_eq!( + status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + } + + #[test] + fn test_upstream_503_uc_does_not_replay_when_entry_is_spoiled() { + let (filter, _entry) = hit_with_503("team-k/actor-3", "10.244.7.3"); + // A refusal and a mid-flight drop on the same binding: some request may have run. + cache::mark_stale("team-k/actor-3", "10.244.7.3"); + cache::mark_spoiled("team-k/actor-3", "10.244.7.3"); + + // recreate_stream has no expectation, so calling it fails the test. + let mut mock = mock_503(RESPONSE_FLAG_UC); + let status = filter.on_response_headers(&mut mock, false); + assert_eq!( + status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + } + + #[test] + fn test_upstream_503_uc_does_not_replay_when_entry_is_spoiled_but_not_stale() { + let (filter, _entry) = hit_with_503("team-k/actor-4", "10.244.7.4"); + cache::mark_spoiled("team-k/actor-4", "10.244.7.4"); + + let mut mock = mock_503(RESPONSE_FLAG_UC); + let status = filter.on_response_headers(&mut mock, false); + assert_eq!( + status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-k/actor-4").is_none()); + } + + #[test] + fn test_eviction_leaves_binding_learned_by_another_request() { + let (filter, _old) = hit_with_503("team-k/actor-5", "10.244.7.5"); + // Another request already learned the actor's new worker. + let newer = cache::insert( + "team-k/actor-5".to_string(), + "10.244.7.50".to_string(), + None, + Duration::from_secs(5), + DEFAULT_MAX_CACHED_ACTORS, + ); + + let mut mock = mock_503(RESPONSE_FLAG_UC); + filter.on_response_headers(&mut mock, false); + assert!(Rc::ptr_eq(&cache::current("team-k/actor-5").unwrap(), &newer)); + } + + #[test] + fn test_upstream_503_with_uh_does_not_replay_when_request_has_body() { + let config = Config::default(); + let entry = cache::insert("team-j/actor-12-body".to_string(), "10.244.6.22".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-j/actor-12-body".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + filter.state.borrow_mut().has_request_body = true; + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + mock + .expect_get_attribute_int() + .returning(|_| Some(RESPONSE_FLAG_UH)); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-j/actor-12-body").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_503_with_uc_does_not_replay_when_request_has_body() { + let config = Config::default(); + let entry = cache::insert("team-j/actor-13".to_string(), "10.244.6.3".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-j/actor-13".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + filter.state.borrow_mut().has_request_body = true; + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + // UpstreamConnectionTermination (UC) flag set by Envoy. + mock + .expect_get_attribute_int() + .returning(|_| Some(RESPONSE_FLAG_UC)); + mock + .expect_get_buffered_request_body_size() + .returning(|| 128); + + // Because the request has a body (and bodies are not buffered in memory), recreate_stream must NOT be called. + // However, the dead worker binding must still be evicted! + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-j/actor-13").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_503_uc_does_not_replay_when_entry_is_not_marked() { + let config = Config::default(); + let entry = cache::insert("team-j/actor-14".to_string(), "10.244.6.4".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-j/actor-14".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + filter.state.borrow_mut().has_request_body = false; + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + // UpstreamConnectionTermination (UC) flag set by Envoy. + mock + .expect_get_attribute_int() + .returning(|_| Some(RESPONSE_FLAG_UC)); + + // No refusal marked the entry stale, so the UC may be a tunnel cut off after the actor + // got the request. It is evicted, but not replayed. + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-j/actor-14").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_503_with_ur_does_not_replay() { + let config = Config::default(); + let entry = cache::insert("team-j/actor-14-ur".to_string(), "10.244.6.41".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-j/actor-14-ur".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + filter.state.borrow_mut().has_request_body = false; + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + // UpstreamRemoteReset (UR) flag set by Envoy. + mock + .expect_get_attribute_int() + .returning(|_| Some(RESPONSE_FLAG_UR)); + + // UR is evicted but not replayed. + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-j/actor-14-ur").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_stale_rejection_does_not_replay_when_request_has_body() { + let config = Config::default(); + let entry = cache::insert("team-j/actor-15".to_string(), "10.244.6.5".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-j/actor-15".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + filter.state.borrow_mut().has_request_body = true; // Request had body (e.g. POST) + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"503"))); + mock + .expect_get_attribute_int() + .returning(|_| Some(RESPONSE_FLAG_UF)); + + // Because request has body (and we do not buffer bodies), recreate_stream must NOT be called. + // The dead worker binding must still be evicted. + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-j/actor-15").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_upstream_421_with_body_does_not_replay() { + let config = Config::default(); + let entry = cache::insert("team-j/actor-16-421".to_string(), "10.244.6.7".to_string(), None, Duration::from_secs(5), DEFAULT_MAX_CACHED_ACTORS); + + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().actor_key = Some("team-j/actor-16-421".to_string()); + filter.state.borrow_mut().was_cache_hit = true; + filter.state.borrow_mut().entry = Some(entry.clone()); + filter.state.borrow_mut().has_request_body = true; // Request has body + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"421"))); + mock + .expect_get_response_header_value() + .withf(|key| key == STALE_ASSIGNMENT_HEADER) + .returning(|_| Some(EnvoyBuffer::new(b"true"))); + mock.expect_get_attribute_int().returning(|_| None); + + // 421 with body: evict cache, do not replay! + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-j/actor-16-421").is_none()); + assert!(!filter.state.borrow().was_cache_hit); + } + + #[test] + fn test_on_request_headers_tracks_request_body() { + let config = Config::default(); + + // 1. Request with end_of_stream: true (no body) + let filter = CacheFilter::new_test_filter(config.clone()); + let mut mock = MockEnvoyHttpFilter::default(); + mock.expect_get_filter_state_bytes().returning(|_| None); + mock + .expect_get_request_header_values() + .returning(|_| vec![]); + filter.on_request_headers(&mut mock, true); + assert!(!filter.state.borrow().has_request_body); + + // 2. Request with end_of_stream: false, content-length: 100 (has body) + let filter = CacheFilter::new_test_filter(config.clone()); + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_request_header_value() + .withf(|key| key == "content-length") + .returning(|_| Some(EnvoyBuffer::new(b"100"))); + mock.expect_get_filter_state_bytes().returning(|_| None); + mock + .expect_get_request_header_values() + .returning(|_| vec![]); + filter.on_request_headers(&mut mock, false); + assert!(filter.state.borrow().has_request_body); + + // 3. Request with end_of_stream: false, content-length: 0 (empty body) + let filter = CacheFilter::new_test_filter(config.clone()); + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_request_header_value() + .withf(|key| key == "content-length") + .returning(|_| Some(EnvoyBuffer::new(b"0"))); + mock.expect_get_filter_state_bytes().returning(|_| None); + mock + .expect_get_request_header_values() + .returning(|_| vec![]); + filter.on_request_headers(&mut mock, false); + assert!(!filter.state.borrow().has_request_body); + + // 4. A GET or HEAD without end_of_stream or content-length may carry a body (a chunked + // or HTTP/2 GET, or an upgrade), so it counts as having one. + for method in [b"GET".as_slice(), b"HEAD".as_slice()] { + let filter = CacheFilter::new_test_filter(config.clone()); + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_request_header_value() + .withf(|key| key == "content-length") + .returning(|_| None); + mock + .expect_get_request_header_value() + .withf(|key| key == ":method") + .returning(move |_| Some(EnvoyBuffer::new(method))); + mock.expect_get_filter_state_bytes().returning(|_| None); + mock + .expect_get_request_header_values() + .returning(|_| vec![]); + filter.on_request_headers(&mut mock, false); + assert!(filter.state.borrow().has_request_body); + } + + // 5. An unparsable content-length counts as a body. + let filter = CacheFilter::new_test_filter(config); + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_request_header_value() + .withf(|key| key == "content-length") + .returning(|_| Some(EnvoyBuffer::new(b"abc"))); + mock.expect_get_filter_state_bytes().returning(|_| None); + mock + .expect_get_request_header_values() + .returning(|_| vec![]); + filter.on_request_headers(&mut mock, false); + assert!(filter.state.borrow().has_request_body); + } + + #[test] + fn test_ipv6_learning_and_routing() { + let config = Config::default(); + let filter = CacheFilter::new_test_filter(config.clone()); + filter.state.borrow_mut().learn_key = Some("team-f/actor-6".to_string()); + filter.state.borrow_mut().was_cache_hit = false; + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .returning(|_| Some(EnvoyBuffer::new(b"200"))); + mock.expect_get_attribute_int().returning(|_| None); + mock + .expect_get_metadata_string() + .withf(|source, ns, key| { + *source == envoy_dynamic_module_type_metadata_source::Dynamic + && ns == ORIGINAL_DST_NAMESPACE + && key == ORIGINAL_DST_ADDRESS_KEY + }) + .returning(|_, _, _| Some(EnvoyBuffer::new(b"[2001:db8::1]:443"))); + mock + .expect_get_metadata_string() + .withf(|source, ns, key| { + *source == envoy_dynamic_module_type_metadata_source::Dynamic + && ns == ORIGINAL_DST_NAMESPACE + && key == WORKER_SPIFFE_ID_KEY + }) + .returning(|_, _, _| None); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + + let entry = cache::current("team-f/actor-6").expect("entry should be cached"); + assert_eq!(entry.worker_ip, "2001:db8::1"); + assert_eq!(entry.worker_spiffe_id, None); + drop(entry); + + let actor = ActorRef { + atespace: "team-f".to_string(), + name: "actor-6".to_string(), + target_port: 8080, + }; + let mut route_mock = MockEnvoyHttpFilter::default(); + route_mock + .expect_set_dynamic_metadata_string() + .withf(|ns, key, val| { + ns == ORIGINAL_DST_NAMESPACE + && key == ORIGINAL_DST_ADDRESS_KEY + && val == "[2001:db8::1]:443" + }) + .returning(|_, _, _| ()); + route_mock + .expect_set_dynamic_metadata_string() + .withf(|ns, key, val| { + ns == ORIGINAL_DST_NAMESPACE && key == ORIGINAL_DST_PORT_KEY && val == "8080" + }) + .returning(|_, _, _| ()); + route_mock + .expect_set_request_header() + .withf(|key, val| key == "x-ate-target-port" && val == b"8080") + .returning(|_, _| true); + route_mock + .expect_set_request_header() + .withf(|key, val| key == TARGET_ACTOR_HEADER && val == b"team-f/actor-6") + .returning(|_, _| true); + + config.route_to(&mut route_mock, &actor, "2001:db8::1", None); + } + + #[test] + fn test_grpc_status_14_on_cache_miss_in_headers_does_not_learn() { + let config = Config::default(); + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().learn_key = Some("team-grpc/actor-miss-h".to_string()); + filter.state.borrow_mut().actor_key = Some("team-grpc/actor-miss-h".to_string()); + filter.state.borrow_mut().was_cache_hit = false; + + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"200"))); + mock + .expect_get_response_header_value() + .withf(|key| key == GRPC_STATUS_HEADER) + .returning(|_| Some(EnvoyBuffer::new(b"14"))); + mock.expect_get_attribute_int().returning(|_| None); + + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + // Entry must NOT have been inserted into cache + assert!(cache::current("team-grpc/actor-miss-h").is_none()); + } + + #[test] + fn test_grpc_status_14_on_cache_miss_in_trailers_removes_learned_binding() { + let config = Config::default(); + let filter = CacheFilter::new_test_filter(config); + filter.state.borrow_mut().learn_key = Some("team-grpc/actor-miss-t".to_string()); + filter.state.borrow_mut().actor_key = Some("team-grpc/actor-miss-t".to_string()); + filter.state.borrow_mut().was_cache_hit = false; + + let metadata_local = b"10.244.6.7:443"; + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_response_header_value() + .withf(|key| key == ":status") + .returning(|_| Some(EnvoyBuffer::new(b"200"))); + mock + .expect_get_response_header_value() + .withf(|key| key == GRPC_STATUS_HEADER) + .returning(|_| None); + mock.expect_get_attribute_int().returning(|_| None); + mock + .expect_get_metadata_string() + .withf(|src, ns, key| { + *src == envoy_dynamic_module_type_metadata_source::Dynamic + && ns == ORIGINAL_DST_NAMESPACE + && key == ORIGINAL_DST_ADDRESS_KEY + }) + .returning(move |_, _, _| Some(EnvoyBuffer::new(metadata_local))); + mock + .expect_get_metadata_string() + .withf(|src, ns, key| { + *src == envoy_dynamic_module_type_metadata_source::Dynamic + && ns == ORIGINAL_DST_NAMESPACE + && key == WORKER_SPIFFE_ID_KEY + }) + .returning(|_, _, _| None); + + // On headers, learning succeeds + let resp_status = filter.on_response_headers(&mut mock, false); + assert_eq!( + resp_status, + envoy_dynamic_module_type_on_http_filter_response_headers_status::Continue + ); + assert!(cache::current("team-grpc/actor-miss-t").is_some()); + + // When trailers arrive with grpc-status: 14, the failed binding is removed + mock + .expect_get_response_trailer_value() + .withf(|key| key == GRPC_STATUS_HEADER) + .returning(|_| Some(EnvoyBuffer::new(b"14"))); + + let trailer_status = filter.on_response_trailers(&mut mock); + assert_eq!( + trailer_status, + envoy_dynamic_module_type_on_http_filter_response_trailers_status::Continue + ); + assert!(cache::current("team-grpc/actor-miss-t").is_none()); + } +} diff --git a/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/lib.rs b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/lib.rs new file mode 100644 index 0000000000..c9932865cd --- /dev/null +++ b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/lib.rs @@ -0,0 +1,53 @@ +// Copyright 2026 The Agent Substrate 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. + +//! The ingress-cache dynamic module provides an HTTP filter that caches +//! actor -> worker bindings to bypass `ext_proc` on warm ingress paths, and the +//! `tunnel_watcher` network filter that marks cache entries from what +//! happens to the CONNECT tunnels they route to. Both filters live in this one +//! library so they share its per-thread cache. + +pub mod cache; +pub mod config; +pub mod filter; +pub mod routing; +pub mod tunnel_watcher; + +pub use cache::*; +pub use config::*; +use envoy_proxy_dynamic_modules_rust_sdk::declare_all_init_functions; +pub use filter::*; +pub use routing::*; +pub use tunnel_watcher::*; + +declare_all_init_functions!( + init, + http: filter::new_http_filter_config_fn, + network: tunnel_watcher::new_network_filter_config_fn, +); + +/// Called when the dynamic module is loaded into Envoy. +fn init() -> bool { + true +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_init() { + assert!(init()); + } +} diff --git a/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/routing.rs b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/routing.rs new file mode 100644 index 0000000000..5c31de7cc8 --- /dev/null +++ b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/routing.rs @@ -0,0 +1,314 @@ +// Copyright 2026 The Agent Substrate 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. + +//! Actor identity resolution and routing metadata helpers for ingress requests. + +use std::num::NonZeroU16; + +use envoy_proxy_dynamic_modules_rust_sdk::EnvoyHttpFilter; + +use crate::config::Config; + +/// Filter-state key carrying the ingress actor routing target (`/`) +/// across Envoy's `CONNECT` internal-listener hop. +pub const TARGET_ACTOR_FILTER_STATE_KEY: &[u8] = b"dev.ate.target.actor"; + +/// Filter-state key carrying the outer `CONNECT` `:authority` across the +/// internal-listener hop. +pub const CONNECT_AUTHORITY_FILTER_STATE_KEY: &[u8] = b"dev.ate.connect.authority"; + +/// Header identifying the actor selected for ingress routing as `/`. +pub const TARGET_ACTOR_HEADER: &str = "ate-target-actor"; + +/// Default actor port when a request does not specify a custom `CONNECT` port. +pub const DEFAULT_ACTOR_PORT: u16 = 80; + +/// Dynamic-metadata namespace and keys read by Envoy's `ORIGINAL_DST` cluster +/// and `actor_connect` upstream tunnel. +pub const ORIGINAL_DST_NAMESPACE: &str = "envoy.filters.listener.original_dst"; +pub const ORIGINAL_DST_ADDRESS_KEY: &str = "local"; +pub const ORIGINAL_DST_PORT_KEY: &str = "port"; +pub const WORKER_SPIFFE_ID_KEY: &str = "worker_spiffe_id"; + +/// Dynamic metadata set on a cache hit so the route table selects the cached route, +/// which has `ext_proc` disabled. Clients can't set dynamic metadata. +pub const CACHE_HIT_METADATA_NAMESPACE: &str = "ate.ingress_cache"; +pub const CACHE_HIT_METADATA_KEY: &str = "hit"; +pub const CACHE_HIT_METADATA_VALUE: &str = "true"; + +/// Response header set by `atunnel` when a request arrives for an actor not +/// hosted on that worker. +pub const STALE_ASSIGNMENT_HEADER: &str = "x-ate-assignment-stale"; + +/// Response header or trailer carrying the gRPC status code. +pub const GRPC_STATUS_HEADER: &str = "grpc-status"; + +/// gRPC status code indicating UNAVAILABLE (`14`). +pub const GRPC_STATUS_UNAVAILABLE: &str = "14"; + +/// An actor reference parsed from a request's routing metadata or headers. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct ActorRef { + pub atespace: String, + pub name: String, + pub target_port: u16, +} + +impl ActorRef { + /// Returns the canonical `/` cache key for this actor. + pub fn cache_key(&self) -> String { + format!("{}/{}", self.atespace, self.name) + } +} + +/// Checks that `name` is a valid RFC-1123 DNS label (`[a-z0-9]([-a-z0-9]*[a-z0-9])?`, +/// 1..=63 characters), matching `resources.IsValidResourceName`. +pub fn is_valid_resource_name(name: &str) -> bool { + (1..=63).contains(&name.len()) + && !name.starts_with('-') + && !name.ends_with('-') + && name + .bytes() + .all(|b| b.is_ascii_lowercase() || b.is_ascii_digit() || b == b'-') +} + +/// Reads a UTF-8 filter-state value by `key`, treating empty values and Envoy's +/// `"-"` unset sentinel as `None`. +fn filter_state_str(envoy_filter: &EHF, key: &[u8]) -> Option { + let buf = envoy_filter.get_filter_state_bytes(key)?; + let s = std::str::from_utf8(buf.as_slice()).ok()?; + (!s.is_empty() && s != "-").then(|| s.to_string()) +} + +/// Reads a single request header value as a UTF-8 `String`. +pub(crate) fn request_header_str( + envoy_filter: &EHF, + key: &str, +) -> Option { + let buf = envoy_filter.get_request_header_value(key)?; + std::str::from_utf8(buf.as_slice()).ok().map(str::to_string) +} + +/// Reads a single response header value as a UTF-8 `String`. +pub(crate) fn response_header_str( + envoy_filter: &EHF, + key: &str, +) -> Option { + let buf = envoy_filter.get_response_header_value(key)?; + std::str::from_utf8(buf.as_slice()).ok().map(str::to_string) +} + +/// Reads a single response trailer value as a UTF-8 `String`. +pub(crate) fn response_trailer_str( + envoy_filter: &EHF, + key: &str, +) -> Option { + let buf = envoy_filter.get_response_trailer_value(key)?; + std::str::from_utf8(buf.as_slice()).ok().map(str::to_string) +} + +/// Reports whether the given `grpc-status` value corresponds to `UNAVAILABLE` (14). +pub fn is_grpc_unavailable(status: &str) -> bool { + status.trim() == GRPC_STATUS_UNAVAILABLE +} + +impl Config { + /// Stamps the resolved worker endpoint and actor target metadata/headers onto + /// the request so Envoy routes directly to `worker_ip:atunnel_port`. + pub fn route_to( + &self, + envoy_filter: &mut EHF, + actor: &ActorRef, + worker_ip: &str, + worker_spiffe_id: Option<&str>, + ) { + let target = if worker_ip.contains(':') && !worker_ip.starts_with('[') { + format!("[{}]:{}", worker_ip, self.atunnel_port) + } else { + format!("{}:{}", worker_ip, self.atunnel_port) + }; + envoy_filter.set_dynamic_metadata_string( + ORIGINAL_DST_NAMESPACE, + ORIGINAL_DST_ADDRESS_KEY, + &target, + ); + envoy_filter.set_dynamic_metadata_string( + ORIGINAL_DST_NAMESPACE, + ORIGINAL_DST_PORT_KEY, + &actor.target_port.to_string(), + ); + if let Some(spiffe_id) = worker_spiffe_id { + envoy_filter.set_dynamic_metadata_string( + ORIGINAL_DST_NAMESPACE, + WORKER_SPIFFE_ID_KEY, + spiffe_id, + ); + } + envoy_filter.set_request_header( + &self.target_port_header, + actor.target_port.to_string().as_bytes(), + ); + // Overwrite ate-target-actor so an untrusted inner header on a CONNECT + // tunnel cannot select a different actor after routing is resolved. + envoy_filter.set_request_header(TARGET_ACTOR_HEADER, actor.cache_key().as_bytes()); + } + + /// Extracts the raw `/` string from filter state or the + /// `ate-target-actor` header, ignoring untrusted inner headers on terminated + /// `CONNECT` tunnels. + pub fn target_actor_value(&self, envoy_filter: &EHF) -> Option { + if let Some(actor) = filter_state_str(envoy_filter, TARGET_ACTOR_FILTER_STATE_KEY) { + return Some(actor); + } + // Requests reaching main_internal via a terminated CONNECT tunnel retain + // the tunnel's authority in CONNECT_AUTHORITY_FILTER_STATE_KEY. For such + // requests, the actor header must have arrived on the outer CONNECT request; + // inner tunneled headers are untrusted and must never be used for routing. + if filter_state_str(envoy_filter, CONNECT_AUTHORITY_FILTER_STATE_KEY).is_some() { + return None; + } + let vals = envoy_filter.get_request_header_values(TARGET_ACTOR_HEADER); + let [val] = vals.as_slice() else { + return None; + }; + std::str::from_utf8(val.as_slice()).ok().map(str::to_string) + } + + /// Resolves the target actor port from `CONNECT` authority filter state or headers, + /// defaulting to [`DEFAULT_ACTOR_PORT`] (`80`). + pub fn resolve_target_port(&self, envoy_filter: &EHF) -> u16 { + let authority = + filter_state_str(envoy_filter, CONNECT_AUTHORITY_FILTER_STATE_KEY).or_else(|| { + if request_header_str(envoy_filter, ":method").as_deref() == Some("CONNECT") { + request_header_str(envoy_filter, ":authority") + } else { + None + } + }); + + authority + .as_deref() + .and_then(Self::parse_authority_port) + .unwrap_or(DEFAULT_ACTOR_PORT) + } + + /// Extracts a non-zero port number from an `authority` string (`host:port` or + /// `[ipv6]:port`). + pub fn parse_authority_port(authority: &str) -> Option { + let (host, port_str) = authority.rsplit_once(':')?; + // A bare IPv6 literal without a port (`2001:db8::1`) contains `:` without brackets. + if host.contains(':') && !(host.starts_with('[') && host.ends_with(']')) { + return None; + } + port_str.parse::().ok().map(NonZeroU16::get) + } + + /// Parses `/` into an [`ActorRef`] after validating both + /// segments as RFC-1123 DNS labels. + pub fn parse_target_actor(value: &str, target_port: u16) -> Option { + let (atespace, name) = value.split_once('/')?; + if name.contains('/') || !is_valid_resource_name(atespace) || !is_valid_resource_name(name) { + return None; + } + Some(ActorRef { + atespace: atespace.to_string(), + name: name.to_string(), + target_port, + }) + } + + /// Resolves the [`ActorRef`] for the current request from filter state and headers. + pub fn resolve_actor_ref(&self, envoy_filter: &EHF) -> Option { + let raw = self.target_actor_value(envoy_filter)?; + let target_port = self.resolve_target_port(envoy_filter); + Self::parse_target_actor(&raw, target_port) + } +} + +// ========================================== +// Tests +// ========================================== + +#[cfg(test)] +mod tests { + use super::*; + use envoy_proxy_dynamic_modules_rust_sdk::{EnvoyBuffer, MockEnvoyHttpFilter}; + + #[test] + fn test_parse_target_actor_and_port() { + let actor = + Config::parse_target_actor("team-a/actor-1", 80).expect("should parse valid actor ref"); + assert_eq!( + actor, + ActorRef { + atespace: "team-a".to_string(), + name: "actor-1".to_string(), + target_port: 80, + } + ); + assert_eq!(actor.cache_key(), "team-a/actor-1"); + + // Invalid actor references (missing slash, extra slash, comma-joined duplicates, uppercase, empty) + assert!(Config::parse_target_actor("actor-1", 80).is_none()); + assert!(Config::parse_target_actor("team-a/actor-1/extra", 80).is_none()); + assert!(Config::parse_target_actor("team-a/actor-1,team-b/actor-2", 80).is_none()); + assert!(Config::parse_target_actor("Team-A/actor-1", 80).is_none()); + assert!(Config::parse_target_actor("/actor-1", 80).is_none()); + assert!(Config::parse_target_actor("team-a/", 80).is_none()); + assert!(Config::parse_target_actor("-team-a/actor-1", 80).is_none()); + assert!(Config::parse_target_actor("team-a/actor-1-", 80).is_none()); + + // Authority port parsing + assert_eq!(Config::parse_authority_port("example.com:8080"), Some(8080)); + assert_eq!( + Config::parse_authority_port("[2001:db8::1]:9090"), + Some(9090) + ); + assert_eq!(Config::parse_authority_port("example.com"), None); + assert_eq!(Config::parse_authority_port("example.com:0"), None); + assert_eq!(Config::parse_authority_port("2001:db8::1"), None); + } + + #[test] + fn test_connect_tunnel_ignores_inner_header_without_outer_filter_state() { + let config = Config::default(); + let mut mock = MockEnvoyHttpFilter::default(); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == TARGET_ACTOR_FILTER_STATE_KEY) + .returning(|_| None); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == CONNECT_AUTHORITY_FILTER_STATE_KEY) + .returning(|_| Some(EnvoyBuffer::new(b"atenet-router:8080"))); + + // Even if an inner header were present, target_actor_value must return None + // when dev.ate.connect.authority is set without dev.ate.target.actor. + assert!(config.resolve_actor_ref(&mock).is_none()); + } + + #[test] + fn test_is_grpc_unavailable() { + assert!(is_grpc_unavailable("14")); + assert!(is_grpc_unavailable(" 14 ")); + assert!(is_grpc_unavailable("14\r\n")); + + assert!(!is_grpc_unavailable("0")); + assert!(!is_grpc_unavailable("1")); + assert!(!is_grpc_unavailable("3")); + assert!(!is_grpc_unavailable("5")); + assert!(!is_grpc_unavailable("")); + assert!(!is_grpc_unavailable("unavailable")); + } +} diff --git a/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/tunnel_watcher.rs b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/tunnel_watcher.rs new file mode 100644 index 0000000000..9d75c713e9 --- /dev/null +++ b/cmd/dataplane/envoy/dynamic-modules/ingress-cache/src/tunnel_watcher.rs @@ -0,0 +1,354 @@ +// Copyright 2026 The Agent Substrate 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. + +//! The `tunnel_watcher` network filter. +//! +//! It runs on the router's `actor_connect` internal listener, ahead of the +//! `tcp_proxy` that opens a CONNECT tunnel to the worker's `atunnel`, and +//! records what happened to each tunnel on the cache entries for its actor and +//! worker: +//! +//! * **stale**: the connection closed with `UF`, so the tunnel was never +//! established and no request bytes reached the actor; +//! * **spoiled**: the tunnel was established and closed while request bytes were +//! waiting for a response, so that request may have reached the actor. +//! +//! The HTTP filter replays a bodiless `503 UC` only if its entry is stale and +//! not spoiled. The marks are always in place before the router reports the +//! `503`: the network filter's close callback runs inside `tcp_proxy`'s close, +//! and the router only sees the close on the next event-loop iteration. +//! +//! The filter never parses the bytes it sees; it only notes which direction +//! they move. `tcp_proxy` keeps reads off until the tunnel is up, so request +//! bytes only pass through once a tunnel is established. + +use std::net::SocketAddr; + +use envoy_proxy_dynamic_modules_rust_sdk::{ + EnvoyCounterId, EnvoyNetworkFilter, EnvoyNetworkFilterConfig, NetworkFilter, NetworkFilterConfig, + abi::{ + envoy_dynamic_module_type_attribute_id, envoy_dynamic_module_type_network_connection_event, + envoy_dynamic_module_type_on_network_filter_data_status, + }, +}; + +use crate::cache; +use crate::filter::RESPONSE_FLAG_UF; + +/// Filter state holding the actor (`/`) a tunnel connection is for. It is part +/// of the tunnel pool's key, so every connection in a pool carries the right value. +pub const TUNNEL_ACTOR_FILTER_STATE_KEY: &str = "dev.ate.tunnel.actor"; + +/// Filter state holding the worker (`ip:port`) a tunnel connection is for. +pub const TUNNEL_WORKER_FILTER_STATE_KEY: &str = "dev.ate.tunnel.worker"; + +/// Counter incremented when a refused tunnel marks cache entries stale. +pub const MARKED_STALE_COUNTER: &str = "ate_ingress_cache.marked_stale"; + +/// Counter incremented when a tunnel cut off mid-request marks cache entries spoiled. +pub const MARKED_SPOILED_COUNTER: &str = "ate_ingress_cache.marked_spoiled"; + +/// Creates the `tunnel_watcher` network filter configuration. +pub fn new_network_filter_config_fn( + envoy_filter_config: &mut EC, + _filter_name: &str, + _filter_config: &[u8], +) -> Option>> { + Some(Box::new(TunnelWatcherConfig { + marked_stale: envoy_filter_config + .define_counter(MARKED_STALE_COUNTER) + .ok(), + marked_spoiled: envoy_filter_config + .define_counter(MARKED_SPOILED_COUNTER) + .ok(), + })) +} + +/// Network filter configuration holding the counter IDs. +pub struct TunnelWatcherConfig { + pub marked_stale: Option, + pub marked_spoiled: Option, +} + +impl NetworkFilterConfig for TunnelWatcherConfig { + fn new_network_filter(&self, _envoy: &mut ENF) -> Box> { + Box::new(TunnelWatcher::new(self.marked_stale, self.marked_spoiled)) + } +} + +/// Per-connection state of the `tunnel_watcher` network filter. +pub struct TunnelWatcher { + /// Counts tunnel connections that closed with `UF` and marked at least one entry stale. + marked_stale: Option, + /// Counts established tunnel connections that closed with a request outstanding and marked + /// at least one entry spoiled. + marked_spoiled: Option, + /// The `(actor, worker IP)` this connection tunnels to, once known. + tunnel: Option<(String, String)>, + /// Whether request bytes went upstream with no response bytes back since. + request_outstanding: bool, +} + +impl TunnelWatcher { + pub fn new(marked_stale: Option, marked_spoiled: Option) -> Self { + Self { + marked_stale, + marked_spoiled, + tunnel: None, + request_outstanding: false, + } + } +} + +fn filter_state_str(envoy_filter: &ENF, key: &str) -> Option { + let buf = envoy_filter.get_filter_state_bytes(key.as_bytes())?; + std::str::from_utf8(buf.as_slice()) + .ok() + .map(str::to_string) +} + +/// Reads the `(actor, worker IP)` a tunnel connection is for. The worker filter state is an +/// `ip:port` socket address; the cache keys entries by the bare IP in canonical form. +fn read_tunnel(envoy_filter: &ENF) -> Option<(String, String)> { + let actor = filter_state_str(envoy_filter, TUNNEL_ACTOR_FILTER_STATE_KEY)?; + let worker = filter_state_str(envoy_filter, TUNNEL_WORKER_FILTER_STATE_KEY)?; + let worker_ip = worker.parse::().ok()?.ip().to_string(); + Some((actor, worker_ip)) +} + +fn increment(envoy_filter: &ENF, counter: Option) { + if let Some(id) = counter { + let _ = envoy_filter.increment_counter(id, 1); + } +} + +impl NetworkFilter for TunnelWatcher { + fn on_new_connection( + &mut self, + envoy_filter: &mut ENF, + ) -> envoy_dynamic_module_type_on_network_filter_data_status { + self.tunnel = read_tunnel(envoy_filter); + envoy_dynamic_module_type_on_network_filter_data_status::Continue + } + + fn on_read( + &mut self, + _envoy_filter: &mut ENF, + data_length: usize, + _end_stream: bool, + ) -> envoy_dynamic_module_type_on_network_filter_data_status { + if data_length > 0 { + self.request_outstanding = true; + } + envoy_dynamic_module_type_on_network_filter_data_status::Continue + } + + fn on_write( + &mut self, + _envoy_filter: &mut ENF, + data_length: usize, + _end_stream: bool, + ) -> envoy_dynamic_module_type_on_network_filter_data_status { + if data_length > 0 { + self.request_outstanding = false; + } + envoy_dynamic_module_type_on_network_filter_data_status::Continue + } + + fn on_event( + &mut self, + envoy_filter: &mut ENF, + event: envoy_dynamic_module_type_network_connection_event, + ) { + let closed = matches!( + event, + envoy_dynamic_module_type_network_connection_event::LocalClose + | envoy_dynamic_module_type_network_connection_event::RemoteClose + ); + if !closed { + return; + } + let Some((actor, worker_ip)) = self.tunnel.take() else { + return; + }; + let flags = envoy_filter + .get_attribute_int(envoy_dynamic_module_type_attribute_id::ResponseFlags) + .unwrap_or(0); + if flags & RESPONSE_FLAG_UF != 0 { + if cache::mark_stale(&actor, &worker_ip) > 0 { + increment(envoy_filter, self.marked_stale); + } + } else if self.request_outstanding && cache::mark_spoiled(&actor, &worker_ip) > 0 { + increment(envoy_filter, self.marked_spoiled); + } + } +} + +// ========================================== +// Tests +// ========================================== + +#[cfg(test)] +mod tests { + use super::*; + use envoy_proxy_dynamic_modules_rust_sdk::{EnvoyBuffer, MockEnvoyNetworkFilter}; + use std::time::Duration; + + use crate::filter::RESPONSE_FLAG_UC; + + const ACTOR: &str = "team-n/actor-1"; + + fn mock_tunnel(worker: &'static str, flags: i64) -> MockEnvoyNetworkFilter { + let mut mock = MockEnvoyNetworkFilter::default(); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == TUNNEL_ACTOR_FILTER_STATE_KEY.as_bytes()) + .returning(|_| Some(EnvoyBuffer::new(ACTOR.as_bytes()))); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == TUNNEL_WORKER_FILTER_STATE_KEY.as_bytes()) + .returning(move |_| Some(EnvoyBuffer::new(worker.as_bytes()))); + mock + .expect_get_attribute_int() + .withf(|id| *id == envoy_dynamic_module_type_attribute_id::ResponseFlags) + .returning(move |_| Some(flags)); + mock.expect_increment_counter().returning(|_, _| Ok(())); + mock + } + + fn close(watcher: &mut TunnelWatcher, mock: &mut MockEnvoyNetworkFilter) { + watcher.on_event(mock, envoy_dynamic_module_type_network_connection_event::LocalClose); + } + + fn held_entry(worker_ip: &str) -> std::rc::Rc { + cache::insert( + ACTOR.to_string(), + worker_ip.to_string(), + None, + Duration::from_secs(5), + crate::config::DEFAULT_MAX_CACHED_ACTORS, + ) + } + + #[test] + fn test_refused_tunnel_marks_entry_stale() { + let entry = held_entry("10.244.8.1"); + let mut mock = mock_tunnel("10.244.8.1:443", RESPONSE_FLAG_UF); + let mut watcher = TunnelWatcher::new(None, None); + watcher.on_new_connection(&mut mock); + // tcp_proxy keeps reads off until the tunnel is up, so a refused tunnel reads nothing. + close(&mut watcher, &mut mock); + assert!(entry.is_stale()); + assert!(!entry.is_spoiled()); + assert!(cache::current(ACTOR).is_none()); + } + + #[test] + fn test_drop_with_request_outstanding_marks_entry_spoiled() { + let entry = held_entry("10.244.8.2"); + let mut mock = mock_tunnel("10.244.8.2:443", RESPONSE_FLAG_UC); + let mut watcher = TunnelWatcher::new(None, None); + watcher.on_new_connection(&mut mock); + watcher.on_read(&mut mock, 120, false); + close(&mut watcher, &mut mock); + assert!(entry.is_spoiled()); + assert!(!entry.is_stale()); + } + + #[test] + fn test_close_after_response_does_not_mark() { + let entry = held_entry("10.244.8.3"); + let mut mock = mock_tunnel("10.244.8.3:443", 0); + let mut watcher = TunnelWatcher::new(None, None); + watcher.on_new_connection(&mut mock); + watcher.on_read(&mut mock, 120, false); + watcher.on_write(&mut mock, 512, false); + close(&mut watcher, &mut mock); + assert!(!entry.is_spoiled()); + assert!(!entry.is_stale()); + assert!(cache::current(ACTOR).is_some()); + } + + #[test] + fn test_idle_kept_alive_tunnel_closing_does_not_mark() { + let entry = held_entry("10.244.8.4"); + let mut mock = mock_tunnel("10.244.8.4:443", 0); + let mut watcher = TunnelWatcher::new(None, None); + watcher.on_new_connection(&mut mock); + close(&mut watcher, &mut mock); + assert!(!entry.is_spoiled()); + assert!(!entry.is_stale()); + } + + #[test] + fn test_ipv6_worker_matches_canonical_entry_ip() { + let entry = held_entry("2001:db8::1"); + let mut mock = mock_tunnel("[2001:db8::1]:443", RESPONSE_FLAG_UF); + let mut watcher = TunnelWatcher::new(None, None); + watcher.on_new_connection(&mut mock); + close(&mut watcher, &mut mock); + assert!(entry.is_stale()); + } + + #[test] + fn test_marks_only_matching_worker() { + let on_b = held_entry("10.244.8.6"); + let mut mock = mock_tunnel("10.244.8.5:443", RESPONSE_FLAG_UF); + let mut watcher = TunnelWatcher::new(None, None); + watcher.on_new_connection(&mut mock); + close(&mut watcher, &mut mock); + assert!(!on_b.is_stale()); + assert!(cache::current(ACTOR).is_some()); + } + + #[test] + fn test_connection_without_tunnel_filter_state_is_ignored() { + let entry = held_entry("10.244.8.7"); + let mut mock = MockEnvoyNetworkFilter::default(); + mock.expect_get_filter_state_bytes().returning(|_| None); + let mut watcher = TunnelWatcher::new(None, None); + watcher.on_new_connection(&mut mock); + watcher.on_read(&mut mock, 10, false); + // get_attribute_int has no expectation: a close must not read anything. + close(&mut watcher, &mut mock); + assert!(!entry.is_stale()); + assert!(!entry.is_spoiled()); + } + + #[test] + fn test_marks_increment_counters() { + let _entry = held_entry("10.244.8.8"); + let stale_id = EnvoyCounterId(11); + let mut mock = MockEnvoyNetworkFilter::default(); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == TUNNEL_ACTOR_FILTER_STATE_KEY.as_bytes()) + .returning(|_| Some(EnvoyBuffer::new(ACTOR.as_bytes()))); + mock + .expect_get_filter_state_bytes() + .withf(|key| key == TUNNEL_WORKER_FILTER_STATE_KEY.as_bytes()) + .returning(|_| Some(EnvoyBuffer::new(b"10.244.8.8:443"))); + mock + .expect_get_attribute_int() + .returning(|_| Some(RESPONSE_FLAG_UF)); + mock + .expect_increment_counter() + .withf(move |id, val| *id == stale_id && *val == 1) + .times(1) + .returning(|_, _| Ok(())); + let mut watcher = TunnelWatcher::new(Some(stale_id), Some(EnvoyCounterId(12))); + watcher.on_new_connection(&mut mock); + close(&mut watcher, &mut mock); + } +} diff --git a/cmd/kubectl-ate/internal/cmd/actor.go b/cmd/kubectl-ate/internal/cmd/actor.go index d342659413..a28b5ebad2 100644 --- a/cmd/kubectl-ate/internal/cmd/actor.go +++ b/cmd/kubectl-ate/internal/cmd/actor.go @@ -445,6 +445,9 @@ func (r *LogsActorRunner) runOneShot(ctx context.Context) error { return fmt.Errorf("actor %s is not currently running on any worker pod", r.actorRef) } + filter := r.filter + filter.uid = actor.GetMetadata().GetUid() + opts := &corev1.PodLogOptions{ Follow: false, } @@ -460,7 +463,7 @@ func (r *LogsActorRunner) runOneShot(ctx context.Context) error { scanner.Buffer(buf, 1024*1024) // Support up to 1MB lines for scanner.Scan() { line := scanner.Text() - filterAndDisplayLogLine(line, r.filter, r.stdout, r.stderr) + filterAndDisplayLogLine(line, filter, r.stdout, r.stderr) } if err := scanner.Err(); err != nil { return fmt.Errorf("error reading log stream: %w", err) @@ -473,6 +476,8 @@ func (r *LogsActorRunner) runFollow(ctx context.Context) error { // lastSeenTime is the kubelet's timestamp on the last line read from // lastWorkerPod, the resume cursor for a reconnect to it. var lastSeenTime time.Time + // lastUID is the UID of the actor the last stream was filtered for. + var lastUID string var waitingLogged bool var lastWaitingState ateapi.ActorState @@ -516,6 +521,17 @@ func (r *LogsActorRunner) runFollow(ctx context.Context) error { } waitingLogged = false + uid := actor.GetMetadata().GetUid() + filter := r.filter + filter.uid = uid + if uid != lastUID { + // A new actor took the name. The last stream may have read some + // of its lines and skipped them, so read the pod log from the + // start. + lastSeenTime = time.Time{} + lastUID = uid + } + // The actor resumed on another worker. switchedPod := podName != lastWorkerPod if switchedPod { @@ -550,7 +566,7 @@ func (r *LogsActorRunner) runFollow(ctx context.Context) error { } var wg sync.WaitGroup - r.startMigrationMonitor(streamCtx, streamCancel, &wg, podName) + r.startMigrationMonitor(streamCtx, streamCancel, &wg, podName, uid) scanner := bufio.NewScanner(stream) buf := make([]byte, 0, 64*1024) @@ -569,7 +585,7 @@ func (r *LogsActorRunner) runFollow(ctx context.Context) error { } else { vlogf(r.stderr, vTrace, "Log line had no kubelet timestamp prefix") } - filterAndDisplayLogLine(line, r.filter, r.stdout, r.stderr) + filterAndDisplayLogLine(line, filter, r.stdout, r.stderr) } scanErr := scanner.Err() stream.Close() @@ -597,12 +613,14 @@ func (r *LogsActorRunner) runFollow(ctx context.Context) error { } // startMigrationMonitor launches a background goroutine to query the control plane -// and aborts the stream context if the actor is suspended and then resumed to a different pod. +// and aborts the stream context if the actor is suspended, resumed to a +// different pod, or replaced by a new actor with the same name. func (r *LogsActorRunner) startMigrationMonitor( ctx context.Context, cancel context.CancelFunc, wg *sync.WaitGroup, currentPod string, + currentUID string, ) { wg.Add(1) go func() { @@ -622,10 +640,10 @@ func (r *LogsActorRunner) startMigrationMonitor( continue } act := resp - if act.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING || act.GetStatus().GetWorkerAssignment().GetWorkerPod() != currentPod { - // Actor suspended or migrated! Cancel stream context to reconnect. - vlogf(r.stderr, vBasic, "Actor %s left pod %s (state=%s, pod=%s); closing current log stream", - r.actorRef, currentPod, act.GetStatus().GetState(), act.GetStatus().GetWorkerAssignment().GetWorkerPod()) + if act.GetStatus().GetState() != ateapi.ActorState_ACTOR_STATE_RUNNING || act.GetStatus().GetWorkerAssignment().GetWorkerPod() != currentPod || act.GetMetadata().GetUid() != currentUID { + // Actor suspended, migrated or recreated. Cancel stream context to reconnect. + vlogf(r.stderr, vBasic, "Actor %s left pod %s or was recreated (state=%s, pod=%s, uid=%s); closing current log stream", + r.actorRef, currentPod, act.GetStatus().GetState(), act.GetStatus().GetWorkerAssignment().GetWorkerPod(), act.GetMetadata().GetUid()) cancel() return } @@ -709,7 +727,11 @@ const ( // them by default, one class of them when source is set, or only the named // container's when container is set. type logLineFilter struct { - target resources.ActorRef + target resources.ActorRef + // uid is the target's UID. The runner sets it once it has fetched the + // actor. A worker pod can host a deleted actor and a new one with the + // same name, and only the UID tells their lines apart. + uid string source logSource container string } @@ -729,14 +751,17 @@ func newLogLineFilter(target resources.ActorRef, source, container string) (logL return logLineFilter{target: target, source: logSource(source), container: container}, nil } -// matches reports whether a line emitted by emitter from containerName (empty -// for lifecycle events) should be displayed. -func (f logLineFilter) matches(emitter resources.ActorRef, containerName string) bool { +// matches reports whether a line emitted by emitter, whose UID is emitterUID, +// from containerName (empty for lifecycle events) should be displayed. +func (f logLineFilter) matches(emitter resources.ActorRef, emitterUID, containerName string) bool { // Actor names are only unique within an atespace, and a worker pod can host // actors from different atespaces over time, so match on both. if emitter != f.target || f.target.Atespace == "" || f.target.Name == "" { return false } + if emitterUID != f.uid { + return false + } switch f.source { case logSourceLifecycle: // f.container is empty here: newLogLineFilter rejects it with lifecycle. @@ -777,13 +802,14 @@ func filterAndDisplayLogLine(line string, filter logLineFilter, w, stderr io.Wri } var emitter resources.ActorRef - var emitterContainer string + var emitterUID, emitterContainer string for _, labelKey := range []string{"logging.googleapis.com/labels", "labels"} { if labelsAny, ok := m[labelKey]; ok { if labels, ok := labelsAny.(map[string]any); ok { if name, ok := labels[string(ateattr.ActorNameKey)].(string); ok && name != "" { emitter.Name = name emitter.Atespace, _ = labels[string(ateattr.AtespaceKey)].(string) + emitterUID, _ = labels[string(ateattr.ActorUIDKey)].(string) emitterContainer, _ = labels[string(ateattr.ActorContainerNameKey)].(string) break } @@ -791,7 +817,7 @@ func filterAndDisplayLogLine(line string, filter logLineFilter, w, stderr io.Wri } } - if !filter.matches(emitter, emitterContainer) { + if !filter.matches(emitter, emitterUID, emitterContainer) { return false } diff --git a/cmd/kubectl-ate/internal/cmd/actor_test.go b/cmd/kubectl-ate/internal/cmd/actor_test.go index f2342dc6f7..406da06ebc 100644 --- a/cmd/kubectl-ate/internal/cmd/actor_test.go +++ b/cmd/kubectl-ate/internal/cmd/actor_test.go @@ -394,6 +394,7 @@ func TestFilterAndDisplayLogLine(t *testing.T) { name string line string target resources.ActorRef + uid string source string container string wantMatched bool @@ -598,6 +599,26 @@ func TestFilterAndDisplayLogLine(t *testing.T) { wantMatched: false, wantOutput: "", }, + { + name: "same UID", + line: `{"time":"2026-05-16T01:03:38Z","message":"Hello","logging.googleapis.com/labels":{"ate.atespace":"space-1","ate.actor.name":"act-1","ate.actor.uid":"uid-2"}}`, + target: resources.ActorRef{Atespace: "space-1", Name: "act-1"}, + uid: "uid-2", + wantMatched: true, + wantOutput: `{"time":"2026-05-16T01:03:38Z","message":"Hello"}`, + }, + { + name: "deleted actor with the same name", + line: `{"time":"2026-05-16T01:03:38Z","message":"Hello","logging.googleapis.com/labels":{"ate.atespace":"space-1","ate.actor.name":"act-1","ate.actor.uid":"uid-1"}}`, + target: resources.ActorRef{Atespace: "space-1", Name: "act-1"}, + uid: "uid-2", + }, + { + name: "line without a UID", + line: `{"time":"2026-05-16T01:03:38Z","message":"Hello","logging.googleapis.com/labels":{"ate.atespace":"space-1","ate.actor.name":"act-1"}}`, + target: resources.ActorRef{Atespace: "space-1", Name: "act-1"}, + uid: "uid-2", + }, { name: "source=containers shows any container's line", line: `{"time":"2026-05-16T01:03:38Z","level":"info","msg":"hi","logging.googleapis.com/labels":{"ate.atespace":"space-1","ate.actor.name":"act-1","ate.actor.container.name":"sidecar"}}`, @@ -629,7 +650,7 @@ func TestFilterAndDisplayLogLine(t *testing.T) { t.Run(tc.name, func(t *testing.T) { var outBuf bytes.Buffer var errBuf bytes.Buffer - matched := filterAndDisplayLogLine(tc.line, logLineFilter{target: tc.target, source: logSource(tc.source), container: tc.container}, &outBuf, &errBuf) + matched := filterAndDisplayLogLine(tc.line, logLineFilter{target: tc.target, uid: tc.uid, source: logSource(tc.source), container: tc.container}, &outBuf, &errBuf) if matched != tc.wantMatched { t.Errorf("got matched = %v, want %v", matched, tc.wantMatched) @@ -724,7 +745,7 @@ func TestLogsActorRunner_Run_OneShotSuccess(t *testing.T) { return nil, fmt.Errorf("unexpected actor name: %s", in.GetActor().GetName()) } return &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Name: actorName}, + Metadata: &ateapi.ResourceMetadata{Name: actorName, Uid: "uid-2"}, Status: &ateapi.ActorStatus{ State: ateapi.ActorState_ACTOR_STATE_RUNNING, WorkerAssignment: &ateapi.WorkerAssignment{ @@ -736,7 +757,9 @@ func TestLogsActorRunner_Run_OneShotSuccess(t *testing.T) { }, } - logLine := `{"time":"2026-05-16T01:03:38Z","level":"info","msg":"Hello world","logging.googleapis.com/labels":{"ate.atespace":"space-1","ate.actor.name":"act-123"}}` + // The first line is from a deleted actor with the same name. + logLine := `{"time":"2026-05-16T01:03:37Z","level":"info","msg":"Goodbye","logging.googleapis.com/labels":{"ate.atespace":"space-1","ate.actor.name":"act-123","ate.actor.uid":"uid-1"}}` + "\n" + + `{"time":"2026-05-16T01:03:38Z","level":"info","msg":"Hello world","logging.googleapis.com/labels":{"ate.atespace":"space-1","ate.actor.name":"act-123","ate.actor.uid":"uid-2"}}` mockStreamer := &mockPodLogsStreamer{ StreamLogsFunc: func(ctx context.Context, ns, name string, opts *corev1.PodLogOptions) (io.ReadCloser, error) { if ns != namespace || name != podName { @@ -1325,6 +1348,111 @@ func TestLogsActorRunner_Run_Follow_ActorSuspendedMidStream(t *testing.T) { } } +// A followed actor that is deleted and recreated on the same pod gets a new +// stream filtered by the new UID. The new stream starts from the top of the +// pod log, because the old stream read and skipped the new actor's first lines. +func TestLogsActorRunner_Run_Follow_ActorRecreatedOnSamePod(t *testing.T) { + actorName := "act-recreated" + + running := func(uid string) *ateapi.Actor { + return &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Name: actorName, Uid: uid}, + Status: &ateapi.ActorStatus{ + State: ateapi.ActorState_ACTOR_STATE_RUNNING, + WorkerAssignment: &ateapi.WorkerAssignment{ + WorkerPod: "pod-1", + WorkerNamespace: "ns", + }, + }, + } + } + + var getActorCalls int + var getActorMu sync.Mutex + lineRead := make(chan struct{}) + + mockAPI := &mockAteAPIClient{ + GetActorFunc: func(ctx context.Context, in *ateapi.GetActorRequest, opts ...grpc.CallOption) (*ateapi.Actor, error) { + getActorMu.Lock() + defer getActorMu.Unlock() + getActorCalls++ + if getActorCalls == 1 { + return running("uid-1"), nil + } + // The monitor sees the new actor only after the first line is read. + select { + case <-lineRead: + case <-ctx.Done(): + return nil, ctx.Err() + } + return running("uid-2"), nil + }, + } + + // The timeout only bounds a failure: a stream that is never cancelled. + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + + // Each line has the kubelet's timestamp prefix, so the resume cursor is used. + line := func(stamp, uid, msg string) string { + return fmt.Sprintf(`%s {"time":"2026-05-16T01:03:38Z","msg":%q,"logging.googleapis.com/labels":{"ate.atespace":"space-1","ate.actor.name":%q,"ate.actor.uid":%q}}`, stamp, msg, actorName, uid) + } + podLog := line("2026-05-16T01:03:38.1Z", "uid-1", "first actor") + "\n" + + line("2026-05-16T01:03:39.1Z", "uid-2", "second actor") + "\n" + + var streamCalls int + var streamMu sync.Mutex + mockStreamer := &mockPodLogsStreamer{ + StreamLogsFunc: func(streamCtx context.Context, ns, name string, opts *corev1.PodLogOptions) (io.ReadCloser, error) { + streamMu.Lock() + defer streamMu.Unlock() + streamCalls++ + + if streamCalls == 1 { + pr, pw := io.Pipe() + go func() { + // The second actor starts before the monitor sees it. + fmt.Fprint(pw, podLog) + close(lineRead) + <-streamCtx.Done() + pw.Close() + }() + return pr, nil + } + + if opts.SinceTime != nil { + t.Errorf("got SinceTime %v for a new actor, want none", opts.SinceTime) + } + cancel() + return io.NopCloser(strings.NewReader(podLog)), nil + }, + } + + var stdout, stderr bytes.Buffer + runner := &LogsActorRunner{ + apiClient: mockAPI, + actorRef: resources.ActorRef{Atespace: "space-1", Name: actorName}, + filter: logLineFilter{target: resources.ActorRef{Atespace: "space-1", Name: actorName}}, + streamer: mockStreamer, + stdout: &stdout, + stderr: &stderr, + follow: true, + pollInterval: 1 * time.Millisecond, + reconnectInterval: 1 * time.Millisecond, + tickerInterval: 1 * time.Millisecond, + } + + if err := runner.Run(ctx); err != nil && err != context.Canceled { + t.Fatalf("unexpected error: %v", err) + } + + want := `{"time":"2026-05-16T01:03:38Z","msg":"first actor"}` + "\n" + + `{"time":"2026-05-16T01:03:38Z","msg":"second actor"}` + "\n" + if got := stdout.String(); got != want { + t.Errorf("got stdout %q, want %q", got, want) + } +} + // The follow resume cursor is the kubelet's timestamp on the last line read, // displayed or not. Not the last displayed line: under a sparse filter such // as --source=lifecycle a reconnect would replay everything since the last diff --git a/cmd/kubectl-ate/internal/cmd/csi_driver.go b/cmd/kubectl-ate/internal/cmd/csi_driver.go new file mode 100644 index 0000000000..27a9b9088f --- /dev/null +++ b/cmd/kubectl-ate/internal/cmd/csi_driver.go @@ -0,0 +1,223 @@ +// Copyright 2026 The Agent Substrate 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" + "fmt" + "io" + + "github.com/spf13/cobra" + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/kubectl-ate/internal/printer" + "google.golang.org/grpc" + "google.golang.org/protobuf/encoding/protojson" +) + +var ( + createCSIDriverFilenameFlag string + updateCSIDriverFilenameFlag string + deleteCSIDriverGuard deleteGuardFlags +) + +type csiDriverClient interface { + GetCsiDriver(ctx context.Context, in *ateapi.GetCsiDriverRequest, opts ...grpc.CallOption) (*ateapi.CsiDriver, error) + ListCsiDrivers(ctx context.Context, in *ateapi.ListCsiDriversRequest, opts ...grpc.CallOption) (*ateapi.ListCsiDriversResponse, error) + CreateCsiDriver(ctx context.Context, in *ateapi.CreateCsiDriverRequest, opts ...grpc.CallOption) (*ateapi.CsiDriver, error) + UpdateCsiDriver(ctx context.Context, in *ateapi.UpdateCsiDriverRequest, opts ...grpc.CallOption) (*ateapi.CsiDriver, error) + DeleteCsiDriver(ctx context.Context, in *ateapi.DeleteCsiDriverRequest, opts ...grpc.CallOption) (*ateapi.CsiDriver, error) +} + +var getCSIDriversCmd = &cobra.Command{ + Use: "csi-driver [name ...]", + Aliases: []string{"csi-drivers"}, + Short: "List all CSI drivers or get one or more CSI drivers", + Long: "List or get CSI drivers.", + Args: cobra.ArbitraryArgs, + RunE: func(cmd *cobra.Command, args []string) error { + apiClient, err := newAPIClient(cmd) + if err != nil { + return fmt.Errorf("failed to connect to ate-api-server: %w", err) + } + defer apiClient.Close() + return runGetCSIDrivers(cmd.Context(), apiClient, cmd.OutOrStdout(), outputFmt, args) + }, +} + +var createCSIDriverCmd = &cobra.Command{ + Use: "csi-driver -f ", + Aliases: []string{"csi-drivers"}, + Short: "Create a CSI driver from a manifest", + Long: `Create a CSI driver from a single YAML or JSON manifest holding one ateapi.CsiDriver message in protojson form (as printed by "kubectl ate get csi-driver -o yaml"). CSI drivers are global-scoped.`, + Args: noArgs("the CSI driver name comes from the manifest passed to -f/--filename", "filename"), + RunE: func(cmd *cobra.Command, args []string) error { + driver, err := loadCSIDriverManifest(cmd.InOrStdin(), createCSIDriverFilenameFlag) + if err != nil { + return err + } + apiClient, err := newAPIClient(cmd) + if err != nil { + return fmt.Errorf("failed to connect to ate-api-server: %w", err) + } + defer apiClient.Close() + return runCreateCSIDriver(cmd.Context(), apiClient, cmd.OutOrStdout(), outputFmt, driver) + }, +} + +var updateCSIDriverCmd = &cobra.Command{ + Use: "csi-driver -f ", + Aliases: []string{"csi-drivers"}, + Short: "Replace a CSI driver from a manifest", + Long: `Replace a CSI driver from a single YAML or JSON manifest holding one ateapi.CsiDriver message in protojson form (as printed by "kubectl ate get csi-driver -o yaml"). Its metadata.uid and metadata.version are required preconditions.`, + Args: noArgs("the CSI driver name comes from the manifest passed to -f/--filename", "filename"), + RunE: func(cmd *cobra.Command, args []string) error { + driver, err := loadCSIDriverForUpdate(cmd.InOrStdin(), updateCSIDriverFilenameFlag) + if err != nil { + return err + } + apiClient, err := newAPIClient(cmd) + if err != nil { + return fmt.Errorf("failed to connect to ate-api-server: %w", err) + } + defer apiClient.Close() + return runUpdateCSIDriver(cmd.Context(), apiClient, cmd.OutOrStdout(), outputFmt, driver) + }, +} + +var deleteCSIDriverCmd = &cobra.Command{ + Use: "csi-driver ", + Aliases: []string{"csi-drivers"}, + Short: "Delete a CSI driver", + Long: "Delete a CSI driver. Pass --uid and/or --version to guard the delete against a concurrent replacement.", + Args: exactlyOneArg(""), + RunE: func(cmd *cobra.Command, args []string) error { + opts, err := deleteOptionsFromFlags(deleteGuardFlags{ + uidSet: cmd.Flags().Changed("uid"), + uid: deleteCSIDriverGuard.uid, + versionSet: cmd.Flags().Changed("version"), + version: deleteCSIDriverGuard.version, + }) + if err != nil { + return wrapUsageError(err) + } + apiClient, err := newAPIClient(cmd) + if err != nil { + return fmt.Errorf("failed to connect to ate-api-server: %w", err) + } + defer apiClient.Close() + return runDeleteCSIDriver(cmd.Context(), apiClient, cmd.OutOrStdout(), args[0], opts) + }, +} + +func runGetCSIDrivers(ctx context.Context, client csiDriverClient, out io.Writer, format string, names []string) error { + if len(names) > 0 { + drivers := make([]*ateapi.CsiDriver, 0, len(names)) + for _, name := range names { + resp, err := client.GetCsiDriver(ctx, &ateapi.GetCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: name}}) + if err != nil { + return fmt.Errorf("failed to get csi driver %q: %w", name, err) + } + drivers = append(drivers, resp) + } + if len(drivers) == 1 { + return printer.PrintCSIDriverTo(out, drivers[0], format) + } + return printer.PrintCSIDriversTo(out, drivers, format) + } + var allDrivers []*ateapi.CsiDriver + for pageToken := ""; ; { + resp, err := client.ListCsiDrivers(ctx, &ateapi.ListCsiDriversRequest{Options: &ateapi.ListOptions{PageSize: 1000, PageToken: pageToken}}) + if err != nil { + return fmt.Errorf("failed to list csi drivers: %w", err) + } + allDrivers = append(allDrivers, resp.GetCsiDrivers()...) + if pageToken = resp.GetNextPageToken(); pageToken == "" { + break + } + } + return printer.PrintCSIDriversTo(out, allDrivers, format) +} + +func runCreateCSIDriver(ctx context.Context, client csiDriverClient, out io.Writer, format string, driver *ateapi.CsiDriver) error { + resp, err := client.CreateCsiDriver(ctx, &ateapi.CreateCsiDriverRequest{CsiDriver: driver}) + if err != nil { + return fmt.Errorf("failed to create csi driver: %w", err) + } + return printer.PrintCSIDriverTo(out, resp, format) +} + +func runUpdateCSIDriver(ctx context.Context, client csiDriverClient, out io.Writer, format string, driver *ateapi.CsiDriver) error { + resp, err := client.UpdateCsiDriver(ctx, &ateapi.UpdateCsiDriverRequest{CsiDriver: driver}) + if err != nil { + return fmt.Errorf("failed to update csi driver: %w", err) + } + return printer.PrintCSIDriverTo(out, resp, format) +} + +func runDeleteCSIDriver(ctx context.Context, client csiDriverClient, out io.Writer, name string, opts *ateapi.DeleteOptions) error { + if _, err := client.DeleteCsiDriver(ctx, &ateapi.DeleteCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: name}, Options: opts}); err != nil { + return fmt.Errorf("failed to delete csi driver: %w", err) + } + fmt.Fprintf(out, "csi driver %q deleted\n", name) + return nil +} + +func loadCSIDriverManifest(in io.Reader, path string) (*ateapi.CsiDriver, error) { + data, err := readFileOrStdin(in, path) + if err != nil { + return nil, err + } + jsonData, err := manifestToJSON(data) + if err != nil { + return nil, fmt.Errorf("failed to parse csi driver manifest %q: %w", path, err) + } + driver := &ateapi.CsiDriver{} + if err := protojson.Unmarshal(jsonData, driver); err != nil { + return nil, fmt.Errorf("failed to parse csi driver manifest %q: invalid CsiDriver: %w", path, err) + } + if got := driver.GetMetadata().GetAtespace(); got != "" { + return nil, fmt.Errorf("csi driver is global-scoped: metadata.atespace must be empty (got %q)", got) + } + if driver.GetMetadata().GetName() == "" { + return nil, fmt.Errorf("failed to parse csi driver manifest %q: metadata.name is required", path) + } + return driver, nil +} + +func loadCSIDriverForUpdate(in io.Reader, path string) (*ateapi.CsiDriver, error) { + driver, err := loadCSIDriverManifest(in, path) + if err != nil { + return nil, err + } + if driver.GetMetadata().GetUid() == "" || driver.GetMetadata().GetVersion() < 1 { + name := driver.GetMetadata().GetName() + return nil, fmt.Errorf(`manifest for csi driver %q lacks the metadata.uid and metadata.version preconditions that "kubectl ate get csi-driver %s -o yaml" prints`, name, name) + } + return driver, nil +} + +func init() { + getCmd.AddCommand(getCSIDriversCmd) + + createCSIDriverCmd.Flags().StringVarP(&createCSIDriverFilenameFlag, "filename", "f", "", "manifest file holding a single JSON or YAML csi-driver document, or - for stdin") + createCmd.AddCommand(createCSIDriverCmd) + + updateCSIDriverCmd.Flags().StringVarP(&updateCSIDriverFilenameFlag, "filename", "f", "", "manifest file holding a single JSON or YAML csi-driver document, or - for stdin") + updateCmd.AddCommand(updateCSIDriverCmd) + + deleteCSIDriverCmd.Flags().StringVar(&deleteCSIDriverGuard.uid, "uid", "", "require the CSI driver to have this UID before deleting") + deleteCSIDriverCmd.Flags().Int64Var(&deleteCSIDriverGuard.version, "version", 0, "require the CSI driver to be at this version before deleting") + deleteCmd.AddCommand(deleteCSIDriverCmd) +} diff --git a/cmd/kubectl-ate/internal/cmd/csi_driver_test.go b/cmd/kubectl-ate/internal/cmd/csi_driver_test.go new file mode 100644 index 0000000000..f5f699e34e --- /dev/null +++ b/cmd/kubectl-ate/internal/cmd/csi_driver_test.go @@ -0,0 +1,404 @@ +// Copyright 2026 The Agent Substrate 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 ( + "bytes" + "context" + "errors" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "go.ate.dev/substrate/api/ateapi/v1" + "google.golang.org/grpc" + "google.golang.org/protobuf/proto" + "google.golang.org/protobuf/testing/protocmp" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func TestCSIDriverCommandArgs(t *testing.T) { + runCommandArgsTests(t, []commandArgsTest{ + {name: "list", command: getCSIDriversCmd}, + {name: "get", command: getCSIDriversCmd, args: []string{"csi-nfs"}}, + {name: "get multiple", command: getCSIDriversCmd, args: []string{"csi-nfs", "pd-csi"}}, + {name: "create missing -f", command: createCSIDriverCmd, wantErr: true}, + {name: "create extra arg", command: createCSIDriverCmd, args: []string{"csi-nfs"}, wantErr: true}, + {name: "update missing -f", command: updateCSIDriverCmd, wantErr: true}, + {name: "update extra arg", command: updateCSIDriverCmd, args: []string{"csi-nfs"}, wantErr: true}, + {name: "delete", command: deleteCSIDriverCmd, args: []string{"csi-nfs"}}, + {name: "delete missing name", command: deleteCSIDriverCmd, wantErr: true}, + {name: "delete extra name", command: deleteCSIDriverCmd, args: []string{"a", "b"}, wantErr: true}, + }) +} + +func TestLoadCSIDriverManifest(t *testing.T) { + t.Parallel() + wantNFS := &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs"}, + DriverName: "nfs.csi.k8s.io", + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "csi-nfs-controller.kube-system.svc", Port: 50052}, + Tls: &ateapi.CsiDriverTlsConfig{ServerName: "csi-nfs-controller.kube-system.svc"}, + } + for _, tc := range []struct { + name, manifest, wantErr string + want *ateapi.CsiDriver + }{ + { + name: "camelCase yaml from stdin", + manifest: "metadata: {name: csi-nfs}\ndriverName: nfs.csi.k8s.io\ncontrollerEndpoint: {host: csi-nfs-controller.kube-system.svc, port: 50052}\ntls: {serverName: csi-nfs-controller.kube-system.svc}\n", + want: wantNFS, + }, + { + name: "snake_case yaml from stdin", + manifest: "metadata: {name: csi-nfs}\ndriver_name: nfs.csi.k8s.io\ncontroller_endpoint: {host: csi-nfs-controller.kube-system.svc, port: 50052}\ntls: {server_name: csi-nfs-controller.kube-system.svc}\n", + want: wantNFS, + }, + { + name: "json input", + manifest: `{"metadata":{"name":"csi-nfs"},"driverName":"nfs.csi.k8s.io","controllerEndpoint":{"host":"csi-nfs-controller.kube-system.svc","port":50052},"tls":{"serverName":"csi-nfs-controller.kube-system.svc"}}`, + want: wantNFS, + }, + {name: "missing metadata.name", manifest: "driverName: nfs.csi.k8s.io\ncontrollerEndpoint: {host: 127.0.0.1, port: 9000}", wantErr: "metadata.name is required"}, + {name: "atespace set", manifest: "metadata: {atespace: team-a, name: csi-nfs}", wantErr: "metadata.atespace must be empty"}, + {name: "unknown field", manifest: "metadata: {name: csi-nfs}\nendpoint: tcp://127.0.0.1:9000", wantErr: "invalid CsiDriver"}, + {name: "empty", manifest: "", wantErr: "manifest is empty"}, + {name: "multi-document yaml", manifest: "metadata: {name: a}\n---\nmetadata: {name: b}\n", wantErr: "manifest holds more than one document"}, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got, err := loadCSIDriverManifest(strings.NewReader(tc.manifest), "-") + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("loadCSIDriverManifest() error = %v, want %q", err, tc.wantErr) + } + return + } + if err != nil || cmp.Diff(tc.want, got, protocmp.Transform()) != "" { + t.Fatalf("loadCSIDriverManifest() = (%v, %v), want %v", got, err, tc.want) + } + }) + } + + t.Run("from file", func(t *testing.T) { + t.Parallel() + path := filepath.Join(t.TempDir(), "csi-nfs.yaml") + content := "metadata: {name: csi-nfs}\ndriverName: nfs.csi.k8s.io\ncontrollerEndpoint: {host: csi-nfs-controller.kube-system.svc, port: 50052}\ntls: {serverName: csi-nfs-controller.kube-system.svc}\n" + if err := os.WriteFile(path, []byte(content), 0o600); err != nil { + t.Fatal(err) + } + got, err := loadCSIDriverManifest(strings.NewReader("ignored"), path) + if err != nil || cmp.Diff(wantNFS, got, protocmp.Transform()) != "" { + t.Fatalf("loadCSIDriverManifest(file) = (%v, %v), want %v", got, err, wantNFS) + } + }) + + t.Run("missing file", func(t *testing.T) { + t.Parallel() + if _, err := loadCSIDriverManifest(strings.NewReader(""), filepath.Join(t.TempDir(), "missing.yaml")); err == nil { + t.Fatal("loadCSIDriverManifest(missing) = nil, want error") + } + }) +} + +func TestLoadCSIDriverForUpdate(t *testing.T) { + t.Parallel() + for _, tc := range []struct { + name string + manifest string + want *ateapi.CsiDriver + wantErr string + }{ + { + name: "manifest carries uid and version", + manifest: "metadata: {name: csi-nfs, uid: u-1, version: \"3\"}\ndriverName: nfs.csi.k8s.io\ncontrollerEndpoint: {host: 127.0.0.1, port: 9000}\n", + want: &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs", Uid: "u-1", Version: 3}, + DriverName: "nfs.csi.k8s.io", + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "127.0.0.1", Port: 9000}, + }, + }, + { + name: "missing uid in manifest", + manifest: "metadata: {name: csi-nfs, version: \"3\"}\ndriverName: nfs.csi.k8s.io\ncontrollerEndpoint: {host: 127.0.0.1, port: 9000}\n", + wantErr: "lacks the metadata.uid and metadata.version preconditions", + }, + { + name: "missing version in manifest", + manifest: "metadata: {name: csi-nfs, uid: u-1}\ndriverName: nfs.csi.k8s.io\ncontrollerEndpoint: {host: 127.0.0.1, port: 9000}\n", + wantErr: "lacks the metadata.uid and metadata.version preconditions", + }, + { + name: "negative version in manifest", + manifest: "metadata: {name: csi-nfs, uid: u-1, version: \"-2\"}\ndriverName: nfs.csi.k8s.io\ncontrollerEndpoint: {host: 127.0.0.1, port: 9000}\n", + wantErr: "lacks the metadata.uid and metadata.version preconditions", + }, + { + name: "atespace set", + manifest: "metadata: {atespace: team-a, name: csi-nfs, uid: u-1, version: \"1\"}\n", + wantErr: "metadata.atespace must be empty", + }, + } { + t.Run(tc.name, func(t *testing.T) { + t.Parallel() + got, err := loadCSIDriverForUpdate(strings.NewReader(tc.manifest), "-") + if tc.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("loadCSIDriverForUpdate() error = %v, want %q", err, tc.wantErr) + } + return + } + if err != nil || cmp.Diff(tc.want, got, protocmp.Transform()) != "" { + t.Fatalf("loadCSIDriverForUpdate() = (%v, %v), want %v", got, err, tc.want) + } + }) + } +} + +type fakeCSIDriverClient struct { + byName map[string]*ateapi.CsiDriver + listPages []*ateapi.ListCsiDriversResponse + listReqs []*ateapi.ListCsiDriversRequest + createReq *ateapi.CreateCsiDriverRequest + updateReq *ateapi.UpdateCsiDriverRequest + deleteReq *ateapi.DeleteCsiDriverRequest + err error +} + +func (f *fakeCSIDriverClient) GetCsiDriver(_ context.Context, req *ateapi.GetCsiDriverRequest, _ ...grpc.CallOption) (*ateapi.CsiDriver, error) { + if f.err != nil { + return nil, f.err + } + return f.byName[req.GetCsiDriver().GetName()], nil +} + +func (f *fakeCSIDriverClient) ListCsiDrivers(_ context.Context, req *ateapi.ListCsiDriversRequest, _ ...grpc.CallOption) (*ateapi.ListCsiDriversResponse, error) { + f.listReqs = append(f.listReqs, req) + if f.err != nil { + return nil, f.err + } + if len(f.listPages) == 0 { + return &ateapi.ListCsiDriversResponse{}, nil + } + page := f.listPages[0] + f.listPages = f.listPages[1:] + return page, nil +} + +func (f *fakeCSIDriverClient) CreateCsiDriver(_ context.Context, req *ateapi.CreateCsiDriverRequest, _ ...grpc.CallOption) (*ateapi.CsiDriver, error) { + f.createReq = req + if f.err != nil { + return nil, f.err + } + created := proto.Clone(req.GetCsiDriver()).(*ateapi.CsiDriver) + created.Metadata.Uid, created.Metadata.Version = "srv-uid-1", 1 + return created, nil +} + +func (f *fakeCSIDriverClient) UpdateCsiDriver(_ context.Context, req *ateapi.UpdateCsiDriverRequest, _ ...grpc.CallOption) (*ateapi.CsiDriver, error) { + f.updateReq = req + if f.err != nil { + return nil, f.err + } + updated := proto.Clone(req.GetCsiDriver()).(*ateapi.CsiDriver) + updated.Metadata.Version++ + return updated, nil +} + +func (f *fakeCSIDriverClient) DeleteCsiDriver(_ context.Context, req *ateapi.DeleteCsiDriverRequest, _ ...grpc.CallOption) (*ateapi.CsiDriver, error) { + f.deleteReq = req + if f.err != nil { + return nil, f.err + } + return &ateapi.CsiDriver{Metadata: &ateapi.ResourceMetadata{Name: req.GetCsiDriver().GetName()}}, nil +} + +func TestCSIDriverRunners(t *testing.T) { + ctx := context.Background() + t0 := timestamppb.New(time.Date(2026, 1, 1, 11, 55, 0, 0, time.UTC)) + csiNFS := &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs", Uid: "u-nfs", Version: 2, CreateTime: t0}, + DriverName: "nfs.csi.k8s.io", + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "csi-nfs.kube-system.svc", Port: 50052}, + Tls: &ateapi.CsiDriverTlsConfig{ServerName: "csi-nfs.kube-system.svc"}, + } + pdCSI := &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "pd-csi", Uid: "u-pd", Version: 1, CreateTime: t0}, + DriverName: "pd.csi.storage.gke.io", + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "pd-csi.kube-system.svc", Port: 9000}, + } + + client := &fakeCSIDriverClient{ + byName: map[string]*ateapi.CsiDriver{"csi-nfs": csiNFS, "pd-csi": pdCSI}, + listPages: []*ateapi.ListCsiDriversResponse{ + {CsiDrivers: []*ateapi.CsiDriver{pdCSI}, NextPageToken: "page-2"}, + {CsiDrivers: []*ateapi.CsiDriver{csiNFS}}, + }, + } + + // Single get -o yaml, plus round-trip into both create -f - and update -f -. + var getOut bytes.Buffer + if err := runGetCSIDrivers(ctx, client, &getOut, "yaml", []string{"csi-nfs"}); err != nil || strings.Contains(getOut.String(), "csiDrivers:") { + t.Fatalf("single get err = %v, out = %s", err, getOut.String()) + } + + createdInput, err := loadCSIDriverManifest(strings.NewReader(getOut.String()), "-") + if err != nil || cmp.Diff(csiNFS, createdInput, protocmp.Transform()) != "" { + t.Fatalf("get -o yaml | create -f - parse = (%v, %v), want %v", createdInput, err, csiNFS) + } + var out bytes.Buffer + if err := runCreateCSIDriver(ctx, client, &out, "yaml", createdInput); err != nil || cmp.Diff(csiNFS, client.createReq.GetCsiDriver(), protocmp.Transform()) != "" { + t.Fatalf("create err = %v, req = %v", err, client.createReq) + } + for _, w := range []string{"uid: srv-uid-1", `version: "1"`, "driverName: nfs.csi.k8s.io"} { + if !strings.Contains(out.String(), w) { + t.Errorf("create out = %q, want server response field %q", out.String(), w) + } + } + + updatedInput, err := loadCSIDriverForUpdate(strings.NewReader(getOut.String()), "-") + if err != nil { + t.Fatalf("get -o yaml | update -f - load error = %v", err) + } + updatedInput.ControllerEndpoint = &ateapi.CsiDriverEndpoint{Host: "csi-nfs-v2.kube-system.svc", Port: 50052} + out.Reset() + if err := runUpdateCSIDriver(ctx, client, &out, "yaml", updatedInput); err != nil || cmp.Diff(updatedInput, client.updateReq.GetCsiDriver(), protocmp.Transform()) != "" { + t.Fatalf("update err = %v, req = %v", err, client.updateReq) + } + for _, w := range []string{"uid: u-nfs", `version: "3"`, "host: csi-nfs-v2.kube-system.svc", "port: 50052"} { + if !strings.Contains(out.String(), w) { + t.Errorf("update out = %q, want server response field %q", out.String(), w) + } + } + + // Multi-name get and paged list. + out.Reset() + if err := runGetCSIDrivers(ctx, client, &out, "yaml", []string{"pd-csi", "csi-nfs"}); err != nil || !strings.Contains(out.String(), "csiDrivers:") { + t.Fatalf("multi get err = %v, out = %s", err, out.String()) + } + out.Reset() + if err := runGetCSIDrivers(ctx, client, &out, "yaml", nil); err != nil || len(client.listReqs) != 2 || client.listReqs[1].GetOptions().GetPageToken() != "page-2" { + t.Fatalf("paged list err = %v, reqs = %+v", err, client.listReqs) + } + + // Delete without guards and with guards. + out.Reset() + if err := runDeleteCSIDriver(ctx, client, &out, "csi-nfs", nil); err != nil || out.String() != "csi driver \"csi-nfs\" deleted\n" { + t.Fatalf("unguarded delete err = %v, out = %q", err, out.String()) + } + if diff := cmp.Diff(&ateapi.DeleteCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}}, client.deleteReq, protocmp.Transform()); diff != "" { + t.Errorf("unguarded deleteReq mismatch (-want +got):\n%s", diff) + } + out.Reset() + opts := &ateapi.DeleteOptions{Uid: "u-nfs", Version: 2} + if err := runDeleteCSIDriver(ctx, client, &out, "csi-nfs", opts); err != nil || out.String() != "csi driver \"csi-nfs\" deleted\n" { + t.Fatalf("guarded delete err = %v, out = %q", err, out.String()) + } + if diff := cmp.Diff(&ateapi.DeleteCsiDriverRequest{CsiDriver: &ateapi.ObjectRef{Name: "csi-nfs"}, Options: opts}, client.deleteReq, protocmp.Transform()); diff != "" { + t.Errorf("guarded deleteReq mismatch (-want +got):\n%s", diff) + } + + // Cobra flag wiring and pre-dial checks not covered by unit helpers. + dir := t.TempDir() + missingKubeconfig := filepath.Join(dir, "missing-kubeconfig") + atespaceFile := filepath.Join(dir, "atespace.yaml") + if err := os.WriteFile(atespaceFile, []byte("metadata: {atespace: a, name: csi-nfs}\n"), 0o600); err != nil { + t.Fatal(err) + } + missingPrecondFile := filepath.Join(dir, "no-precond.yaml") + if err := os.WriteFile(missingPrecondFile, []byte("metadata: {name: csi-nfs}\ndriverName: nfs.csi.k8s.io\ncontrollerEndpoint: {host: 127.0.0.1, port: 9000}\n"), 0o600); err != nil { + t.Fatal(err) + } + for _, tc := range []struct { + name string + args []string + wantErr string + wantUsage bool + }{ + { + name: "create -f rejected before connect", + args: []string{"--kubeconfig", missingKubeconfig, "create", "csi-driver", "-f", atespaceFile}, + wantErr: "metadata.atespace must be empty", + }, + { + name: "update -f missing preconditions rejected before connect", + args: []string{"--kubeconfig", missingKubeconfig, "update", "csi-driver", "-f", missingPrecondFile}, + wantErr: "lacks the metadata.uid and metadata.version preconditions", + }, + { + name: "delete --version 0 is usage error", + args: []string{"--kubeconfig", missingKubeconfig, "delete", "csi-driver", "csi-nfs", "--version", "0"}, + wantErr: "--version must be at least 1, got 0", + wantUsage: true, + }, + { + name: "delete negative --version is usage error", + args: []string{"--kubeconfig", missingKubeconfig, "delete", "csi-driver", "csi-nfs", "--version=-5"}, + wantErr: "--version must be at least 1, got -5", + wantUsage: true, + }, + { + name: "delete empty --uid is usage error", + args: []string{"--kubeconfig", missingKubeconfig, "delete", "csi-driver", "csi-nfs", "--uid", ""}, + wantErr: "--uid must not be empty", + wantUsage: true, + }, + } { + if _, stderr, err := runRootCLI(t, tc.args...); err == nil || !strings.Contains(err.Error(), tc.wantErr) { + t.Fatalf("%s: runRootCLI(%v) error = %v (stderr = %q), want %q", tc.name, tc.args, err, stderr, tc.wantErr) + } else { + var uerr *usageError + if errors.As(err, &uerr) != tc.wantUsage { + t.Fatalf("%s: errors.As(usageError) = %v, want %v (err = %v)", tc.name, errors.As(err, &uerr), tc.wantUsage, err) + } + } + } +} + +func TestCSIDriverRunnersPropagateErrors(t *testing.T) { + ctx := context.Background() + boom := errors.New("boom") + client := &fakeCSIDriverClient{err: boom} + driver := &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "x", Uid: "u-1", Version: 1}, + DriverName: "d.csi.example.io", + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "127.0.0.1", Port: 9000}, + } + var out bytes.Buffer + for _, tc := range []struct { + name, want string + run func() error + }{ + {"get", `failed to get csi driver "x"`, func() error { return runGetCSIDrivers(ctx, client, &out, "table", []string{"x"}) }}, + {"list", "failed to list csi drivers", func() error { return runGetCSIDrivers(ctx, client, &out, "table", nil) }}, + {"create", "failed to create csi driver", func() error { return runCreateCSIDriver(ctx, client, &out, "yaml", driver) }}, + {"update", "failed to update csi driver", func() error { return runUpdateCSIDriver(ctx, client, &out, "yaml", driver) }}, + {"delete", "failed to delete csi driver", func() error { return runDeleteCSIDriver(ctx, client, &out, "x", nil) }}, + } { + t.Run(tc.name, func(t *testing.T) { + out.Reset() + err := tc.run() + if !errors.Is(err, boom) || !strings.Contains(err.Error(), tc.want) { + t.Fatalf("err = %v, want %q wrapping boom", err, tc.want) + } + if out.Len() != 0 { + t.Errorf("out = %q, want nothing printed on error", out.String()) + } + }) + } +} diff --git a/cmd/kubectl-ate/internal/cmd/external_volume.go b/cmd/kubectl-ate/internal/cmd/external_volume.go new file mode 100644 index 0000000000..a1db1a385f --- /dev/null +++ b/cmd/kubectl-ate/internal/cmd/external_volume.go @@ -0,0 +1,88 @@ +// Copyright 2026 The Agent Substrate 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 ( + "fmt" + + "github.com/spf13/cobra" + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/cmd/kubectl-ate/internal/printer" +) + +var ( + getExternalVolumeAtespaceFlag string + getExternalVolumeAllAtespacesFlag bool +) + +var getExternalVolumesCmd = &cobra.Command{ + Use: "external-volume [volume-name ...]", + Aliases: []string{"external-volumes", "externalvolume", "externalvolumes"}, + Short: "List or get external volumes", + Args: cobra.ArbitraryArgs, + RunE: func(cmd *cobra.Command, args []string) error { + if err := validateAtespaceFlags("external volumes", args, getExternalVolumeAtespaceFlag, getExternalVolumeAllAtespacesFlag); err != nil { + return err + } + + ctx := cmd.Context() + client, err := newAPIClient(cmd) + if err != nil { + return fmt.Errorf("failed to connect to ate-api-server: %w", err) + } + defer client.Close() + + if len(args) > 0 { + volumes := make([]*ateapi.ExternalVolume, 0, len(args)) + for _, name := range args { + volume, err := client.GetExternalVolume(ctx, &ateapi.GetExternalVolumeRequest{ + ExternalVolume: &ateapi.ObjectRef{Atespace: getExternalVolumeAtespaceFlag, Name: name}, + }) + if err != nil { + return fmt.Errorf("failed to get external volume %q: %w", name, err) + } + volumes = append(volumes, volume) + } + if len(volumes) == 1 { + return printer.PrintExternalVolumeTo(cmd.OutOrStdout(), volumes[0], outputFmt) + } + return printer.PrintExternalVolumesTo(cmd.OutOrStdout(), volumes, outputFmt) + } + + var volumes []*ateapi.ExternalVolume + pageToken := "" + for { + resp, err := client.ListExternalVolumes(ctx, &ateapi.ListExternalVolumesRequest{ + Atespace: getExternalVolumeAtespaceFlag, + Options: &ateapi.ListOptions{PageSize: 1000, PageToken: pageToken}, + }) + if err != nil { + return fmt.Errorf("failed to list external volumes: %w", err) + } + volumes = append(volumes, resp.GetExternalVolumes()...) + pageToken = resp.GetNextPageToken() + if pageToken == "" { + break + } + } + return printer.PrintExternalVolumesTo(cmd.OutOrStdout(), volumes, outputFmt) + }, +} + +func init() { + getExternalVolumesCmd.Flags().StringVarP(&getExternalVolumeAtespaceFlag, "atespace", "a", "", "get external volumes in a specific atespace (mutually exclusive with --all-atespaces)") + getExternalVolumesCmd.Flags().BoolVarP(&getExternalVolumeAllAtespacesFlag, "all-atespaces", "A", false, "get external volumes across all atespaces (mutually exclusive with --atespace)") + getCmd.AddCommand(getExternalVolumesCmd) +} diff --git a/cmd/kubectl-ate/internal/cmd/get_test.go b/cmd/kubectl-ate/internal/cmd/get_test.go index 91495c5945..3edb45d7e8 100644 --- a/cmd/kubectl-ate/internal/cmd/get_test.go +++ b/cmd/kubectl-ate/internal/cmd/get_test.go @@ -36,6 +36,7 @@ func TestGetScopeBeforeConnecting(t *testing.T) { {"actors", getActorsCmd, &getActorAtespaceFlag, &getActorAllAtespacesFlag}, {"actor templates", getActorTemplatesCmd, &getActorTemplateAtespaceFlag, &getActorTemplateAllAtespacesFlag}, {"tags", getTagsCmd, &getTagAtespaceFlag, &getTagAllAtespacesFlag}, + {"external volumes", getExternalVolumesCmd, &getExternalVolumeAtespaceFlag, &getExternalVolumeAllAtespacesFlag}, } { t.Run(resource.name, func(t *testing.T) { previousAtespace, previousAll := *resource.atespace, *resource.all diff --git a/cmd/kubectl-ate/internal/cmd/root.go b/cmd/kubectl-ate/internal/cmd/root.go index d2b722fb61..d2eba63f76 100644 --- a/cmd/kubectl-ate/internal/cmd/root.go +++ b/cmd/kubectl-ate/internal/cmd/root.go @@ -17,11 +17,14 @@ package cmd import ( "errors" "fmt" + "io" "os" "strings" "github.com/spf13/cobra" + "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc/metadata" + "google.golang.org/grpc/status" "go.ate.dev/substrate/internal/preview" "go.ate.dev/substrate/internal/version" @@ -74,6 +77,7 @@ func executeRoot(root *cobra.Command) error { return err } fmt.Fprintf(errOut, "Error: %v\n", err) + printDebugInfo(errOut, err) var uerr *usageError if errors.As(err, &uerr) { fmt.Fprintf(errOut, "\n%s", executedCmd.UsageString()) @@ -88,6 +92,29 @@ type reportedError struct{ error } func (e reportedError) Unwrap() error { return e.error } +func printDebugInfo(w io.Writer, err error) { + st, ok := status.FromError(err) + if !ok { + return + } + for _, detail := range st.Details() { + debugInfo, ok := detail.(*errdetails.DebugInfo) + if !ok { + continue + } + detailMsg := debugInfo.GetDetail() + stackEntries := debugInfo.GetStackEntries() + if detailMsg != "" { + fmt.Fprintf(w, "Debug info: %s\n", detailMsg) + } else if len(stackEntries) > 0 { + fmt.Fprintln(w, "Debug info:") + } + for _, entry := range stackEntries { + fmt.Fprintf(w, " %s\n", entry) + } + } +} + func Execute() { if err := executeRoot(rootCmd); err != nil { os.Exit(1) diff --git a/cmd/kubectl-ate/internal/cmd/validation_test.go b/cmd/kubectl-ate/internal/cmd/validation_test.go index c2a8b72654..444a2e4012 100644 --- a/cmd/kubectl-ate/internal/cmd/validation_test.go +++ b/cmd/kubectl-ate/internal/cmd/validation_test.go @@ -16,11 +16,15 @@ package cmd import ( "bytes" + "fmt" "strings" "testing" "github.com/spf13/cobra" "github.com/spf13/pflag" + "google.golang.org/genproto/googleapis/rpc/errdetails" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" ) func resetFlagsRecursive(c *cobra.Command) { @@ -554,3 +558,89 @@ func TestRuntimeErrorsDoNotPrintUsage(t *testing.T) { t.Errorf("expected runtime error not to print Usage, got:\n%s", stderr) } } + +func TestExecuteRootPrintsDebugInfo(t *testing.T) { + statusWithDebug := func(t *testing.T, detail string, stack ...string) error { + t.Helper() + st, err := status.New(codes.Aborted, "concurrent update conflict, please retry").WithDetails(&errdetails.DebugInfo{ + Detail: detail, + StackEntries: stack, + }) + if err != nil { + t.Fatalf("WithDetails: %v", err) + } + return st.Err() + } + + tests := []struct { + name string + cmdErr error + wantSubstrs []string + notWantSubstrs []string + }{ + { + name: "direct gRPC status with DebugInfo", + cmdErr: statusWithDebug(t, "concurrent update conflict, please retry: row version mismatch"), + wantSubstrs: []string{ + "Error: rpc error: code = Aborted desc = concurrent update conflict, please retry", + "Debug info: concurrent update conflict, please retry: row version mismatch", + }, + }, + { + name: "wrapped gRPC status with DebugInfo and stack entries", + cmdErr: fmt.Errorf("failed to resume actor: %w", statusWithDebug(t, "conflict: store.ErrNotFound", "frame1", "frame2")), + wantSubstrs: []string{ + "Error: failed to resume actor: rpc error: code = Aborted desc = concurrent update conflict, please retry", + "Debug info: conflict: store.ErrNotFound", + " frame1", + " frame2", + }, + }, + { + name: "DebugInfo with stack entries only prints header", + cmdErr: statusWithDebug(t, "", "frame1"), + wantSubstrs: []string{ + "Error: rpc error: code = Aborted desc = concurrent update conflict, please retry", + "Debug info:\n frame1", + }, + }, + { + name: "gRPC status without DebugInfo", + cmdErr: status.Error(codes.NotFound, "Actor foo not found"), + wantSubstrs: []string{"Error: rpc error: code = NotFound desc = Actor foo not found"}, + notWantSubstrs: []string{"Debug info:"}, + }, + } + + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var errBuf bytes.Buffer + cmd := &cobra.Command{ + Use: "test-cmd", + SilenceUsage: true, + SilenceErrors: true, + RunE: func(cmd *cobra.Command, args []string) error { + return tc.cmdErr + }, + } + cmd.SetErr(&errBuf) + cmd.SetArgs([]string{}) + + if err := executeRoot(cmd); err == nil { + t.Fatal("expected error, got nil") + } + + stderr := errBuf.String() + for _, want := range tc.wantSubstrs { + if !strings.Contains(stderr, want) { + t.Errorf("stderr = %q, want it to contain %q", stderr, want) + } + } + for _, notWant := range tc.notWantSubstrs { + if strings.Contains(stderr, notWant) { + t.Errorf("stderr = %q, did not want it to contain %q", stderr, notWant) + } + } + }) + } +} diff --git a/cmd/kubectl-ate/internal/printer/csi_driver.go b/cmd/kubectl-ate/internal/printer/csi_driver.go new file mode 100644 index 0000000000..5500e43e7b --- /dev/null +++ b/cmd/kubectl-ate/internal/printer/csi_driver.go @@ -0,0 +1,77 @@ +// Copyright 2026 The Agent Substrate 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 printer + +import ( + "cmp" + "fmt" + "io" + "net" + "slices" + "strconv" + "text/tabwriter" + + "go.ate.dev/substrate/api/ateapi/v1" +) + +func formatCSIDriverEndpoint(ep *ateapi.CsiDriverEndpoint) string { + if ep == nil || ep.GetHost() == "" { + return "" + } + return net.JoinHostPort(ep.GetHost(), strconv.Itoa(int(ep.GetPort()))) +} + +func formatCSIDriverTLS(tls *ateapi.CsiDriverTlsConfig) string { + if tls == nil { + return "disabled" + } + return "mtls (pod-identity)" +} + +// PrintCSIDriversTo prints a slice of CSI drivers to the provided writer. +func PrintCSIDriversTo(out io.Writer, drivers []*ateapi.CsiDriver, format string) error { + slices.SortFunc(drivers, func(a, b *ateapi.CsiDriver) int { + return cmp.Compare(a.GetMetadata().GetName(), b.GetMetadata().GetName()) + }) + switch format { + case "json", "yaml": + return printProto(out, &ateapi.ListCsiDriversResponse{CsiDrivers: drivers}, format) + case "table": + w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) + fmt.Fprintln(w, "NAME\tDRIVER\tCONTROLLER-ENDPOINT\tTLS\tAGE") + for _, d := range drivers { + fmt.Fprintf( + w, + "%s\t%s\t%s\t%s\t%s\n", + d.GetMetadata().GetName(), + d.GetDriverName(), + formatCSIDriverEndpoint(d.GetControllerEndpoint()), + formatCSIDriverTLS(d.GetTls()), + formatAge(d.GetMetadata().GetCreateTime()), + ) + } + return w.Flush() + default: + return fmt.Errorf("unsupported format %q", format) + } +} + +// PrintCSIDriverTo prints a single CSI driver to the provided writer. +func PrintCSIDriverTo(out io.Writer, driver *ateapi.CsiDriver, format string) error { + if format == "json" || format == "yaml" { + return printProto(out, driver, format) + } + return PrintCSIDriversTo(out, []*ateapi.CsiDriver{driver}, format) +} diff --git a/cmd/kubectl-ate/internal/printer/csi_driver_test.go b/cmd/kubectl-ate/internal/printer/csi_driver_test.go new file mode 100644 index 0000000000..570c71585a --- /dev/null +++ b/cmd/kubectl-ate/internal/printer/csi_driver_test.go @@ -0,0 +1,87 @@ +// Copyright 2026 The Agent Substrate 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 printer + +import ( + "bytes" + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "go.ate.dev/substrate/api/ateapi/v1" + "google.golang.org/protobuf/types/known/timestamppb" +) + +func TestPrintCSIDrivers(t *testing.T) { + now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + pinNow(t, now) + + csiNFS := &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-nfs", Uid: "u-1", Version: 1, CreateTime: timestamppb.New(now.Add(-10 * time.Minute))}, + DriverName: "nfs.csi.k8s.io", + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "csi-nfs.kube-system.svc", Port: 50052}, + Tls: &ateapi.CsiDriverTlsConfig{ServerName: "csi-nfs.kube-system.svc"}, + } + csiPD := &ateapi.CsiDriver{ + Metadata: &ateapi.ResourceMetadata{Name: "csi-pd", CreateTime: timestamppb.New(now.Add(-5 * time.Hour))}, + DriverName: "pd.csi.storage.gke.io", + ControllerEndpoint: &ateapi.CsiDriverEndpoint{Host: "::1", Port: 9000}, + } + + var buf bytes.Buffer + if err := PrintCSIDriversTo(&buf, []*ateapi.CsiDriver{csiPD, csiNFS}, "table"); err != nil { + t.Fatalf("PrintCSIDriversTo(table) error = %v", err) + } + wantTable := "NAME DRIVER CONTROLLER-ENDPOINT TLS AGE\n" + + "csi-nfs nfs.csi.k8s.io csi-nfs.kube-system.svc:50052 mtls (pod-identity) 10m\n" + + "csi-pd pd.csi.storage.gke.io [::1]:9000 disabled 5h\n" + if diff := cmp.Diff(wantTable, buf.String()); diff != "" { + t.Errorf("table mismatch (-want +got):\n%s", diff) + } + + for _, tc := range []struct { + name, format string + single bool + wantSub []string + wantErr bool + }{ + {name: "list json", format: "json", wantSub: []string{`"csiDrivers"`, `"driverName": "nfs.csi.k8s.io"`}}, + {name: "list yaml", format: "yaml", wantSub: []string{"csiDrivers:", "driverName: nfs.csi.k8s.io"}}, + {name: "single json bare object", single: true, format: "json", wantSub: []string{`"driverName": "nfs.csi.k8s.io"`, `"uid": "u-1"`}}, + {name: "single yaml bare object", single: true, format: "yaml", wantSub: []string{"driverName: nfs.csi.k8s.io", "uid: u-1", `version: "1"`}}, + {name: "single table", single: true, format: "table", wantSub: []string{"NAME", "csi-nfs nfs.csi.k8s.io csi-nfs.kube-system.svc:50052 mtls (pod-identity) 10m"}}, + {name: "unsupported list format", format: "xml", wantErr: true}, + {name: "unsupported single format", single: true, format: "xml", wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + var out bytes.Buffer + var err error + if tc.single { + err = PrintCSIDriverTo(&out, csiNFS, tc.format) + } else { + err = PrintCSIDriversTo(&out, []*ateapi.CsiDriver{csiNFS}, tc.format) + } + if (err != nil) != tc.wantErr { + t.Fatalf("error = %v, wantErr %v", err, tc.wantErr) + } + for _, w := range tc.wantSub { + if !strings.Contains(out.String(), w) { + t.Errorf("output = %q, want substring %q", out.String(), w) + } + } + }) + } +} diff --git a/cmd/kubectl-ate/internal/printer/printer.go b/cmd/kubectl-ate/internal/printer/printer.go index 7d68707b8e..6a0752b1fa 100644 --- a/cmd/kubectl-ate/internal/printer/printer.go +++ b/cmd/kubectl-ate/internal/printer/printer.go @@ -385,6 +385,44 @@ func PrintTagTo(out io.Writer, tag *ateapi.Tag, format string) error { return PrintTagsTo(out, []*ateapi.Tag{tag}, format) } +// PrintExternalVolumesTo prints external volumes to the provided writer. +func PrintExternalVolumesTo(out io.Writer, volumes []*ateapi.ExternalVolume, format string) error { + slices.SortFunc(volumes, func(a, b *ateapi.ExternalVolume) int { + if c := cmp.Compare(a.GetMetadata().GetAtespace(), b.GetMetadata().GetAtespace()); c != 0 { + return c + } + return cmp.Compare(a.GetMetadata().GetName(), b.GetMetadata().GetName()) + }) + switch format { + case "json", "yaml": + return printProto(out, &ateapi.ListExternalVolumesResponse{ExternalVolumes: volumes}, format) + case "table": + w := tabwriter.NewWriter(out, 0, 0, 3, ' ', 0) + fmt.Fprintln(w, "ATESPACE\tNAME\tDRIVER\tVOLUME ID\tAGE") + for _, volume := range volumes { + driver, volumeID := "", "" + if csi := volume.GetStatus().GetCsi(); csi != nil { + driver, volumeID = csi.GetDriverName(), csi.GetVolumeId() + } + fmt.Fprintf(w, "%s\t%s\t%s\t%s\t%s\n", + volume.GetMetadata().GetAtespace(), volume.GetMetadata().GetName(), + driver, volumeID, + formatAge(volume.GetMetadata().GetCreateTime())) + } + return w.Flush() + default: + return fmt.Errorf("unsupported format %q", format) + } +} + +// PrintExternalVolumeTo prints a single external volume to the provided writer. +func PrintExternalVolumeTo(out io.Writer, volume *ateapi.ExternalVolume, format string) error { + if format == "json" || format == "yaml" { + return printProto(out, volume, format) + } + return PrintExternalVolumesTo(out, []*ateapi.ExternalVolume{volume}, format) +} + func sortAtespaces(atespaces []*ateapi.Atespace) { slices.SortFunc(atespaces, func(a, b *ateapi.Atespace) int { return cmp.Compare(a.GetMetadata().GetName(), b.GetMetadata().GetName()) diff --git a/cmd/kubectl-ate/internal/printer/printer_test.go b/cmd/kubectl-ate/internal/printer/printer_test.go index 82fd02c3df..c30fb76fd4 100644 --- a/cmd/kubectl-ate/internal/printer/printer_test.go +++ b/cmd/kubectl-ate/internal/printer/printer_test.go @@ -699,6 +699,95 @@ func TestPrintTagTo_YAML(t *testing.T) { } } +func TestPrintExternalVolumesTo_Table(t *testing.T) { + now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) + pinNow(t, now) + + var buf bytes.Buffer + volumes := []*ateapi.ExternalVolume{ + { + Metadata: &ateapi.ResourceMetadata{ + Atespace: "team-a", + Name: "shared", + CreateTime: timestamppb.New(now.Add(-5 * time.Minute)), + }, + Status: &ateapi.ExternalVolumeStatus{Csi: &ateapi.CsiVolumeStatus{VolumeId: "nfs-server#exports#shared", DriverName: "nfs.csi.k8s.io"}}, + }, + { + Metadata: &ateapi.ResourceMetadata{ + Atespace: "team-a", + Name: "adopted", + CreateTime: timestamppb.New(now.Add(-5 * time.Hour)), + }, + Status: &ateapi.ExternalVolumeStatus{Csi: &ateapi.CsiVolumeStatus{VolumeId: "projects/p/zones/z/disks/preexisting", DriverName: "pd.csi.storage.gke.io"}}, + }, + { + Metadata: &ateapi.ResourceMetadata{ + Atespace: "team-a", + Name: "unprovisioned", + CreateTime: timestamppb.New(now.Add(-5 * time.Second)), + }, + }, + } + + if err := PrintExternalVolumesTo(&buf, volumes, "table"); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + expected := `ATESPACE NAME DRIVER VOLUME ID AGE +team-a adopted pd.csi.storage.gke.io projects/p/zones/z/disks/preexisting 5h +team-a shared nfs.csi.k8s.io nfs-server#exports#shared 5m +team-a unprovisioned 5s +` + if diff := cmp.Diff(expected, buf.String()); diff != "" { + t.Errorf("output mismatch (-want +got):\n%s", diff) + } +} + +func TestPrintExternalVolumesTo_Invalid(t *testing.T) { + var buf bytes.Buffer + if err := PrintExternalVolumesTo(&buf, nil, "xml"); err == nil { + t.Errorf("expected error for invalid format, got nil") + } +} + +func TestPrintExternalVolumeTo_JSON(t *testing.T) { + var buf bytes.Buffer + volume := &ateapi.ExternalVolume{Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "shared"}} + + if err := PrintExternalVolumeTo(&buf, volume, "json"); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + expected := `{ + "metadata": { + "atespace": "team-a", + "name": "shared" + } +} +` + if diff := cmp.Diff(expected, buf.String()); diff != "" { + t.Errorf("output mismatch (-want +got):\n%s", diff) + } +} + +func TestPrintExternalVolumeTo_YAML(t *testing.T) { + var buf bytes.Buffer + volume := &ateapi.ExternalVolume{Metadata: &ateapi.ResourceMetadata{Atespace: "team-a", Name: "shared"}} + + if err := PrintExternalVolumeTo(&buf, volume, "yaml"); err != nil { + t.Fatalf("unexpected error: %v", err) + } + + expected := `metadata: + atespace: team-a + name: shared +` + if diff := cmp.Diff(expected, buf.String()); diff != "" { + t.Errorf("output mismatch (-want +got):\n%s", diff) + } +} + func TestPrintAtespacesTo_Table(t *testing.T) { now := time.Date(2026, 1, 1, 12, 0, 0, 0, time.UTC) pinNow(t, now) diff --git a/cmd/objectstore-plugin/README.md b/cmd/objectstore-plugin/README.md index e5a72d7a55..ee52b4ed38 100644 --- a/cmd/objectstore-plugin/README.md +++ b/cmd/objectstore-plugin/README.md @@ -18,15 +18,15 @@ created from. The exchange is private to this plugin, defined in On the node side, `node` mode on GCS dials that exchange, at `--exchange-address` through the ate-api-server Service, verified with `--exchange-ca-file` and `--exchange-server-name`. Each `FetchSnapshot` or -`UploadSnapshot` runs on a storage client built with the actor's token. The -token and the client are cached under the JWT they were obtained for, never -under a claim read out of it, while at least twenty minutes remain, so the -transfers that follow one another for an actor share connections. A client -that leaves the cache is not closed, its connections close once idle. A request -GCS refuses with a cached token is retried once with a token the exchange -re-derives, and a second refusal is `PERMISSION_DENIED`. A transfer without -`actor_jwt` is `INVALID_ARGUMENT` on GCS. S3 ignores the field and transfers -with the pod's own credentials. +`UploadSnapshot` runs on a storage client built with the actor's token over a +shared HTTP/2 transport pool. The token and the client are cached under the JWT +they were obtained for, never under a claim read out of it, while at least +twenty minutes remain. A client that leaves the cache is not closed, so an +in-flight transfer finishes on the shared pool. A request GCS refuses with a +cached token is retried once with a token the exchange re-derives, and a second +refusal is `PERMISSION_DENIED`. A transfer without `actor_jwt` is +`INVALID_ARGUMENT` on GCS. S3 ignores the field and transfers with the pod's +own credentials. The JWT is the one ate-api-server mints for atelet through `WorkerService.MintWorkerActorJwt`, with the audience named on the @@ -69,8 +69,11 @@ This binary's, GCS and S3: that is the seam between its backends. - `internal/objectstoreplugin/gcsboundary`: grants to Credential Access Boundary rules. -- `internal/objectstoreplugin/gcsissuer`: the GCS `Issuer`, STS exchange and - token cache. +- `internal/objectstoreplugin/gcsissuer`: the GCS `Issuer`, one STS exchange + per source token, local minting, an STS exchange per actor for a boundary + too large to mint locally, and the token cache. +- `internal/proto/clientsideboundarypb`: the Credential Access Boundary + `gcsissuer` encrypts into each token, in Google's format. - `internal/objectstoreplugin/exchangeclient`: the node side on GCS, the exchange call and the cache of tokens and storage clients per JWT. The `Credentials` interface in `internal/objectstoreplugin` is its seam. diff --git a/cmd/objectstore-plugin/main.go b/cmd/objectstore-plugin/main.go index 4a2d7ae15a..c68d055984 100644 --- a/cmd/objectstore-plugin/main.go +++ b/cmd/objectstore-plugin/main.go @@ -91,7 +91,7 @@ func main() { ctx := context.Background() serverboot.InitLogger() - if err := preview.Init(*previewFlags...); err != nil { + if _, err := preview.New(*previewFlags...); err != nil { serverboot.Fatal(ctx, "Invalid --preview", err) } if *socket == "" { diff --git a/cmd/podcertcontroller/main.go b/cmd/podcertcontroller/main.go index 291d8dac4e..5cef10198e 100644 --- a/cmd/podcertcontroller/main.go +++ b/cmd/podcertcontroller/main.go @@ -134,7 +134,7 @@ func main() { return } slog.SetDefault(slog.New(slog.NewJSONHandler(os.Stdout, nil))) - if err := preview.Init(*previewFlags...); err != nil { + if _, err := preview.New(*previewFlags...); err != nil { slog.ErrorContext(ctx, "Invalid --preview", slog.Any("err", err)) os.Exit(1) } diff --git a/demos/egress/README.md b/demos/egress/README.md index 9f6d198593..4e9c559c57 100644 --- a/demos/egress/README.md +++ b/demos/egress/README.md @@ -76,6 +76,7 @@ test, and manual walkthrough are otherwise the same. | Actor authentication | Co-located atenet `ext_proc` | Built-in `substrateEgress` policy | | Configuration | Envoy bootstrap in `atenet-egress.yaml` | Static agentgateway ConfigMap overlay | | Access log | Text beginning with `[egress]`, including actor SAN | Structured log including `substrate.connect.authority` | +| WebSocket egress | Carried over HTTP/1.1 | Refused with `403 Forbidden` | The experimental additional egress `ext_proc` service currently requires Envoy; the installer rejects that option with agentgateway rather than silently omitting it. @@ -90,7 +91,7 @@ rejects that option with agentgateway rather than silently omitting it. container started with `--mode=egress`; agentgateway uses its built-in `substrateEgress` policy and does not need that sidecar. The installer renders the matching configuration and container. - **Egress opt-in** — `ate-api-server --default-egress-gateway-address=atenet-egress.ate-system.svc:443` - (set in `manifests/ate-install/ate-api-server.yaml`). ateapi stamps the address onto every + (the default of `ate-setup --default-egress-gateway-address`). ateapi stamps the address onto every atelet `Run`/`Restore`, which turns on tunneled egress cluster-wide. - **Egress policy** — the gateway denies by default, so the demo Actor needs an `EgressPolicy` before its fetches succeed. `kubectl ate create egress-policy` creates one from a manifest @@ -220,6 +221,8 @@ the Actor dial that address as a cleartext-HTTP/2 gRPC server and return what ca } ``` +Add `"tls":true` to dial the target over TLS. The server is verified against the Actor's roots. + One RPC per streaming shape, because each fails differently over a network path: - **unary `Echo`** — always run. Its status arrives in trailers, *after* the response body, which @@ -237,8 +240,9 @@ failed RPC answers `502` and still carries its gRPC code in the same field. `internal/e2e/suites/networking` drives this endpoint against the `testserver` fixture's `grpc` subcommand (`internal/e2e/fixtures/testserver`, deployed by `e2e.DeployServerPod` from the shared -server-pod manifest) in `TestActorEgressGRPC`; the same fixture, or any h2c gRPC server reachable -from the cluster, works for a manual run. +server-pod manifest) in `TestActorEgressGRPC`, and over TLS under an `https` rule in +`TestActorEgressGRPCOverTLS`; the same fixture, or any h2c gRPC server reachable from the cluster, +works for a manual run. ## Notes / limitations diff --git a/demos/egress/main.go b/demos/egress/main.go index ba573330d1..decb63e2f8 100644 --- a/demos/egress/main.go +++ b/demos/egress/main.go @@ -39,6 +39,7 @@ import ( "github.com/gorilla/websocket" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" grpcstatus "google.golang.org/grpc/status" @@ -99,10 +100,12 @@ type websocketResponse struct { // grpcRequest asks for one unary Echo against target, and additionally for a // server-stream or a bidirectional stream when the matching count is positive. type grpcRequest struct { - // Target is the gRPC server to dial, as host:port. Cleartext HTTP/2: the - // point of the demo is that the actor speaks plainly and the egress path - // carries it, so there is nothing here to configure TLS with. - Target string `json:"target"` + // Target is the gRPC server to dial, as host:port, over cleartext HTTP/2 + // unless TLS is set. + Target string `json:"target"` + // TLS dials Target over TLS and verifies the server against the actor's + // roots. + TLS bool `json:"tls,omitempty"` Message string `json:"message"` StreamCount int32 `json:"streamCount,omitempty"` // BidiCount is how many messages to send over a bidirectional stream, @@ -771,6 +774,11 @@ func handleGRPC(w http.ResponseWriter, r *http.Request) { return } + transportCredentials := insecure.NewCredentials() + if input.TLS { + transportCredentials = credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS12}) + } + ctx, cancel := context.WithTimeout(r.Context(), requestTimeout) defer cancel() @@ -779,7 +787,7 @@ func handleGRPC(w http.ResponseWriter, r *http.Request) { // snapshot does not survive one: the peer is long gone by the time the // actor resumes, and every RPC on it would fail in a way that looks like a // broken gateway. - conn, err := grpc.NewClient(input.Target, grpc.WithTransportCredentials(insecure.NewCredentials())) + conn, err := grpc.NewClient(input.Target, grpc.WithTransportCredentials(transportCredentials)) if err != nil { writeJSON(w, http.StatusBadRequest, grpcResponse{Error: fmt.Sprintf("dialing %s: %v", input.Target, err)}) return diff --git a/demos/egress/main_test.go b/demos/egress/main_test.go index 82a0e64c28..718cc6c257 100644 --- a/demos/egress/main_test.go +++ b/demos/egress/main_test.go @@ -36,6 +36,7 @@ import ( "github.com/gorilla/websocket" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" "go.ate.dev/substrate/internal/proto/grpcechopb" "go.ate.dev/substrate/internal/testcert" @@ -480,14 +481,14 @@ func (echoServer) EchoBidi(stream grpc.BidiStreamingServer[grpcechopb.EchoReques } // startEchoServer serves Echo on loopback and returns its host:port. -func startEchoServer(t *testing.T) string { +func startEchoServer(t *testing.T, opts ...grpc.ServerOption) string { t.Helper() listener, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatalf("listening on loopback: %v", err) } - server := grpc.NewServer() + server := grpc.NewServer(opts...) grpcechopb.RegisterEchoServer(server, echoServer{}) go func() { if err := server.Serve(listener); err != nil { @@ -588,6 +589,24 @@ func TestGRPCBidi(t *testing.T) { } } +// With tls the call verifies the server, which is what lets the e2e read a +// successful call as proof of the certificate the actor saw. The server here +// has a certificate the default roots do not trust. +func TestGRPCOverTLSVerifiesTheServer(t *testing.T) { + material := testcert.NewServerTLS(t, net.ParseIP("127.0.0.1")) + certificate, err := tls.X509KeyPair(material.Certificate, material.PrivateKey) + if err != nil { + t.Fatalf("loading server certificate: %v", err) + } + target := startEchoServer(t, grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{certificate}}))) + + recorder, got := postGRPC(t, fmt.Sprintf(`{"target":%q,"tls":true,"message":"hello"}`, target)) + + if recorder.Code != http.StatusBadGateway || got.Code != codes.Unavailable.String() || !strings.Contains(got.Error, "certificate") { + t.Errorf("status = %d, body = %+v; want %d, code Unavailable and a certificate error", recorder.Code, got, http.StatusBadGateway) + } +} + // A failed RPC must still report its gRPC code. That code is the only part of // the answer that proves trailers arrived, so collapsing it into the HTTP // status would erase the thing the e2e is looking for. diff --git a/docs/api-style-guide.md b/docs/api-style-guide.md index e360a1939b..a9a672af51 100644 --- a/docs/api-style-guide.md +++ b/docs/api-style-guide.md @@ -340,14 +340,21 @@ allow external controllers and upstream systems / automations to react to resour Custom methods are for operations that don't map cleanly to CRUD: lifecycle transitions (Suspend, Resume, Revert), long-running actions, or commands with side effects that standard Update semantics would misrepresent. ```proto -rpc SuspendActor(SuspendActorRequest) returns (SuspendActorResponse) {} +rpc ResumeActor(ResumeActorRequest) returns (ResumeActorResponse) {} + +message ResumeActorRequest { + message Options { + int64 version = 1; + string uid = 2; + } -message SuspendActorRequest { ObjectRef actor = 1; + Options options = 2; } -message SuspendActorResponse { +message ResumeActorResponse { Actor actor = 1; + bool resumed = 2; } ``` @@ -357,6 +364,7 @@ Rules: - Request message name **must** match the RPC name with a `Request` suffix. - The request **must** identify the target resource using an `ObjectRef` field (for both atespace-scoped and global-scoped resources). - Response message name **must** match the RPC name with a `Response` suffix. A custom method **must not** return the resource directly; put it in a field of the response, so method-specific output can be added later (e.g., `ResumeActorResponse.resumed`). +- Cross-cutting control fields (such as `version` and `uid` preconditions, dry-run, or idempotency controls) belong in an optional `options` field typed as a nested `message Options` inside the request message. Method-specific inputs stay at the top level of the request (e.g., `MintActorJwtRequest.audiences`). `SuspendActorRequest.options` is an exception for `v1.0.0` compatibility: it uses the top-level `SuspendOptions` message, which also keeps `mode` where it shipped. --- @@ -553,7 +561,7 @@ updated, err := client.UpdateActor(ctx, &UpdateActorRequest{ - `version` and `uid` are control fields managed by the server, not mutable fields. A client echoes them back as guards, it never edits them. - Both are **required**: an update that leaves `version` (0) or `uid` ("") unset is rejected with `INVALID_ARGUMENT`. There is no blind by-name update. A client that has not read the resource cannot update it; a client that has read it already holds both values. -- The requirement is on Update only. Delete's guards stay optional (below), and Create assigns both fields rather than checking them. +- The requirement is on Update only. The guards of Delete and of custom methods stay optional (below), and Create assigns both fields rather than checking them. - Modify what you read, do not reconstruct it: step 2 above mutates the message the server returned rather than assembling a new `Actor`. - This matters when the server is newer than the client: a reconstructed message does not carry the fields the client does not recognize, and an update that omits an immutable field is rejected rather than silently rewriting it. @@ -574,12 +582,26 @@ message DeleteOptions { } ``` +**Custom methods:** the guards are `version` and `uid` fields in the request's `options` message (a nested `Options` message on the request, or `SuspendOptions` on `SuspendActorRequest` for `v1.0.0` compatibility). The server checks them against the resource it is about to act on, before any early return for a resource already in the requested state: + +```proto +message ResumeActorRequest { + message Options { + int64 version = 1; // 0 = skip + string uid = 2; // "" = skip + } + + ObjectRef actor = 1; + Options options = 2; +} +``` + **Server behavior (applies to `version` and `uid` alike):** - If the client provides a `version` or `uid` that does not match the server's current value: return `ABORTED`. - On Update, if the client omits either guard: return `INVALID_ARGUMENT`. The request is malformed, so this is decided before the resource is read. -- On Delete, if the client omits a guard: skip that check. +- On Delete or a custom method, if the client omits a guard: skip that check. -So Update never gives last-writer-wins, while Delete still does by default. +So Update never gives last-writer-wins, while Delete and custom methods still do by default. --- @@ -668,7 +690,7 @@ All fields of all APIs must be validated. We use ## 11. Annotations -Resources and methods carry proto options that say which messages are resources, how they nest, and which resource each RPC operates on. +Resources, methods, and fields carry proto options that say which messages are resources, how they nest, which resource each RPC operates on, and which elements are in preview. ### 11.1 Resources @@ -731,6 +753,36 @@ Rules: - `resource` is the resource's message name, and that message **must** carry a `(resource)` option. - A subresource's method names the subresource, not its parent: `EgressPolicy` for `GetActorEgressPolicy`. +### 11.3 Preview gates + +A method or field that is part of a preview feature **must** name its gate: + +```proto +rpc ResizeActor(ResizeActorRequest) returns (ResizeActorResponse) { + option (method) = { + resource : "Actor" + preview_gate : { name : "MyFeature" } + }; +} + +// +k8s:ifDisabled(MyFeature)=+k8s:forbidden +// +k8s:optional +MyFeatureConfig my_feature = 7 [ (field).preview_gate.name = "MyFeature" ]; + +// +k8s:optional +MyFeatureStatus my_feature_status = 4 [ (field).preview_gate = { + name : "MyFeature" + allow_when_disabled : true +} ]; +``` + +Rules: +- The gate **must** be declared in `internal/preview`. +- A field with preview gate `` **must** also have `+k8s:ifDisabled()=+k8s:forbidden`, and vice versa, unless the gate sets `allow_when_disabled`. +- A field the server writes, such as one in `status`, **must** set `allow_when_disabled` and **must not** have the `ifDisabled` tag. + +See [Preview gates](dev/preview-gates.md) for how gates are enforced. + --- ## 12. Sensitive Fields (`debug_redact`) @@ -781,7 +833,7 @@ Selector worker_selector = 2; 1. **Summary**: the first paragraph, one or two sentences saying what the element is or does. It stands on its own: a reader who stops after it knows what the element is for. Every element's comment starts with one, fields and enum values included. 2. **Details**: any further paragraphs, for what a user needs beyond the summary, such as constraints, defaults, and how the element interacts with others. 3. **Internal notes**: text for API maintainers rather than API users, such as why a bound was chosen or a `TODO`, wrapped in `(--` and `--)`, as in [AIP-192](https://google.aip.dev/192#internal-comments). A note may span lines and may sit anywhere before the directives, including between paragraphs. Only the note is left out of the API's documentation. Text after it is still documented. -4. **Directives**: the `+k8s:` validation directives (see section #10) and `+ate:` tags such as `+ate:preview` (see [Preview Gates](dev/preview-gates.md)), last. Nothing may follow them: a `#` note on a directive stays on that directive's line. +4. **Directives**: the `+k8s:` validation directives (see section #10), last. Nothing may follow them: a `#` note on a directive stays on that directive's line. ### 13.2 Formatting diff --git a/docs/api-validation.md b/docs/api-validation.md index b78d562bb1..665993e016 100644 --- a/docs/api-validation.md +++ b/docs/api-validation.md @@ -88,14 +88,9 @@ learn these rules. ### Alpha / beta tags -Some tags are designated "alpha" or "beta" in validation-gen. If we try to use -such a tag in our APIs, we will get a warning. To get around this, we must -acknowledge that we are using an alpha or beta tag by adding a `+k8s:alpha` or -`+k8s:beta` tag prefix. Example: - -``` -// +k8s:alpha(since: "0.0")=+k8s:theAlphaTagWeWantToUse -``` +Some tags are designated "alpha" or "beta" in validation-gen; the `--docs` +output shows the level of each tag. The semantics of an alpha tag may change +in a future release, so prefer a stable tag when one fits. ### Rules for all fields @@ -136,13 +131,13 @@ requiring awkward evolution. Consider using an enum instead of a boolean. All string fields must have either a `+k8s:format=` tag or a `+k8s:maxLength=` tag. The format tag is preferred when possible. -validation-gen supports a number of formats, and can easily be extended to -support new ones. +validation-gen supports a number of formats, and we can define our own (see +"Custom formats" below). -If validation-gen does not support the format you need, you can use a -combination of `+k8s:maxLength` and `+k8s:customValidation` (see below) tags. -If a string field does not have an a priori known format, then it must at least -have a `+k8s:maxLength` tag. +If no format fits and a regular expression cannot describe the value, you can +use a combination of `+k8s:maxLength` and `+k8s:customValidation` (see below) +tags. If a string field does not have an a priori known format, then it must +at least have a `+k8s:maxLength` tag. ### Rules for struct (message) fields @@ -389,8 +384,44 @@ be specified, we can do this: ObjectRef worker = 1; ``` -Subfields may not be nested, but that will come in a future release. If you -need deeper subfield validation, you can use `+k8s:customValidation` (see below). +Subfield tags can be nested to reach deeper fields: + +``` +// +k8s:required +// +k8s:subfield(metadata)=+k8s:required +// +k8s:subfield(metadata)=+k8s:subfield(atespace)=+k8s:required +Tag tag = 1; +``` + +A subfield validation is skipped when the message which holds the subfield is +unset, so tag the intermediate field as required if it must be present. + +### Custom formats + +When validation-gen has no format for a value which a regular expression can +describe, we can define one in `.validation-extensions.yaml`. Example: + +``` +formats: + - name: ate-singleton-name + docs: This field must be "default" + pattern: (^$|^default$) + message: must be "default" +``` + +The new format is used like a built-in one: + +``` +// +k8s:required +// +k8s:format=ate-singleton-name +string name = 1; +``` + +The pattern is only anchored if it says so with `^` and `$`. A format which is +applied through `+k8s:subfield` is evaluated even when the subfield is empty, +so the pattern should accept the empty string and leave emptiness to +`+k8s:optional` and `+k8s:required`. Every format needs an exhaustive test in +`internal/apivalidationtest`. ### Custom validation diff --git a/docs/assets/actor-call-diagram.svg b/docs/assets/actor-call-diagram.svg index d7e14dedb8..94670c77cd 100644 --- a/docs/assets/actor-call-diagram.svg +++ b/docs/assets/actor-call-diagram.svg @@ -2,211 +2,211 @@ Substrate architecture and data flows - - - - - + + + + + - + - - Kubernetes cluster - - ate-system namespace: control plane - - Kubernetes - - podcertificate-controller-system - - Worker node - - Worker Pod, worker namespace - - Sandbox: gVisor or microVM - - Sandbox: gVisor or microVM + + Kubernetes cluster + + ate-system namespace: control plane + + Kubernetes + + podcertificate-controller-system + + Worker node + + Worker Pod, worker namespace + + Sandbox: gVisor or microVM + + Sandbox: gVisor or microVM - - - - - - - - - - - - - + + + + + + + + + + + + + - + - + - + - + - + - + - + - + - + - + - + - + - + - + - - Application layer - agent framework, - end-user auth + + Application layer + agent framework, + end-user auth - - External relying - parties + + External relying + parties - - External services - and tools + + External services + and tools - - - Snapshot bucket + + + Snapshot bucket - - - Sandbox assets - (SandboxConfig) + + + Sandbox assets + (SandboxConfig) - - atenet-router - ingress gateway + + atenet-router + ingress gateway - - ate-api-server - OpenFGA authz, identity minting, - objectstore-plugin sidecar + + ate-api-server + OpenFGA authz, identity minting, + objectstore-plugin sidecar - - ate-controller + + ate-controller - - ate-idp-server - OIDC discovery, JWKS + + ate-idp-server + OIDC discovery, JWKS - - - PostgreSQL + + + PostgreSQL - - k8s-credential-provider - egress secrets + + k8s-credential-provider + egress secrets - - atenet-egress - egress gateway + + atenet-egress + egress gateway - - kube-apiserver + + kube-apiserver - - podcertcontroller - pod, DNS, DB certs + + podcertcontroller + pod, DNS, DB certs - - ateworker + atunnel - ingress listener, egress redirect, - DNS relay + + ateworker + atunnel + ingress listener, egress redirect, + DNS relay - - atelet DaemonSet - objectstore-plugin sidecar + + atelet DaemonSet + objectstore-plugin sidecar - - Actor A - untrusted code, no credentials + + Actor A + untrusted code, no credentials - - Actor B - untrusted code, no credentials + + Actor B + untrusted code, no credentials - - Container image - registry + + Container image + registry - - A1 - create actor - - A2 - save record - - B1 - send request - - B2 - resume actor - - B3 - restore actor - - B4 - get snapshot - - B5 - start sandbox - - B6 - forward request - - B7 - deliver - - B8 - call a tool - - B9 - forward as this actor - - B10 - get credential - - B11 - call with credential - - A: create an actor - - B: send a request to an actor - - Supporting connection - - Sandbox: untrusted actor code - - Worker Pod: shared by many actors - - Node - - Control plane namespace - - Untrusted - - Node and worker components - - Control plane components - - Outside Substrate + + A1 + create actor + + A2 + save record + + B1 + send request + + B2 + resume actor + + B3 + restore actor + + B4 + get snapshot + + B5 + start sandbox + + B6 + forward request + + B7 + deliver + + B8 + call a tool + + B9 + forward as this actor + + B10 + get credential + + B11 + call with credential + + A: create an actor + + B: send a request to an actor + + Supporting connection + + Sandbox: untrusted actor code + + Worker Pod: shared by many actors + + Node + + Control plane namespace + + Untrusted + + Node and worker components + + Control plane components + + Outside Substrate diff --git a/docs/assets/actor-template-diagram.svg b/docs/assets/actor-template-diagram.svg index 179e966453..8f56a7fe7f 100644 --- a/docs/assets/actor-template-diagram.svg +++ b/docs/assets/actor-template-diagram.svg @@ -2,131 +2,131 @@ Substrate actor template creation - - - - - + + + + + - + - - Kubernetes cluster - - ate-system namespace: control plane - - Worker node - - Worker Pod, worker namespace - - Sandbox: gVisor or microVM + + Kubernetes cluster + + ate-system namespace: control plane + + Worker node + + Worker Pod, worker namespace + + Sandbox: gVisor or microVM - - - - - - - - - + + + + + + + + + - + - + - - Application layer - agent framework, - end-user auth + + Application layer + agent framework, + end-user auth - - ate-api-server - OpenFGA authz, identity minting, - objectstore-plugin sidecar + + ate-api-server + OpenFGA authz, identity minting, + objectstore-plugin sidecar - - - PostgreSQL + + + PostgreSQL - - ateworker + atunnel - ingress listener, egress redirect, - DNS relay + + ateworker + atunnel + ingress listener, egress redirect, + DNS relay - - atelet DaemonSet - objectstore-plugin sidecar + + atelet DaemonSet + objectstore-plugin sidecar - - Golden actor - built from the template + + Golden actor + built from the template - - - Snapshot bucket + + + Snapshot bucket - - - Sandbox assets - (SandboxConfig) + + + Sandbox assets + (SandboxConfig) - - Container image - registry + + Container image + registry - - P1 - create template - - P2 - run golden actor - - P3 - pull image - - P4 - start sandbox - - P5 - get actor certificate - - P6 - mint certificate - - P7 - suspend golden actor - - P8 - get storage credential - - P9 - upload snapshot - - P10 - copy tag snapshot - - P10 - mark ready - - P: prepare an actor template - - Other connection - - Sandbox: untrusted actor code - - Worker Pod: shared by many actors - - Node - - Control plane namespace - - Untrusted - - Node and worker components - - Control plane components - - Outside Substrate + + P1 + create template + + P2 + run golden actor + + P3 + pull image + + P4 + start sandbox + + P5 + get actor certificate + + P6 + mint certificate + + P7 + suspend golden actor + + P8 + get storage credential + + P9 + upload snapshot + + P10 + copy tag snapshot + + P10 + mark ready + + P: prepare an actor template + + Other connection + + Sandbox: untrusted actor code + + Worker Pod: shared by many actors + + Node + + Control plane namespace + + Untrusted + + Node and worker components + + Control plane components + + Outside Substrate diff --git a/docs/assets/identity-actor-to-actor.svg b/docs/assets/identity-actor-to-actor.svg new file mode 100644 index 0000000000..75ea853495 --- /dev/null +++ b/docs/assets/identity-actor-to-actor.svg @@ -0,0 +1,38 @@ + +Actor to actor: Actor A calls through the egress gateway, which injects A's JWT; the frontend verifies it and routes to Actor B via ingress + + + + +Substrate + +App frontend +your app + +Ingress +trusted +frontends + +Actor A +sandbox • no creds + +Egress gateway +policy + injection + +Actor B +sandbox • no creds + + +1 + + +2 + +A's JWT + + +3 + + +4 + diff --git a/docs/assets/identity-actor-to-cloud.svg b/docs/assets/identity-actor-to-cloud.svg new file mode 100644 index 0000000000..d92fff226e --- /dev/null +++ b/docs/assets/identity-actor-to-cloud.svg @@ -0,0 +1,36 @@ + +Actor to cloud: the egress gateway asks the credential provider to exchange Actor A's JWT at the cloud STS and injects the resulting token + + + + +Substrate + +Actor A +sandbox • no creds + +Egress gateway +policy + injection + +Credential provider +token exchange plugin + +Cloud APIs +storage, compute, … + +Cloud STS +token exchange + + +1 + + +2 + + +3 + + +4 + + diff --git a/docs/assets/identity-actor-to-saas.svg b/docs/assets/identity-actor-to-saas.svg new file mode 100644 index 0000000000..071f43bef3 --- /dev/null +++ b/docs/assets/identity-actor-to-saas.svg @@ -0,0 +1,34 @@ + +Actor to SaaS: the egress gateway matches an egress rule and swaps the placeholder for an OAuth access token that the credential provider gets from an OAuth token broker + + + + +Substrate + +Actor A +sandbox • no creds + +Egress gateway +policy + injection + +Credential provider +token broker plugin + +GitHub, cloud, +SaaS APIs + +OAuth token broker +holds refresh tokens + + + +1 + + +2 + + +3 + + diff --git a/docs/assets/identity-sre-debugging.svg b/docs/assets/identity-sre-debugging.svg new file mode 100644 index 0000000000..9488ec2904 --- /dev/null +++ b/docs/assets/identity-sre-debugging.svg @@ -0,0 +1,30 @@ + +SRE debugging: an engineer gets a short-lived SSO token and uses it against the Substrate API to manage Actor B + + + + +Substrate + +SSO / IdP +your identity +provider + +SRE / dev +debugging + +Substrate API +control plane + +Actor B +sandbox • no creds + + +1 + + +2 + + +3 + diff --git a/docs/assets/identity-user-to-actor.svg b/docs/assets/identity-user-to-actor.svg new file mode 100644 index 0000000000..3422ab746f --- /dev/null +++ b/docs/assets/identity-user-to-actor.svg @@ -0,0 +1,35 @@ + +User to actor: Alice signs in via SSO, the app frontend calls ingress, ingress routes to Actor A + + + + +Substrate + +Alice +user + +SSO / IdP +your identity +provider + +App frontend +your app + +Ingress +trusted +frontends + +Actor A +sandbox • no creds + + + +1 + + +2 + + +3 + diff --git a/docs/assets/security-boundaries.svg b/docs/assets/security-boundaries.svg index 6030a8010f..5121a3d2c2 100644 --- a/docs/assets/security-boundaries.svg +++ b/docs/assets/security-boundaries.svg @@ -2,84 +2,84 @@ Substrate security boundaries - - - - - + + + + + - + - - Substrate - - Control plane - - Worker node - - Sandbox - - Sandbox + + Substrate + + Control plane + + Worker node + + Sandbox + + Sandbox - - - - - - - - + + + + + + + + - - Your application - authenticates end users + + Your application + authenticates end users - - Substrate API - authorization per atespace + + Substrate API + authorization per atespace - - Ingress gateway - authenticated callers + + Ingress gateway + authenticated callers - - Egress gateway - destination policy, - credential injection + + Egress gateway + destination policy, + credential injection - - Actor A - no credentials + + Actor A + no credentials - - Actor B - no credentials + + Actor B + no credentials - - Node supervisor + + Node supervisor - - External services - and tools + + External services + and tools - - - Snapshot storage + + + Snapshot storage - manage actors - per-actor credentials (GCS) - - 1 - - 1 - - 2 - - 2 - - 3 - - 4 - invoke + manage actors + per-actor credentials (GCS) + + 1 + + 1 + + 2 + + 2 + + 3 + + 4 + invoke diff --git a/docs/concepts/architecture.md b/docs/concepts/architecture.md index e7182ec3b2..9ea3d15467 100644 --- a/docs/concepts/architecture.md +++ b/docs/concepts/architecture.md @@ -143,6 +143,64 @@ Kubernetes is the industry standard platform for running modern workloads. It is built to support a wide array of workloads, and it can scale to very large clusters. Agent Substrate leverages Kubernetes for infrastructure provisioning and worker lifecycle management (Kubernetes Pods). It builds on top of Kubernetes features like Pods and Pod autoscaling, while Agent Substrate provides agent-specific scheduling and control to achieve lower latency. Using Kubernetes as the underlying system enables consistent infrastructure management across all workloads types that are required for end to end agentic deployments and allows holistic infrastructure optimizations for RL scenarios that span agentic, inference and training cycles. +### Namespace-scoped Kubernetes watches + +By default, `atecontroller` and `atelet` watch WorkerPools in all Kubernetes +namespaces. To manage workloads in a single namespace, set the same flag on +both binaries, for example: + +```text +--watch-namespace=agent-workloads +``` + +This scopes the controller's WorkerPool, Deployment, NetworkPolicy, and worker +Pod caches, including its separate worker syncer. It also scopes atelet's +WorkerPool and worker Pod informers. +The atelet stats poller limits its Pod LISTs to the same namespace. Both atelet +Pod queries retain their node and worker-label selectors. +An empty value watches all namespaces. +Both binaries reject invalid namespace names at startup and log the effective +scope. The API server reads worker counts from the Worker registry and has no +WorkerPool informer. It waits up to one minute for its required Kubernetes +caches and reports any that fail to sync. +The controller's worker syncer also waits up to one minute. If its caches have +not synced, it logs the pending ones and exits. +The worker syncer's startup scan leaves registry entries from other namespaces +alone, because a Pod absent from a scoped cache is not necessarily deleted. +It logs a single warning with the skipped count and watched namespace when +such entries exist. + +The system namespace remains the Pod's `POD_NAMESPACE`, supplied by the +Kubernetes downward API. The API server still watches atelet Pods there, and +the controller still watches the `egress-mitm-ca-pool` Secret there. The flag +does not move system components or scope cluster resources. + +The flag changes requests, not RBAC grants. For a restricted installation, +replace the default broad ClusterRoleBindings with namespace RoleBindings for +namespaced resources and separate ClusterRoleBindings for cluster resources. +Preserve the verbs from the existing role definitions: + +| Component | Namespace grants | Cluster grants still required | +| --- | --- | --- | +| `atecontroller` | WorkerPools and their status/finalizers, Deployments, NetworkPolicies, and Pods in the watched namespace; the CA pool Secret and API EndpointSlices in the system namespace | ClusterTrustBundles and the egress MITM signer attestation permission | +| `ateapi` | atelet Pods in the system namespace | Nodes (`get`), CSIDriverConfigs, and StorageClasses | +| `atelet` | WorkerPools, worker Pods, and Warning Event writes (`create` and `patch` on `events.k8s.io` Events) in the watched namespace; API EndpointSlices in the system namespace | SandboxConfigs, CSIDriverConfigs, and ClusterTrustBundles | + +A Role alone cannot grant the remaining cluster permissions. Keeping the +default ClusterRoleBindings also keeps their broader access, regardless of the +flag. The installer does not rewrite those bindings when this flag is added. +Keep the API server's WorkerPool grant while upgrading from a version that +still watches WorkerPools. + +This setting does not partition the PostgreSQL Worker registry, constrain API +principals, or provide tenant isolation. Before narrowing an existing +installation's scope, drain and retire workloads outside the new namespace; +otherwise their registered Workers remain available to the API scheduler while +this controller no longer manages their Pods. The atelet also treats workers +absent from its scoped Pod cache as deleted and removes their local runtime files. +Configure RBAC before starting the scoped components, and use the same watch +namespace on each replica. + ### Why do we need a specialized control plane for Agent Substrate? * Idle Pods still consume resources. While Kubernetes is very scalable, compute capacity is finite and has real costs. Whether we're talking about @@ -336,7 +394,7 @@ The node-level subsystem manages the physical execution of sandboxes and the mov * **Storage Mover**: External snapshots move through an *object-store plugin*, a sidecar that serves the `objectstore.v1` gRPC API over a Unix socket in its pod. `atelet`'s sidecar (`NodeProvider`) uploads and fetches a snapshot's files; `ate-api-server`'s sidecar (`ControlProvider`) copies and deletes whole snapshots. Neither main process talks to object storage for snapshots. The in-tree plugin, `cmd/objectstore-plugin`, backs the API with GCS or S3; `ATE_STORAGE_BACKEND` on the sidecar (unset or `gcs`, or `s3` with the `AWS_*` variables) selects which, see `manifests/ate-install/atelet.yaml`, `ate-api-server.yaml`, and the kind overlay for an S3 example. The same `atelet` sidecar serves `AssetProvider`, which fetches every sandbox asset; `atelet` reads a `gs://` asset anonymously only when the plugin cannot serve it, which covers public buckets such as `gs://gvisor`. The plugin stages each download where `atelet` cannot read it, and copies it into `atelet`'s cache only if its sha256 matches; it refuses any URL under a snapshot location. `atelet` verifies the sha256 again and has no object storage credentials or settings of its own. - * **Sandbox Asset Cache**: `atelet` keeps one node-local, content-addressed cache of the sandbox binaries every actor runs on and gives each actor hard links into it, prewarms each local worker's default runtime and keeps it linked under the worker's directory, and evicts to a byte budget without taking anything an actor or a worker still uses. See the [Sandbox Asset Cache](sandbox-asset-cache.md) page. + * **Sandbox Asset Cache**: `atelet` keeps one node-local, content-addressed cache of the sandbox binaries every actor runs on and gives each actor hard links into it, links each local worker's default runtime under the worker's directory as it writes the worker's sandbox runtimes file, and evicts to a byte budget without taking anything an actor or a worker still uses. See the [Sandbox Asset Cache](sandbox-asset-cache.md) page. ### Sandbox Classes @@ -378,7 +436,7 @@ Handles actor-aware ingress routing, on-demand resumption, and policy-enforced e Actor is tunneled through `atunnel` to `atenet-egress`, which enforces destination policy and resolves credential replacement effects without placing ambient secrets in the sandbox (see the - [Network Egress Contract](../guides/network-egress.md) and + [Egress PEP contract](../guides/egress-traffic.md#egress-pep-contract) and [Egress Credential Injection](../guides/egress-credential-injection.md)). * **Latency**: The data plane is optimized for low-latency activation by bypassing Kubernetes' eventual consistency and performing atomic physical assignments. diff --git a/docs/concepts/request-parking.md b/docs/concepts/request-parking.md index 6ebb9d24d0..90652862e4 100644 --- a/docs/concepts/request-parking.md +++ b/docs/concepts/request-parking.md @@ -54,23 +54,22 @@ keeps retrying with exponential backoff until either **The budget bounds retries, not a committed resume.** When the budget elapses the router stops starting new resume attempts, but an attempt already in flight is **never canceled**: by then the control plane has committed work to -it, and canceling would discard an in-progress restore. Instead the router -waits for that attempt's real result: a restore that overshoots the budget -(routine under node contention) is **served late** rather than failed, and a -late retryable error still surfaces as the capacity `503`. The attempt is -bounded by the control plane's own server-side RPC deadline, and Envoy's -ext_proc message timeout (`budget + 5s`) remains the ceiling on how long a -client is held either way. +it, and canceling would discard an in-progress restore. Instead a request keeps +waiting for that attempt until 1s before Envoy's ext_proc message timeout +(`budget + 5s`). A restore that overshoots the budget (routine under node +contention) is **served late** if it finishes by then, and a late retryable +error still surfaces as the capacity `503`. If the attempt is still running, +the router ends the wait and answers `503 "actor is still resuming, +retry"`. **Worst-case occupancy.** A parked request's lot slot is held until its caller -stops waiting; with the Envoy dataplane that is bounded by the ext_proc -message timeout (`budget + 5s`). The resume attempt itself can outlive every -caller: it carries no client-side deadline and runs until ateapi's -server-side maximum RPC deadline, holding that actor's flight entry. +stops waiting, which is at most `budget + 4s`. The resume attempt itself can +outlive every caller: it carries no client-side deadline and runs until +ateapi's server-side maximum RPC deadline, holding that actor's flight entry. New requests for the same actor during that window do not start another -control-plane call — they join the in-flight attempt, and if it has not -resolved by their own stream deadline they are ended by the dataplane's -timeout rather than a router verdict. +control-plane call. They join the in-flight attempt, wait up to the same +`budget + 4s` from their own arrival, and get the same "still resuming" `503` +if it has not finished. To bound resource use and provide backpressure, parked requests are admitted to a **parking lot** of fixed capacity (`--parked-request-max`, default `1024`). A @@ -140,8 +139,9 @@ Envoy sidecar) alive until in-flight streams finish, and the ext_proc drain deadline (`--drain-timeout`) defaults to a value derived from `--parked-request-budget` and is validated at startup to be `>=` the budget — so a parked request always gets its full budget and a normal verdict (routed -`200` or capacity `503`) even mid-termination. See the graceful-shutdown knobs -(`--drain-delay`, `--drain-timeout`) in `manifests/ate-install/atenet-router.yaml`. +`200` or the router's `503`) even mid-termination. See the graceful-shutdown +knobs (`--drain-delay`, `--drain-timeout`) in +`manifests/ate-install/atenet-router.yaml`. ## Configuration @@ -174,7 +174,7 @@ bounds the wait. | `served` | The resume succeeded and the request was routed to its worker. | | `budget_exhausted` | The park budget elapsed while the resume was still blocked on a retryable condition (pool saturated, a concurrent operation holding the actor, or the control plane unavailable) — the signal that capacity, not a fault, is the bottleneck. | | `canceled` | The client disconnected while parked (request context canceled). | - | `timeout` | The request's own deadline expired while parked (distinct from the park budget). | + | `timeout` | The request's own deadline expired while parked, or the router stopped waiting because the resume was still running (the "still resuming" `503`). | | `error` | The resume failed with a non-retryable error (`NotFound`, `PermissionDenied`, ...). | - `atenet.router.parking.rejected` — counter: requests shed because the lot was diff --git a/docs/concepts/sandbox-asset-cache.md b/docs/concepts/sandbox-asset-cache.md index 15e87022a7..6e5de6e202 100644 --- a/docs/concepts/sandbox-asset-cache.md +++ b/docs/concepts/sandbox-asset-cache.md @@ -34,8 +34,8 @@ cannot cross mounts. | `sandbox-asset-cache/` | The cache (`--sandbox-asset-cache-dir`). `entries//data` is a cached file or extracted tree, published read-only with execute bits kept; `tmp/` holds in-flight downloads; `.rm-*` are retired entries awaiting removal. An entry directory's mtime is its last-use clock. | | `actors//sandbox-assets/` | The actor's assets, each a hard link into the cache, named by asset name. The only location a worker runs a sandbox binary from; the worker checks that a request names the actor's own directory. `sandbox-assets.staging/` beside it exists only while a Run fetches. | | `workers//sandbox-runtimes.json` | What each worker advertises to the control plane, written by `atelet`. | -| `workers//default-runtime//` | The worker's default runtimes, one directory per default its file advertises, by bundle hash, one per sandbox class, linked in from the cache by the prewarmer. These links are what keeps a default runtime cached while no actor runs it; the syncer removes a directory when the file stops naming its runtime, and they all go with the worker's directory when the pod does. | -| `sandbox-asset-scratch/` | Short-lived destinations for fetches that have no actor and no worker directory to link into: the assets the worker sandbox syncer stages when checking a version (and probes `runsc` for CPU features). Wiped at startup. | +| `workers//default-runtime//` | The worker's default runtimes, one directory per default its file advertises, by bundle hash, one per sandbox class, linked in from the cache by the worker sandbox syncer as it builds the file. These links are what keeps a default runtime cached while no actor runs it; the syncer removes a directory when the file stops naming its runtime, and they all go with the worker's directory when the pod does. | +| `sandbox-asset-scratch/` | Short-lived destinations for fetches that have no actor and no worker directory to link into: the assets the worker sandbox syncer stages to verify a restorable version, and the `runsc` it probes for CPU features. Wiped at startup. | | `sandbox-runtime-index.json` | The runtime index serialized: every runtime a worker on this node has advertised, by hash, with the asset record the hash was computed from. | | `cache-boot-id` | The node's boot ID when `atelet` last started. A different ID at startup means the node rebooted, so `atelet` empties the cache first. | @@ -77,18 +77,18 @@ pool runs, hashes every enabled version, and: - **registers** every hash in the runtime index, with its record, and writes the index file durably, *before* anything else, so a hash is resolvable before the worker can register it with the control plane; -- fetches each version's assets into the cache (every sync for a microVM - default, and once per `atelet` process for restorable microVM versions and - gVisor `runsc` digests), probes what a snapshot taken on the runtime must - find again (CPU features for gVisor, host CPU identity for microVM), and - writes the worker's `sandbox-runtimes.json`, from which the worker - registers; +- stages the **default** version's assets into its directory under the + worker's `default-runtime/`, on every sync, linking them from the cache + and fetching what the cache lacks, so they stay cached while no actor + runs them; stages each restorable version's assets once per `atelet` + process to verify them; probes what a snapshot taken on the runtime must + find again (CPU features for gVisor, once per `runsc` digest; host CPU + identity for microVM); and writes the worker's `sandbox-runtimes.json`, + from which the worker registers; - records what the worker now advertises, which is what the written file says; -- makes the worker's `default-runtime/` directory match the file's - **default** runtimes, and hands each to the **prewarmer**, which links - the default's cached assets into the runtime's directory so they stay - cached while no actor runs them. +- removes the directories under `default-runtime/` of the defaults the file + no longer names, which unlinks them. A `SandboxConfig` or `WorkerPool` change registers the affected pools' runtimes at once and rewrites their files after a jitter of up to thirty @@ -109,49 +109,42 @@ before. ### The default runtime directories A worker's default runtime must stay cached while no actor runs it, and the -cache has one way to say "in use": a hard link. So the prewarmer leaves its -links in a directory that belongs to the worker, and the syncer decides -which directories exist. Nothing counts references and nothing prunes. - -- Once a worker's file is written and registered, the syncer makes - `default-runtime/` hold one directory per default the file names, by - bundle hash, and nothing else: the directory of a default the file no - longer names is removed, which unlinks that runtime, and an empty one is - created for each default that lacks one. Then it hands the prewarmer one - item per default, the hash and its directory. -- The hand-over comes after the build on purpose. A build that fails, as a - permanent `runsc` probe failure does, leaves the file and so the - directories as they were, with the previous default still linked and still - advertised. Unless an evicted gVisor version was promoted to default, the - build has already fetched the default's assets into the cache, so the - prewarm is just hard links. -- The prewarm fills what exists and creates nothing. It checks that its - directory is there, stages into it, and on an error checks again: a - directory gone, after a later sync or the pod's removal, means the item - was superseded, and it ends without a retry and without recreating - anything. A directory the syncer already filled costs a stat per asset, so - a re-sync with an unchanged default downloads nothing and leaves the links - alone. -- A failed prewarm retries with backoff and gives up after eight attempts. - The directory stays, empty or partial, until the next sync; an actor - placed on that default meanwhile stages on demand. +cache has one way to say "in use": a hard link. So the syncer stages the +default into a directory that belongs to the worker and leaves the links +there. Nothing counts references: a directory exists while the worker's +file names its runtime as a default. + +- The build stages the default into `default-runtime//` before the + file names it, through the same cache call an actor's activation uses: a + directory already filled costs a stat per asset, a missing asset is linked + from the cache, and an evicted one is downloaded again. A default the + cache cannot serve fails the build, which leaves the file, and so the + previous default's directory, as they were. The gVisor probe runs a + `runsc` linked into the scratch directory for it, not the one under the + worker's directory. +- Once the file is written and registered, the syncer removes everything + under `default-runtime/` but the directories of the defaults the file + names, which unlinks the retired runtime. The new default is linked before + the old one is unlinked, so the worker holds one throughout. +- A build that fails after staging the default, as a permanent `runsc` + probe failure does, leaves the new directory beside the previous + default's. That pins one more runtime until a later sync writes the file + and prunes; nothing reads the directory meanwhile. - A pod's removal removes its whole directory, links included. After a restart the directories of pods still on the node keep protecting their defaults with no wait on the syncer, and the startup sweep removes the directories of pods that are gone. - Cache writes aren't synced, so after a node reboot atelet empties the cache and removes every worker's `default-runtime/` directory at startup. The - syncer and the prewarmer then rebuild them as on a new node. + syncer then rebuilds them as on a new node. The old default's directory is removed as soon as the file names the new -default: by then the worker has registered the new default (and unless an -evicted gVisor version was promoted to default, the build has already fetched -it into the cache), so nothing new is placed on the old one. Actors already -running on it hold their own links, and restores of snapshots taken on it go -through the on-demand path like every non-default version. Several pods of -one pool each hold their own links to the same entries; the entry becomes -evictable when the last of them goes. One queue and one worker drain the -prewarm items in order. +default, which is linked under the worker by then. The worker registers the +new file a moment later; an actor the control plane places on the old +default before that fetches it on demand, like every non-default version, +as does a restore of a snapshot taken on it. Actors already running on it +hold their own links. Several pods of one pool each hold their own links to +the same entries; the entry becomes evictable when the last of them goes. ## Eviction diff --git a/docs/dev/best-practices/metrics.md b/docs/dev/best-practices/metrics.md index 55203163c4..f6d806d5d6 100644 --- a/docs/dev/best-practices/metrics.md +++ b/docs/dev/best-practices/metrics.md @@ -155,7 +155,10 @@ ones every new metric meets: * **Bounded or catalog-scoped.** Every `ate.*` label is either an enumeration with a fixed value list, or names an object an operator created (a template, a pool). Nothing on a metric label comes from a request payload, an error - message, a hostname, or a path. + message, a hostname, or a path. The one per-object label is + `ate.worker.name`, on the `ate.worker.*` resource instruments only: one + series per live worker, like `k8s.node.name` on node metrics. Do not add it + to other instruments. * **Normalize at the producer.** When a value arrives from the wire or from a file nothing validated, map it onto the bounded set before recording: `ateattr.NormalizeSandboxClass`, `ateattr.NormalizeOperationName`, @@ -311,7 +314,11 @@ _, err = meter.RegisterCallback(func(_ context.Context, o metric.Observer) error Two habits from `RegisterWorkerCount` in ateapi: if the source is unavailable, return nil and observe nothing this cycle rather than observing zero; and seed the series an alert depends on with an explicit zero, so "no idle workers" is a -`0` and not a missing series. +`0` and not a missing series. Seed from what the source knows. ateapi learns a +pool and its sandbox class from its workers, so a pool with no `Worker` or whose +workers have not reported a class gets no zero series. The +`ate.workerpool.workers` section of `docs/guides/observability.md` gives the +query that allows for both. Keep the callback cheap and lock-free where you can. It runs on every collection (every 10 s on kind, every 60 s in production) and on every Prometheus scrape. diff --git a/docs/dev/mitm-egress-test-runbook.md b/docs/dev/mitm-egress-test-runbook.md index 1a11fdb156..a4855d1f51 100644 --- a/docs/dev/mitm-egress-test-runbook.md +++ b/docs/dev/mitm-egress-test-runbook.md @@ -54,8 +54,9 @@ E2E_SANDBOX_CLASS=microvm hack/run-e2e-kind.sh ./internal/e2e/suites/networking ``` The HTTPS protocol test checks a verified HTTP/1.1 request to a local TLS -origin on port 8443. The WebSocket tests check that both `ws` and `wss` -upgrades are denied with HTTP 403 before the origin receives any messages. +origin on port 8443. The WebSocket tests open `ws` and `wss` connections to a +local echo origin and check the echoes. On the agentgateway dataplane they +check that the handshake is refused with HTTP 403 instead. The delayed-restore test issues a fresh origin certificate after the Actor is suspended, then checks that the restored microVM can complete the TLS request. diff --git a/docs/dev/preview-gates.md b/docs/dev/preview-gates.md index 6a55c0952c..715759ae55 100644 --- a/docs/dev/preview-gates.md +++ b/docs/dev/preview-gates.md @@ -1,32 +1,16 @@ -# Preview gates +# Implementing preview gates -A preview gate lets a new feature ship in a release while staying off by -default. This gives users an opportunity to try things but protects them from -accidentally using things that we are not confident in. Operators enable gates -explicitly on the server side, and API clients must also say they mean to use -preview features. Gates are coarse switches; they are not access control. +See [Preview Gates](../reference/preview-gates.md) for what preview gates are, +how operators and clients enable them, and the list of available gates. This +guide covers how contributors declare, enforce, and test gates in code. -There are only two states: a feature is either **preview** (gated, off unless -enabled) or **GA** (always on). There is no alpha or beta. - -## How a gate is enabled - -Two independent switches must both be on before a request can use a gated -feature: - -1. **Server side:** every substrate binary takes `--preview=`, a - comma-separated list of gate names, or `ALL` for all of them. Install with - ate-setup's `preview` setting (`ATE_PREVIEW`, `--preview=`), which - passes the same value to every substrate container. atecontroller passes its - own gates on to the ateworker containers of each WorkerPool. -2. **Client side:** a gRPC request to ate-api must send the - `Ate-Preview-Allowed: true` metadata header (`preview.Header`). - `kubectl ate --preview` sends it. A request without it is treated as if - every gate were off. +## Internal components Substrate's own components (atelet, atenet, atecontroller) dial ate-api with -`preview.DialOptionsWithOptIn()`, so they are never blocked by the header -check. ate-setup does the same when it is run with preview gates. +`preview.DialOptionsWithOptIn()`, so they are never blocked by the +`Ate-Preview-Allowed` (`preview.Header`) check. ate-setup does the same when it +is run with preview gates. +Process-level gates that do not change an API use only the server-side switch. ## Adding a gate @@ -44,7 +28,8 @@ var realKnownGates = []Gate{ } ``` -Gate should always be named in UpperCamelCase. +Gate should always be named in UpperCamelCase. Document every gate in +[`docs/reference/preview-gates.md`](../reference/preview-gates.md). ## Gating API fields @@ -52,44 +37,77 @@ Gate the fields a **user** sets with a declarative validation tag in the `.proto`, then regenerate (`hack/update/codegen.sh`): ```proto - // +ate:preview=MyFeature // +k8s:ifDisabled(MyFeature)=+k8s:forbidden // +k8s:optional - MyFeatureConfig my_feature = 7; + MyFeatureConfig my_feature = 7 [ (field).preview_gate.name = "MyFeature" ]; ``` -- `+ate:preview=` marks the field as part of a preview feature, for - readers and docs. It does not enforce anything. +- `(field).preview_gate` marks the field as part of a preview feature, for + readers and tools. It does not enforce anything. - `+k8s:ifDisabled()=+k8s:forbidden` rejects the field when the gate is off for this request. -The gate state reaches the validators through `apivalidation.MakeCreateOp(ctx)` -and `apivalidation.MakeUpdateOp(ctx)`. Every `Validate*` wrapper must build its -`operation.Operation` with one of these, not with a bare -`operation.Operation{...}` literal; otherwise the field is never gated. +`apitool validate` checks that the gate exists, and that a field has both or +neither, with the same gate. A field whose preview gate sets +`allow_when_disabled` must not have the tag. + +The gate state reaches the validators through `operation.Operation`. Every +`Validate*` wrapper in `cmd/ateapi/internal/apivalidation` takes `*preview.Gates` +and builds its operation with `MakeCreateOp(ctx, gates)` or +`MakeUpdateOp(ctx, gates)`, which attach the enabled gates for `ctx`. Unchanged values are not re-validated on update, so an object created while a gate was on stays usable after the gate is turned off. -**Do not gate fields the server writes**, such as `status`. The server writes -them while doing system work, such as deleting an actor, and gating them can +**Do not reject fields the server writes**, such as `status`. The server writes +them while doing system work, such as deleting an actor, and rejecting them can leave objects that cannot be cleaned up after a gate is turned off. This is subtle and will require careful thinking when implementing a gated feature. +Mark these fields with `allow_when_disabled` and no `ifDisabled` tag: + +```proto + // +k8s:optional + MyFeatureStatus my_feature_status = 4 [ (field).preview_gate = { + name : "MyFeature" + allow_when_disabled : true + } ]; +``` + +## Gating RPC methods + +Name the gate in the method's annotation: + +```proto + rpc ResizeActor(ResizeActorRequest) returns (ResizeActorResponse) { + option (method) = { + resource : "Actor" + preview_gate : { name : "MyFeature" } + }; + } +``` + +Calls to a gated method fail with `FAILED_PRECONDITION` when the gate is off +for the request. Streaming methods cannot be gated. ## Gating behavior in code +A binary builds its gates once with `preview.New(*previewFlags...)` and passes +the `*preview.Gates` to the code that checks them. In ate-api, `RPCService`, +`ServiceImpl`, `ActorWorkflow`, `WorkerWorkflow`, and `workerservice.Server` +each hold it as `gates`. + For a check made while handling a user request, use the context-aware form: ```go -if !preview.IsEnabledFor(ctx, preview.GateMyFeature) { +if !s.gates.IsEnabledFor(ctx, preview.GateMyFeature) { return nil, resources.ToAPIError(field.ErrorList{field.Forbidden( path, "requires the MyFeature preview gate and a client that opts in to "+ "preview features (kubectl ate --preview, or the "+preview.Header+" header)")}) } ``` -Use `preview.IsEnabled(gate)` only for checks that are about the process, not -the request, e.g. whether a component should start a feature at all. +Use `gates.IsEnabled(gate)` only for checks that are about the server, not the +request, e.g. whether a component should start a feature at all. Be deliberate about what happens when a gate is turned **off** while the feature is in use. Prefer to keep cleanup paths (delete, suspend, detach) @@ -114,16 +132,18 @@ through the interceptor, such as background reconcilers, are not opted out. Test gated code both with and without the gate. -- Unit tests: `preview.InitForTest(t, "MyFeature")`, or with no gate names for - all-off. It restores the previous state when the test ends. Tests that use - it cannot run in parallel. -- Tests of the gate mechanism itself use `preview.InitForTestFake` with fake - gate names, so they don't depend on real gates. +- Unit tests: pass `preview.NewForTest(t, "MyFeature")`, or with no gate names + for all-off, to the code under test. In `controlapi`, `testGates` has the + gates most tests run with. +- Tests that must not depend on real gates use `preview.NewForTestFake` with + fake gate names. - `apivalidation` tables: `assertValidate` takes `want` (gates off) and `wantWithPreview`, keyed by a `--preview` value such as `"ALL"`. -- Functional tests (`controlapi/functionaltest`): `setupPreviewTest` gives a - client that sends the header, and `tc.noOptInClient` one that does not. - Neither enables a gate; call `preview.InitForTest` for that. +- Functional tests (`cmd/ateapi/internal/functionaltest`): ate-api runs with + every gate on. A test that uses a preview feature creates its harness with + `harness.New(t, harness.WithPreviewClient())`, whose clients send the + header; `h.ControlWithoutPreview()` is one that does not. A test cannot turn + a gate off. - E2E tests: start a test of a preview feature with `e2e.RequirePreview(t, preview.GateMyFeature)`. It skips unless the suite was run with `--preview` naming that gate, which must match what the @@ -133,17 +153,16 @@ Test gated code both with and without the gate. hack/run-e2e-kind.sh -v -args --preview=ALL ``` - CI runs every e2e lane with preview gates both off and on, and requires - `--preview` to be passed (even as empty) so a lane cannot silently skip - every preview test. + CI runs e2e lanes with preview gates off and on where the cluster supports + both configurations. It requires `--preview` to be passed (even as empty) so + a lane cannot silently skip every preview test. ## Graduating or removing a gate When the feature goes GA, or is removed, keep the gate name in `realKnownGates` for a while so existing `--preview` values still parse, but make the feature always on (GA) or always off (removed). Then delete the -`ifDisabled` tags, `IsEnabled`/`IsEnabledFor` checks, and `RequirePreview` -calls. +`preview_gate` options, `ifDisabled` tags, `IsEnabled`/`IsEnabledFor` checks, +and `RequirePreview` calls, and update [`docs/reference/preview-gates.md`](../reference/preview-gates.md). - diff --git a/docs/examples/gmp-alerting-rules.yaml b/docs/examples/gmp-alerting-rules.yaml index ae63d1aff7..79cc7f71c9 100644 --- a/docs/examples/gmp-alerting-rules.yaml +++ b/docs/examples/gmp-alerting-rules.yaml @@ -292,7 +292,9 @@ spec: # - Look for workers in all states except "unschedulable." Ignore unknown # sandbox classes. # - Sum across all (remaining) workload states (e.g. excluding - # "unschedulable"). Alert if this is lower than the lowest number of + # "unschedulable"). Fall back to 0 when a pool has no registered worker + # with a known sandbox class, so pools with no Worker or only unknown + # workers still fire. Alert if this is lower than the lowest number of # desired workers over the last five minutes. # - Each replica of ate-api-server emits these metrics, so we need a way to # resolve disagreements between them on the correct number of actual and @@ -337,9 +339,15 @@ spec: rules: - alert: SubstrateWorkerPoolCapacityNotDelivered expr: | - sum by (ate_workerpool_namespace, ate_workerpool_name) ( - max by (ate_workerpool_namespace, ate_workerpool_name, ate_worker_state, ate_sandbox_class) ( - aterules:workerpool_actual_workers:label_replaced + ( + sum by (ate_workerpool_namespace, ate_workerpool_name) ( + max by (ate_workerpool_namespace, ate_workerpool_name, ate_worker_state, ate_sandbox_class) ( + aterules:workerpool_actual_workers:label_replaced + ) + ) + or + 0 * min by (ate_workerpool_namespace, ate_workerpool_name) ( + aterules:workerpool_desired_workers:label_replaced ) ) < diff --git a/docs/get-started/quickstart.md b/docs/get-started/quickstart.md index e0a87e2eb3..2186c35988 100644 --- a/docs/get-started/quickstart.md +++ b/docs/get-started/quickstart.md @@ -34,6 +34,8 @@ hack/create-kind-cluster.sh # 2. Target the local kind cluster in every shell that runs ate-setup export ATE_INSTALL_KIND=true +# IPv6-only clusters require IPv6 actor networking. +# export ATE_PREVIEW=ActorIPv6 # 3. Install Agent Substrate, PostgreSQL, and snapshot storage (rustfs) go run ./cmd/ate-setup deploy ate-system --credential-provider='{"name":"k8s.io"}' \ @@ -53,6 +55,9 @@ kubectl ate proxy actor my-counter-1 -a ate-demo-counter > [!IMPORTANT] > `{"name":"k8s.io"}` deploys the bundled credential provider with an empty, default-deny namespace policy. Before an actor can have a credential injected, grant its atespace the namespaces whose Secrets it may read; see [Egress Credential Injection](../guides/egress-credential-injection.md#enable-it). +> [!IMPORTANT] +> An IPv6-only kind cluster needs working DNS and outbound HTTPS from its worker Pods to every sandbox asset URL. The default gVisor configuration uses `storage.googleapis.com`. Kind configures IPv6 Pod and Service addresses but does not provide public IPv6 routing or NAT64. Configure native IPv6 egress, NAT64, or an HTTP proxy before installing Substrate. + **Teardown:** When finished, remove the local cluster and registry with: ```bash diff --git a/docs/guides/actor-jwt-federation.md b/docs/guides/actor-jwt-federation.md index b56adca259..80c0292e36 100644 --- a/docs/guides/actor-jwt-federation.md +++ b/docs/guides/actor-jwt-federation.md @@ -67,6 +67,6 @@ If the relying party doesn't accept ES256, To check the setup, have an egress policy inject a token for the relying party's audience into a request to a server you control, and present that -token to the relying party. Substrate can't yet present an actor JWT to a -cloud token exchange endpoint itself; see +token to the relying party. The gateway can't present an actor JWT to a cloud +token exchange endpoint itself, but a custom credential provider can; see [Known limitations](actor-jwts.md#known-limitations). diff --git a/docs/guides/actor-jwts.md b/docs/guides/actor-jwts.md index 300f03e48c..b8a9334b72 100644 --- a/docs/guides/actor-jwts.md +++ b/docs/guides/actor-jwts.md @@ -216,10 +216,12 @@ each step and what to do about a compromised key. receives the token. An upstream that echoes request headers hands the token back to the actor. A relying party should check `sub` or `actor.ate.dev` as well as `aud`. -- **No cloud token exchange.** Cloud token exchange endpoints take the JWT as - a request parameter, and the gateway only replaces headers, so Substrate - can't yet trade an actor JWT for cloud credentials - ([#1661](https://github.com/agent-substrate/substrate/issues/1661)). +- **No built-in cloud token exchange.** Cloud token exchange endpoints take + the JWT as a request parameter, and the gateway only replaces headers, so the + gateway can't trade an actor JWT for cloud credentials itself + ([#1661](https://github.com/agent-substrate/substrate/issues/1661)). A + custom credential provider can; see + [Actor → Cloud](../security/identity.md#actor--cloud). - **A recreated actor can get a stale UID.** The gateway caches tokens by actor name. For up to two thirds of a token's lifetime after an actor is recreated, the gateway can inject a token whose `actorUID` names the old actor diff --git a/docs/guides/authentication.md b/docs/guides/authentication.md index c822a39ba0..f170813820 100644 --- a/docs/guides/authentication.md +++ b/docs/guides/authentication.md @@ -22,6 +22,9 @@ that principal may do. `sub`. - A call with no certificate and no valid token gets `Unauthenticated`. +For identity in flows that don't call `ate-api-server`, such as actors calling +other services, see the [Identity Overview](../security/identity.md). + ## Which credential to use | Caller | Credential | Principal | diff --git a/docs/guides/authorization.md b/docs/guides/authorization.md index 4de4c65184..4e2e784f19 100644 --- a/docs/guides/authorization.md +++ b/docs/guides/authorization.md @@ -127,8 +127,11 @@ one **atespace**. | Create, update, delete egress policies | ✅ | | ✅ | ✅ | | | Create, publish, delete tags | ✅ | | ✅ | ✅ | | | Create an actor from a tag (`sourceTag`) | ✅ | | ✅ | ✅ | | +| Get and list external volumes | ✅ | ✅ | ✅ | ✅ | ✅ | | Workers: get, list, list assignments | ✅ | ✅ | | | | | Workers: create, update, delete, drain | ✅ | | | | | +| CSI drivers: get, list | ✅ | ✅ | | | | +| CSI drivers: create, update, delete | ✅ | | | | | ### System roles @@ -137,12 +140,14 @@ through their pod certificates. `ate-api-server`'s `--controller-spiffe-id`, `--egress-gateway-spiffe-id`, `--ingress-router-spiffe-id` and `--api-server-sidecar-spiffe-id` flags bind them, defaulting to the install's; `atelet`'s comes from `--atelet-service-account`. +An empty value of `--egress-gateway-spiffe-id` or `--ingress-router-spiffe-id` +leaves that role with no holder. | Role | Held by | Allows | |---|---|---| | `controller` | `ate-controller` | Create, get, list, update, delete and drain workers | | `egress_gateway` | `atenet-egress`, and any other SPIFFE IDs passed with `--egress-gateway-spiffe-id`, which ate-setup sets from `ATE_EGRESS_GATEWAY_EXTRA_SPIFFE_IDS` | Get actors and their egress policies; list actors across all atespaces; mint actor JWTs | -| `ingress_router` | `atenet-router` | Resume actors; list actors across all atespaces | +| `ingress_router` | `atenet-router`, and any other SPIFFE IDs passed with `--ingress-router-spiffe-id`. The flag replaces the default, so list `atenet-router` too | Resume actors; list actors across all atespaces | | `atelet` | `atelet` | Get actors' egress policies, for the worker that enforces them | | `api_server_sidecar` | the `ate-api-server` pod identity, which its sidecars share, today the objectstore control plugin | Get actors, to derive the snapshot prefixes a per-actor storage credential may cover | @@ -202,6 +207,15 @@ viewer, and a global role holds the same role in every atespace. So | `DeleteTag` | `can_delete`, the tag | Editor of its atespace | | `ListTags` | `can_list_tags`, the atespace, or global if none is given | Atespace viewer; global viewer for all atespaces | +### External volumes + +An `ExternalVolume` is read-only: the server creates and deletes it. + +| RPC | Permission, on | Allowed for | +|---|---|---| +| `GetExternalVolume` | `can_get`, the external volume | Viewer of its atespace | +| `ListExternalVolumes` | `can_list_external_volumes`, the atespace, or global if none is given | Atespace viewer; global viewer for all atespaces | + ### Workers Workers have no atespace; their permissions come from the global scope. @@ -216,6 +230,18 @@ Workers have no atespace; their permissions come from the global scope. | `DrainWorker` | `can_drain`, the worker | Global owner; `ate-controller` | | `ListWorkerActorAssignments` | `can_list_actor_assignments`, the worker | Global viewer | +### CSI drivers + +CSI drivers have no atespace; their permissions come from the global scope. + +| RPC | Permission, on | Allowed for | +|---|---|---| +| `CreateCsiDriver` | `can_create_csi_driver`, global | Global owner | +| `ListCsiDrivers` | `can_list_csi_drivers`, global | Global viewer | +| `GetCsiDriver` | `can_get`, the driver | Global viewer | +| `UpdateCsiDriver` | `can_update`, the driver | Global owner | +| `DeleteCsiDriver` | `can_delete`, the driver | Global owner | + ### WorkerService The interceptor skips these; each handler requires `atelet`'s pod diff --git a/docs/guides/benchmarking.md b/docs/guides/benchmarking.md index 829ef4d9fc..be773a9496 100644 --- a/docs/guides/benchmarking.md +++ b/docs/guides/benchmarking.md @@ -23,6 +23,10 @@ scenario ladder, read [observability.md](observability.md). > Source the environment configuration file (e.g., `source .ate-dev-env.sh`) > first so `PROJECT_ID` etc. are set. > +> The deploy scripts also source `.ate-dev-env.sh` themselves, which overrides +> anything set in the shell. When driving a cluster other than the one that file +> describes, set `NO_DEV_ENV=1` and export every setting explicitly instead. +> > **For Local Kind Clusters**: Set `KO_DOCKER_REPO` to the local registry so images are pulled without remote cloud credentials: > ```bash > export KO_DOCKER_REPO="localhost:5001" @@ -251,9 +255,11 @@ a run does not show up as a burst of failures. #### Sweperf Log Lines -The boomer log also carries per-task facts for post-processing such as the goodput script in -`tools/goodput`, which decides from them whether a task was good. The benchmark judges -nothing. Durations are in milliseconds. +The boomer log also carries per-task facts for post-processing, which run +evaluations can read with the `cel` source's `json_lines` reader +(`benchmarking/evaluate/README.md`), where a test entry's config decides +whether a task was good. The benchmark judges nothing. Durations are in +milliseconds. * `Completed sweperf cycle`: `actor`, `cycle`, `cel_ms` (0 when the execute failed), `wall_ms` (resume start to cycle end), `ok` (the execute succeeded, and so did the suspend @@ -273,6 +279,8 @@ nothing. Durations are in milliseconds. the no-op resume got an asynchronous ack, so always for a one-cycle task), `retries` (failed resumes), `failed`, and the first failure's `fail_step` (`resume`, `execute` or `suspend`) and `fail_cycle`. +* `SuspendActorAsync failed` (`SuspendActor failed` in the sync lifecycle mode): `actor` and + `err`. Like the other failure lines, it ties a task that never logged a record to its actor. * `sweperf on_start failed`: also carries `user`, to tie a failed start to its user. * `sweperf shutdown started`: the worker began tearing down. Startups and cycles in flight are canceled: interrupted tasks log no task record, and startup failures logged after it @@ -411,8 +419,9 @@ deployment fails loudly instead of showing up as OOM-flaky steps. * `--agentsession-awake` — turnover mode when above 0 (default 0, off). Each session registers by creating its actor, running step 1, and parking it. After registration is idle for 1 minute, the worker wakes this many sessions - and swaps `--target-rps` idle awake sessions with parked ones each second - (both per worker; tracked in `agentsession_turnover_sessions`). Each woken + and then swaps idle awake sessions with parked ones at `--target-rps` swaps + per second, evenly spaced (both per worker; tracked in + `agentsession_turnover_sessions`). Each woken session runs its next step immediately (ignoring the script's think times). Requires a fixed user count, and a stop from the master ends turnover for that worker process until it restarts. See @@ -429,12 +438,13 @@ turnover. Three things keep them apart: the `SuspendActor` and `SuspendActorAsync` rows hold only the turnover's parks. * The runner finds the end of the fill in boomer's log line - `agentsession: turnover fill done` and adds a `turnover_window` row to - `stats.jsonl` ([`locust/turnover_window.py`](../../benchmarking/locust/turnover_window.py)). - It holds each request's count (`requests_`), failures - (`failures_`) and rate (`rps_`) from there to the end of the run - (`window_start`, `window_end`), read from `stats_history.csv`. Read the swap - rate from `rps_TimeToWake` against `--target-rps`. + `agentsession: turnover fill done` and adds a `turnover_` row for + each request to `stats.jsonl` ([`locust/turnover_window.py`](../../benchmarking/locust/turnover_window.py)). + Each holds the request's `request_count`, `failure_count`, `requests_per_s` + and `failures_per_s` from there to the end of the run (`window_start`, + `window_end`), read from `stats_history.csv`. These are the keys of the + whole-run rows. Read the swap rate from the `requests_per_s` of + `turnover_TimeToWake` against `--target-rps`. * The server telemetry's steady-state window starts at the same point, so the memory, PSI and snapshot figures cover the turnover only. @@ -621,8 +631,15 @@ see [automation/ateapi-cold-resume.md](../../benchmarking/automation/ateapi-cold `200:3m@1000`, changes it as the step starts. Keep the users at or above the rate times the p99 of one resume plus one suspend in seconds, or the step falls short of its rate. +* `--burst-size`: Release cold resumes in waves of up to this many users at an + interval of `burst_size / target_rps` seconds instead of spacing them one by + one (default `0`, smooth pacing). Positive values require `--target-rps > 0` + on the command line and in every `--ladder` step. With `p99` as one resume + plus one suspend in seconds, keep the users at or above `burst_size` times + `floor(p99 / interval) + 1`, or `resume_rps` falls short of `target_rps`. + When users equal `burst_size`, this keeps `interval` above `p99`. -The web UI shows the same field. +The web UI shows the same fields. Trim the start of each ladder step. A rate change reaches boomer at its next poll of the master, within 10 s, and a step that adds users carries their @@ -669,7 +686,8 @@ gcloud storage cat "$RUN/stats.jsonl" | grep '"metric": "ladder_step_' ``` `` is the orchestrator's `--dest`, and its log has the full `RUN` path -on each `Uploaded ... -> gs://...` line. +on each `Uploaded ... -> gs://...` line. All runs of one orchestrator invocation +share its `run_ts`. ### Isolate Mode @@ -838,6 +856,14 @@ them are checked into the repository. [analysis/README.md](../../benchmarking/analysis/README.md#automated-runs)). * `server_summary.json`: server-side telemetry harvested from Prometheus, including the per-sample bin-packing timeseries. +* `evaluation.json`: for a test entry with `evaluations`, the run judged + against them: a summary verdict, and per evaluation each condition with its + CEL expression and verdict and every value its sources read. `stats.jsonl` + then also has one `evaluation_` row per evaluation and an + `evaluations` row for the summary. Evaluations never change `status.json` or + the exit code. See [evaluate/README.md](../../benchmarking/evaluate/README.md); + to judge a stored run again, run `python3 -m evaluate --from-run` from + `benchmarking/`. ### Density frontiers @@ -914,6 +940,15 @@ actually did, independent of what the load generator reported. * `pod_psi.cpu_stall_pct`, `mem_stall_pct`, `io_stall_pct`: the same for each worker pod's cgroup slice, which also holds its gVisor sandbox, with every pod's samples pooled. `pod_psi.pods` is how many pods were seen. +* `node_disk.read_mb_s`, `write_mb_s`: disk throughput in MiB/s per device + (such as `/dev/nvme0n1`) on the nodes hosting a worker pod, from cAdvisor's + `container_fs_{reads,writes}_bytes_total` on the root cgroup, with every + node's samples pooled per device. Every device cAdvisor reports is kept, + including `/dev/root`, which can read 0 while the disk holding it carries the + traffic. `node_disk.nodes` is how many nodes were seen. In `stats.jsonl` the + keys name the device without `/dev/`, as in + `node_disk_nvme0n1_write_p99_mb_s`. A device's keys are absent when it was + never seen, and `null` when it was seen only outside the steady-state window. * `snapshots.size_p50_mb` through `size_p99_mb`: actor memory image sizes. * `snapshots.size_avg_mb`: mean memory image size. * `snapshots.restore_p50_s` through `restore_p99_s`, `restore_mean_s`, and the @@ -960,6 +995,20 @@ actually did, independent of what the load generator reported. `--actor-stats-poll-interval` (default 1m), so these move in steps of a minute or more. `actor` matches one worker pod's actors only when the node runs one worker pod. +* `cpu.node`, `worker`, `atelet`, `actor`: CPU cores used, in the shape of + `working_set` with `total_cores` and `max_cores`. `node`, `worker` and + `atelet` are one-minute rates from cAdvisor. `worker` is the whole worker + pod: its actors and the suspend, restore and sandbox work done for them. + `actor` is the actors' own CPU time as the atelet reports it + (`ate_actor_stats_cpu_time_seconds_total`), a three-minute rate per atelet + with every template summed. The longer window flattens short peaks, so + compare `actor` with the other blocks by p50, not by p99 or `max`. `actor` + can undercount: an activation loses the CPU it used after the atelet's last + sample of it, so a short one can lose most of it (see the note on + `ate.actor.stats.cpu.time` in + [`metrics.yaml`](../metrics/registry/metrics.yaml)). In a run with many + suspends and resumes, `worker` minus `actor` then overstates the work done + outside the actors. * `oom_events.node`, `pod`: OOM kills over the run, from cAdvisor's `container_oom_events_total`. `node` counts only global OOMs. `pod` counts kills inside a worker pod (actor sandboxes and the worker container) and is @@ -992,18 +1041,18 @@ starts when the fill ends instead (see [Analyzing a Turnover Run](#analyzing-a-turnover-run)). Counts, means and `checkpoint_mb_s` come from the growth of the histogram's sum and count across the window, and the size, restore and checkpoint percentiles -are interpolated inside its buckets. PSI is a one-minute rolling average read -every 10s. +are interpolated inside its buckets. PSI and disk throughput are one-minute +rolling averages read every 10s. The atelet exports before Prometheus scrapes it, so the harvest waits `--atelet-lag-s` seconds (default 70, enough for the OTel SDK's 60s default -export and a 10s scrape) and reads the snapshot, `active_actors` and actor -working set windows half that late, stamping `active_actors` and actor -working set points back by the same amount. The window ends at the last -full-load sample, so teardown suspends are left out. +export and a 10s scrape) and reads the snapshot, `active_actors`, actor +working set and actor CPU windows half that late, stamping `active_actors`, +actor working set and actor CPU points back by the same amount. The window +ends at the last full-load sample, so teardown suspends are left out. `metadata.start_ts` and `end_ts` bound the whole run, which the packing, -`active_actors` and `working_set` timeseries cover. `steady_start_ts` and +`active_actors`, `working_set` and `cpu` timeseries cover. `steady_start_ts` and `steady_end_ts` bound the steady-state window. A flat subset of the numbers also goes into a `server_summary` row in `stats.jsonl`. diff --git a/docs/guides/csi-deployment.md b/docs/guides/csi-deployment.md index c340f36fc4..33031324a3 100644 --- a/docs/guides/csi-deployment.md +++ b/docs/guides/csi-deployment.md @@ -45,7 +45,13 @@ Standard CSI controller deployments can be made network-accessible and secured i ### Exposing via a Kubernetes `Service` -Create a Kubernetes `Service` targeting the CSI Controller pods. This provides a stable DNS name and load balancing across controller replicas. +Create a Kubernetes `Service` targeting the CSI Controller pods. This provides a stable DNS name for the controller. + +`ateapi` spreads controller RPCs across replicas only when the `Service` is headless (`clusterIP: None`), so its DNS name returns each pod's address. With a regular `Service`, every RPC from one `ateapi` replica goes to the same controller pod. Even with a headless `Service`, `ateapi` spreads RPCs only over the pods it resolved when it connected. A controller pod added later gets no RPCs until a connection to the controller fails or drops. + +Every `ate-api-server` replica (2 by default) calls the controller directly, with no leader election in front of it. So a driver whose controller can't serve calls on several replicas at the same time must run one controller replica (`replicas: 1`), with either kind of `Service`. A regular `Service` keeps each `ateapi` replica on one controller pod, but two `ateapi` replicas can still reach two different pods. Only run more controller replicas if any of them can serve any call at any time. + +A headless `Service` skips kube-proxy, so `ateapi` dials `:`, and the `Service`'s `targetPort` mapping does not apply. Set the `Service` `port` and the port in `controllerEndpoint` to the port the controller pod listens on. In the [`csi-nfs` example](#example-csi-nfs-controller-deployment-with-envoy-tls-proxy) below, that is Envoy's port `10000`, not `50052`. Create the `Service` before the controller pods when the proxy's serving certificate comes from Substrate's `servicedns.podcert.ate.dev/identity` signer: it issues the certificate for the `..svc` names of the `Service`s selecting the pod, and refuses to issue one for a pod no `Service` selects yet. The `Service` name is also what `spec.tls.serverName` in the `CSIDriverConfig` must be. @@ -192,6 +198,15 @@ data: #### 2. Envoy Sidecar in `csi-nfs-controller` Deployment +The `envoy-proxy` sidecar shares `socket-dir` (`/csi`) with the CSI driver +container and mounts the Envoy configuration (`envoy-config`), the Service DNS +serving certificate (`servicedns-certs`), and the Pod Identity trust bundle +(`podidentity-ca`). Even when the CSI driver container itself requires elevated +privileges (such as [the upstream `csi-nfs-controller` manifest](../../hack/third_party/csi-driver-nfs/deploy/csi-nfs-controller.yaml)), +the Envoy sidecar runs with a restricted `securityContext` +(`allowPrivilegeEscalation: false`, `readOnlyRootFilesystem: true`, and all +capabilities dropped). + ```yaml apiVersion: apps/v1 kind: Deployment @@ -212,15 +227,22 @@ spec: # Upstream CSI NFS driver container listening on local Unix socket - name: nfs image: registry.k8s.io/sig-storage/nfsplugin:v4.13.4 + securityContext: + privileged: true args: - "--nodeid=$(NODE_ID)" - "--endpoint=unix:///csi/csi.sock" + env: + - name: NODE_ID + valueFrom: + fieldRef: + fieldPath: spec.nodeName volumeMounts: - name: socket-dir mountPath: /csi # Envoy proxy sidecar terminating mTLS and forwarding to /csi/csi.sock - name: envoy-proxy - image: envoyproxy/envoy:v1.39.5@sha256:8fc594a5d85eb76dca24155cfb9208882406873932b20cf33649a0a611194c43 + image: envoyproxy/envoy:v1.40.0@sha256:459f2a6404c340fe6afccd69d85527012d47f3c036765493e6f8f3113fa384de command: - "/usr/local/bin/envoy" args: diff --git a/docs/guides/csi-volumes.md b/docs/guides/csi-volumes.md index fe9ba21bea..5e980edc91 100644 --- a/docs/guides/csi-volumes.md +++ b/docs/guides/csi-volumes.md @@ -116,8 +116,16 @@ volumeMounts: * `name`: Must match the declared `volumes[].name`. * `mountPath`: Unix path inside the container sandbox where the volume will be mounted. -> [!NOTE] -> All declared volumes in `volumes` must be mounted by at least one container. +#### Non-root containers + +Containers run as their image's `USER`. When non-root containers mount an external volume, atelet gives the volume their primary group on every `Run` and `Restore`: + +* A driver that reports the CSI `VOLUME_MOUNT_GROUP` node capability gets the group as `volume_mount_group` and applies it itself. +* For other drivers, atelet sets the volume's top directory to that group and, as Kubernetes `fsGroup` does, adds owner and group read, write and execute plus setgid. The others bits stay as the driver created them, so a `755` directory becomes `2775` and a `750` one becomes `2770`. Setgid makes new files and directories inherit the group. Only the top directory changes, and the owner stays as the driver created it. atelet does this as root on the node, so NFS exports must allow it (`no_root_squash`), which gVisor already needs to create files. This is best effort. If it fails, for example on a FUSE driver or a `root_squash` export, atelet logs a warning in its own log and mounts the volume as it is, and the storage admin must grant the containers access. + +Non-root containers of one actor that mount the same volume must share a primary group, for example with `USER 1000:500` in each image. Otherwise the resume fails with an error naming the volume, the containers and their groups, and the actor moves to `ACTOR_STATE_CRASHED`. Volumes that only root containers mount are left alone. + +New files get the process's umask, `022` by default, so other users in the group can't modify them. Images whose users must modify each other's files set `umask 002` in their entrypoint. --- @@ -212,3 +220,22 @@ volumes: capacityBytes: 5368709120 # 5Gi storageClassName: csi-nfs-sc ``` + +## 5. External Volume Records + +An `ExternalVolume` is an atespace-scoped record of a storage volume. Its +`status.csi` names the volume the way the node plugin needs it: the CSI driver +(`driverName`), the volume ID in the format the driver expects (`volumeId`), +and the mount metadata passed to the node plugin (`volumeContext`). An +atespace cannot be deleted while it holds one. + +The record is read-only: the server creates and deletes it. Reading one works +with the `ExternalVolumes` preview gate off and needs no `--preview`: + +```bash +kubectl ate get external-volumes -a ate-demo +``` + +Nothing creates an `ExternalVolume` yet. Every external volume an actor mounts +is still provisioned for that actor from `volumes[].external.template`, as +described above, and recorded on the actor. diff --git a/docs/guides/dataplane-timeouts.md b/docs/guides/dataplane-timeouts.md new file mode 100644 index 0000000000..a881ae3741 --- /dev/null +++ b/docs/guides/dataplane-timeouts.md @@ -0,0 +1,21 @@ +# Dataplane Timeouts + +Substrate dataplane timeouts are tuned to support streaming or long running requests, such as inference. +Timeouts for ingress and egress traffic are the same. On the ingress path timeouts are defined for +connections and requests between client and actor, and on the egress path between actor and origin +server. Internal CONNECT tunnels between Atunnel and Ingress or Egress gateways are transparent to +the traffic and do not have configured timeouts. One exception: Atunnel closes a connection from the +Ingress gateway when a write to it makes no progress for 10 seconds, which ends every tunnel on that +connection. + +| Timeout | Description | Default Value | User Configurable | +|---|---|---|---| +| Idle connection timeout | Timeout for connections without outstanding requests. | 5 minutes | No | +| Maximum connection duration | Maximum lifetime of a connection. | Disabled | No | +| Request timeout | Maximum time for request headers, body and trailers (if present) to be received. | Disabled | No | +| Request headers timeout | Maximum time for request headers to be received. | 10 seconds | No | +| Request idle timeout | Timeout for requests without network activity. | Disabled | No | +| Maximum request duration | Maximum lifetime of a request from the start to the end of response. | Disabled | No | +| Response timeout | Timeout for response to be fully received. | 5 minutes | Yes. See --route-timeout | +| TLS handshake timeout | Timeout for compltetion of TLS handshake. | 10 seconds | No | + diff --git a/docs/guides/egress-credential-injection.md b/docs/guides/egress-credential-injection.md index 9919d64b37..5c1e8568c5 100644 --- a/docs/guides/egress-credential-injection.md +++ b/docs/guides/egress-credential-injection.md @@ -120,9 +120,10 @@ A credential URI has the form `ate-secret:///`. The host names the provider that resolves it, and the provider interprets the path. The API requires the host to be a DNS-1123 subdomain and the path to -have at least two non-empty segments. It rejects a port, userinfo, query, fragment, -percent-encoding, or trailing slash. A URI the provider refuses denies the -request with 403. +have at least two non-empty segments, and allows at most 1024 characters. It +rejects a port, userinfo, query, fragment, percent-encoding, `.` or `..` +segment, or trailing slash. A URI the provider refuses denies the request with +403. * **Kubernetes Secrets** (provider class `k8s.io`) — see [The reference provider](#the-reference-provider). @@ -259,13 +260,30 @@ kubectl -n ate-system edit configmap k8s-credential-provider-namespace-policy - ns1 ``` -The provider loads the policy **once at startup** and does not yet reload it, -so after editing, restart the provider: +The provider rereads the policy when the kubelet updates the mounted ConfigMap, +which can take a minute or so; no restart is needed. If the edited policy fails +to parse, the provider logs the error and keeps enforcing the previous one; +`/statusz` on the provider shows the error and the grants in force. + +After an edit, check that the provider enforces the new policy. The `/statusz` +page listens on the pod's loopback address, port 4040, so reach it through a +port-forward: ```bash -kubectl -n ate-system rollout restart deployment/k8s-credential-provider +kubectl -n ate-system port-forward deployment/k8s-credential-provider 4040:4040 ``` +Then, from another terminal, open `http://localhost:4040/statusz`, or read the +JSON form: + +```bash +curl -s 'http://localhost:4040/statusz?format=json' | jq '{policy_grant_details, policy_error}' +``` + +`policy_grant_details` lists the namespaces each atespace is granted, with any +`secretSelector` labels. Once it shows your edit and `policy_error` is null, +the new policy is in force. + For a first smoke test, grant your actor's atespace `ns1` as above and apply a sample secret that the URI in the sample policy resolves to: @@ -300,6 +318,53 @@ was denied: kubectl -n ate-system logs deployment/atenet-egress -c ext-proc | grep 'egress denied' ``` +### Origins signed by a private CA + +For an `https` rule the gateway opens its own TLS connection to the origin. It +verifies the origin's certificate and hostname against the public roots in the +gateway image, so a request to an origin signed by a private CA fails. + +On the Envoy dataplane, `--egress-upstream-ca-bundle-configmap` **replaces** those +roots with a PEM bundle from a ConfigMap in `ate-system`. It takes the +ConfigMap's name and reads its `ca.crt` key, or takes `NAME/KEY` to read +another key. + +```bash +# The public roots in the gateway image, read from a running install. +kubectl -n ate-system exec deployment/atenet-egress -c envoy -- \ + cat /etc/ssl/certs/ca-certificates.crt > public-roots.pem +cat public-roots.pem private-ca.pem > ca.crt +kubectl -n ate-system create configmap egress-roots --from-file=ca.crt +go run ./cmd/ate-setup deploy atenet --credential-provider='{"name":"k8s.io"}' \ + --egress-upstream-ca-bundle-configmap=egress-roots +``` + +The deploy checks the ConfigMap before it applies anything: the key must hold +only PEM X.509 certificates. The check is stricter than Envoy. It refuses a +certificate that Go's `crypto/x509` cannot parse, such as a root with a +negative serial number in some operating systems' bundles. On a new install +create the `ate-system` namespace and the ConfigMap first. + +- The bundle replaces the public roots. Include them if actors also reach + public origins through `https` rules. +- The public roots in the bundle are a snapshot of the gateway image. After an + upgrade that changes the gateway's Envoy image, read them again with the + first command above, rebuild `ca.crt` and update the ConfigMap. A stale + bundle lacks the roots the new image added and still trusts the ones it + removed. +- The gateway trusts the bundle for every actor and every `https` origin. + Whoever holds a CA in it can issue a certificate the gateway accepts for any + hostname. +- To rotate a CA, update the ConfigMap. The gateway reloads it without a + restart once kubelet syncs the volume. Add the new CA before the origin + switches certificates, and remove the old one afterwards. +- The deploy check does not run when the ConfigMap changes. A running gateway + keeps the previous bundle if the new one fails to load. A gateway pod that + starts on a bundle it cannot load fails every request under an `https` rule + until the ConfigMap holds one it can. Envoy skips a certificate it cannot + read, such as an indented block, without an error. +- An API may replace this setting. + ### Operational notes **Transient 503s right after (re)deploying the provider.** The gateway keeps a @@ -317,6 +382,11 @@ lifetime, and that token's UID claim names the old actor. credential per actor and URI. Set `cacheTtl: 0s` on the provider's `atenetEgress.extraCredentialProviders` entry to skip the cache. +**The reference provider caches Secrets.** It reuses each Secret it reads for +`--secret-cache-ttl` (10s by default; 0 disables the cache). A rotated value, +a label change, or a deleted Secret can take that long to take effect. The +namespace policy is checked on every fetch. + **Scope of the reference provider's RBAC.** The sample deployment grants read on Secrets cluster-wide so the policy may name any namespace; a production deployment should scope this to the namespaces the provider is allowed to diff --git a/docs/guides/egress-traffic.md b/docs/guides/egress-traffic.md index 2f77ec2f9e..89deef2d35 100644 --- a/docs/guides/egress-traffic.md +++ b/docs/guides/egress-traffic.md @@ -4,13 +4,33 @@ linkTitle: "Egress Traffic" weight: 7 aliases: - "/docs/guides/egress/" + - "/docs/guides/network-egress/" description: > - Supported outbound actor protocols, DNS relay filtering, and what actors see when egress is refused. + Supported actor traffic and the contract between atunnel and the egress policy enforcement point. --- # Egress Traffic -This document specifies the supported egress traffic for [GA](https://github.com/agent-substrate/substrate/milestone/3). +This document specifies supported egress traffic and the contract between +Substrate and its egress policy enforcement point (PEP). + +> [!NOTE] +> Substrate supports IPv4-only and dual-stack Kubernetes clusters by default. +> IPv6-only clusters require the `ActorIPv6` preview gate. + +Every actor gets the private IPv4 network `169.254.17.0/30`. Actor networks are +either IPv4-only or dual-stack; they are never IPv6-only. With +`ATE_PREVIEW=ActorIPv6`, an actor whose worker Pod has an IPv6 address also gets +`fd00:169:254::/126`. Actor ingress, DNS, and wakeup probes use the IPv4 network. +Applications must listen on IPv4 or on a dual-stack socket. IPv6-only listeners, +such as Go's `tcp6`, are not supported. + +Before traffic reaches the PEP, ateworker rejects packets destined for the +IPv4 link-local range `169.254.0.0/16` or the IPv6 link-local range `fe80::/10`. +The internal actor networks `169.254.17.0/30` and `fd00:169:254::/126` are exempt +because they carry traffic to the actor gateway. The IPv4 network also carries +DNS, ingress, and wakeup probes. Localhost traffic remains inside the actor +sandbox. Actor TCP egress (except DNS to the sandbox's gateway) is redirected to atunnel, which opens a CONNECT tunnel to the egress gateway. Egress gateway applies policy. @@ -29,8 +49,20 @@ within about 5 seconds. > the actor's egress policy has a rule for it with > `kubectl ate get egress-policy -a -o yaml`. +The egress gateway caches each actor's policy for `--egress-policy-cache-ttl` +(10s by default). A policy change applies to new requests and connections at +the gateway within that time. + +> [!WARNING] +> Best practice is to name each actor with a UUID and never reuse an actor's +> name after it is deleted. Policies are cached temporarily and reuse of a name +> can result in application of the policy of a deleted actor with the same name +> ([#3267](https://github.com/agent-substrate/substrate/issues/3267)). Nothing +> in Substrate enforces name uniqueness across time: after actor `atespace1/foo` +> is deleted, a new actor can be created as `atespace1/foo`. + Other UDP and other traffic is rejected by nftables and never reaches the egress -gateway. +gateway. The actor receives an ICMP destination-unreachable response. This applies to an actor's own telemetry too: an OpenTelemetry SDK inside the actor cannot reach the collector until the actor has an `http` egress rule for it. See @@ -42,14 +74,34 @@ cannot reach the collector until the actor has an `http` egress rule for it. See | :---- | :---- | :---- | :---- | :---- | | any | HTTP(S) 1.1 / 2 | Supported with policy controls | atunnel -> egress gateway -> origin | `403 Forbidden`. For HTTPS whose SNI matches no `https` or `tls_passthrough` rule, the gateway closes the connection during the TLS handshake, without an HTTP response. | | any | TLS whose SNI matches a `tls_passthrough` rule | Relayed to the SNI hostname without inspection, so WebSocket, CONNECT, and other TCP inside it get through | atunnel -> egress gateway -> origin | Closed during the TLS handshake. | -| any | WebSocket | Blocked | atunnel -> egress gateway | `403 Forbidden` | +| any | WebSocket (`ws://`, `wss://`) over HTTP/1.1 | Supported under `http` and `https` rules. See [WebSocket](#websocket). | atunnel -> egress gateway -> origin | The same as for HTTP(S) above. | +| any | gRPC, cleartext or over TLS | Supported under `http` and `https` rules, unary and streaming. | atunnel -> egress gateway -> origin | The call fails with `PERMISSION_DENIED`. For TLS whose SNI matches no `https` or `tls_passthrough` rule, it fails with `UNAVAILABLE`. | +| any | Other HTTP upgrades | Blocked. An `h2c` upgrade offer is ignored, and the request is served over HTTP/1.1. | atunnel -> egress gateway | `403 Forbidden` | | any | Standard HTTP(S) CONNECT (forward-proxy tunnel) | Blocked | atunnel -> egress gateway | `403 Forbidden` | | 53 | DNS to the sandbox's gateway | Allowed for hostnames matching the actor's egress policy | sandbox DNS relay -> worker pod's resolvers | `NXDOMAIN` | | any | Any other TCP | Blocked | atunnel -> egress gateway | A client that sends first gets `400 Bad Request` before the connection closes. If the client waits for the server to speak first, the connection closes after about 1 second with no data. Only the gateway logs the refusal. | -See the [Network Egress Contract](network-egress.md#refusal-responses-and-policy-changes) -for refusal status codes, policy-refresh semantics, and the distinction between DNS -refusals and HTTP policy denials. +See [Refusal responses and policy changes](#refusal-responses-and-policy-changes) +for policy-refresh semantics and the distinction between DNS refusals and HTTP +policy denials. + +### WebSocket + +A `ws://` handshake is decided by the actor's `http` rules and a `wss://` +handshake by its `https` rules, like any other request to that host and port. +Credential effects apply to the handshake. + +- The gateway does not read the frames that follow. Policy and credentials are + applied once, at the handshake. A later policy change does not end an open + connection, and an injected credential is not refreshed. +- A connection with no data in either direction for 5 minutes is reset. Ping + and pong frames count as data, so send one more often than that. +- A gateway rollout closes open connections, and suspending the actor closes + all of its connections. Reconnect when that happens. +- Only the HTTP/1.1 handshake is supported. The gateway does not offer + WebSocket over HTTP/2 (RFC 8441). +- The agentgateway dataplane does not carry WebSocket yet. It answers the + handshake with `403 Forbidden`. ## UDP @@ -57,13 +109,129 @@ refusals and HTTP policy denials. | Port | Traffic | Behavior | Path | What the actor sees when refused | | :---- | :---- | :---- | :---- | :---- | | 53 | DNS to the sandbox's gateway | Allowed for hostnames matching the actor's egress policy | sandbox DNS relay -> worker pod's resolvers | `NXDOMAIN` | -| any other | Any other UDP | Blocked | n/a | Packets are dropped, not rejected: no ICMP port-unreachable is sent, so the client hangs until its own timeout. | +| any other | Any other UDP | Blocked | n/a | ICMP destination unreachable. | ## Other protocols Everything that is neither TCP nor UDP is rejected with ICMP network unreachable. +## Egress PEP contract + +`atunnel` opens an mTLS HTTP/1.1 or HTTP/2 CONNECT tunnel to the PEP, as +negotiated by ALPN. The CONNECT request target and HTTP/1.1 `Host` header +(HTTP/2 `:authority`) contain the original destination IP and port derived from +the actor's TCP connection. + +### Refusal responses and policy changes + +For cleartext HTTP requests and HTTP requests on an authorized intercepted TLS +connection, a request denied by policy MUST receive HTTP 403. WebSocket upgrades, +other HTTP upgrades, and actor-originated CONNECT requests inside the tunnel MUST +also receive HTTP 403, regardless of whether the destination is otherwise allowed. +This applies to cleartext HTTP and intercepted HTTPS, including mixed-case HTTP +upgrade tokens, and does not affect atunnel's outer CONNECT. The PEP MUST NOT open +an upstream connection or apply credential effects for these refused requests. +Response bodies are implementation-specific. + +A TLS passthrough authorization lasts for that connection. A policy update MUST +apply to new connections after cached policy decisions expire; it need not +terminate an already authorized connection. If a new ClientHello no longer +matches a passthrough rule, the PEP MUST NOT pass the TLS connection through. +If an HTTPS rule matches the SNI and original destination port, the PEP MAY +intercept the connection and authorize each HTTP request under that rule. +Otherwise, the PEP MUST close the connection at ClientHello, without completing +the TLS handshake, returning an HTTP response, or opening an upstream connection. +An HTTP rule alone MUST NOT authorize TLS. Missing or invalid SNI MUST also close +the connection without completing TLS. Unsupported protocols MAY close the +connection without an HTTP response. + +DNS authorization happens before the PEP and is independent of the protocol and +port being dialed. Removing every rule for a hostname can prevent resolution +before the connection reaches the PEP; that refusal does not promise an HTTP +status or a particular resolver error string. + +### Trust boundary + +The PEP MUST NOT trust any decision or attestation from the actor. It MUST trust +only information carried through Substrate-controlled channels, such as the actor +certificate and the CONNECT request produced by atunnel. In particular, an +actor-provided HTTP hostname or TLS SNI does not prove that the original +destination has that name. When authorization uses that hostname, the PEP MUST +route to the authorized hostname rather than use it to authorize an arbitrary IP +address from the CONNECT request. + +The PEP MUST NOT connect to a loopback, link-local, or unspecified address under +any rule, including `*`. It MUST check the address after resolving the hostname, +because an actor can point a public name at any address. + +### Server-side TLS + +The PEP MUST serve TLS using a certificate valid for its configured hostname and +chained to a CA trusted by `atunnel`. `atunnel` uses that hostname as the TLS +server name and MUST reject a certificate it cannot verify. + +### Client authorization + +`atunnel` MUST present an actor-specific client certificate when connecting to +the PEP. Before the actor's workload starts, `atunnel` generates a private key +and requests a short-lived certificate through the node-local atelet. Egress is +active from then on because a workload may need the network to become ready; it +does not wait for the wakeup probe as ingress does. The private key remains in +`atunnel`. The certificate identifies the actor by atespace, name, and UID and is +scoped to the `atunnel` purpose. + +The PEP MUST verify the certificate chain and lifetime against the Actor Identity +CA, require the client authentication usage, and require exactly one valid +`ActorIdentity` extension whose atespace, actor name, actor UID, and purpose are +present. The current extension OID is `1.3.6.1.4.1.11129.2.12.2`; it is allocated +under Google's enterprise number and will change after the CNCF donation. The +purpose MUST be `atunnel`, and the certificate's actor URI SAN MUST identify the +same actor as the extension. The PEP MUST then confirm with ate-api-server that +the actor still exists, its current UID matches the certificate, and it is placed +on a worker in `RESUMING` or `RUNNING`. The PEP MUST reject the CONNECT request if +any check fails. + +```text +CURRENT CONNECT EGRESS PATH (one tunnel per actor TCP connection except destination port 53) + + Actor sandbox Worker pod / ateworker Egress PEP Authorized upstream + +------------------+ +--------------------------+ +-------------------------+ +------------------+ + | Actor process | | nftables | | mTLS listener | | Target selected | + | (untrusted) | | TCP REDIRECT | | + CONNECT terminator | | under policy | + +--------+---------+ +------------+-------------+ +------------+------------+ +--------+---------+ + | connect(IP:port) | | | + +-------------------------------->| | | + | SO_ORIGINAL_DST | | + v | | + +------------+-------------+ | | + | atunnel | | | + | (trusted tunnel client) | | | + +------------+-------------+ | | + | | | + | TLS 1.2+ mutual authentication | | + | actor-specific client certificate | | + +---------------------------------->| verify certificate and | + | | authorize current actor | + | | | + | HTTP/1.1 CONNECT IP:port | | + | Host: IP:port | | + +---------------------------------->| validate destination; | + | | evaluate egress policy | + | | | + | HTTP/1.1 2xx | | + |<----------------------------------+ | + | | CIDR/all policy: | + | | dial now; | + | | hostname policy: | + | | inspect inner request | + | | before dialing | + | +------------------------->| + | | | + |<================ raw bidirectional bytes inside CONNECT ===========>|<========================>| + | (PEP may pass through, inspect, redirect, or MITM according to policy) | +``` + ## Requesting support If you would like Substrate to support egress traffic that is blocked above, please diff --git a/docs/guides/network-egress.md b/docs/guides/network-egress.md deleted file mode 100644 index db10c29678..0000000000 --- a/docs/guides/network-egress.md +++ /dev/null @@ -1,104 +0,0 @@ ---- -title: "Network Egress" -linkTitle: "Network Egress" -weight: 8 -description: > - How atunnel and the egress gateway tunnel, authenticate, and apply policy to outbound actor traffic. ---- - -# Network Egress Contract - -Last updated: 10/20/2026 - -## Overview - -Agent Substrate enforces that all outbound traffic from an actor, except traffic sent to TCP or UDP destination port 53, MUST go through an egress policy enforcement point (PEP). That PEP can (optionally) inspect, filter, or redirect the traffic according to substrate-native egress policies. This document describes the contract between substrate and egress PEPs. - -## Transport - -At present, actor TCP traffic exits the sandbox through [`atunnel`](../reference/glossary.md#components) and is forwarded on to the PEP. The exception is DNS: TCP and UDP traffic to port 53 on the sandbox's gateway bypasses the PEP and is answered by the sandbox's DNS relay, which forwards a query to the worker pod's resolvers only when the queried hostname matches a host or host wildcard in the actor's egress policy; queries from an actor without a policy, or for a hostname not matched by any rule, are answered `NXDOMAIN`. All other protocols are blocked. `atunnel` is configured with the PEP's network address and port at startup and uses that address to open an mTLS HTTP/1.1 or HTTP/2 CONNECT tunnel to the PEP, as negotiated by ALPN. The CONNECT request target and HTTP/1.1 `Host` header (HTTP/2 `:authority`) are set to the original destination IP and port that `atunnel` derived from the actor's TCP connection. Actor networking is currently IPv4-only. - -Before traffic reaches the egress PEP, ateworker rejects packets destined for the IPv4 link-local range `169.254.0.0/16` or the IPv6 link-local range `fe80::/10`. The internal actor network `169.254.17.0/30` is exempt because it carries traffic for the actor gateway, DNS relay, ingress, and wakeup probes. Localhost traffic remains inside the actor sandbox and does not traverse the PEP. Access to non-link-local destinations remains controlled by substrate egress policy and, at the `WorkerPool` boundary, Kubernetes NetworkPolicy. - -## Refusal responses and policy changes - -The [supported traffic table](egress-traffic.md) defines the permitted protocols. -For cleartext HTTP requests and HTTP requests on an authorized intercepted TLS -connection, a request denied by policy MUST receive HTTP 403. WebSocket upgrades, -other HTTP upgrades, and actor-originated CONNECT requests inside the tunnel MUST -also receive HTTP 403, regardless of whether the destination is otherwise allowed. -This applies to cleartext HTTP and intercepted HTTPS, including mixed-case HTTP -upgrade tokens, and does not affect atunnel's outer CONNECT. The PEP MUST NOT open an upstream connection -or apply credential effects for these refused requests. Response bodies are -implementation-specific. - -A TLS passthrough authorization lasts for that connection. A policy update MUST -apply to new connections after cached policy decisions expire; it need not -terminate an already authorized connection. If a new ClientHello no longer -matches a passthrough rule, the PEP MUST NOT pass the TLS connection through. -If an HTTPS rule matches the SNI and original destination port, the PEP MAY -intercept the connection and authorize each HTTP request under that rule. -Otherwise, the PEP MUST close the connection at ClientHello, without completing -the TLS handshake, returning an HTTP response, or opening an upstream connection. -An HTTP rule alone MUST NOT authorize TLS. -Missing or invalid SNI MUST also close the connection without completing TLS. -Unsupported protocols MAY close the connection without an HTTP response. - -DNS authorization happens before the PEP and is independent of the protocol and -port being dialed. Removing every rule for a hostname can prevent resolution -before the connection reaches the PEP; that refusal does not promise an HTTP -status or a particular resolver error string. - -## Trust Boundary - -In substrate, we consider everything originating from the actor to be untrusted. The egress PEP MUST NOT trust any decision or attestation coming from the actor itself; it MUST instead trust only information carried through substrate-controlled channels (e.g. the actor certificate and the CONNECT request produced by atunnel). For example, the PEP MUST NOT treat an actor-provided HTTP hostname or TLS SNI as proof that the original destination has that name. The PEP MAY use the hostname as a policy input, but when authorization is based on that hostname, it MUST route the traffic to the authorized hostname rather than use the hostname to authorize an arbitrary IP address from the CONNECT request. - -## Server-side TLS - -The egress PEP MUST serve TLS using a certificate that is valid for the configured PEP hostname and chains to a CA trusted by `atunnel`. `atunnel` uses the configured PEP hostname as the TLS server name and MUST reject the connection if it cannot verify the PEP's certificate. - -## Client Authorization - -`atunnel` MUST present an actor-specific client certificate when connecting to the PEP. Before the actor's workload starts, `atunnel` generates a private key and requests a short-lived certificate from substrate through the node-local atelet, and egress is active from then on: a workload may need the network to become ready, so egress does not wait for the wakeup probe the way ingress does. The private key remains in `atunnel`. The certificate identifies the actor by its atespace, name, and UID and is scoped to the `atunnel` purpose. - -The PEP MUST require and verify the client certificate before accepting a CONNECT request. It MUST verify the certificate chain and lifetime against the Actor Identity CA, require the client authentication usage, and require exactly one valid `ActorIdentity` extension whose atespace, actor name, actor UID, and purpose are present. The current extension OID is `1.3.6.1.4.1.11129.2.12.2`; it is allocated under Google's enterprise number and will change after the CNCF donation is complete. The purpose MUST be `atunnel`, and the certificate's actor URI SAN MUST identify the same actor as the extension. The PEP MUST then confirm with ate-api-server that the actor still exists, that its current UID matches the certificate, and that it is placed on a worker: `RESUMING` (booting or restoring there) or `RUNNING`. The PEP MUST reject the CONNECT request if any of these checks fail. - -```text -CURRENT CONNECT EGRESS PATH (one tunnel per actor TCP connection except destination port 53) - - Actor sandbox Worker pod / ateworker Egress PEP Authorized upstream - +------------------+ +--------------------------+ +-------------------------+ +------------------+ - | Actor process | | nftables | | mTLS listener | | Target selected | - | (untrusted) | | TCP REDIRECT | | + CONNECT terminator | | under policy | - +--------+---------+ +------------+-------------+ +------------+------------+ +--------+---------+ - | connect(IP:port) | | | - +-------------------------------->| | | - | SO_ORIGINAL_DST | | - v | | - +------------+-------------+ | | - | atunnel | | | - | (trusted tunnel client) | | | - +------------+-------------+ | | - | | | - | TLS 1.2+ mutual authentication | | - | actor-specific client certificate | | - +---------------------------------->| verify certificate and | - | | authorize current actor | - | | | - | HTTP/1.1 CONNECT IP:port | | - | Host: IP:port | | - +---------------------------------->| validate destination; | - | | evaluate egress policy | - | | | - | HTTP/1.1 2xx | | - |<----------------------------------+ | - | | CIDR/all policy: | - | | dial now; | - | | hostname policy: | - | | inspect inner request | - | | before dialing | - | +------------------------->| - | | | - |<================ raw bidirectional bytes inside CONNECT ===========>|<========================>| - | (PEP may pass through, inspect, redirect, or MITM according to policy) | -``` diff --git a/docs/guides/observability.md b/docs/guides/observability.md index bee010e4ad..0f5fc92388 100644 --- a/docs/guides/observability.md +++ b/docs/guides/observability.md @@ -24,7 +24,7 @@ To make underlying infrastructure transitions transparent, Agent Substrate estab Currently, Agent Substrate automatically wraps container output and injects these metadata labels into **container logs**. For metrics and distributed tracing, Agent Substrate provides foundational system telemetry and head-sampled request tracing (10% by default, 1% at the router), with roadmap plans to fully integrate actor-level correlation. -`ate.*` is reserved for Substrate. An actor's own log lines pass through untouched except for keys in that namespace, which are dropped before the record is written, so nothing a workload emits can be read as platform-issued attribution. +`ate.*` is reserved for Substrate on every container log record. The forwarder drops actor-supplied keys in that namespace from the top level and label groups of structured records. Plain-text log content stays inside the `message` field. --- @@ -32,6 +32,10 @@ Currently, Agent Substrate automatically wraps container output and injects thes Agent Substrate captures container standard output/error, wraps them into structured JSON log entries, and injects the `ate.*` metadata labels. +The forwarder preserves structured JSON log lines of at most 32 KiB, subject to the metadata rules above. It splits longer lines into plain-text `message` chunks of at most 32 KiB before JSON encoding. Each chunk carries the container's identity labels, and chunk boundaries preserve valid UTF-8 characters. The top-level field `ate.log.partial` is `true` on each non-final chunk. The final chunk omits the field. Structured fields such as severity and trace IDs remain text inside the chunks. The size limit bounds the worker's log buffering and leaves room for JSON escaping and metadata. + +On microVM, each container record also carries the top-level field `log.iostream` with the value `stdout` or `stderr`. When reading a worker's output, consumers can group chunks by `ate.actor.uid`, `ate.actor.container.name`, and `log.iostream`. On gVisor, stdout and stderr share a pipe, so the field is absent. The forwarder ignores actor-supplied top-level `log.iostream` values. + ### Active Actor Inspection via CLI For quick, on-demand debugging of an active actor, use the Agent Substrate CLI: @@ -141,7 +145,7 @@ resource.labels.pod_name="counter-c995fdf4c-m7d96" Substrate-emitted records carry top-level `trace_id`, `span_id`, and `trace_flags` in lowercase hex, the names the [OpenTelemetry spec](https://opentelemetry.io/docs/specs/otel/compatibility/logging_trace_context/) fixes for non-OTLP log formats. That covers component logs (every `slog.*Context` call, via [`internal/contextlogging`](../../internal/contextlogging)) and the synthetic actor lifecycle records, so a suspend or resume log line joins the RPC that drove it. -An actor's **own** lines carry trace context only if the actor emits these fields itself, in which case they pass through unchanged. Substrate cannot supply them: one forwarder goroutine covers a container's whole output stream and cannot tell which request produced a given line. Per-line correlation for actor logs arrives with the actor telemetry relay ([#853](https://github.com/agent-substrate/substrate/issues/853)), where the actor's own SDK carries the context. +An actor's **own** lines carry trace context only if the actor emits these fields itself in a JSON line of at most 32 KiB, in which case they pass through unchanged. Longer lines become plain-text chunks and lose structured trace correlation. Substrate cannot supply trace context: one forwarder goroutine covers a whole container stream and cannot tell which request produced a given line. Per-line correlation for actor logs arrives with the actor telemetry relay ([#853](https://github.com/agent-substrate/substrate/issues/853)), where the actor's own SDK carries the context. --- @@ -212,7 +216,18 @@ ateworker-gvisor's `Sandbox has no processes left while the actor is hosted` is "ate.sandbox.oom_kills":3} ``` -The actor still reports `RUNNING` after this record; nothing moves it to `CRASHED` yet ([#2211](https://github.com/agent-substrate/substrate/issues/2211)). It does not fire when an application container exits while the sentry is still up, or during a checkpoint or terminate. The count covers the life of the cgroup leaf, so a leaf left behind by an earlier activation of the same actor carries its count forward. +The actor still reports `RUNNING` after this record; nothing moves it to `CRASHED` yet ([#2211](https://github.com/agent-substrate/substrate/issues/2211)). It does not fire when an application container exits while the sentry is still up (see `Actor container exited` below), or during a checkpoint or terminate. The count covers the life of the cgroup leaf, so a leaf left behind by an earlier activation of the same actor carries its count forward. + +`Actor container exited` is a WARN that ateworker-gvisor and ateworker-microvm write when an application container exits while its sandbox stays up. It is in the actor's log, so `kubectl ate logs` shows it by default and with `--source=lifecycle`: + +```json +{"time":"…","level":"WARN","message":"Actor container exited", + "labels":{"ate.atespace":"ate-demo-counter","ate.actor.name":"counter-1","ate.actor.uid":"8f2a…", + "ate.template.atespace":"ate-demo-counter","ate.template.name":"counter"}, + "ate.actor.exited_container.name":"counter","process.exit.code":137} +``` + +The record is a WARN for each exit code, also for 0: the template does not say if a container is expected to finish. `process.exit.code` is the value that the runtime returned: `runsc wait` on gVisor, the guest agent on a microVM. On gVisor it is absent if runsc gave none. Select the record by `ate.actor.exited_container.name`. A container can write a top-level key outside `ate.*` in its own lines, so it can write the same message and a `process.exit.code`. ateworker removes each `ate.*` key that a container writes, so only ateworker can write `ate.actor.exited_container.name`. A sandbox that dies gives no such record: `Sandbox died` or `Micro-VM died` covers it. The record does not change the actor's state. ateworker-gvisor writes no record for a container that closed its own stdout and stderr, or for an exit during a terminate or a checkpoint that succeeds. ateworker-microvm writes the record in those cases if the guest agent reports the exit before the stop. An exit in the last milliseconds before a suspend can give its record at the next restore, or no record. ateworker-microvm also writes the record for an exit during a boot or a restore that then fails, and ateworker-gvisor does not. A microVM that is restored from a snapshot gives no second record for a container that exited before the snapshot, which includes an actor made from a template's snapshot. Neither worker writes a record for an exit of a process that is not the container's first process, or for an exit after the worker starts its shutdown. #### The same records over OTLP @@ -261,7 +276,7 @@ The stdout record carries the same flat `ate.*` keys as the OTLP event, dated wh jsonPayload.msg="Actor usage sampled" AND jsonPayload."ate.actor.uid"="8f2a…" ``` -* **The measurements** follow [the rules above](#the-same-records-over-otlp): absent while the actor is pending, CPU in seconds since the activation began, memory usage and working set absolute. An activation that ends any other way, as by a crash, has no `final` record, so take the highest CPU per epoch rather than wait for one. The `final` reading is taken just before the teardown, bounded on a microVM to 10ms. When it fails or times out, the `final` record repeats the newest measured sample, dated when that sample was read, or is pending when none was measured. +* **The measurements** follow [the rules above](#the-same-records-over-otlp): absent while the actor is pending, CPU in seconds since the activation began, memory usage and working set absolute. An activation whose sandbox dies on its own still gets a `final` record when the ateworker tears it down: on gVisor its CPU and memory peak are read after the death and its memory usage and working set are absent, since the memory went with the processes, and on a microVM the newest sample stands in. An activation that ends any other way, as by a lost worker, has no `final` record, so take the highest CPU per epoch rather than wait for one. The `final` reading is taken just before the teardown, bounded on a microVM to 10ms. When it fails or times out, the `final` record repeats the newest measured sample, dated when that sample was read, or is pending when none was measured. * **Cadence**: `--usage-sample-interval` on the ateworker sets the timer (default `1m`, at least `50s`). Each sweep writes one periodic record per actor, and `GetActiveWorkloadStats` serves the latest sample rather than reading again. * **Trace context**: `initial` records come from the Run or Restore call (on a microVM, from a goroutine the call starts, so the record can land just before or after the call returns) and `final` records from the call that tears the activation down, a Checkpoint, a Terminate, or, on a microVM, the Run or Restore that re-hosts it; both carry that call's span, like any record in [Joining Logs to Traces](#joining-logs-to-traces). `periodic` records come from the sampler, and a shutdown's `final` records from the drain, which serve no request, so they carry none. * **Delivery is best-effort**: the stdout record ignores `--log-level` and sits behind a bounded queue, so a stalled log consumer costs records, with a warning, never the sampler. @@ -291,6 +306,7 @@ Agent Substrate emits foundational OpenTelemetry system and server metrics to mo | `ate.workerpool.desired_workers` | atecontroller | up/down counter | number of worker pods requested for a WorkerPool, from `spec.replicas` (labels `ate.workerpool.namespace`, `ate.workerpool.name`) | | `ate.workerpool.ready_workers` | atecontroller | up/down counter | number of worker pods currently ready for a WorkerPool, from `status.readyReplicas` (labels `ate.workerpool.namespace`, `ate.workerpool.name`) | | `ate.workerpool.workers` | ateapi | up/down counter | live worker count per pool, split by state (`idle`/`partial`/`at_capacity`/`unschedulable`) and sandbox class to provide fleet capacity and saturation at a glance. Every ateapi replica reports the whole fleet: take the `avg` by pool namespace, pool, state, and sandbox class first, then `sum` (example query below the table) | +| `ate.worker.{cpu,memory,actor}.{capacity,allocated}` | ateapi | up/down counter | per-worker room and bookings, the substrate form of `k8s.node.{cpu,memory,pod}.allocatable`. Capacity is what actors can book; allocated is what they booked (limits plus runtime overhead), not what they use. CPU is in cores, memory in bytes (labels `ate.worker.name`, `k8s.pod.name`, `k8s.node.name`, `ate.workerpool.namespace`, `ate.workerpool.name`, `ate.sandbox.class`) | | `ate.actor.lifecycle.operation.duration` | ateapi | histogram | how long each actor operation (create/resume/suspend/delete/revert) takes and whether it failed (`error.type` present = failure, absent = success); labeled by operation, template, pool (`ate.workerpool.namespace` + `ate.workerpool.name`), sandbox class, snapshot kind on resume, and snapshot fidelity on resume and suspend; already-running resume no-ops are not recorded so the histogram tracks actual activations, not router traffic | | `ate.scheduler.assignment.duration` | ateapi | histogram | time of one attempt to assign a worker to an actor, with one record for each resume (ateapi retries an attempt that loses a race for a worker and records only the last attempt), with the outcome (`assigned` / `no_capacity` / `error`), the assigned pool (`ate.workerpool.namespace` + `ate.workerpool.name`) and sandbox class to catch scheduling latency and capacity starvation problems | | `ate.actor.restore.duration` | atelet | histogram | how long each phase of a restore takes on the worker node, which is where cold-start latency actually goes once ateapi hands off (labels `ate.snapshot.phase`, `ate.snapshot.kind`, `ate.snapshot.fidelity`, `ate.template.atespace`, `ate.template.name`, `ate.sandbox.class`) | @@ -305,6 +321,7 @@ Agent Substrate emits foundational OpenTelemetry system and server metrics to mo | `ate.filecache.size` | atelet | up/down counter | bytes of disk a node-local file cache occupies, by `ate.filecache.name`, read on each collection; compare with `--sandbox-asset-cache-max-bytes` | | `ate.filecache.evictions` | atelet | counter | entries the eviction passes removed from a node-local file cache, by `ate.filecache.name`; a steady rate at the budget means the cache thrashes and actors pay for downloads again | | `ate.filecache.gc.passes` | atelet | counter | eviction passes over a node-local file cache, by `ate.filecache.name`, that had work to do, by outcome (`ate.filecache.gc.outcome`: `complete`, `shortfall`, `skipped`); a pass within budget is not counted | +| `ate.dns.queries` | ateworker-gvisor & ateworker-microvm | counter | actor DNS queries the sandbox DNS relay checked against the actor's egress policy, by `ate.dns.decision` (`allowed` or `denied`); a denied query gets `NXDOMAIN`, and most lookups also cause denials for the worker pod's search domains, which resolvers try first | The table lists the OpenTelemetry instrument names. How a name appears in a query depends on the backend (Cloud Monitoring (GMP) / Kind collector). @@ -325,6 +342,76 @@ For `ate.workerpool.workers`: When one backend receives several clusters, add `cluster` to both groupings, or same-named pools in different clusters merge. +* A worker counts under `ate.sandbox.class` `unknown` until its process reports a class, and only a worker with a known class gives its pool zero-valued series for that class. A pool with no `Worker` at all (for example, when none of its pods is scheduled) has no series on `ate.workerpool.workers`. So `idle == 0` alone does not fire when every worker in a pool is `unknown` or when a pool has no `Worker`. Idle workers per pool, with both cases as 0: + + ```promql + ( + sum by ("ate.workerpool.namespace", "ate.workerpool.name") ( + avg by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.state", "ate.sandbox.class") ( + {"ate.workerpool.workers", "ate.worker.state"="idle", "ate.sandbox.class"!="unknown"} + ) + ) + or + 0 * sum by ("ate.workerpool.namespace", "ate.workerpool.name") ( + avg by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.state", "ate.sandbox.class") ( + {"ate.workerpool.workers"} + ) + ) + or + 0 * max by ("ate.workerpool.namespace", "ate.workerpool.name") ( + {"ate.workerpool.desired_workers"} > 0 + ) + ) + ``` + + Alert on `== 0`. The second branch covers a pool whose workers all report `unknown`. The third branch covers a pool with `spec.replicas > 0` and no `Worker` yet. That branch requires a backend that receives `atecontroller`'s metrics, which the kind Prometheus does not (see [Local Metrics with Prometheus](#local-metrics-with-prometheus-kind-cluster)). + +For the `ate.worker.*` resource instruments: +* They are per worker, not per pool, because free room does not add up across workers: ten workers with 0.5 CPU free each cannot take a 1 CPU actor. A pool total is a sum over its workers. +* A worker has a capacity series for a resource only while the scheduler can place on it (active, registered, with actor slots, and it reported the resource). A draining worker, one that just restarted, or a resource the worker does not report has no capacity series rather than a 0, so it never reads as free room or as full. Every worker reports allocated, at 0 when it holds nothing, so a draining worker that empties drops to 0 instead of vanishing. +* The actor capacity is a safety limit, like the kubelet pod limit, not a target. CPU and memory are the better signals that a worker is full. +* Every ateapi replica reports every worker. Unlike `ate.workerpool.workers`, a worker is its own series, so take the `max` by worker first. The labels are the same on both sides, so `allocated / capacity` is the utilization of one worker. +* `k8s.pod.name` and `k8s.node.name` name the worker's pod and node, the values the worker's own telemetry has as resource attributes, so the bookings join with what the pod really uses. +* One series per worker per instrument. The OpenTelemetry SDK keeps 2000 series per instrument by default and folds the rest into one `otel.metric.overflow` series, so a fleet of more than 2000 workers must raise `OTEL_GO_X_CARDINALITY_LIMIT` on ateapi. +* A Worker is named after its pod UID, so a replaced pod is a new series. ateapi stops reporting a deleted worker at once, but the backend keeps its last sample for its lookback window, bookings included when the Worker was deleted before its actors left (5 minutes by default in Prometheus, and the collector's Prometheus exporter keeps it for its `metric_expiration`, also 5 minutes). For that long a pool that lost workers still counts them, which makes it look less full than it is. + + Actors in operation per pool: + + ```promql + sum by ("ate.workerpool.namespace", "ate.workerpool.name") ( + max by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.name") ( + {"ate.worker.actor.allocated"} + ) + ) + ``` + + The share of each pool's schedulable workers that booked more than 80% of any resource. This is a stopgap autoscaling signal for a HorizontalPodAutoscaler until Substrate scales pools itself. Pair it with the `no_capacity` rate of `ate.scheduler.assignment.duration`, which fires when an actor fits on no worker while the pool still looks below the limit: + + ```promql + count by ("ate.workerpool.namespace", "ate.workerpool.name") ( + ( + max by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.name") ({"ate.worker.cpu.allocated"}) + / max by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.name") ({"ate.worker.cpu.capacity"}) > 0.8 + ) + or + ( + max by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.name") ({"ate.worker.memory.allocated"}) + / max by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.name") ({"ate.worker.memory.capacity"}) > 0.8 + ) + or + ( + max by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.name") ({"ate.worker.actor.allocated"}) + / max by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.name") ({"ate.worker.actor.capacity"}) > 0.8 + ) + ) + / + count by ("ate.workerpool.namespace", "ate.workerpool.name") ( + max by ("ate.workerpool.namespace", "ate.workerpool.name", "ate.worker.name") ({"ate.worker.actor.capacity"}) + ) + ``` + + `or` keeps one series per worker, so a worker over the limit on two resources counts once. A pool with no worker over the limit has no series rather than 0. + For `atenet.router.route.duration`: * `ate.router.outcome` categorizes the route attempt result: `ok`, `cancelled`, `timeout`, `no_capacity`, `failed_precondition`, `lock_conflict`, `not_found`, `unavailable`, `rate_limited`, `denied`, or `resume_error`. `denied` is a request the router refused by policy (a 403 or `PermissionDenied`), such as an egress request outside the actor's egress policy; `resume_error` is left for a resume that failed for any other reason, a router defect. * The router and the scheduler both report `no_capacity` for one condition, but they count different events. The scheduler records one sample on `ate.scheduler.assignment.duration` for each resume. The router records one sample for each request. Many requests can join one resume, and one parked request can cause more than one resume. Thus do not compare the two counts directly. @@ -384,7 +471,7 @@ Four files, and not one: Weaver permits only `groups` and `imports` at the top level of a registry file, and it refuses a file that has any other top-level key. Thus `substrate.yaml` is beside the registry directory and not in it. It records: -* **`upstream_semconv_version`** — the version of the upstream semantic conventions that Substrate borrows `error.type`, `file.name` and the `rpc.*` attributes from. +* **`upstream_semconv_version`** records the version of the upstream semantic conventions that define `error.type`, `file.name`, `log.iostream`, `rpc.*`, and `server.port`. * **`bridged_metric_families`** — the metrics that atecontroller exports but Substrate does not define, as prefixes. `controller_runtime_version` records the version of controller-runtime that the list comes from. * **`cardinality_rules`** — the rules that keep the number of series small. No rule is enforced at this time. Each rule says what could enforce it. * **`lint_exceptions`** — the known debt. @@ -406,7 +493,7 @@ A queue that has never processed an item bridges as an exponential histogram wit ### Scraping instead of pushing -ateapi, atelet, atenet-router and the credential provider also serve every instrument on their Prometheus `/metrics` endpoint. A cluster that scrapes those endpoints sets `OTEL_METRICS_EXPORTER=prometheus` on the components, so each series reaches the backend once. With `prometheus` the components install no OTLP metric reader and keep the Prometheus one; traces and logs are unaffected. `none` stops the push too. For now `/metrics` stays on for every value, including `otlp` and `none`. The health probes have moved to their own server on `:9091`, so `:9090` serves only `/metrics`; turning it off for `otlp` and `none` is tracked in [#2067](https://github.com/agent-substrate/substrate/issues/2067). The variable takes a comma-separated list, with the same rules as `OTEL_LOGS_EXPORTER`. Unset is `otlp,prometheus`, or `otlp` alone on ateworker. `otlp` keeps the push, and `prometheus` or `none` stops it. ateworker serves no `/metrics`, so there `prometheus` is skipped as unknown with a warning, and the push stays on unless the variable is `none`. +ateapi, atelet, atenet-router and the credential provider also serve every instrument on their Prometheus `/metrics` endpoint. A cluster that scrapes those endpoints sets `OTEL_METRICS_EXPORTER=prometheus` on the components, so each series reaches the backend once. With `prometheus` the components install no OTLP metric reader and keep the Prometheus one; traces and logs are unaffected. `none` stops the push too. The credential provider is the exception to scraping: its NetworkPolicy admits only the egress gateway, so nothing can scrape its `/metrics`, and with `prometheus` or `none` in `ate-otel-config` its metrics leave the pod on no path. For now `/metrics` stays on for every value, including `otlp` and `none`. The health probes have moved to their own server on `:9091`, so `:9090` serves only `/metrics`; turning it off for `otlp` and `none` is tracked in [#2067](https://github.com/agent-substrate/substrate/issues/2067). The variable takes a comma-separated list, with the same rules as `OTEL_LOGS_EXPORTER`. Unset is `otlp,prometheus`, or `otlp` alone on ateworker. `otlp` keeps the push, and `prometheus` or `none` stops it. ateworker serves no `/metrics`, so there `prometheus` is skipped as unknown with a warning, and the push stays on unless the variable is `none`. `ate-controller` does not propagate its own value to the worker pods: ateworker serves no `/metrics`, and `none` would leave it exporting no metrics at all. To set the variable on ateworker, set `ATE_WORKER_OTEL_METRICS_EXPORTER` in `ate-otel-config` (or the controller's `--otel-metrics-exporter` flag). @@ -430,7 +517,7 @@ To explore metrics locally: > **Note:** Storage is ephemeral (`emptyDir`), so metrics are lost when the Prometheus pod restarts. -> **Note:** This Prometheus does not see every instrument. It scrapes the `/metrics` endpoint (`:9090`) of the pods annotated `prometheus.io/scrape`, which are `ate-api-server`, `atelet`, and `atenet-router`. From the collector it keeps only the `substrate_*` counts of the count connector and the collector's own `otelcol_*` counters ([`manifests/ate-install/kind/prometheus.yaml`](../../manifests/ate-install/kind/prometheus.yaml)), so that the scraped services are not counted twice. The metrics that ateworker (including its `rpc.server.call.duration`) and atecontroller (`ate.workerpool.desired_workers`, `ate.workerpool.ready_workers`, and the bridged controller-runtime families) push over OTLP reach the collector but do not appear in this UI. The credential provider's metrics appear in neither: its pod carries no scrape annotation and does not read `ate-otel-config`, so its OTLP push goes to the SDK default `localhost:4317` and fails. +> **Note:** This Prometheus does not see every instrument. It scrapes the `/metrics` endpoint (`:9090`) of the pods annotated `prometheus.io/scrape`, which are `ate-api-server`, `atelet`, and `atenet-router`. From the collector it keeps only the `substrate_*` counts of the count connector and the collector's own `otelcol_*` counters ([`manifests/ate-install/kind/prometheus.yaml`](../../manifests/ate-install/kind/prometheus.yaml)), so that the scraped services are not counted twice. The metrics that ateworker (including its `rpc.server.call.duration`) and atecontroller (`ate.workerpool.desired_workers`, `ate.workerpool.ready_workers`, and the bridged controller-runtime families) push over OTLP reach the collector but do not appear in this UI. The credential provider's metrics also reach the collector but not this UI: its pod carries no scrape annotation, and its NetworkPolicy admits no scraper. > **Roadmap Note (Actor-Level Metrics):** The control plane latency, snapshot performance, and fleet utilization instruments above are in place. What remains is actor-level correlation: telemetry that an actor emits itself carries no Substrate-injected identity yet ([#853](https://github.com/agent-substrate/substrate/issues/853), [#761](https://github.com/agent-substrate/substrate/issues/761)). @@ -484,7 +571,7 @@ To visualize traces locally: Telemetry is emitted over OTLP to your configured OpenTelemetry Collector. -> In Kind, `ateapi`, `atelet`, `ate-controller`, `atenet-router`, and `atenet-egress` are pointed at the in-cluster `opentelemetry-collector` in `otel-system`, and the controller propagates the endpoint to the worker pods it creates, so the telemetry of these components and of the workers lands locally (Prometheus exporter on `:8889`, Jaeger UI for traces, and the collector's `debug` exporter for OTLP logs). The Kubernetes credential provider is the exception: it does not read the endpoint (see the [note on the Kind Prometheus](#2-metrics)). +> In Kind, `ateapi`, `atelet`, `ate-controller`, `atenet-router`, `atenet-egress`, and `k8s-credential-provider` are pointed at the in-cluster `opentelemetry-collector` in `otel-system`, and the controller propagates the endpoint to the worker pods it creates, so the telemetry of these components and of the workers lands locally (Prometheus exporter on `:8889`, Jaeger UI for traces, and the collector's `debug` exporter for OTLP logs). The Kubernetes credential provider sends only metrics, so it is not among the sources of traces and OTLP logs, and its metrics are not in the Kind Prometheus UI (see the [note on the Kind Prometheus](#2-metrics)). > > Each of these components reads that endpoint from the shared `ate-otel-config` ConfigMap ([`manifests/ate-install/ate-otel-config.yaml`](../../manifests/ate-install/ate-otel-config.yaml), with a Kind replacement of the same name under [`manifests/ate-install/kind/`](../../manifests/ate-install/kind/ate-otel-config.yaml)). Editing it does not restart the pods that consume it — follow a change with `kubectl rollout restart`. > @@ -523,7 +610,7 @@ Verbatim forwarding is restricted to known ateworker sources and refuses anythin ### Actor telemetry needs an egress policy -An actor's own OpenTelemetry SDK does not use the relay. It dials the collector over the network like any other outbound connection, and that connection is subject to the actor egress lockdown described in [Network Egress](network-egress.md): every actor TCP connection is redirected into `atunnel` and carried to the egress gateway, which refuses anything the actor's `EgressPolicy` does not allow. An actor with no policy, or a policy with no matching rule, cannot reach the collector at all. With no policy, or a policy whose rules do not include the collector's hostname, the actor cannot even resolve the collector's name: the sandbox's DNS relay answers its queries `NXDOMAIN`, so each export fails before it connects. If a rule allows the hostname on another protocol or port (for example, `*` on port `443`), DNS resolves the name, the SDK sees `Unavailable: connection reset by peer` on each export, and the gateway logs why it denied the connection. +An actor's own OpenTelemetry SDK does not use the relay. It dials the collector over the network like any other outbound connection, and that connection is subject to the actor lockdown described in [Egress Traffic](egress-traffic.md): every actor TCP connection is redirected into `atunnel` and carried to the egress gateway, which refuses anything the actor's `EgressPolicy` does not allow. An actor with no policy, or a policy with no matching rule, cannot reach the collector at all. With no policy, or a policy whose rules do not include the collector's hostname, the actor cannot even resolve the collector's name: the sandbox's DNS relay answers its queries `NXDOMAIN`, so each export fails before it connects. If a rule allows the hostname on another protocol or port (for example, `*` on port `443`), DNS resolves the name, the SDK sees `Unavailable: connection reset by peer` on each export, and the gateway logs why it denied the connection. To let an actor export, give it an `http` rule naming the collector's Service and the OTLP ports. It must be an `http` rule, not `https`: the OTLP/gRPC exporter is gRPC over cleartext HTTP/2 (h2c) on `4317`, which an `http` rule admits, and the OTLP/HTTP exporter is cleartext HTTP/1.1 on `4318`. On Kind the collector is `opentelemetry-collector.otel-system.svc`. Whatever the name, it has to match the host the actor's `OTEL_EXPORTER_OTLP_ENDPOINT` names, because the rule is matched on the request authority. diff --git a/docs/guides/operator-install.md b/docs/guides/operator-install.md index c62050a5c0..4383918092 100644 --- a/docs/guides/operator-install.md +++ b/docs/guides/operator-install.md @@ -283,6 +283,7 @@ demos, the [benchmarks](benchmarking.md#settings), and the | `actorJWT.issuer` | `ACTOR_JWT_ISSUER` | `--actor-jwt-issuer` | — | (global) | | `ateapi.authz.bootstrapOwners` | `ATE_API_AUTHZ_BOOTSTRAP_OWNERS` | `--ateapi-authz-bootstrap-owners` | `system:serviceaccount::ate-client` | (global) | | `ateapi.authz.egressGatewayExtraSPIFFEIDs` | `ATE_EGRESS_GATEWAY_EXTRA_SPIFFE_IDS` | `--egress-gateway-extra-spiffe-ids` | — | (global) | +| `ateapi.defaultEgressGatewayAddress` | `ATE_DEFAULT_EGRESS_GATEWAY_ADDRESS` | `--default-egress-gateway-address` | `atenet-egress.ate-system.svc:443` | (global) | | `ateapi.expectedJWTIssuer` | `EXPECTED_JWT_ISSUER` | `--ateapi-expected-jwt-issuer` | — | (global) | | `ateapi.logLevel` | `ATE_API_LOG_LEVEL` | `--ateapi-log-level` | — | (global) | | `ateapi.postgres.cloudsql.gsa` | `ATE_API_POSTGRES_CLOUDSQL_GSA` | `--ateapi-postgres-cloudsql-gsa` | — | (global) | @@ -300,6 +301,9 @@ demos, the [benchmarks](benchmarking.md#settings), and the | `atenet.dataplane` | `ATE_ATENET_DATAPLANE` | `--atenet-dataplane` | `envoy` | (global) | | `atenet.egress.additionalExtprocService` | `ATE_ADDITIONAL_EGRESS_EXTPROC_SERVICE` | `--experimental-additional-egress-extproc-service` | — | (global) | | `atenet.egress.credentialProvider` | `ATE_CREDENTIAL_PROVIDER` | `--credential-provider` | — | (global) | +| `atenet.egress.skip` | `ATE_INSTALL_NO_ATENET_EGRESS` | `--no-atenet-egress` | `false` | (global) | +| `atenet.egress.upstreamCABundleConfigMap` | `ATE_EGRESS_UPSTREAM_CA_BUNDLE_CONFIGMAP` | `--egress-upstream-ca-bundle-configmap` | — | (global) | +| `atenet.router.skip` | `ATE_INSTALL_NO_ATENET_ROUTER` | `--no-atenet-router` | `false` | (global) | | `clusterSize` | `ATE_INSTALL_CLUSTER_SIZE` | `--cluster-size` | `size0` | (global) | | `context` | `KUBECTL_CONTEXT` | `--context` | — | (global) | | `cordonSystemInfraComponents` | `ATE_INSTALL_CORDON_SYSTEM_INFRA_COMPONENTS` | `--cordon-system-infra-components` | `false` | (global) | @@ -320,6 +324,7 @@ demos, the [benchmarks](benchmarking.md#settings), and the | `namespace` | `ATE_NAMESPACE` | `--namespace` | `ate-system` | (global) | | `otlpEndpoint` | `ATE_OTLP_ENDPOINT` | `--otlp-endpoint` | — | (global) | | `podcert.workersPerSigner` | `ATE_INSTALL_PODCERT_WORKERS_PER_SIGNER` | `--podcert-workers-per-signer` | `0` | (global) | +| `pprof` | `ATE_INSTALL_PPROF` | `--pprof` | `off` | (global) | | `preview` | `ATE_PREVIEW` | `--preview` | — | (global) | | `publish.binariesDir` | `ATE_PUBLISH_BINARIES_DIR` | `--out` | `bin/release` | `publish release-binaries` | | `publish.overwrite` | `ATE_PUBLISH_OVERWRITE` | `--overwrite` | `false` | `publish release-images` | @@ -336,6 +341,11 @@ ate-api-server stores every actor and tag snapshot under a cluster-wide `--snapshot-location`, an object-storage URI such as `gs://BUCKET/PREFIX/`. Its path segments may contain only ASCII letters, digits, `_` and `-` (see [Snapshot Storage Layout](../reference/api-guide.md#snapshot-storage-layout)). +Keep a `gs://` location's bucket name and path within 338 characters together. +Under a longer one, ate-api-server logs a warning at startup, and an actor +whose prefix does not fit the 512 bytes GCS accepts in a locally minted +snapshot transfer token gets its token from STS, which counts against the STS +quota. Set it with `SNAPSHOT_LOCATION` (or ate-setup's `--snapshot-location`). It has no default, and ate-setup fails before deploying without it unless the `PerTemplateSnapshotLocation` preview gate is enabled. Even with the gate, the diff --git a/docs/metrics/registry/events.yaml b/docs/metrics/registry/events.yaml index e945be4097..5b4dd8054e 100644 --- a/docs/metrics/registry/events.yaml +++ b/docs/metrics/registry/events.yaml @@ -114,11 +114,14 @@ groups: sample can carry an earlier timestamp than the records before it. The initial record is absent when the first reading fails. The final record is written when the ateworker tears the activation down: a checkpoint, a - terminate, a graceful shutdown of the worker, or a re-host on a - microVM. It is read just before the teardown and repeats the newest - sample when that read fails or times out, or is pending when none was - measured. It is absent when the activation ends otherwise, as by a - crash, a lost worker, or a re-host on gVisor. Thus take the highest + terminate, a graceful shutdown of the worker, a sandbox that dies on its + own, or a re-host on a microVM. It is read just before the teardown and + repeats the newest sample when that read fails or times out, or is + pending when none was measured. After a gVisor sandbox dies, the read + gives its CPU and memory peak at death, and memory usage and working set + are absent, since its memory went with its processes; a dead microVM + cannot be read, so its newest sample stands in. It is absent when the activation ends otherwise, as by a lost + worker or a re-host on gVisor. Thus take the highest ate.stats.cpu.time per ate.actor.uid and ate.actor.epoch rather than wait for the final record. @@ -164,13 +167,17 @@ groups: requirement_level: required - ref: ate.stats.memory.usage requirement_level: - conditionally_required: ate.stats.source is not unspecified. + conditionally_required: > + ate.stats.source is not unspecified, and the reading is not of a + gVisor sandbox with no process left. - ref: ate.stats.memory.peak requirement_level: conditionally_required: ate.stats.source is not unspecified and the source reports a peak. - ref: ate.stats.memory.working_set requirement_level: - conditionally_required: ate.stats.source is not unspecified. + conditionally_required: > + ate.stats.source is not unspecified, and the reading is not of a + gVisor sandbox with no process left. - ref: ate.stats.cpu.time requirement_level: conditionally_required: ate.stats.source is not unspecified. diff --git a/docs/metrics/registry/metrics.yaml b/docs/metrics/registry/metrics.yaml index 93d4214b07..df49ff115b 100644 --- a/docs/metrics/registry/metrics.yaml +++ b/docs/metrics/registry/metrics.yaml @@ -168,6 +168,16 @@ groups: crashes because its worker is lost, or the operation is not in this list. This is the default value. + - id: registry.ate.log + type: attribute_group + brief: Metadata of container log records. + attributes: + - id: ate.log.partial + stability: development + type: boolean + brief: Whether another chunk of the same log line follows. + note: Logs only. Set to true on non-final chunks and absent otherwise. + - id: registry.ate.template type: attribute_group brief: > @@ -242,6 +252,19 @@ groups: brief: > The scheduler places no actor on the worker. It is not active, or it has not reported an actor capacity yet. + - id: ate.worker.name + stability: development + type: string + brief: The name of the Worker. A Worker is named after the UID of its pod. + note: > + Only on the ate.worker.* resource instruments. It has one value for + each live worker, like k8s.node.name on the Kubernetes node metrics, + thus the series count follows the size of the fleet. A new pod is a + new Worker, so it starts new series. The OpenTelemetry SDK keeps + 2000 series for each instrument by default and folds the rest into + one otel.metric.overflow series. A fleet of more than 2000 workers + must raise OTEL_GO_X_CARDINALITY_LIMIT on ateapi. + examples: [0b6c1f6e-6d0a-4c43-9a43-8f4a2b0e7d11] - id: registry.ate.sandbox type: attribute_group @@ -283,6 +306,22 @@ groups: hosted actor's sandbox has no process left. A leaf left behind by an earlier activation of the same actor carries its count forward. examples: [0, 3] + - id: ate.actor.exited_container.name + stability: development + type: string + brief: > + The name of an actor container that exited while its sandbox stayed + up. + note: > + Logs only. It is only ever recorded beside actor identity, which no + metric may carry. ateworker-gvisor and ateworker-microvm set it on + the "Actor container exited" record. The record is not a line that + the container wrote, so it does not use ate.actor.container.name. + Select the record by this key. A container can write a top-level key + outside ate.* in its own lines, so it can write the same message and + a process.exit.code. ateworker removes each ate.* key that a + container writes, so only ateworker can write this key. + examples: ["counter"] - id: registry.ate.snapshot type: attribute_group @@ -434,7 +473,10 @@ groups: not a failure. Thus it has no error.type key. The cause can be full workers, or no worker that meets the constraints, such as a wrong sandbox class or a required node that is gone. Only the - first cause needs more workers. + first cause needs more workers. An actor that is larger than + each worker that meets its constraints gets the error outcome + with FailedPrecondition, because more workers of the same size + do not help. - id: error stability: development value: error @@ -634,6 +676,30 @@ groups: value: skipped brief: The pass could not size the cache and removed nothing. It retries on the next tick. + - id: registry.ate.dns + type: attribute_group + brief: > + The labels of the DNS relay of the sandbox. The relay checks each DNS + query of the actor against the egress policy of the actor. + attributes: + - id: ate.dns.decision + stability: development + brief: The decision of the egress policy on one DNS query. + type: + members: + - id: allowed + stability: development + value: allowed + brief: A rule of the policy allows the name. The relay sends the query to the resolvers of the worker pod. + - id: denied + stability: development + value: denied + brief: > + No rule allows the name, or the relay could not fetch the + policy and holds no earlier copy. The relay answers NXDOMAIN. + Thus the actor sees the same error as for a name that does not + exist. + - id: registry.ate.stats type: attribute_group brief: The labels of the resource measurements of the actors. @@ -679,16 +745,22 @@ groups: value: final brief: > The last sample of an activation, written when a checkpoint, a - terminate, a graceful shutdown, or a re-host on ateworker-microvm - ends it. When the sandbox is still running, ateworker reads the - stats just before the teardown; when no read runs, or the read - fails or times out, it repeats the newest measured sample, or - writes a pending record when there is none. + terminate, a graceful shutdown, a sandbox that dies on its own, + or a re-host on ateworker-microvm ends it. When the sandbox is + still running, ateworker reads the stats just before the + teardown. After a gVisor sandbox dies, it reads the CPU and memory + peak, and leaves memory usage and working set out. When no read runs, + or the read fails or times out, it repeats the newest measured + sample, or writes a pending record when there is none. - id: ate.stats.memory.usage stability: development type: int brief: The memory in use, in bytes. Absolute, not per activation. - note: Logs only. The log field of the instrument ate.actor.stats.memory.usage. + note: > + Logs only. The log field of the instrument + ate.actor.stats.memory.usage. Absent on a gVisor record read after + the sandbox died, as its final record: its cgroup keeps the CPU, but + its memory went with its processes, so no one measured it. examples: [41943040] - id: ate.stats.memory.peak stability: development @@ -702,7 +774,10 @@ groups: stability: development type: int brief: The memory in use less the reclaimable page cache, in bytes. - note: Logs only. The log field of the instrument ate.actor.stats.memory.working_set. + note: > + Logs only. The log field of the instrument + ate.actor.stats.memory.working_set. Absent on a gVisor record read + after the sandbox died, as ate.stats.memory.usage is. examples: [33554432] - id: ate.stats.cpu.time stability: development @@ -769,11 +844,55 @@ groups: code. On ate.imagecache.requests it holds the HTTP status of the registry. examples: ["ResourceExhausted", "404", "_OTHER"] + - id: process.exit.code + stability: development + type: int + brief: > + The exit code of the container named by + ate.actor.exited_container.name. + note: > + Logs only. ateworker-gvisor and ateworker-microvm set it on the + "Actor container exited" record. It is the value that the runtime + returned. Absent when the runtime gave no exit code. + examples: [0, 1, 137] - id: file.name stability: stable type: string brief: The name of one image in a snapshot. examples: [pages.img] + - id: k8s.node.name + stability: development + type: string + brief: > + The Kubernetes node of the worker pod that an ate.worker.* data point + describes. It is not the node of the component that sends it. + examples: [node-1] + - id: k8s.pod.name + stability: development + type: string + brief: > + The worker pod that an ate.worker.* data point describes. It is not + the pod of the component that sends it, which is on the resource. + note: > + The worker sends the same value as a resource attribute on its own + telemetry, thus the two join. A collector that copies resource + attributes into the labels of a series, such as + resource_to_telemetry_conversion, puts the ateapi pod on the same key. + examples: [pool-a-7c9d8] + - id: log.iostream + stability: development + brief: The container stream that produced the log record. + note: Logs only. Absent when stdout and stderr share a pipe. + type: + members: + - id: stdout + stability: development + value: stdout + brief: The container's standard output. + - id: stderr + stability: development + value: stderr + brief: The container's standard error. - id: rpc.method stability: stable type: string @@ -857,17 +976,26 @@ groups: pool, and the counts can be fractional while the replicas disagree. Within one replica you can add the counts together. The sum across the states is the size of the pool. The sum across the pools is the size of - the fleet. Thus this instrument is an UpDownCounter - and not a gauge. ateapi sets every state to 0 for each known pool. Thus a - full pool or an empty pool reports 0. An absent series would stop an alert - on idle == 0. + the fleet. Thus this instrument is an UpDownCounter and not a gauge. For + each worker with a known class, ateapi sets every state of that pool and + class to 0. Thus a full pool reports 0 for idle, and an alert on + idle == 0 fires. A pool with no Worker has no series here; atecontroller + reports ate.workerpool.desired_workers and ate.workerpool.ready_workers + for every WorkerPool, and the idle query in docs/guides/observability.md + uses ate.workerpool.desired_workers to take a pool with no Worker as 0 + idle. The states count workers, not actor slots. A worker with 1 of 20 slots used and one with 19 of 20 are both partial. Do not read utilization of the pool from this instrument. - A worker with the class unknown is not capacity of the pool: the scheduler - puts no actor on it. Thus a query that asks how much capacity a pool has - must keep ate.sandbox.class, because a sum across the classes adds that - worker back into the total. + A worker counts under the class unknown from its creation, and again from + each restart, until its process registers and reports a class. Such a + worker is not capacity of the pool: the scheduler puts no actor on it. + Thus a query that asks how much capacity a pool has must keep + ate.sandbox.class, because a sum across the classes adds that worker back + into the total. An unknown worker seeds no series. Thus a pool whose + workers all count under unknown has no series for its class, and an alert + on idle == 0 alone does not fire for it. The idle query in + docs/guides/observability.md takes such a pool as 0 idle too. annotations: substrate: emitted_by: [ateapi] @@ -884,6 +1012,225 @@ groups: - ref: ate.sandbox.class requirement_level: required + - id: metric.ate.worker.cpu.capacity + type: metric + metric_name: ate.worker.cpu.capacity + instrument: updowncounter + unit: "{cpu}" + stability: development + brief: The CPU cores of a worker that actors can book. + note: > + The substrate form of k8s.node.cpu.allocatable. ateapi reads it with + a callback from WorkerStatus.capacity, one series for each worker. A + worker has this series only while the scheduler can place an actor on + it: it is active, its process registered, it has actor slots, and it + reported the resource. + Thus a draining worker, or one that just restarted, never reads as free + room. Divide ate.worker.cpu.allocated by this instrument for the utilization of + one worker. Each ateapi replica reports every worker; take the max by + ate.worker.name before you add workers together. + The unit is cores, not the millicores of the API. + annotations: + substrate: + emitted_by: [ateapi] + golden_signals: [saturation] + code_anchor: cmd/ateapi/internal/controlapi/metrics.go + cuj: How much CPU can each worker in the pool still book? + attributes: + - ref: ate.worker.name + requirement_level: required + - ref: k8s.pod.name + requirement_level: required + - ref: k8s.node.name + requirement_level: required + - ref: ate.workerpool.namespace + requirement_level: required + - ref: ate.workerpool.name + requirement_level: required + - ref: ate.sandbox.class + requirement_level: required + + - id: metric.ate.worker.cpu.allocated + type: metric + metric_name: ate.worker.cpu.allocated + instrument: updowncounter + unit: "{cpu}" + stability: development + brief: The CPU cores of a worker that its actors booked. + note: > + What the actors on a worker booked from WorkerStatus.allocated: their + limits plus the overhead of the runtime, not what they use. Every + worker has this series, at 0 when it holds nothing, so the ratio exists + and a worker that empties drops to 0 instead of leaving its last + bookings in the backend. It can exceed the capacity after the capacity + shrinks. Each ateapi replica reports every worker; take the max + by ate.worker.name before you add workers together. + annotations: + substrate: + emitted_by: [ateapi] + golden_signals: [saturation] + code_anchor: cmd/ateapi/internal/controlapi/metrics.go + cuj: How much CPU can each worker in the pool still book? + attributes: + - ref: ate.worker.name + requirement_level: required + - ref: k8s.pod.name + requirement_level: required + - ref: k8s.node.name + requirement_level: required + - ref: ate.workerpool.namespace + requirement_level: required + - ref: ate.workerpool.name + requirement_level: required + - ref: ate.sandbox.class + requirement_level: required + + - id: metric.ate.worker.memory.capacity + type: metric + metric_name: ate.worker.memory.capacity + instrument: updowncounter + unit: "By" + stability: development + brief: The memory of a worker that actors can book. + note: > + The substrate form of k8s.node.memory.allocatable. ateapi reads it with + a callback from WorkerStatus.capacity, one series for each worker. A + worker has this series only while the scheduler can place an actor on + it: it is active, its process registered, it has actor slots, and it + reported the resource. + Thus a draining worker, or one that just restarted, never reads as free + room. Divide ate.worker.memory.allocated by this instrument for the utilization of + one worker. Each ateapi replica reports every worker; take the max by + ate.worker.name before you add workers together. + annotations: + substrate: + emitted_by: [ateapi] + golden_signals: [saturation] + code_anchor: cmd/ateapi/internal/controlapi/metrics.go + cuj: How much memory can each worker in the pool still book? + attributes: + - ref: ate.worker.name + requirement_level: required + - ref: k8s.pod.name + requirement_level: required + - ref: k8s.node.name + requirement_level: required + - ref: ate.workerpool.namespace + requirement_level: required + - ref: ate.workerpool.name + requirement_level: required + - ref: ate.sandbox.class + requirement_level: required + + - id: metric.ate.worker.memory.allocated + type: metric + metric_name: ate.worker.memory.allocated + instrument: updowncounter + unit: "By" + stability: development + brief: The memory of a worker that its actors booked. + note: > + What the actors on a worker booked from WorkerStatus.allocated: their + limits plus the overhead of the runtime, not what they use. Every + worker has this series, at 0 when it holds nothing, so the ratio exists + and a worker that empties drops to 0 instead of leaving its last + bookings in the backend. It can exceed the capacity after the capacity + shrinks. Each ateapi replica reports every worker; take the max + by ate.worker.name before you add workers together. + annotations: + substrate: + emitted_by: [ateapi] + golden_signals: [saturation] + code_anchor: cmd/ateapi/internal/controlapi/metrics.go + cuj: How much memory can each worker in the pool still book? + attributes: + - ref: ate.worker.name + requirement_level: required + - ref: k8s.pod.name + requirement_level: required + - ref: k8s.node.name + requirement_level: required + - ref: ate.workerpool.namespace + requirement_level: required + - ref: ate.workerpool.name + requirement_level: required + - ref: ate.sandbox.class + requirement_level: required + + - id: metric.ate.worker.actor.capacity + type: metric + metric_name: ate.worker.actor.capacity + instrument: updowncounter + unit: "{actor}" + stability: development + brief: The number of actors that a worker can hold. + note: > + The substrate form of k8s.node.pod.allocatable. ateapi reads it with + a callback from WorkerStatus.capacity, one series for each worker. A + worker has this series only while the scheduler can place an actor on + it: it is active, its process registered, it has actor slots, and it + reported the resource. + Thus a draining worker, or one that just restarted, never reads as free + room. Divide ate.worker.actor.allocated by this instrument for the utilization of + one worker. Each ateapi replica reports every worker; take the max by + ate.worker.name before you add workers together. + The actor capacity is a safety limit, like the pod limit of a kubelet, + and not a target. CPU and memory are the better signals of a full worker. + annotations: + substrate: + emitted_by: [ateapi] + golden_signals: [saturation] + code_anchor: cmd/ateapi/internal/controlapi/metrics.go + cuj: How many actors are in operation, and on which worker? + attributes: + - ref: ate.worker.name + requirement_level: required + - ref: k8s.pod.name + requirement_level: required + - ref: k8s.node.name + requirement_level: required + - ref: ate.workerpool.namespace + requirement_level: required + - ref: ate.workerpool.name + requirement_level: required + - ref: ate.sandbox.class + requirement_level: required + + - id: metric.ate.worker.actor.allocated + type: metric + metric_name: ate.worker.actor.allocated + instrument: updowncounter + unit: "{actor}" + stability: development + brief: The number of actors assigned to a worker. + note: > + What the actors on a worker booked from WorkerStatus.allocated: their + limits plus the overhead of the runtime, not what they use. Every + worker has this series, at 0 when it holds nothing, so the ratio exists + and a worker that empties drops to 0 instead of leaving its last + bookings in the backend. It can exceed the capacity after the capacity + shrinks. Each ateapi replica reports every worker; take the max + by ate.worker.name before you add workers together. + annotations: + substrate: + emitted_by: [ateapi] + golden_signals: [saturation] + code_anchor: cmd/ateapi/internal/controlapi/metrics.go + cuj: How many actors are in operation, and on which worker? + attributes: + - ref: ate.worker.name + requirement_level: required + - ref: k8s.pod.name + requirement_level: required + - ref: k8s.node.name + requirement_level: required + - ref: ate.workerpool.namespace + requirement_level: required + - ref: ate.workerpool.name + requirement_level: required + - ref: ate.sandbox.class + requirement_level: required + - id: metric.ate.actor.lifecycle.operation.duration type: metric metric_name: ate.actor.lifecycle.operation.duration @@ -949,9 +1296,15 @@ groups: stability: development brief: The time of one attempt of the scheduler to assign a worker during a resume. note: > - One resume gives one record. ateapi retries an attempt that loses a race + One resume gives at most one record. ateapi retries an attempt that loses a race for a worker, and records only the last attempt. If the retries run out, the outcome is error, and error.type is the code that the caller gets. + If a pinned actor has no room on its node, ateapi tries to detach it from + that node, and the attempt on that node gives no record. Before the + detach, ateapi asks the scheduler for a worker on any node. If there is + none, that check gives the record. If the detach fails after the check, + the resume gives no record. After a detach that succeeds, the next + attempt gives the record. The buckets are smaller than the buckets of the lifecycle histogram. This step is a read of the cache and some writes to the store. It is not a restore of some seconds. But the buckets go to 5 s. Thus you can see a @@ -1598,6 +1951,35 @@ groups: - ref: ate.router.outcome requirement_level: required + # --------------------------------------------------------------------------- + # Metrics. ateworker + # --------------------------------------------------------------------------- + + - id: metric.ate.dns.queries + type: metric + metric_name: ate.dns.queries + instrument: counter + unit: "{query}" + stability: development + brief: The number of actor DNS queries that the DNS relay of the sandbox checked against the egress policy, by decision. + note: > + The sandbox keeps the search domains of the worker pod and ndots:5. Thus + a stub resolver tries the search domains before most names, and most + lookups cause denials, even when a rule allows the name. Compare the + denied rate with its usual level. A rise means that egress policies block + names that actors look up. The actor sees only "bad address" or "could + not resolve host". The relay does not count a query that it drops or + rejects before the policy check, such as a malformed query. + annotations: + substrate: + emitted_by: [ateworker-gvisor, ateworker-microvm] + golden_signals: [traffic, errors] + code_anchor: internal/atunnel/dns/metrics.go + cuj: Actors cannot resolve external names. Does an egress policy deny them? + attributes: + - ref: ate.dns.decision + requirement_level: required + # --------------------------------------------------------------------------- # Metrics. Upstream instrumentation # --------------------------------------------------------------------------- @@ -1611,9 +1993,8 @@ groups: brief: The time, the rate and the errors of each gRPC method on the server. note: > The otelgrpc interceptor sends this instrument. The code of Substrate does - not make it. This instrument is the only metric of ateworker. ateworker has it on - the gRPC interface that atelet calls. credprovider is the - kubernetes-secrets credential provider in + not make it. ateworker has it on the gRPC interface that atelet calls. + credprovider is the kubernetes-secrets credential provider in cmd/credential-provider/kubernetes-secrets. annotations: substrate: diff --git a/docs/metrics/substrate.yaml b/docs/metrics/substrate.yaml index 03cf473c4e..6211a0c81a 100644 --- a/docs/metrics/substrate.yaml +++ b/docs/metrics/substrate.yaml @@ -26,9 +26,9 @@ registry_version: 1 # The version of the upstream semantic conventions that Substrate borrows from. -# Substrate takes error.type, file.name, the rpc.* attributes and server.port -# from it. This is the only version that the code imports under cmd/, internal/ -# and pkg/. +# Substrate takes error.type, file.name, k8s.node.name, k8s.pod.name, +# log.iostream, process.exit.code, the rpc.* attributes and server.port from it. +# This is the only version that the code imports under cmd/, internal/ and pkg/. # It is not the version of this registry: manifest.yaml holds that. upstream_semconv_version: 1.40.0 @@ -52,7 +52,7 @@ upstream_semconv_version: 1.40.0 # call of metrics.Registry.MustRegister in the module, and check which of those # packages `go list -deps ./cmd/atecontroller` links. # ----------------------------------------------------------------------------- -controller_runtime_version: v0.24.1 +controller_runtime_version: v0.25.1-0.20261119155835-be0153ca8953 bridged_metric_families: - prefix: controller_runtime_reconcile_ @@ -158,6 +158,11 @@ cardinality_rules: hold the literal "unknown" when the router has no template to name. The router sends that constant in place of the empty string. It does not send a value that the request gave. + A second exception: ate.worker.name on the ate.worker.* resource + instruments has one value for each live worker, like k8s.node.name on the + Kubernetes node metrics. The control plane names the Worker, not a + request, and the fleet bounds the count. Only those instruments carry it, + with k8s.pod.name and k8s.node.name of the same worker. enforced: false could_be_enforced_by: > A Weaver Rego policy can make each ate.* attribute of type string give a @@ -218,8 +223,10 @@ blind_spots: - area: actor population brief: > Nothing counts the actors by state. These metrics count the operations and - not the actors. They can count one actor more than one time. Issue #433 - has the ate.actors instrument. It does not exist at this time. + not the actors. They can count one actor more than one time. The sum of + ate.worker.actor.allocated counts the actors that hold a worker, but no + other state. Issue #433 has the ate.actors instrument. It does not exist + at this time. - area: image cache cost and eviction code: internal/imagecache brief: > @@ -236,7 +243,8 @@ blind_spots: above, gRPC requests with a grpc-status other than OK, any response flag, and a 1% sample of the rest. The runtime keys access_log.min_status and access_log.sample on the admin port restore - full logging while you debug. + full logging while you debug. An override applies to one replica and + lasts until that pod restarts. - area: ate-idp-server code: cmd/ate-idp-server brief: > diff --git a/docs/reference/api-guide.md b/docs/reference/api-guide.md index e8baa8c878..3617f2115c 100644 --- a/docs/reference/api-guide.md +++ b/docs/reference/api-guide.md @@ -37,7 +37,7 @@ The `WorkerPool` defines the pool of physical "warm" compute capacity. It manage | `priorityClassName` | `string` | `spec.priorityClassName` | | `nodeAffinity` | `NodeAffinity` | `spec.affinity.nodeAffinity` | | `resources` | `ResourceRequirements` | `spec.containers[].resources` | -| `serviceAccountName` | `string` | `spec.serviceAccountName`; defaults to `ateworker`, which the controller creates | +| `serviceAccountName` | `string` | `spec.serviceAccountName`; defaults to `ateworker`, which the controller creates. Worker pods never get a ServiceAccount token. | Keys in `ate.dev/` and its subdomains (for example, `policy.ate.dev/`) are reserved for controllers and cannot be set in `template.labels` or @@ -52,9 +52,8 @@ metadata; they do not affect actor scheduling. Actor selectors match Substrate sets a fixed capability set for each sandbox runtime. Every worker drops `ALL` container-runtime default capabilities and adds back only the set -below: 9 capabilities for gVisor and 11 for microVM. These permissions are not -configurable per pool. Actor containers are configured separately through -`ActorTemplate.containers[].securityContext`. +below. These permissions are not configurable per pool. Actor containers are +configured separately through `ActorTemplate.containers[].securityContext`. Workers run as UID/GID 0 with `privileged: false` and `allowPrivilegeEscalation: false`. They retain `SYS_ADMIN` and `NET_ADMIN` for @@ -70,6 +69,7 @@ permissions described in [Security](../security/security.md). | `DAC_READ_SEARCH` | Not granted | Not granted; virtiofsd runs with file handles off (`--inode-file-handles=never`) and needs it only to open them | | `FSETID` | Not granted | Retained for virtiofsd's setgid-file behavior | | `NET_RAW` | Needed to open the sandbox's raw socket | Not granted | +| `IPC_LOCK` | Lets runsc create each sandbox's pin ring, which holds the sandbox's resources so that they are released after the sandbox exits. Without it, the sandbox takes longer to exit | Not granted | | `SETFCAP`, `SETUID` | Needed to start runsc's gofer | Retained in virtiofsd's child set; `SETUID` is needed for non-root guest file creation | | `SETGID` | Needed to start runsc's gofer | Needed by virtiofsd to drop supplementary groups | | `DAC_OVERRIDE` | Needed to mount the rootfs overlay | Same | @@ -150,7 +150,7 @@ The `ActorTemplate` defines the code, environment, and state-management policies | `containers` | `[]Container` | **Required.** The workload definition — see [Container Fields](#container-fields) below. Each container may also declare an optional `wakeupProbe` HTTP probe — see [Container Wakeup Probe](#container-wakeup-probe-wakeupprobe). | | `workerSelector` | `*Selector` | Optional. Gates which `WorkerPool`s actors from this template may use, by matching against each pool's labels (`matchLabels`). If unset, all pools are eligible (subject to the actor's own `worker_selector`). The pool sets the sandbox class, so this is also how a template pins one: if your cluster has pools of more than one sandbox class and the workload needs a particular class, make sure the selector points only at pools of that class. An actor booting with no snapshot and no selector may run on any class, and keeps it from its first checkpoint on. An actor created from the golden snapshot or a `sourceTag` runs on that snapshot's class. See [Sandbox Classes](sandbox-classes.md) for what differs between classes. The pools a template selects must also share a CPU architecture; see `sandboxRuntime` under [Snapshot Storage Layout](#snapshot-storage-layout). | | `snapshotConfig` | `SnapshotConfig` | Optional; omitted fields take their defaults. The base object-storage location snapshots are written under (`storageLocation`; **Preview**, `PerTemplateSnapshotLocation` gate), the snapshot fidelity (`preferredFidelity`) every Suspend captures, and automated golden snapshot creation (`goldenSnapshotConfig.mode`). See [Snapshot Storage Layout](#snapshot-storage-layout). | -| `volumes` | `[]Volume` | Optional. Volumes the containers may mount, each a `durableDir`, an `image` read-only OCI image volume (`image.reference`, pinned by digest), an `external` CSI volume source (**Preview**, `ExternalVolumes` gate; see [CSI Volumes Guide](../guides/csi-volumes.md)), or a `systemInfo` volume (see [SystemInfo Volumes](#systeminfo-volumes)). Every declared volume must be mounted by at least one container. A `durableDir` is created `0777`, as Kubernetes creates an emptyDir, so a container running as any user can write it. A snapshot restores it with the mode it had, so the container's own chmod survives suspend and resume. | +| `volumes` | `[]Volume` | Optional. Volumes the containers may mount, each a `durableDir`, an `image` read-only OCI image volume (`image.reference`, pinned by digest), an `external` CSI volume source (**Preview**, `ExternalVolumes` gate; see [CSI Volumes Guide](../guides/csi-volumes.md), including how non-root containers get write access), or a `systemInfo` volume (see [SystemInfo Volumes](#systeminfo-volumes)). A declared volume need not be mounted by any container. A `durableDir` is created `0777`, as Kubernetes creates an emptyDir, so a container running as any user can write it. A snapshot restores it with the mode it had, so the container's own chmod survives suspend and resume. | | `resources` | `*ResourceRequirements` | Required. Declares each actor's compute size via `limits`, which must set both `cpuMillicores` and `memoryBytes` — see [Sandbox Right-Sizing](#sandbox-right-sizing-resources). Immutable, like the rest of the template. | | `goldenEgressPolicy` | `EgressPolicyTemplate` | **Preview** (`GoldenEgressPolicy` gate). Optional egress policy for the golden actor during initialization. Requires at least one rule, using the same rule defaults and validation as `EgressPolicy`. See [Golden Egress Policy](#golden-egress-policy-goldenegresspolicy). | @@ -162,7 +162,7 @@ The sandbox runtime and its binaries (e.g. the gVisor `runsc` binary, or a micro > `goldenEgressPolicy` is a **preview** feature. Enable > `--preview=GoldenEgressPolicy` on the server (or through > ate-setup's `preview` setting), and opt in on the client with `kubectl ate --preview` -> or the `Ate-Preview-Allowed: true` gRPC metadata header. See [Preview gates](../dev/preview-gates.md). +> or the `Ate-Preview-Allowed: true` gRPC metadata header. See [Preview Gates](preview-gates.md). Set `goldenEgressPolicy` on an ActorTemplate to give its golden actor network access during initialization. For example, this template field @@ -484,6 +484,8 @@ Every owner's prefix starts with `/atespaces/`. So where a location is ate-api-server refuses to start with a `--snapshot-location` that breaks these rules, `ate-setup deploy` rejects it, and creating a template rejects such a `storageLocation`. Creating a tag checks the location the tag is stored under and fails with `FAILED_PRECONDITION` on one that breaks them. +A template's `gs://` `storageLocation` may also be at most 338 characters for the bucket name and path together, so each actor's prefix fits the 512 bytes GCS accepts in a locally minted snapshot transfer token. A longer `--snapshot-location` still works. ate-api-server logs a warning at startup, and an actor whose prefix does not fit gets its token from STS, which counts against the STS quota. + An owner is collected by deleting everything under its prefix, and it can delete nothing else. That is what makes a borrowed snapshot safe: an actor created from a tag points at a URI under `tags/`, which its own prefix does not cover. See [Snapshot lifetime](#snapshot-lifetime). An `Actor` reports its snapshots in the server-managed `status.snapshots` (and @@ -624,7 +626,7 @@ metadata: sandboxconfig.ate.dev/is-class-default: "true" spec: sandboxClass: gvisor - defaultVersion: v7 + defaultVersion: v8 versions: - name: v6 state: Enabled @@ -648,6 +650,17 @@ spec: gvisor: url: "gs://gvisor/releases/release/20261102.0/aarch64/gvisor.tar.zstd" sha256: "f702ae92ad7a0c4134be34ca23f52966dbb696db0c0f5b8ec439210ab2cd7c6a" + - name: v8 + state: Enabled + assets: + amd64: + gvisor: + url: "gs://gvisor/releases/nightly/2026-12-02/x86_64/gvisor.tar.zstd" + sha256: "e4bb791370872192ea91211a5d9f0e7b3cb6d55248c1168ce82dd76ffef73e64" + arm64: + gvisor: + url: "gs://gvisor/releases/nightly/2026-12-02/aarch64/gvisor.tar.zstd" + sha256: "54c4357298d1f12122b6cc18078ecf7b5cc1ac2ee1ef7032f170cb6e7c5ef75d" ``` ### MicroVM SandboxConfig @@ -680,9 +693,11 @@ When an `ActorTemplate` is created with golden snapshots enabled: Golden actors follow ordinary lifecycle and ingress policies and appear in Actor lists. Leave these resources to the controller: modifying or deleting -them can interrupt Golden creation, and deleting a published Golden tag -invalidates the template's recorded reference. `DeleteActorTemplate` collects -its Golden tag and any unfinished Golden actor. +them can interrupt Golden creation. While a template exists, `DeleteTag` +refuses its Golden tag with `FailedPrecondition`, because actors created +without a `sourceTag` start from it. It still finishes a delete of that tag +that failed partway. `DeleteActorTemplate` collects its Golden tag and any +unfinished Golden actor. Golden capture follows `preferredFidelity`. MEMORY preserves processes and memory; VOLUMES preserves startup data in mounted volumes and starts new processes on @@ -751,7 +766,7 @@ Replaces the mutable fields of an existing actor with the ones in the request (` * `actor`: `Actor` — the complete replacement actor. `metadata.atespace` and `metadata.name` identify the resource; `metadata.uid` and `metadata.version` are **required** preconditions. `metadata` and `status` are server-owned and whatever the request carries in them is ignored. `source_tag` is immutable. * `actor_template` may change only while the actor is `SUSPENDED`. The new template must declare the same volumes and volume mounts. Once the actor owns an external snapshot, the new template must also store snapshots under the same location: its `snapshotConfig.storageLocation` with the `PerTemplateSnapshotLocation` preview gate, otherwise ate-api-server's `--snapshot-location` (see [Snapshot Storage Layout](#snapshot-storage-layout)). * `worker_selector` may be updated or cleared (`nil`) in any state, but not while another operation is changing the actor. The updated selector takes effect on the next `ResumeActor`. - * A suspended actor with a local snapshot is initially pinned to its node (see `locality` in [Snapshot Storage Layout](#snapshot-storage-layout)). `ResumeActor` first looks for a worker there matching the template and actor selectors. If none is available but a worker satisfies the remaining constraints without node or runtime restrictions, resume detaches the checkpoint and retries placement. If no eligible worker has room, it returns `RESOURCE_EXHAUSTED`. + * A suspended actor with a local snapshot is initially pinned to its node (see `locality` in [Snapshot Storage Layout](#snapshot-storage-layout)). `ResumeActor` first looks for a worker there matching the template and actor selectors. If none is available but a worker satisfies the remaining constraints without node or runtime restrictions, resume detaches the checkpoint and retries placement. If no eligible worker has room, it returns `RESOURCE_EXHAUSTED`. If at least one worker on any node is eligible and the actor is larger than each of them, it returns `FAILED_PRECONDITION`. * **Response:** the updated `Actor`. * **Errors:** `INVALID_ARGUMENT` if `uid` or `version` is unset, or if the request changes an immutable field (including by leaving one unset). `FAILED_PRECONDITION` if the actor is marked for deletion or if a change to `actor_template` breaks one of the rules above. `ABORTED` if either guard no longer matches the stored resource, or while another operation is changing the actor (retry the same request). @@ -761,16 +776,25 @@ Because the guards are required and only a read supplies them, an update is alwa Activates a suspended actor by restoring it onto a physical worker. * **Request:** `ResumeActorRequest` * `actor`: `ObjectRef` of the actor to resume. + * `options`: (Optional) `version` and `uid` guards on the actor. A mismatch returns `ABORTED`. A call can change `version` before it fails, so read the actor again before a retry. * **Response:** `ResumeActorResponse` containing the updated `Actor` object (including the physical worker placement in `status.worker_assignment`). -* **Errors:** `RESOURCE_EXHAUSTED` if no eligible worker has room. `FAILED_PRECONDITION` if the actor is `ACTOR_STATE_CRASHED`. When a suspended actor's node is deleted, resume restores its local snapshot on another node from the snapshot's upload, even if atelet never reported the upload complete. Resume does this once another node has room. If atelet finds no upload, resume moves the actor to `ACTOR_STATE_CRASHED` and returns `FAILED_PRECONDITION`. `RevertActor` then returns it to its last completed external snapshot. Revert deletes an upload that was never reported complete, so a snapshot is lost if its restore fails for another reason, or if the actor is reverted before it resumes. +* **Errors:** `RESOURCE_EXHAUSTED` if no eligible worker has room. `FAILED_PRECONDITION` if the actor is `ACTOR_STATE_CRASHED`, or if at least one worker is eligible and the actor is larger than each of them, even when empty. Unavailable workers count, so a short outage gives `RESOURCE_EXHAUSTED`. A new worker counts once it first registers. When a suspended actor's node is deleted, resume restores its local snapshot on another node from the snapshot's upload, even if atelet never reported the upload complete. Resume does this once another node has room. If atelet finds no upload, resume moves the actor to `ACTOR_STATE_CRASHED` and returns `FAILED_PRECONDITION`. `RevertActor` then returns it to its last completed external snapshot. Revert deletes an upload that was never reported complete, so a snapshot is lost if its restore fails for another reason, or if the actor is reverted before it resumes. + +The API server assigns a new UUID to each Run or Restore call and stores it in +`status.worker_assignment.actor_activation_uid` when the Actor becomes RUNNING. +Workers bind that UUID to the runtime they start. Activations started by an +older API server can have an empty UID. Crash reports accept the activation UID +field for protocol compatibility. Crash handling uses the Actor and Worker +identities and will check the Actor activation UID in a future release. #### `SuspendActor` Hibernate a running actor, capturing its current RAM and disk state into a snapshot. * **Request:** `SuspendActorRequest` * `actor`: `ObjectRef` of the actor to suspend. * `options.mode`: (Optional) `DURABILITY_MODE_SYNCHRONOUS` returns once the snapshot is `COMPLETED` in object storage. `DURABILITY_MODE_ASYNCHRONOUS` returns once the snapshot is captured on the worker's node, and atelet uploads it in the background. Unset runs an asynchronous suspend. + * `options.version`, `options.uid`: (Optional) `version` and `uid` guards on the actor. A mismatch returns `ABORTED`. A call can change `version` before it fails, so read the actor again before a retry. * **Response:** `SuspendActorResponse` containing the `Actor` object in `ACTOR_STATE_SUSPENDED`, with its snapshot in `status.snapshots`. -* Called on an actor that is already `ACTOR_STATE_SUSPENDED`, it returns the actor as it is, in either mode. After an asynchronous suspend, atelet uploads the snapshot in the background, so `status.snapshots` may still show a `PENDING` `durableSnapshot`. +* Called on an actor that is already `ACTOR_STATE_SUSPENDED`, it returns the actor as it is, in either mode, unless an `options.version` or `options.uid` guard does not match. After an asynchronous suspend, atelet uploads the snapshot in the background, so `status.snapshots` may still show a `PENDING` `durableSnapshot`. * A snapshot generation conflict returns `ABORTED` without crashing the actor. The actor can remain `ACTOR_STATE_SUSPENDING`, with its worker assignment and previous completed snapshot kept for recovery. Read the actor's latest state before retrying; repeating a stale request cannot resolve a persistent disagreement with atelet. * A successful suspend releases the actor's previous external snapshot: an actor keeps one, and only tags outlive it. To keep the snapshot a suspend just wrote, tag it with `CreateTag` while the actor is still suspended. After an asynchronous suspend, `CreateTag` first has atelet upload the snapshot if it has not already, so the call can take as long as that upload. If the upload fails, so does `CreateTag`, and the actor is left as it was. @@ -793,6 +817,7 @@ Deletion always runs before the database reference is dropped, and a failure fai Discards an actor's live or crashed execution and transitions it to `ACTOR_STATE_SUSPENDED` at its last completed external snapshot (`status.snapshots`). * **Request:** `RevertActorRequest` * `actor`: `ObjectRef` of the actor to revert. Accepted from `ACTOR_STATE_RUNNING` and `ACTOR_STATE_CRASHED` (plus `ACTOR_STATE_REVERTING` for idempotent retries), and from `ACTOR_STATE_SUSPENDED` when the actor's latest snapshot is node-local. Calling `RevertActor` on an `ACTOR_STATE_SUSPENDED` actor with no node-local snapshot returns `FAILED_PRECONDITION`. + * `options`: (Optional) `version` and `uid` guards on the actor. A mismatch returns `ABORTED`. A call can change `version` before it fails, so read the actor again before a retry. * **Response:** `RevertActorResponse` containing the reverted `Actor` in `ACTOR_STATE_SUSPENDED`. * Reverting terminates any bound worker sandbox, clears node-local checkpoints, and garbage-collects any partial external snapshot left by an interrupted suspend while preserving the last committed durable snapshot in `status.snapshots`. * External volumes are not reverted. Their contents are never part of a snapshot, so a reverted actor comes back with its memory and root filesystem rewound but its volumes exactly as the discarded execution left them. diff --git a/docs/reference/kubectl-ate.md b/docs/reference/kubectl-ate.md index 6e3e9819ca..b676fa887d 100644 --- a/docs/reference/kubectl-ate.md +++ b/docs/reference/kubectl-ate.md @@ -4,7 +4,7 @@ linkTitle: "CLI Reference" weight: 3 card_icon: "fa-solid fa-terminal" description: > - Manage atespaces, actor templates, actors, snapshots, egress policies, and logs with the kubectl-ate plugin. + Manage atespaces, CSI drivers, actor templates, actors, snapshots, egress policies, and logs with the kubectl-ate plugin. --- # `kubectl-ate` @@ -102,7 +102,7 @@ kubectl ate top workers > **Note:** `get actors` requires either `--atespace ` / `-a ` (one atespace) or `-A`/`--all-atespaces` (all atespaces) — there is no default atespace. Getting a single actor always requires `--atespace`/`-a`, since an actor is addressed by `(atespace, name)`. `-a` (lower-case) scopes to one atespace; `-A` (upper-case) spans all. -> **Note:** Actors, workers, and actor templates are not Kubernetes CRDs — they live in the Substrate control plane's PostgreSQL database, not `etcd`. `kubectl get actor`, `kubectl get worker`, and `kubectl get actortemplate` will not return anything; only `kubectl ate get …` queries the control plane (see [Actor Templates](#actor-templates)). `kubectl get workerpool` *does* work, because pools are CRDs. +> **Note:** Actors, workers, actor templates, and CSI drivers live in the Substrate control plane's PostgreSQL database, not `etcd`. `kubectl get actor`, `kubectl get worker`, and `kubectl get actortemplate` return nothing; only `kubectl ate get …` queries the control plane (see [Actor Templates](#actor-templates) and [CSI Drivers](#csi-drivers)). `kubectl get csidriverconfig` lists the `ate.dev/v1` `CSIDriverConfig` CRD objects, which are separate from the control-plane `CsiDriver` that `kubectl ate get csi-driver` shows. `kubectl get workerpool` *does* work, because pools are CRDs. #### `kubectl ate get actor` output columns @@ -144,11 +144,11 @@ kubectl ate get atespaces # Get an atespace kubectl ate get atespace -# Delete an atespace (must be empty: fails if any actors, templates, or tags remain) +# Delete an atespace (must be empty: fails if any actors, templates, tags, or external volumes remain) kubectl ate delete atespace ``` -> **Note:** `create actor … -a ` requires the atespace to already exist, otherwise it fails with `FailedPrecondition`. `delete atespace` only removes an **empty** atespace. Delete its actors, actor templates, and tags first (cascade delete is not yet supported). +> **Note:** `create actor … -a ` requires the atespace to already exist, otherwise it fails with `FailedPrecondition`. `delete atespace` only removes an **empty** atespace. Delete its actors, actor templates, tags, and external volumes first (cascade delete is not yet supported). #### `kubectl ate get atespace` output columns @@ -157,6 +157,53 @@ kubectl ate delete atespace | `NAME` | The atespace name. Globally unique — atespaces are global-scoped. | | `AGE` | Time elapsed since the atespace was created. | +### CSI Drivers + +A **CSI driver** (`CsiDriver`) is a global-scoped resource that records connection settings for a CSI driver (`driverName`): its controller gRPC endpoint (`controllerEndpoint`) and mTLS settings (`tls`). `driverName` is immutable after creation, while `controllerEndpoint` and `tls` can be replaced with `update`. Creating or updating a CSI driver requires the `ExternalVolumes` preview gate on the server and `--preview` on the CLI; `get` and `delete` work even when the gate is disabled so existing drivers can be inspected and removed. + +Example `csi-driver.yaml`: + +```yaml +metadata: + name: csi-nfs +driverName: nfs.csi.k8s.io +controllerEndpoint: + host: csi-nfs-controller.kube-system.svc.cluster.local + port: 50052 +tls: + serverName: csi-nfs-controller.kube-system.svc +``` + +```bash +# Create a CSI driver from a manifest (protojson-shaped +# ateapi.CsiDriver, a single YAML/JSON document; use -f - for stdin). +kubectl ate create csi-driver -f csi-driver.yaml --preview + +# List all CSI drivers, or get one (also: -o yaml prints the re-applyable manifest). +kubectl ate get csi-drivers +kubectl ate get csi-driver -o yaml + +# Replace a CSI driver: dump it (with metadata.uid and metadata.version), +# edit mutable fields, and send it back. +kubectl ate get csi-driver -o yaml > csi-driver.yaml +$EDITOR csi-driver.yaml +kubectl ate update csi-driver -f csi-driver.yaml --preview + +# Delete a CSI driver (optionally guarded by --uid and/or --version). +kubectl ate delete csi-driver +kubectl ate delete csi-driver --uid --version +``` + +#### `kubectl ate get csi-driver` output columns + +| Column | Meaning | +|---|---| +| `NAME` | The CSI driver resource name. Globally unique; CSI drivers are global-scoped. | +| `DRIVER` | The unique CSI driver name (`driverName`) this resource binds to. | +| `CONTROLLER-ENDPOINT` | The CSI controller gRPC endpoint (`host:port`). | +| `TLS` | Controller connection TLS mode: `mtls (pod-identity)` or `disabled`. | +| `AGE` | Time elapsed since the CSI driver was created. | + ### Actor Templates An **actor template** describes what an actor runs: containers, volumes, @@ -263,9 +310,34 @@ kubectl ate create actor -a --template - kubectl ate delete tag -a ``` +### External Volumes + +An `ExternalVolume` is an atespace-scoped record of a storage volume, named by +its CSI driver and the volume ID in the format the driver expects. It is +read-only: the server creates and deletes it, and nothing creates one yet. +Reading one works with the `ExternalVolumes` preview gate off; see +[CSI Volumes](../guides/csi-volumes.md#5-external-volume-records). + +```bash +# List an atespace's external volumes, all atespaces' external volumes, or resolve them by name. +kubectl ate get external-volumes -a +kubectl ate get external-volumes -A +kubectl ate get external-volume [ ...] -a +``` + +#### `kubectl ate get external-volume` output columns + +| Column | Meaning | +|---|---| +| `ATESPACE` | The atespace the external volume belongs to. | +| `NAME` | The external volume's name, unique within its atespace. | +| `DRIVER` | The CSI driver name, or `` until the volume is provisioned. | +| `VOLUME ID` | The volume's ID in the storage system, in the format the driver expects, or `` until the volume is provisioned. | +| `AGE` | Time elapsed since the external volume was created. | + ### Egress Policies -An actor has at most one egress policy. See [Egress Traffic](../guides/egress-traffic.md), [Network Egress](../guides/network-egress.md), [MITM Trust Bundle](../guides/egress-trust-bundle.md), and [Egress Credential Injection](../guides/egress-credential-injection.md) for how outbound traffic is mediated and how rules are evaluated. +An actor has at most one egress policy. See [Egress Traffic](../guides/egress-traffic.md), [MITM Trust Bundle](../guides/egress-trust-bundle.md), and [Egress Credential Injection](../guides/egress-credential-injection.md) for how outbound traffic is mediated and how rules are evaluated. Example `policy.yaml`: diff --git a/docs/reference/preview-gates.md b/docs/reference/preview-gates.md new file mode 100644 index 0000000000..85fdee99d1 --- /dev/null +++ b/docs/reference/preview-gates.md @@ -0,0 +1,56 @@ +--- +title: "Preview Gates" +linkTitle: "Preview Gates" +weight: 7 +description: > + Explore, understand, and enable preview features on Agent Substrate servers and clients. +--- + +# Preview Gates + + Every feature in Agent Substrate is either in **preview** (gated and off by default) or **GA** (always on). Preview gates allow including new features in a release before they're considered stable, keeping them disabled by default. Preview APIs and behavior are outside the compatibility policy and may change or be removed between releases. Preview gates do **not** enforce access control. + +## Enabling and Using Preview Features + +Using a gated feature in the Control API requires enabling the gate on the server and (sometimes) opting in on the client: + +1. **Server** enablement: + + - Pass `--preview=` to each Substrate binary as a comma-separated list of gate names, or `ALL` to enable all preview features. + - When deploying with `ate-setup`, set `preview` in the configuration file, `ATE_PREVIEW` in the environment, or `--preview=` on the command line (see the [Operator Install Guide](../guides/operator-install.md)). + - Unknown gate names cause startup to fail. + - Component-level gates that expose no Control API fields take effect as soon as `--preview` is enabled on the server. + - When a feature reaches GA or is removed, `--preview` continues to accept its gate name for compatibility while keeping the feature fixed on (if GA) or off (if removed). + +2. **Client** enablement: + + - The client header is only required for requests that invoke a gated RPC method or configure a gated feature, such as creating an `ActorTemplate` with a gated field or calling `CreateActor` from a template with external volumes. Subsequent RPCs on an existing `Actor` or `ActorTemplate`, including `ResumeActor`, `SuspendActor`, `RevertActor`, `DeleteActor`, and `DeleteActorTemplate`, do not require the header. + - Send the `Ate-Preview-Allowed: true` gRPC metadata header on requests to `ate-api-server`. + - Without this header, `ate-api-server` rejects requests that set gated fields, create gated resources, or call gated RPC methods (returning `FAILED_PRECONDITION` for gated methods). + - Pass `--preview` to `kubectl ate` to send the header from the CLI (see the [CLI Reference](kubectl-ate.md#global-flags)). + - If `--preview` is later turned off on the server, unchanged fields on existing objects are not re-validated on update, and `SuspendActor`, `DeleteActor`, `DeleteActorTemplate`, and `DeleteTag` continue to release workers, detach external volumes, and delete snapshots so existing objects are not stranded. + + +## Available Preview Gates + +This is the list of up-to-date description of current preview features. + +### `ActorIPv6` + +`ActorIPv6` adds IPv6 to actor networks on workers whose Pods have an IPv6 address. IPv6-only clusters require it. Actor networks retain their private IPv4 link for ingress, DNS, and wakeup probes, so applications must listen on IPv4 or a dual-stack socket. Enable `--preview=ActorIPv6` on the server; no client opt-in is required. See [Egress Traffic](../guides/egress-traffic.md) for the networking contract. + +### `ExternalVolumes` + +`ExternalVolumes` integrates Agent Substrate with Container Storage Interface (CSI) drivers to dynamically provision per-actor external volumes and attach or detach them as actors resume and suspend. Enable it when actors need larger or CSI-backed persistent filesystems whose state stays on external storage across suspends and resumes. Enable `--preview=ExternalVolumes` on the server, opt in on the client, register a `CSIDriverConfig` for each CSI driver, and configure volume capacity and `StorageClass` under `volumes[].external` on `ActorTemplate`. See full documentation at [CSI Volumes](../guides/csi-volumes.md) and [Deploying CSI Drivers](../guides/csi-deployment.md). + +### `GoldenEgressPolicy` + +`GoldenEgressPolicy` lets an `ActorTemplate` define outbound network rules that the template controller applies to the temporary golden actor while building its golden snapshot. Actors later created from the template keep default-deny outbound networking until given their own `EgressPolicy`. Enable it when golden snapshot warmup must reach external endpoints, such as package registries or model stores, without granting that network access to actors at runtime. Enable `--preview=GoldenEgressPolicy` on the server, opt in on the client, and configure rules in `golden_egress_policy` on `ActorTemplate`. See full documentation at [Golden Egress Policy](api-guide.md#golden-egress-policy-goldenegresspolicy). + +### `IngressCache` + +`IngressCache` caches `/` to worker IP bindings in `atenet-router` (`--atenet-dataplane=envoy`) so bodiless HTTP requests to warm actors bypass `ext_proc`, evicting stale bindings and replaying cached requests that never reached the actor. Enable it to lower ingress latency (on cache hit) and reduce `ResumeActor` load on `ate-api-server`. Enable `--preview=IngressCache` on the server (no client header is required) and optionally tune `--ingress-cache-ttl` and `--ingress-cache-max-cached-actors` on `atenet-router`. See full documentation at [Envoy Substrate Ingress Cache](../../cmd/dataplane/envoy/dynamic-modules/ingress-cache/README.md). + +### `PerTemplateSnapshotLocation` + +`PerTemplateSnapshotLocation` lets each `ActorTemplate` store actor snapshots under its own object-storage URI prefix instead of `ate-api-server`'s cluster-wide `--snapshot-location`. Enable it to isolate snapshot storage across buckets or prefixes per workload or tenant, or to deploy `ate-api-server` without a cluster-wide default snapshot location. Enable `--preview=PerTemplateSnapshotLocation` on the server, opt in on the client, and set `snapshot_config.storage_location` on `ActorTemplate`. See full documentation at [Snapshot Storage Layout](api-guide.md#snapshot-storage-layout) and [Snapshot storage](../guides/operator-install.md#snapshot-storage). diff --git a/docs/reference/resource-model.md b/docs/reference/resource-model.md index 05fa1136ef..b3834d8498 100644 --- a/docs/reference/resource-model.md +++ b/docs/reference/resource-model.md @@ -44,7 +44,9 @@ Global │ ├── ActorTemplate │ ├── Actor │ │ └── EgressPolicy "default" subresource (singleton) -│ └── Tag +│ ├── Tag +│ └── ExternalVolume +├── CsiDriver └── Worker └── ActorAssignment subresource (one per hosted Actor, managed by Substrate) ``` @@ -57,6 +59,8 @@ Global | `ActorTemplate` | Atespace | 0..N | Clients | | `Actor` | Atespace | 0..N | Clients | | `Tag` | Atespace | 0..N | Clients | +| `ExternalVolume` | Atespace | 0..N | Substrate | +| `CsiDriver` | Global | 0..N | Clients | | `Worker` | Global | 0..N | Substrate | ## Subresources @@ -97,14 +101,17 @@ classDiagram class Actor class EgressPolicy class Tag + class ExternalVolume class Worker class ActorAssignment + class CsiDriver } Atespace "1" *-- "0..1" AtespaceAccessPolicy Atespace "1" o-- "*" ActorTemplate Atespace "1" o-- "*" Actor Atespace "1" o-- "*" Tag + Atespace "1" o-- "*" ExternalVolume Actor "1" *-- "0..1" EgressPolicy Worker "1" *-- "*" ActorAssignment Actor "*" --> "1" ActorTemplate : actor_template diff --git a/docs/reference/version-skew-policy.md b/docs/reference/version-skew-policy.md index dfcb3462e5..0efa8a8fe4 100644 --- a/docs/reference/version-skew-policy.md +++ b/docs/reference/version-skew-policy.md @@ -102,7 +102,7 @@ The schema is updated with `ate-api-server`, and migrations follow [postgresql-s ### Data on nodes and in snapshots -This covers Substrate's own data only. The sandbox runtime's checkpoint files follow the runtime's own rules: a restore across runtime versions keeps only the file systems. On gVisor, `runsc` writes those file systems as `fscheckpoint` bundles (see [SandboxConfig](#sandboxconfig)). On microVM, `ateworker-microvm` writes them as tar files, which are Substrate's own data and follow the snapshot rules below. +This covers Substrate's own data only. The sandbox runtime's checkpoint files follow the runtime's own rules: a restore across runtime versions keeps only the file systems. On gVisor, `runsc` writes those file systems as `fscheckpoint` bundles (see [SandboxConfig](#sandboxconfig)). On microVM, `ateworker-microvm` writes them as tar files, which are Substrate's own data and follow the snapshot rules below. Restoring a microVM memory snapshot created without the `ActorIPv6` preview gate onto a worker with actor IPv6 enabled is unsupported because the snapshot contains the guest network configuration. MicroVM snapshots with actor IPv6 record their IP families as a runtime compatibility requirement. This section is about data one release writes and another release reads, whether that is a different component or the same component after an upgrade or a rollback. Substrate's data comes in two kinds, by how long it lives. diff --git a/docs/security/extensibility.md b/docs/security/extensibility.md index 65b4faa1e7..7ae4feba94 100644 --- a/docs/security/extensibility.md +++ b/docs/security/extensibility.md @@ -24,7 +24,7 @@ You can add your own [`ext_proc`](https://www.envoyproxy.io/docs/envoy/latest/co ## Replace: bring your own gateway -- **Egress:** you can point actors at your own policy enforcement point (PEP) instead of `atenet-egress`. Your PEP must meet the [Network Egress Contract](../guides/network-egress.md): it must verify the actor's certificate and reject any traffic it can't attribute to a running actor. Honoring Substrate's `EgressPolicy` is encouraged but not required. The installer doesn't have a bring-your-own mode yet. +- **Egress:** you can point actors at your own policy enforcement point (PEP) instead of `atenet-egress`. Your PEP must meet the [egress PEP contract](../guides/egress-traffic.md#egress-pep-contract): it must verify the actor's certificate and reject any traffic it can't attribute to a running actor. Honoring Substrate's `EgressPolicy` is encouraged but not required. The installer doesn't have a bring-your-own mode yet. - **Ingress:** planned. `atenet-router` does more than filter traffic: it wakes suspended actors and routes requests to their workers. A replacement router will need to call Substrate, either through the Substrate ext_proc or via the Substrate API, for those steps. If you replace a gateway, the authentication and authorization it enforced become your responsibility. diff --git a/docs/security/identity.md b/docs/security/identity.md new file mode 100644 index 0000000000..08c16e6106 --- /dev/null +++ b/docs/security/identity.md @@ -0,0 +1,99 @@ +--- +title: "Identity Overview" +linkTitle: "Identity Overview" +weight: 4 +description: > + Identity system overview and explanation of common call flows. +--- + +# Identity overview + +Substrate identity is designed to easily integrate with external systems. +IdP-issued identities for humans are recognized by Substrate, and +Substrate-issued identities for actors are recognized by external APIs. In +this document we explain the core identity flows. More advanced identity +systems such as On-Behalf-Of +([#3715](https://github.com/agent-substrate/substrate/issues/3715)) and ID-JAG +([#3714](https://github.com/agent-substrate/substrate/issues/3714)) are being +designed. + +| Flow | Credential | Issued by | +|---|---|---| +| [User → Actor](#user--actor) | The user's SSO token | Your human IdP | +| [SRE / dev → Substrate](#sre--dev--substrate) | Short-lived OIDC token | The same human IdP | +| [Actor → Actor](#actor--actor) | Actor JWT, injected at egress | Substrate | +| [Actor → Cloud](#actor--cloud) | Actor JWT, federated via OIDC | Substrate, trusted by the cloud's Security Token Service (STS) | +| [Actor → SaaS](#actor--saas-with-oauth) | OAuth access token, injected at egress | The SaaS OAuth server | + +## User → Actor + +![User to actor flow](../assets/identity-user-to-actor.svg) + +1. Alice signs in to your app through your SSO. Your app frontend will make any + necessary connections to Substrate on her behalf. +2. The frontend calls the ingress router (`atenet-router`) over mTLS. The + router only accepts the SPIFFE IDs listed in + [`ingressAllowedSPIFFEIDs`](../guides/operator-install.md#ingress-to-actors). +3. The router routes the request to Actor A. + +Substrate does not see Alice's SSO token. + +## SRE / dev → Substrate + +![SRE debugging flow](../assets/identity-sre-debugging.svg) + +1. The engineer gets a short-lived token from your SSO. +2. The engineer calls `ate-api-server` with the token. The server trusts your + SSO issuer as a + [JWT provider](../guides/authentication.md#configuring-jwt-providers), and + [roles](../guides/authorization.md#roles) are granted per atespace. +3. The engineer can inspect, suspend, and delete actors. + +## Actor → Actor + +![Actor to actor flow](../assets/identity-actor-to-actor.svg) + +1. Actor A calls Actor B through the egress gateway (`atenet-egress`). +2. The gateway injects an [actor JWT](../guides/actor-jwts.md) for A and sends + the request to your app frontend. +3. The frontend verifies the JWT and checks whether A may call B. +4. The frontend calls the ingress router, which routes the request to Actor B. + +Actors can't reach each other directly. Your frontend authorizes every call. +The router authorizes ingress per allowlisted client today, so an allowlisted +frontend can reach every actor. Per-atespace ingress authorization will remove +the need for the hop through the app frontend and is tracked in +[#3589](https://github.com/agent-substrate/substrate/issues/3589). + +## Actor → Cloud + +![Actor to cloud flow](../assets/identity-actor-to-cloud.svg) + +1. Actor A sends a request with a placeholder header. +2. The egress gateway asks a token exchange credential provider for a + credential. +3. The provider exchanges A's actor JWT at the cloud STS, which + [trusts Substrate's issuer](../guides/actor-jwt-federation.md) through OIDC + federation. +4. The gateway injects the cloud token. + +Substrate will support native token exchange soon +([#1661](https://github.com/agent-substrate/substrate/issues/1661)). In the +meantime, you can write a token exchange credential provider using the +[credential provider API](../guides/egress-credential-injection.md#the-plugin-api). +The provider gets the actor JWT by calling `MintActorJwt` with its own +SPIFFE ID, which needs the +[`egress_gateway` role](../guides/authorization.md#system-roles) +(`--egress-gateway-spiffe-id`). + +## Actor → SaaS with OAuth + +![Actor to SaaS flow](../assets/identity-actor-to-saas.svg) + +1. Actor A sends a request with a placeholder header. +2. The egress gateway fetches the access token from a + [credential provider](../guides/egress-credential-injection.md). The + provider gets it from an OAuth token broker, which holds each user's + refresh token. You can implement the broker yourself, or use one provided + by a cloud provider. +3. The gateway injects the token. diff --git a/docs/security/security.md b/docs/security/security.md index 56232556bb..ce6455244d 100644 --- a/docs/security/security.md +++ b/docs/security/security.md @@ -10,7 +10,7 @@ description: > Substrate delivers zero trust for agents. Every agent has an identity, but no credentials, no open network, and no escape from the sandbox. -Agent Substrate executes untrusted actors at scale in a multi-tenant environment where workloads are dynamic and memory states migrate continuously across physical infrastructure. All security controls operate within Substrate's cold-start and resume latency budget. This document defines the high-level security principles. For identity and credential configuration, see the [Authentication Guide](../guides/authentication.md). Detailed threat scenarios and mitigating invariants are documented [in the threat model](threat-model.md). +Agent Substrate executes untrusted actors at scale in a multi-tenant environment where workloads are dynamic and memory states migrate continuously across physical infrastructure. All security controls operate within Substrate's cold-start and resume latency budget. This document defines the high-level security principles. For human and actor identities, see the [Identity Overview](identity.md). To configure access to `ate-api-server`, see the [Authentication Guide](../guides/authentication.md). Detailed threat scenarios and mitigating invariants are documented [in the threat model](threat-model.md). ## Security Boundaries @@ -30,7 +30,7 @@ Your application is outside these boundaries: it authenticates end users and dec Substrate provides the foundational base for agent security: - Sandboxing: built-in compute, storage, and networking separation. -- Identity: identity issuance is built-in and designed to federate with other identity systems. See the [Substrate Identity Critical User Journeys](https://docs.google.com/document/d/1seJNYQmsQYLCrYYzB9AmuxpSGSPCC3-u3tPNFsK2edc/edit?resourcekey=0-D6q8_0vqF6LPEk0BxWMTaA&tab=t.0#heading=h.6qjmtncwtihi). +- Identity: identity issuance is built-in and designed to federate with other identity systems. See the [Identity Overview](identity.md). - Gateway: built-in ingress and egress filtering that can do destination filtering and credential injection. We expect the application layer creating actors using substrate to be responsible for: @@ -61,7 +61,7 @@ Substrate is designed to safely run mutually hostile, untrusted actors from disp | **Always Sandboxed** | Every actor is required to run inside a strong compute sandbox. A linux container is not sufficient or supported. Our security design relies on strong containment. | Met (gVisor, CHV microVM) | | **Per-Actor Storage Segregation** | Storage and persistent volume state must be strictly segregated per actor. Actors cannot traverse, enumerate, or access persistence belonging to other actors. Restoring a snapshot must re-validate the actor's current tenant authorization before execution resumes. | Met (Segregation)
Future (Per-Actor Encryption, Restore Authorization) | | **Per-Actor Network Isolation** | Guest network stacks are segregated per actor. Lateral peer-to-peer network communication between co-located actors on the same host or across the cluster is blocked by default; inter-actor communication must route through authenticated, policy-enforced gateways. | Met (Private netns, atunnel) | -| **Delete Guarantee** | Reset, scrub, and sanitize local ephemeral volumes, cached state, and worker runtime environments between actor scheduling cycles to prevent cross-tenant data leakage. | In Progress (atelet resetActorDirs) | +| **Delete Guarantee** | Reset, scrub, and sanitize local ephemeral volumes, cached state, and worker runtime environments between actor scheduling cycles to prevent cross-tenant data leakage. | In Progress (`cmd/atelet/internal/actordirs`) | | **Worker Capability Reduction** | Worker pods use `privileged: false`, `allowPrivilegeEscalation: false` and fixed runtime-specific capability sets. They still run as root with `SYS_ADMIN` and `NET_ADMIN`; see [Worker security](../reference/api-guide.md#worker-security). | In Progress (root with `SYS_ADMIN`; no worker user namespace yet) | | **Node Blast Radius Containment** | A compromise of an individual sandbox guest or node supervisor restricts impact to the actors and identities actively co-located on that node. | In Progress (Node-attested PodIdentity, checkActorOnNode) | | **Atespace Separation** | The Substrate equivalent of a Kubernetes namespace that is used to group resources and partition object storage snapshot paths. OpenFGA relationship-based access control (ReBAC) is integrated for API authorization, but it does not yet enforce inter-atespace network policies or resource quotas. | In-Progress (OpenFGA ReBAC; network policies and quotas pending) | @@ -95,7 +95,7 @@ Other forms of tenancy: | :--- | :--- | :--- | | **No Access by Default** | Sandboxed actors and worker nodes launch with default-deny networking and have zero network or API access to control plane services (`ate-api-server`, Kubernetes API servers, PostgreSQL state store). DNS is filtered against allowed policy hostnames. Every control plane pod in `ate-system` also denies [ingress by default](../../manifests/ate-install/ate-system-networkpolicies.yaml), admitting only the flows the control plane needs. | Met (Loopback, private netns, link-local block, DNS relay filtering, ate-system NetworkPolicies) | | **Authenticated and Policy-Enforced Ingress** | Inbound invocations to actors terminate at authenticated edge routers (`atenet-router`), which authenticate callers and verify invocation policies before triggering on-demand actor cold-start or resume. | Met (atenet-router mTLS, atunnel mTLS) | -| **Fail-Closed Policy-Enforced Egress Gateway** | Outbound traffic is funneled through the multi-tenant egress proxy (`atenet-egress`), which validates actor identity, enforces destination host allowlists, executes TLS inspection or prompt filtering, and dynamically injects target credentials. If an egress policy enforcement point (PEP) is unconfigured/fails egress is dropped. Unsupported protocols are dropped; see [Egress Traffic](../guides/egress-traffic.md), [Network Egress](../guides/network-egress.md), [MITM Trust Bundle](../guides/egress-trust-bundle.md), and [Egress Credential Injection](../guides/egress-credential-injection.md) for specifics. | Met (atenet-egress fail-closed PEP, DNS filtering, non-TCP drop) | +| **Fail-Closed Policy-Enforced Egress Gateway** | Outbound traffic is funneled through the multi-tenant egress proxy (`atenet-egress`), which validates actor identity, enforces destination host allowlists, executes TLS inspection or prompt filtering, and dynamically injects target credentials. If an egress policy enforcement point (PEP) is unconfigured/fails egress is dropped. Unsupported protocols are dropped; see [Egress Traffic](../guides/egress-traffic.md), [MITM Trust Bundle](../guides/egress-trust-bundle.md), and [Egress Credential Injection](../guides/egress-credential-injection.md) for specifics. | Met (atenet-egress fail-closed PEP, DNS filtering, non-TCP drop) | ### Authorization diff --git a/docs/security/threat-model.md b/docs/security/threat-model.md index 99c714aab2..d3fe739b47 100644 --- a/docs/security/threat-model.md +++ b/docs/security/threat-model.md @@ -137,6 +137,7 @@ Substrate is expected to sit behind the user's service, not on the internet, so | T-11 | High | Improper handling of Secrets | Ensure there is an official, secure, recommended way for actors to use secrets, like API access tokens, without the secret entering the sandbox. | Inject credentials at the egress gateway so secrets never enter the sandbox. | Without an official path, users put secrets in plaintext fields. | | T-13 | Medium | Flat namespace of actors encourages broad permission grants or complex graph-oriented policy. | Support a grouping mechanism that can be used in policy controls. | Atespaces as the policy grouping unit, like Kubernetes namespaces. | | | T-14 | Medium | DNS misconfiguration | Access to DNS configuration should be limited to authoritative controllers. Routing should use stable configurations and query the API for the current worker assignment before forwarding requests. | Keep controllers with sensitive access off actor nodes. Limit who can update DNS configuration. Gateways get the worker assignment from the Substrate API, with bounded caching. mTLS from gateway to worker. | Invalidate cached assignments when actors move. | +| T-44 | Medium | Benchmark-only pprof listeners are enabled on a cluster that serves real actors. | Profiling endpoints are off by default. Enabling them is an explicit operator choice, and only the peers that collect profiles can reach them. | Leave `--pprof-listen-addr` and `--worker-pprof` unset outside benchmark clusters, and warn in their help text. Serve pprof on its own port. Admit only the profile scraper to that port with NetworkPolicy. | pprof has no authentication. Profiles hold call stacks, sizes and counts, and `/debug/pprof/cmdline` shows the daemon's flags. Profiles still show which operations a worker's actors run and when, and repeated goroutine dumps or long traces slow the process. The router can also reach a worker's pprof port, since the worker NetworkPolicy admits it on all ports. That adds little, because the router already carries all actor traffic to the worker. | ## Attacks from Actors diff --git a/docs/threats.json b/docs/threats.json index afdccd6e9a..80f58b119c 100644 --- a/docs/threats.json +++ b/docs/threats.json @@ -103,6 +103,14 @@ "suggested_concrete_mitigations": "Keep controllers with sensitive access off actor nodes. Limit who can update DNS configuration. Gateways get the worker assignment from the Substrate API, with bounded caching. mTLS from gateway to worker.", "notes": "Invalidate cached assignments when actors move." }, + { + "threat_id": "T-44", + "priority": "Medium", + "threat": "Benchmark-only pprof listeners are enabled on a cluster that serves real actors.", + "mitigating_invariants": "Profiling endpoints are off by default. Enabling them is an explicit operator choice, and only the peers that collect profiles can reach them.", + "suggested_concrete_mitigations": "Leave `--pprof-listen-addr` and `--worker-pprof` unset outside benchmark clusters, and warn in their help text. Serve pprof on its own port. Admit only the profile scraper to that port with NetworkPolicy.", + "notes": "pprof has no authentication. Profiles hold call stacks, sizes and counts, and `/debug/pprof/cmdline` shows the daemon's flags. Profiles still show which operations a worker's actors run and when, and repeated goroutine dumps or long traces slow the process. The router can also reach a worker's pprof port, since the worker NetworkPolicy admits it on all ports. That adds little, because the router already carries all actor traffic to the worker." + }, { "threat_id": "T-15", "priority": "Critical", diff --git a/go.mod b/go.mod index 072f618c46..29b9bb4ca9 100644 --- a/go.mod +++ b/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 require ( cloud.google.com/go/compute/metadata v0.9.0 @@ -23,9 +23,10 @@ require ( github.com/containerd/ttrpc v1.2.8 github.com/distribution/reference v0.6.0 github.com/envoyproxy/go-control-plane v0.14.0 - github.com/envoyproxy/go-control-plane/envoy v1.37.1-0.20260812071801-353463cc7248 + github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be github.com/fsnotify/fsnotify v1.9.0 github.com/go-logr/logr v1.4.4 + github.com/google/cel-go v0.31.0 github.com/google/go-cmp v0.7.0 github.com/google/go-containerregistry v0.21.7 github.com/google/nftables v0.3.0 @@ -33,7 +34,7 @@ require ( github.com/googleapis/gax-go/v2 v2.21.0 github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 github.com/jackc/pgx/v5 v5.10.0 - github.com/klauspost/compress v1.19.1 + github.com/klauspost/compress v1.20.4 github.com/moby/sys/user v0.4.1 github.com/myzhan/boomer v1.6.1-0.20250711115830-8a2c7ce4c7b1 github.com/opencontainers/runtime-spec v1.3.0 @@ -42,58 +43,62 @@ require ( github.com/openfga/openfga v1.20.0 github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 github.com/pressly/goose/v3 v3.27.3 - github.com/prometheus/client_golang v1.24.1 + github.com/prometheus/client_golang v1.25.0 github.com/spf13/cobra v1.10.2 github.com/spf13/pflag v1.0.10 - github.com/spiffe/go-spiffe/v2 v2.7.0 + github.com/spiffe/go-spiffe/v2 v2.8.1 github.com/stretchr/testify v1.12.1 github.com/testcontainers/testcontainers-go v0.44.0 github.com/testcontainers/testcontainers-go/modules/postgres v0.44.0 + github.com/tink-crypto/tink-go/v2 v2.9.0 github.com/vishvananda/netlink v1.3.1 github.com/vishvananda/netns v0.0.5 go.opentelemetry.io/contrib/bridges/prometheus v0.68.0 - go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 - go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 - go.opentelemetry.io/otel v1.45.0 + go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 + go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 + go.opentelemetry.io/otel v1.47.0 go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0 go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 go.opentelemetry.io/otel/exporters/prometheus v0.65.0 - go.opentelemetry.io/otel/log v0.21.0 - go.opentelemetry.io/otel/metric v1.45.0 - go.opentelemetry.io/otel/sdk v1.45.0 - go.opentelemetry.io/otel/sdk/log v0.21.0 - go.opentelemetry.io/otel/sdk/metric v1.45.0 - go.opentelemetry.io/otel/trace v1.45.0 + go.opentelemetry.io/otel/log v1.47.0 + go.opentelemetry.io/otel/metric v1.47.0 + go.opentelemetry.io/otel/sdk v1.47.0 + go.opentelemetry.io/otel/sdk/log v1.47.0 + go.opentelemetry.io/otel/sdk/metric v1.47.0 + go.opentelemetry.io/otel/trace v1.47.0 go.opentelemetry.io/proto/otlp v1.11.0 - golang.org/x/net v0.60.0 - golang.org/x/oauth2 v0.36.0 + golang.org/x/net v0.62.0 + golang.org/x/oauth2 v0.37.0 golang.org/x/sync v0.24.0 golang.org/x/sys v0.49.0 golang.org/x/term v0.47.0 - golang.org/x/time v0.15.0 + golang.org/x/time v0.16.0 google.golang.org/api v0.274.0 - google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d - google.golang.org/grpc v1.83.2 + google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 + google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc + google.golang.org/grpc v1.85.0 google.golang.org/protobuf v1.36.12 gopkg.in/yaml.v3 v3.0.1 helm.sh/helm/v4 v4.3.1 - k8s.io/api v0.37.1 - k8s.io/apiextensions-apiserver v0.37.1 - k8s.io/apimachinery v0.37.1 - k8s.io/cli-runtime v0.37.1 - k8s.io/client-go v0.37.1 - k8s.io/kubelet v0.37.0 - k8s.io/metrics v0.37.1 + k8s.io/api v0.38.0-beta.0 + k8s.io/apiextensions-api v0.38.0-beta.0 + k8s.io/apimachinery v0.38.0-beta.0 + k8s.io/cli-runtime v0.38.0-beta.0 + k8s.io/client-go v0.38.0-beta.0 + k8s.io/klog/v2 v2.140.0 + k8s.io/kubelet v0.38.0-beta.0 + k8s.io/metrics v0.38.0-beta.0 k8s.io/utils v0.0.0-20260626114624-be93311217bd + // TODO(#3821): move to a tagged release once one supports Kubernetes 1.38. sigs.k8s.io/controller-runtime v0.25.2 - sigs.k8s.io/kustomize/api v0.21.1 - sigs.k8s.io/kustomize/kyaml v0.21.2 + sigs.k8s.io/kustomize/api v0.21.3 + sigs.k8s.io/kustomize/kyaml v0.21.3 sigs.k8s.io/yaml v1.6.0 ) require ( - cel.dev/expr v0.25.2 // indirect + cel.dev/expr v0.25.3 // indirect cloud.google.com/go v0.123.0 // indirect cloud.google.com/go/auth v0.19.0 // indirect cloud.google.com/go/auth/oauth2adapt v0.2.8 // indirect @@ -102,7 +107,7 @@ require ( dario.cat/mergo v1.0.2 // indirect github.com/Azure/go-ansiterm v0.0.0-20250102033503-faa5f7b0171c // indirect github.com/BurntSushi/toml v1.6.0 // indirect - github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 // indirect + github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 // indirect github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/resourcemapping v0.55.0 // indirect github.com/IBM/pgxpoolprometheus v1.1.3 // indirect @@ -161,7 +166,6 @@ require ( github.com/dustin/go-humanize v1.0.1 // indirect github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a // indirect github.com/ebitengine/purego v0.10.1 // indirect - github.com/emicklei/go-restful/v3 v3.13.0 // indirect github.com/emirpasic/gods v1.18.1 // indirect github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 // indirect github.com/envoyproxy/protoc-gen-validate v1.3.3 // indirect @@ -172,31 +176,22 @@ require ( github.com/fatih/color v1.19.0 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect github.com/fluxcd/cli-utils v1.2.2 // indirect - github.com/fxamacker/cbor/v2 v2.9.1 // indirect + github.com/fxamacker/cbor/v2 v2.9.4 // indirect github.com/go-errors/errors v1.5.1 // indirect github.com/go-gorp/gorp/v3 v3.1.0 // indirect - github.com/go-jose/go-jose/v4 v4.1.4 // indirect + github.com/go-jose/go-jose/v4 v4.1.9 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-ole/go-ole v1.3.0 // indirect - github.com/go-openapi/jsonpointer v1.0.0 // indirect - github.com/go-openapi/jsonreference v1.0.0 // indirect - github.com/go-openapi/swag v0.28.0 // indirect - github.com/go-openapi/swag/cmdutils v0.28.0 // indirect - github.com/go-openapi/swag/conv v0.28.0 // indirect - github.com/go-openapi/swag/fileutils v0.28.0 // indirect - github.com/go-openapi/swag/jsonutils v0.28.0 // indirect - github.com/go-openapi/swag/loading v0.28.0 // indirect - github.com/go-openapi/swag/mangling v0.28.0 // indirect - github.com/go-openapi/swag/netutils v0.28.0 // indirect - github.com/go-openapi/swag/pools v0.28.0 // indirect - github.com/go-openapi/swag/stringutils v0.28.0 // indirect - github.com/go-openapi/swag/typeutils v0.28.0 // indirect - github.com/go-openapi/swag/yamlutils v0.28.0 // indirect + github.com/go-openapi/jsonpointer v1.0.2 // indirect + github.com/go-openapi/jsonreference v1.0.2 // indirect + github.com/go-openapi/swag/conv v0.29.2 // indirect + github.com/go-openapi/swag/jsonutils v0.29.2 // indirect + github.com/go-openapi/swag/pools v0.29.2 // indirect + github.com/go-openapi/swag/typeutils v0.29.2 // indirect github.com/go-viper/mapstructure/v2 v2.5.0 // indirect github.com/gobwas/glob v0.2.3 // indirect github.com/gofrs/flock v0.13.0 // indirect github.com/google/btree v1.1.3 // indirect - github.com/google/cel-go v0.31.0 // indirect github.com/google/gnostic-models v0.7.1 // indirect github.com/google/pprof v0.0.0-20260802141513-ef3492d7dac3 // indirect github.com/google/s2a-go v0.1.9 // indirect @@ -212,7 +207,6 @@ require ( github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 // indirect github.com/jackc/puddle/v2 v2.2.2 // indirect github.com/jmoiron/sqlx v1.4.0 // indirect - github.com/json-iterator/go v1.1.12 // indirect github.com/klauspost/cpuid/v2 v2.0.9 // indirect github.com/lann/builder v0.0.0-20180802200727-47ae307949d0 // indirect github.com/lann/ps v0.0.0-20150810152359-62de8c46ede0 // indirect @@ -241,8 +235,6 @@ require ( github.com/moby/sys/sequential v0.7.0 // indirect github.com/moby/sys/userns v0.1.0 // indirect github.com/moby/term v0.5.2 // 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/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 // indirect github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 // indirect github.com/muesli/cancelreader v0.2.2 // indirect @@ -258,14 +250,15 @@ require ( github.com/olekukonko/tablewriter v1.0.8 // indirect github.com/opencontainers/go-digest v1.0.0 // indirect github.com/opencontainers/image-spec v1.1.1 // indirect + github.com/pandatix/go-abnf v0.5.5 // indirect github.com/pelletier/go-toml/v2 v2.4.0 // indirect - github.com/peterbourgon/diskv v2.0.1+incompatible // indirect + github.com/peterbourgon/diskv/v3 v3.0.1 // indirect github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 // indirect github.com/power-devops/perfstat v0.0.0-20240221224432-82ca36839d55 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.70.1 // indirect + github.com/prometheus/client_model v0.6.3 // indirect + github.com/prometheus/common v0.73.1 // indirect github.com/prometheus/otlptranslator v1.0.0 // indirect - github.com/prometheus/procfs v0.21.1 // indirect + github.com/prometheus/procfs v0.22.0 // indirect github.com/rivo/uniseg v0.4.7 // indirect github.com/rubenv/sql-migrate v1.8.1 // indirect github.com/russross/blackfriday/v2 v2.1.0 // indirect @@ -275,7 +268,7 @@ require ( github.com/shirou/gopsutil v3.21.11+incompatible // indirect github.com/shirou/gopsutil/v4 v4.26.6 // indirect github.com/shopspring/decimal v1.4.0 // indirect - github.com/sirupsen/logrus v1.9.4 // indirect + github.com/sirupsen/logrus v1.10.2 // indirect github.com/sourcegraph/conc v0.3.0 // indirect github.com/spf13/afero v1.15.0 // indirect github.com/spf13/cast v1.10.0 // indirect @@ -293,32 +286,33 @@ require ( github.com/zeebo/xxh3 v1.0.2 // indirect github.com/zeromq/goczmq v4.1.0+incompatible // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect - go.opentelemetry.io/contrib/detectors/gcp v1.44.0 // indirect - go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 // indirect + go.opentelemetry.io/contrib/detectors/gcp v1.45.0 // indirect + go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect go.uber.org/mock v0.6.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/crypto v0.58.0 // indirect - golang.org/x/exp v0.0.0-20260718201538-764159d718ef // indirect + golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect golang.org/x/text v0.43.0 // indirect gomodules.xyz/jsonpatch/v2 v2.4.0 // indirect gonum.org/v1/gonum v0.17.0 // indirect google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect gopkg.in/evanphx/json-patch.v4 v4.13.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - k8s.io/apiserver v0.37.1 // indirect - k8s.io/component-base v0.37.1 // indirect - k8s.io/klog/v2 v2.140.0 // indirect - k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect + k8s.io/apiextensions-apiserver v0.38.0-beta.0 // indirect + k8s.io/apiserver v0.38.0-beta.0 // indirect + k8s.io/component-base v0.38.0-beta.0 // indirect + k8s.io/kube-openapi v0.0.0-20261014044854-ca3452a79603 // indirect k8s.io/kubectl v0.37.1 // indirect - k8s.io/streaming v0.37.1 // indirect + k8s.io/streaming v0.38.0-beta.0 // indirect oras.land/oras-go/v2 v2.6.2 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect + sigs.k8s.io/structured-merge-diff/v7 v7.0.1 // indirect ) -replace k8s.io/apimachinery => k8s.io/apimachinery v0.36.0-alpha.2.0.20260904094813-f8600edbddc8 +// helm requires controller-runtime v0.25.2, which does not build against +// apimachinery v0.38. Keep the pin the k8s.io modules above need. +replace sigs.k8s.io/controller-runtime => sigs.k8s.io/controller-runtime v0.25.1-0.20261119155835-be0153ca8953 diff --git a/go.sum b/go.sum index 6fe5d94408..0bd0dc7fc2 100644 --- a/go.sum +++ b/go.sum @@ -1,5 +1,5 @@ -cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= -cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0= +cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= cloud.google.com/go v0.26.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= cloud.google.com/go v0.123.0 h1:2NAUJwPR47q+E35uaJeYoNhuNEM9kM8SjgRgdeOJUSE= cloud.google.com/go v0.123.0/go.mod h1:xBoMV08QcqUGuPW65Qfm1o9Y4zKZBpGS+7bImXLTAZU= @@ -35,8 +35,8 @@ github.com/BurntSushi/toml v1.6.0 h1:dRaEfpa2VI55EwlIW72hMRHdWouJeRF7TPYhI+AUQjk github.com/BurntSushi/toml v1.6.0/go.mod h1:ukJfTF/6rtPPRCnwkur4qwRxa8vTRFBF0uk2lLoLwho= github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU= github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0 h1:l7+6kwRMJNwdCvYdDl7Eax+wzEYHSnNY7zrrfbhDdTA= -github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.33.0/go.mod h1:pJTkW8hEUIIi3Pf65lPZOnn4Y81yCllX6IWk2jNXdkM= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 h1:bN1gA3of5bXtbnLsRPrwfmbbe7A5UWFlcTHseujLnpc= +github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0/go.mod h1:Yj5vHEz/aAepZGliRJsA6uvHAVAQyEwajq9ORCHPxzM= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0 h1:UnDZ/zFfG1JhH/DqxIZYU/1CUAlTUScoXD/LcM2Ykk8= github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.55.0/go.mod h1:IA1C1U7jO/ENqm/vhi7V9YYpBsp+IMyqNrEN94N7tVc= github.com/GoogleCloudPlatform/opentelemetry-operations-go/internal/cloudmock v0.55.0 h1:7t/qx5Ost0s0wbA/VDrByOooURhp+ikYwv20i9Y07TQ= @@ -120,6 +120,8 @@ github.com/blang/semver/v4 v4.0.0 h1:1PFHFE6yCCTv8C1TeyNNarDzntLi7wMI5i/pzqYIsAM github.com/blang/semver/v4 v4.0.0/go.mod h1:IbckMUScFkM3pff0VJDNKRiT6TG/YpiHIM2yvyW5YoQ= github.com/bshuster-repo/logrus-logstash-hook v1.1.0 h1:o2FzZifLg+z/DN1OFmzTWzZZx/roaqt8IPZCIVco8r4= github.com/bshuster-repo/logrus-logstash-hook v1.1.0/go.mod h1:Q2aXOe7rNuPgbBtPCOzYyWDvKX7+FpxE5sRdvcPoui0= +github.com/c2sp/wycheproof v0.0.0-20260105152342-fca0d3ba9f12 h1:C34LW7dhWgjAaAOdNB8z2UCyJsXDjC6UTILljHuqOlI= +github.com/c2sp/wycheproof v0.0.0-20260105152342-fca0d3ba9f12/go.mod h1:U1QjrC6KepOmtVmJn3QsKOTd9HliGr/da5afPEhLRnk= github.com/catppuccin/go v0.3.0 h1:d+0/YicIq+hSTo5oPuRi5kOpqkVA5tAsU6dNhvRu+aY= github.com/catppuccin/go v0.3.0/go.mod h1:8IHJuMGaUUjQM82qBrGNBv7LFq6JI3NnQCF6MOlZjpc= github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8= @@ -222,8 +224,6 @@ github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a h1:UwSIFv5g github.com/dylibso/observe-sdk/go v0.0.0-20240819160327-2d926c5d788a/go.mod h1:C8DzXehI4zAbrdlbtOByKX6pfivJTBiV9Jjqv56Yd9Q= github.com/ebitengine/purego v0.10.1 h1:dewVBCBT2GaMu1SrNTYxQhgQBethzfhiwvZiLGP/qyY= github.com/ebitengine/purego v0.10.1/go.mod h1:iIjxzd6CiRiOG0UyXP+V1+jWqUXVjPKLAI0mRfJZTmQ= -github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= -github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/emirpasic/gods v1.18.1 h1:FXtiHYKDGKCW2KzwZKx0iC0PQmdlorYgdFG9jPXJ1Bc= github.com/emirpasic/gods v1.18.1/go.mod h1:8tpGGwCnJ5H4r6BWwaV6OrWmMoPhUl5jm/FMNAnJvWQ= github.com/envoyproxy/go-control-plane v0.9.0/go.mod h1:YTl/9mNaCwkRvm6d1a2C3ymFceY/DCBVvsKhRF0iEA4= @@ -231,8 +231,8 @@ github.com/envoyproxy/go-control-plane v0.9.1-0.20191026205805-5f8ba28d4473/go.m github.com/envoyproxy/go-control-plane v0.9.4/go.mod h1:6rpuAdCZL397s3pYoYcLgu1mIlRU8Am5FuJP05cCM98= github.com/envoyproxy/go-control-plane v0.14.0 h1:hbG2kr4RuFj222B6+7T83thSPqLjwBIfQawTkC++2HA= github.com/envoyproxy/go-control-plane v0.14.0/go.mod h1:NcS5X47pLl/hfqxU70yPwL9ZMkUlwlKxtAohpi2wBEU= -github.com/envoyproxy/go-control-plane/envoy v1.37.1-0.20260812071801-353463cc7248 h1:+HVeI0tXxznym8nR2TFJ1S0rxbzER4aevVcMA/Bl/i0= -github.com/envoyproxy/go-control-plane/envoy v1.37.1-0.20260812071801-353463cc7248/go.mod h1:tjY7cZvIhlQAKRpob4GSOkZYAqtoTPtgWZXGhOTWbhQ= +github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be h1:SWe0x6yfglnxuvOiYgTTnNq7QD/yvqthOh1RBI8Bj8w= +github.com/envoyproxy/go-control-plane/envoy v1.39.1-0.20260819172001-e6e3fd93e4be/go.mod h1:PYEOlng9XcrulfyWpm49jECTPV0LT4q8cO7fLW/xwgk= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0 h1:/G9QYbddjL25KvtKTv3an9lx6VBE2cnb8wp1vEGNYGI= github.com/envoyproxy/go-control-plane/ratelimit v0.1.0/go.mod h1:Wk+tMFAFbCXaJPzVVHnPgRKdUdwW/KdbRt94AzgRee4= github.com/envoyproxy/protoc-gen-validate v0.1.0/go.mod h1:iSmxcyjqTsJpI2R4NaDN7+kN2VEUnK/pcBlmesArF7c= @@ -260,14 +260,14 @@ github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHk github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0= github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k= github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0= -github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= -github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/fxamacker/cbor/v2 v2.9.4 h1:xwjVlxEMR3S605oUlgBjKLTTeGFciYPGYCtF/35LKGo= +github.com/fxamacker/cbor/v2 v2.9.4/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk= github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og= github.com/go-gorp/gorp/v3 v3.1.0 h1:ItKF/Vbuj31dmV4jxA1qblpSwkl9g1typ24xoe70IGs= github.com/go-gorp/gorp/v3 v3.1.0/go.mod h1:dLEjIyyRNiXvNZ8PSmzpt1GsWAUK8kjVhEpjH8TixEw= -github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= -github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.9 h1:pKfeQkig1NmgK4hJrZYXLEYURXfoJB61Larw0uIW4gY= +github.com/go-jose/go-jose/v4 v4.1.9/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-kit/log v0.1.0/go.mod h1:zbhenjAZHb184qTLMA9ZjW7ThYL0H2mk7Q6pNt4vbaY= github.com/go-logfmt/logfmt v0.5.0/go.mod h1:wCYkCAKZfumFQihp8CzCvQ3paCTfi41vtzG1KdI/P7A= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= @@ -280,40 +280,25 @@ github.com/go-logr/zapr v1.3.0/go.mod h1:YKepepNBd1u/oyhd/yQmtjVXmm9uML4IXUgMOwR github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0= github.com/go-ole/go-ole v1.3.0 h1:Dt6ye7+vXGIKZ7Xtk4s6/xVdGDQynvom7xCFEdWr6uE= github.com/go-ole/go-ole v1.3.0/go.mod h1:5LS6F96DhAwUc7C+1HLexzMXY1xGRSryjyPPKW6zv78= -github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= -github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= -github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= -github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0= +github.com/go-openapi/jsonpointer v1.0.2 h1:NbW7xT2b+l7x+JefiPGDsZWsrLk1ogrz4AHK1TTzMt8= +github.com/go-openapi/jsonpointer v1.0.2/go.mod h1:N0rI4MbNKD7xAFTiHtB+5Nhrg2j/wwYg7m7Fmb4/jk8= +github.com/go-openapi/jsonreference v1.0.2 h1:oS4et8FOf3p3UQxEo4Xt0esijmBUM+F259Xl72OSZsc= +github.com/go-openapi/jsonreference v1.0.2/go.mod h1:TbUNSOo+fcorZjFaNoiSDSoaNnnZtqJtLGR1PuvE/Cs= github.com/go-openapi/swag v0.28.0 h1:xkgbOSKj6DZziNpyqRRAOt3GJGtgjgsd2RoyT30VWuw= -github.com/go-openapi/swag v0.28.0/go.mod h1:4qYnT3Cqr1p1VknOdPo70evN4rgQnAg6jwApHyxSGIg= -github.com/go-openapi/swag/cmdutils v0.28.0 h1:7TOeNtkYru1SG8Y34tDh9WBbLsMqGnptuxWiHREPZ4Q= -github.com/go-openapi/swag/cmdutils v0.28.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.28.0 h1:GtqqbyFe7vR5Y7ehxG9W6/OvrSFdf1OLeTGp40TqxH8= -github.com/go-openapi/swag/conv v0.28.0/go.mod h1:mbUE+mzctnhxi864m0Q07SpN8OowD9JhxmxuYvZZD/k= -github.com/go-openapi/swag/fileutils v0.28.0 h1:Z04XWQD7R8Eq+7GnOrjovBxPPmZzsS4gt2H2GPGIViU= -github.com/go-openapi/swag/fileutils v0.28.0/go.mod h1:VvJFZLTZS0AI854gEQz5tk7dBESdLjiNUMSZ/th2ry8= -github.com/go-openapi/swag/jsonutils v0.28.0 h1:YIch6FwO7RXzeAnbO8Tu7dWBZeUEH+4nA0HXltVTnv4= -github.com/go-openapi/swag/jsonutils v0.28.0/go.mod h1:CYM3WlTUcagR2ZoHdz54di/cbBqt82tuxuXgAjxw+mg= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0 h1:qV+VVUAx5Oro8WjVWpZeql7YReTKhT4smR4zhcOQZr0= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY= -github.com/go-openapi/swag/loading v0.28.0 h1:td8QZdZC9MIYGGSnSPKShKiK22I2tU5UQvuUhIBPRLU= -github.com/go-openapi/swag/loading v0.28.0/go.mod h1:rXB0QiQX5mMveXEA7ouM4KiiM9jVJe4K6BVbwhD1M4k= -github.com/go-openapi/swag/mangling v0.28.0 h1:pH8eyeNO9SLYsTMWJrurnNfKmDa28XrlA+HePVD53VM= -github.com/go-openapi/swag/mangling v0.28.0/go.mod h1:jtBE2+V+3pILxOR7Vgce+Cwp6A2PgZbvVqfNntbVs0w= -github.com/go-openapi/swag/netutils v0.28.0 h1:YXN6TALEi2pzts8/8GNm6T61HTAZsieukGZidap989k= -github.com/go-openapi/swag/netutils v0.28.0/go.mod h1:J+WYyFMLtvtCGqa6jLv+YNUmIKI3ZRQRrvfNDMoQoEQ= -github.com/go-openapi/swag/pools v0.28.0 h1:HPMZWSAfce3rdVTFcjFiCIBtDg9h4x2QlRrHipwhxeU= -github.com/go-openapi/swag/pools v0.28.0/go.mod h1:kVQefhSK5RWuRe7BXsL8htgBPAMpN7HDGpGEknqugeE= -github.com/go-openapi/swag/stringutils v0.28.0 h1:ixsc9iYgDPubHL/8nSkbnryEHpD2VRlBMLKpQyPXcDU= -github.com/go-openapi/swag/stringutils v0.28.0/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM= -github.com/go-openapi/swag/typeutils v0.28.0 h1:nRBKSBXjDgf01VDPB3fWeD9nQuhCOVeIYAkUx2tbkyY= -github.com/go-openapi/swag/typeutils v0.28.0/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ= -github.com/go-openapi/swag/yamlutils v0.28.0 h1:TV3JXH6DS46KUroDtMLAYHGkdWf5VDq3wVWFirmzROY= -github.com/go-openapi/swag/yamlutils v0.28.0/go.mod h1:x0q/yndZHEgk9Rx3DyDqzFUmHy55KTvIZldvF2dTJXs= -github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0= -github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo= -github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug= -github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/go-openapi/swag/conv v0.29.2 h1:8c9shoB8l0QRSR6ymq1llHdBWDqpIgJfjTGHx3Vuhm0= +github.com/go-openapi/swag/conv v0.29.2/go.mod h1:AZS0YigTNf8qNtD6WqJz/N4RUNmpr76SyjFGkq4+p6Q= +github.com/go-openapi/swag/jsonutils v0.29.2 h1:uZNSD2/rJDYAfvsLYkykTzXuyxM3QpDKV9jhRHrMu6k= +github.com/go-openapi/swag/jsonutils v0.29.2/go.mod h1:ONTdNvj3Y+IXRzfa17E+Rgt2ns/qiSOYjIo2K7v2yDs= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2 h1:w+Fd6EBOMGlC74GYGHqCLGyb3Bpams8TtNrgM/SG4jo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2/go.mod h1:HC2egPORFzbj/gf05Zrfgz8Mgplx3oW7hgGi7pjZVhM= +github.com/go-openapi/swag/pools v0.29.2 h1:PlGoDRF8WtSyXkedZZkpW3f9wDhFf3u8KtaBcmgmh8c= +github.com/go-openapi/swag/pools v0.29.2/go.mod h1:V3lhxVT4qDYRqc2MRSSbLsTYIYV/2HlHafhyEkmzLIc= +github.com/go-openapi/swag/typeutils v0.29.2 h1:O7aVvkTs3pXwikgtrPLenigEMdQFgONKRooQA9pgf2I= +github.com/go-openapi/swag/typeutils v0.29.2/go.mod h1:7+GDG+uz9Ke+eVt4rClZg7wklSDp8hT/mKNh/pC26TE= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0 h1:wPW6YRgx3+SID1yUy/Xwa17L8kFEaEKod2VRbJDZNUs= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0/go.mod h1:mI1M88etYbc3PhgHsWQK2kwvNwW5aGFqMPbmib+SGIs= +github.com/go-openapi/testify/v2 v2.8.0 h1:19QDx5b57p8KjO2E4sgs/woL4Akp+FGLRlVm2xn0Rho= +github.com/go-openapi/testify/v2 v2.8.0/go.mod h1:4gUN8jC+RqOE2qjW/vDmfyTvl5BCht4qL7oca0odrak= github.com/go-sql-driver/mysql v1.8.1/go.mod h1:wEBSXgmK//2ZFJyE+qWnIsVGmvmEKlqwuVSjsCm7DZg= github.com/go-sql-driver/mysql v1.10.0 h1:Q+1LV8DkHJvSYAdR83XzuhDaTykuDx0l6fkXxoWCWfw= github.com/go-sql-driver/mysql v1.10.0/go.mod h1:M+cqaI7+xxXGG9swrdeUIoPG3Y3KCkF0pZej+SK+nWk= @@ -338,6 +323,7 @@ github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y github.com/golang/protobuf v1.3.3/go.mod h1:vzj43D7+SQXF/4pzW/hwtAqwc6iTitCiVSaWz5lYuqw= 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.0.0/go.mod h1:lNA+9X1NB3Zf8V7Ke586lFgjr2dZNuvo3lPJSGZ5JPQ= 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.31.0 h1:H0bhpFTqOvmHrBGrWKp7ZlhBm5Hh8PYUEXnwxT1LL7A= @@ -349,7 +335,6 @@ github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= github.com/google/go-containerregistry v0.21.7 h1:/vPFuVXDjtFREsVArW+0h1CIl5urnOhzei4X2DMW9IU= github.com/google/go-containerregistry v0.21.7/go.mod h1:kjSbt7/zMsKLWfnHrIvKvhXHUw91jbe9DNjPPJ32gXE= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0= github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= github.com/google/martian/v3 v3.3.3 h1:DIhPTQrbPkgs2yJYdXU/eNACCG5DVQjySNRNlflZ9Fc= @@ -404,12 +389,10 @@ github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= github.com/jmoiron/sqlx v1.4.0 h1:1PLqN7S1UYp5t4SrVVnt4nUVNemrDAtxlulVe+Qgm3o= github.com/jmoiron/sqlx v1.4.0/go.mod h1:ZrZ7UsYB/weZdl2Bxg6jCRO9c3YHl8r3ahlKmRT4JLY= -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.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ= @@ -485,12 +468,6 @@ github.com/moby/sys/userns v0.1.0 h1:tVLXkFOxVu9A64/yh59slHVv9ahO9UIev4JZusOLG/g github.com/moby/sys/userns v0.1.0/go.mod h1:IHUYgu/kao6N8YZlp9Cf444ySSvCmDlmzUcYfDHOl28= github.com/moby/term v0.5.2 h1:6qk3FJAFDs6i/q3W/pQ97SX192qKfZgGjCQqfCJkgzQ= github.com/moby/term v0.5.2/go.mod h1:d3djjFCrjnB+fl8NJux+EJzu0msscUP+f8it8hPkFLc= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00 h1:n6/2gBQ3RWajuToeY6ZtZTIKv2v7ThUy5KKusIT0yc0= github.com/monochromegane/go-gitignore v0.0.0-20200626010858-205db1a8cc00/go.mod h1:Pm3mSP3c5uWn86xMLZ5Sa7JB9GsEZySvHYXCTK4E9q4= github.com/muesli/ansi v0.0.0-20230316100256-276c6243b2f6 h1:ZK8zHtRHOkbHy6Mmr5D264iyp3TiX5OmNcI5cIARiQI= @@ -523,8 +500,8 @@ github.com/olekukonko/tablewriter v1.0.8 h1:f6wJzHg4QUtJdvrVPKco4QTrAylgaU0+b9br github.com/olekukonko/tablewriter v1.0.8/go.mod h1:H428M+HzoUXC6JU2Abj9IT9ooRmdq9CxuDmKMtrOCMs= github.com/onsi/ginkgo/v2 v2.32.0 h1:Hw7s2pVrQo/8Yz5N77qdnpHaoc+c6cC9WIV1Jce+J6E= github.com/onsi/ginkgo/v2 v2.32.0/go.mod h1:+aXOY+vzZ5mu2iI2HpTZUPmM//oQfsNFX6gU9kNcA44= -github.com/onsi/gomega v1.42.1 h1:iN1rCUX+44NZ1Dc97MPoeFYbFR0vh8zxoxMFwKdyZ6I= -github.com/onsi/gomega v1.42.1/go.mod h1:REff/hsDsodHoKlWsP2mAPhu1+5/6hVYNf9rIEBpeSg= +github.com/onsi/gomega v1.44.0 h1:eAiGl3Pw5jz5GQdDff0BcxYpAX1JxW8xD7mFUuwNfZQ= +github.com/onsi/gomega v1.44.0/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA= github.com/opencontainers/go-digest v1.0.0 h1:apOUWs51W5PlhuyGyz9FCeeBIOUDA/6nW8Oi/yOhh5U= github.com/opencontainers/go-digest v1.0.0/go.mod h1:0JzlMkj0TRzQZfJkVvzbP0HBR3IKzErnv2BNG4W4MAM= github.com/opencontainers/image-spec v1.1.1 h1:y0fUlFfIZhPF1W537XOLg0/fcx6zcHCJwooC2xJA040= @@ -538,11 +515,13 @@ github.com/openfga/language/pkg/go v0.3.2-0.20260730144454-83fedf8a4e70/go.mod h github.com/openfga/openfga v1.20.0 h1:5dly6ON46VgH8xA1/tn2lNuJzxol0f7TGAwiDzIS6YA= github.com/openfga/openfga v1.20.0/go.mod h1:Rq7ij090J1lZRn322Ttc/b11ZaN/0ogph+rPAP0SNAE= github.com/opentracing/opentracing-go v1.1.0/go.mod h1:UkNAQd3GIcIGf0SeVgPpRdFStlNbqXla1AfSYxPUl2o= +github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM= +github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc= github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o= github.com/pelletier/go-toml/v2 v2.4.0 h1:Mwu0mAkUKbittDs3/ADDWXqMmq3EOK2VHiuCkV00Row= github.com/pelletier/go-toml/v2 v2.4.0/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY= -github.com/peterbourgon/diskv v2.0.1+incompatible h1:UBdAOUP5p4RWqPBg048CAvpKN+vxiaj6gdUUzhl4XmI= -github.com/peterbourgon/diskv v2.0.1+incompatible/go.mod h1:uqqh8zWWbv1HBMNONnaR/tNboyR3/BZd58JJSHlUSCU= +github.com/peterbourgon/diskv/v3 v3.0.1 h1:x06SQA46+PKIUftmEujdwSEpIx8kR+M9eLYsUxeYveU= +github.com/peterbourgon/diskv/v3 v3.0.1/go.mod h1:kJ5Ny7vLdARGU3WUuy6uzO6T0nb/2gWcT1JiBvRmb5o= github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= @@ -557,17 +536,17 @@ github.com/poy/onpar v1.1.2 h1:QaNrNiZx0+Nar5dLgTVp5mXkyoVFIbepjyEoGSnhbAY= github.com/poy/onpar v1.1.2/go.mod h1:6X8FLNoxyr9kkmnlqpK6LSoiOtrO6MICtWwEuWkLjzg= github.com/pressly/goose/v3 v3.27.3 h1:pIglVHjw99r4e/hDHHwbl9vfOsDMqUokfkXo6+n/RxA= github.com/pressly/goose/v3 v3.27.3/go.mod h1:Dag+xpV6o20HR2LFY1j0q6MDwc3f7vPUFDA77R+0yGY= -github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= -github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= +github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= +github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= -github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= +github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= +github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= +github.com/prometheus/common v0.73.1 h1:SZWh/j4AvhCdhX8jvYSnxvPxhWlC9QZkjJ+tOrEr7kU= +github.com/prometheus/common v0.73.1/go.mod h1:I9aA/Ukz9s1olOobh8KtCkU7B1mQPQsB9UvQPsUQ1Dk= github.com/prometheus/otlptranslator v1.0.0 h1:s0LJW/iN9dkIH+EnhiD3BlkkP5QVIUVEoIwkU+A6qos= github.com/prometheus/otlptranslator v1.0.0/go.mod h1:vRYWnXvI6aWGpsdY/mOT/cbeVRBlPWtBNDb7kGR3uKM= -github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= -github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= +github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= github.com/redis/go-redis/extra/rediscmd/v9 v9.0.5 h1:EaDatTxkdHG+U3Bk4EUr+DZ7fOGwTfezUiUJMaIcaho= github.com/redis/go-redis/extra/rediscmd/v9 v9.0.5/go.mod h1:fyalQWdtzDBECAQFBJuQe5bzQ02jGd5Qcbgb97Flm7U= github.com/redis/go-redis/extra/redisotel/v9 v9.0.5 h1:EfpWLLCyXw8PSM2/XNJLjI3Pb27yVE+gIAfeqp8LUCc= @@ -599,8 +578,8 @@ github.com/shirou/gopsutil/v4 v4.26.6/go.mod h1:LZ6ewCSkBqUpvSOf+LsTGnRinC6iaNUN github.com/shopspring/decimal v1.4.0 h1:bxl37RwXBklmTi0C79JfXCEBD1cqqHt0bbgBAGFp81k= github.com/shopspring/decimal v1.4.0/go.mod h1:gawqmDU56v4yIKSwfBSFip1HdCCXN8/+DMd9qYNcwME= github.com/sirupsen/logrus v1.4.2/go.mod h1:tLMulIdttU9McNUspp0xgXVQah82FyeX6MwdIuYE2rE= -github.com/sirupsen/logrus v1.9.4 h1:TsZE7l11zFCLZnZ+teH4Umoq5BhEIfIzfRDZ1Uzql2w= -github.com/sirupsen/logrus v1.9.4/go.mod h1:ftWc9WdOfJ0a92nsE2jF5u5ZwH8Bv2zdeOC42RjbV2g= +github.com/sirupsen/logrus v1.10.2 h1:G2SED73/qrAu6YwbdxOD6peLkCBI3z7L+ykJFTXJBBo= +github.com/sirupsen/logrus v1.10.2/go.mod h1:SLEg8TqYulVKKfIGHldVp2K2aYz2DKSVBq4g/H5bR7Q= github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo= github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0= github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I= @@ -614,8 +593,8 @@ github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/viper v1.20.1 h1:ZMi+z/lvLyPSCoNtFCpqjy0S4kPbirhpTMwl8BkW9X4= github.com/spf13/viper v1.20.1/go.mod h1:P9Mdzt1zoHIG8m2eZQinpiBjo6kCmZSKBClNNqjJvu4= -github.com/spiffe/go-spiffe/v2 v2.7.0 h1:uXe1MflJoHw58wAUvxVlcM7WpKtijWG7I1UidcGh6g4= -github.com/spiffe/go-spiffe/v2 v2.7.0/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= +github.com/spiffe/go-spiffe/v2 v2.8.1 h1:eXZMLsu+3MLEPJyGJkolqtVrteZfQdUpOWj6LTiDl/E= +github.com/spiffe/go-spiffe/v2 v2.8.1/go.mod h1:47Q0Q9/AqGha8QLHp+kxpH4Wca7X7EnOtlIJy3mxZ3U= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= github.com/stretchr/objx v0.5.3 h1:jmXUvGomnU1o3W/V5h2VEradbpJDwGrzugQQvL0POH4= @@ -637,6 +616,8 @@ github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834 h1:ZF+QBjOI+tILZ github.com/tetratelabs/wabin v0.0.0-20230304001439-f6f874872834/go.mod h1:m9ymHTgNSEjuxvw8E7WWe4Pl4hZQHXONY8wE6dMLaRk= github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0= +github.com/tink-crypto/tink-go/v2 v2.9.0 h1:uvjgS1IYDB4zhDK0Zow8ZFB73IjzMAoSqW0JkFnvkrc= +github.com/tink-crypto/tink-go/v2 v2.9.0/go.mod h1:aNXZeyxjQU9iqAeARRNmbESXUW6Mao1HRCCTY8B1TFM= github.com/tklauser/go-sysconf v0.4.0 h1:7H0uAN+7RkwWRaxhYXDLqa5V3LPrJeV8wmD9dRUgPQU= github.com/tklauser/go-sysconf v0.4.0/go.mod h1:8mTNWyog7H+MpKijp4VmKJAd2bbYQ2zuUwkYRbUArPI= github.com/tklauser/numcpus v0.12.0 h1:NR85qdvHA9pFse3x3weVZ0r0ST8R6l5RHbZrlRaqob4= @@ -667,16 +648,16 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/bridges/prometheus v0.68.0 h1:w3zlHYETbDwXyWHZlyyR58ZC39XGi8rAhkBgUgJ9d5w= go.opentelemetry.io/contrib/bridges/prometheus v0.68.0/go.mod h1:GR/mClR2nn7vE8RLwxKjoBNg+QtgdDhRzxVa93koy5o= -go.opentelemetry.io/contrib/detectors/gcp v1.44.0 h1:NmLfL734pJhM0JKaYd2Y28+nY9dPRWYAAbxhRCrKXPw= -go.opentelemetry.io/contrib/detectors/gcp v1.44.0/go.mod h1:tNAsgd8avTGke1+MndXlU5Cru4PQ9Ai/cCNWQv/ZJ/s= +go.opentelemetry.io/contrib/detectors/gcp v1.45.0 h1:9jR0ZPRok9ryaOQ2Wx8rg5F7Aon59mxrqbVI60/vlBk= +go.opentelemetry.io/contrib/detectors/gcp v1.45.0/go.mod h1:VSme3o2fvSg5bVg0dRzyHaj4Z5EVhG+g2Fde6LKzmQA= go.opentelemetry.io/contrib/exporters/autoexport v0.67.0 h1:4fnRcNpc6YFtG3zsFw9achKn3XgmxPxuMuqIL5rE8e8= go.opentelemetry.io/contrib/exporters/autoexport v0.67.0/go.mod h1:qTvIHMFKoxW7HXg02gm6/Wofhq5p3Ib/A/NNt1EoBSQ= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0 h1:oECp5f+hN7nkwjU/8BxQ/q23bGPb8FIrD839owX222E= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0/go.mod h1:DqEFwLumhzMBDQv9PcWbyoDxHI/4lAk6CM4nJBH39sc= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0/go.mod h1:A+EVhDakAj1waJBPhmTszZaSr08ww8MRRKy1nB1rqck= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0 h1:WseeVYf5dJZTsyPiyW5L14k5qsSibqXAMTSiFEDiWr0= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0/go.mod h1:SiLZnQS6Qk2eCpvr2CH/XMAOa64TWGXxEZJZCpD2Lmc= go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.21.0 h1:fvNHGyo3CdRv/DQveXqhqBxnKTDyRaC5sMSQxilX/A0= @@ -685,8 +666,8 @@ go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0 h1:8UQ go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetricgrpc v1.43.0/go.mod h1:2lmweYCiHYpEjQ/lSJBYhj9jP1zvCvQW4BqL9dnT7FQ= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0 h1:w1K+pCJoPpQifuVpsKamUdn9U0zM3xUziVOqsGksUrY= go.opentelemetry.io/otel/exporters/otlp/otlpmetric/otlpmetrichttp v1.43.0/go.mod h1:HBy4BjzgVE8139ieRI75oXm3EcDN+6GhD88JT1Kjvxg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracehttp v1.45.0 h1:QBajQ2SrwQijzHyZbQlPsuIzpl/ll8DY6wPWsajeGcI= @@ -699,22 +680,22 @@ go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0 h1:TC+BewnDpeiAmc go.opentelemetry.io/otel/exporters/stdout/stdoutmetric v1.43.0/go.mod h1:J/ZyF4vfPwsSr9xJSPyQ4LqtcTPULFR64KwTikGLe+A= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.45.0 h1:lsA/S1bxgdbyFGkTj+3meEdJ6ADVU7QoFstV6MXgE68= go.opentelemetry.io/otel/exporters/stdout/stdouttrace v1.45.0/go.mod h1:L7u+MirGoB1bjeLH66+xDykF4RC8C3RN7lIFpBiewUo= -go.opentelemetry.io/otel/log v0.21.0 h1:SLsVDGmtyBrdw8/a2Z0bOIxou/+bN4z56GebH7T0LvA= -go.opentelemetry.io/otel/log v0.21.0/go.mod h1:iReetQrZL9Wyg84cCkOoCmqDHS5RCFfyxC7J+r8fn8g= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/metric/x v0.67.0 h1:PcicCNZFkZ4bXfSooXdo3WN7RBOVOtjVdo1wD358Uns= -go.opentelemetry.io/otel/metric/x v0.67.0/go.mod h1:FBjCWZe6wgcqxcMtjdGiClDKXb2YxxXii0CXftE4QtI= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/log v0.21.0 h1:QsE7XSR0ktQdKmRKGnR+f1ObGF32WG+7MER/P9KgmYc= -go.opentelemetry.io/otel/sdk/log v0.21.0/go.mod h1:m9mApjCoD2/1QuKCAptjv+BrG9WKOvQLVdNx+iBldTo= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/metric/x v0.69.0 h1:DjRLr15H83v+hCW7JA9NoJvOkYTtmq5YoDRbe9deYpM= +go.opentelemetry.io/otel/metric/x v0.69.0/go.mod h1:uVvsMPMFFyj/HUQfrUnH3JjnOQ1dwFDorgFLRBasM0k= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/sdk/log v1.47.0 h1:W4N/ZfgpkRRnmARnqYoQ6BrWA0mrj8IzVDNLlpmUJZY= +go.opentelemetry.io/otel/sdk/log v1.47.0/go.mod h1:Wu74Z2EmOKXi2FleSNAb0Hyau2G+r5kubSEMJw5aAMs= go.opentelemetry.io/otel/sdk/log/logtest v0.21.0 h1:X+JBBgKlswCGYsmgL0CnoUUtlE//VB345c84jYAYkdQ= go.opentelemetry.io/otel/sdk/log/logtest v0.21.0/go.mod h1:HD1575K8e6sIFBBDd5tZB3t9DlMytWXq9FuR+Y4rfjE= -go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= -go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= +go.opentelemetry.io/otel/sdk/metric v1.47.0 h1:lfISg2j93VT6yqdk9OfUaZmw/GfcZqCCV3jdXtsPnKw= +go.opentelemetry.io/otel/sdk/metric v1.47.0/go.mod h1:ypLp+mW1Nt2x+Szt3b5/i1syodyts49lMOwxpDI3VGw= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= go.uber.org/atomic v1.7.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc= @@ -740,8 +721,8 @@ golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPh golang.org/x/crypto v0.58.0 h1:COkYLr4k7nDI4r6QtMML2AfzeIswWHAJthLS6K/M/54= golang.org/x/crypto v0.58.0/go.mod h1:Xh+kl5A+M0gMiWDytH2Hhr5Z7WbNCpv/eB/EFgfSk+w= golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA= -golang.org/x/exp v0.0.0-20260718201538-764159d718ef h1:LkZ48HFgy/TvhTI0bcWkjgFkgLyKUwcTbDjS0DUjw+A= -golang.org/x/exp v0.0.0-20260718201538-764159d718ef/go.mod h1:EdfpwwqSu+0Li0mzskwHU6FWDV3t9Q+RZDo3QMUtL3Q= +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/lint v0.0.0-20181026193005-c67002cb31c3/go.mod h1:UVdnD1Gm6xHRNCYTkRU2/jEulfH38KcIWyp/GAMgvoE= golang.org/x/lint v0.0.0-20190227174305-5b3e6a55c961/go.mod h1:wehouNa3lNwaWXcvxsM5YxQ5yQlVC4a0KAMCusXpPoU= golang.org/x/lint v0.0.0-20190313153728-d0100b6bd8b3/go.mod h1:6SW0HCj/g11FgYtHlgUYUwCkIfeOF89ocIRzGO/8vkc= @@ -758,11 +739,11 @@ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn 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.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U= -golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= -golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +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-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= @@ -791,8 +772,8 @@ 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.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= -golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +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-20190114222345-bf090417da8b/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ= golang.org/x/tools v0.0.0-20190226205152-f727befe758c/go.mod h1:9Yl7xja0Znq3iFh3HoIrodX9oNMXvdceNzlUR8zjMvY= @@ -821,17 +802,17 @@ google.golang.org/genproto v0.0.0-20190819201941-24fa4b261c55/go.mod h1:DMBHOl98 google.golang.org/genproto v0.0.0-20200423170343-7949de9c1215/go.mod h1:55QSHmfGQM9UVYDPBsyGGes0y52j32PQ3BqQfXhyH3c= google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0= google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= +google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 h1:lrupDmKL3p5kEX1M92oan027eCKcouzjuPbH6YBK+Rs= +google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1/go.mod h1:q/3oV3jAi5vwelxsVAprMBC8BcM2zmNe+IjRGd+9/ks= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c= google.golang.org/grpc v1.23.0/go.mod h1:Y5yQAOtifL1yxbo5wqy6BxZv8vAUGQwXBOALyacEbxg= google.golang.org/grpc v1.25.1/go.mod h1:c3i+UQWmh7LiEpx4sFZnkU36qjEYZ0imhYfXVyQciAY= google.golang.org/grpc v1.27.0/go.mod h1:qbnxyOmOxrQa7FizSgH+ReBfzJrCY1pSN7KXBS8abTk= google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk= -google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= -google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -856,32 +837,36 @@ helm.sh/helm/v4 v4.3.1 h1:UndCoLe9UPmNoL7IvWzaUXveL7T5t/ijoorEmgJdI9g= helm.sh/helm/v4 v4.3.1/go.mod h1:Z663D/wNQG1UsG3X7svSEBPvosFVel4SIw4YIMZwmuY= honnef.co/go/tools v0.0.0-20190102054323-c2f93a96b099/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= honnef.co/go/tools v0.0.0-20190523083050-ea95bdfd59fc/go.mod h1:rf3lG4BRIbNafJWhAfAdb/ePZxsR/4RtNHQocxwk9r4= -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.36.0-alpha.2.0.20260904094813-f8600edbddc8 h1:DM+nt+gJGNT2flQOkxKzrPCNuwOqwxcfSCHBUnvmweY= -k8s.io/apimachinery v0.36.0-alpha.2.0.20260904094813-f8600edbddc8/go.mod h1:1Um7tr4O65Pd822NFLn+MI08uCzUIPahh2lCPsWzNgk= -k8s.io/apiserver v0.37.1 h1:dUsNwjsvItyVKNpC1N0AhQ0OBSiUJKfWz004vPifOe0= -k8s.io/apiserver v0.37.1/go.mod h1:EWXW6PntGfOC2uD9GGVobnOExgFoX1z0hZo7f7Rs7Ng= -k8s.io/cli-runtime v0.37.1 h1:3mir5bM4XjMJHW3SMRk++3Ylf4YQne0XFFsW+IGT85U= -k8s.io/cli-runtime v0.37.1/go.mod h1:g3VQOm71f//aNbp79g0az9jBRTrvPjAHz7WxVysbZ4M= -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/api v0.38.0-beta.0 h1:XNdTOZpYukwZVGtrPpCJL8NdXcUcD1O10qPJysD97z4= +k8s.io/api v0.38.0-beta.0/go.mod h1:g2MZyHPSQpJ1zxJ7JhY9wCHmkgeQOuG0Cpsa2sE6Ebo= +k8s.io/apiextensions-api v0.38.0-beta.0 h1:ke50na8OeqEVfhYxa3WfJ7i4TxScQn/smux137Argvo= +k8s.io/apiextensions-api v0.38.0-beta.0/go.mod h1:8IizFVJhXKzRc3EiuM/6RUU2cFZv3qHs1mysqyCSmuM= +k8s.io/apiextensions-apiserver v0.38.0-beta.0 h1:P/otRhWvvCa/fJ6xMMVjQG0hrnl65U71AD0m3xfrNHA= +k8s.io/apiextensions-apiserver v0.38.0-beta.0/go.mod h1:IpzXx3wNm12chepPRiQ8sWsr0C13jzUlJBWDs0BVX/Y= +k8s.io/apimachinery v0.38.0-beta.0 h1:CS7Bz3Pac/I0lb6nhzJHjT98PPUf/YgYMYaC3aroFO0= +k8s.io/apimachinery v0.38.0-beta.0/go.mod h1:KGRxGxSx+JnNcp6M3neG7/bzPdeeE7uPDiEItuUEiWg= +k8s.io/apiserver v0.38.0-beta.0 h1:LGpXWlBzJEwiPedcveOGnW0OGVx4l6qdj7+zEqLyNBM= +k8s.io/apiserver v0.38.0-beta.0/go.mod h1:R3fruOmkiYpNCSIUiWHMqcLaKuzsH2cQOzYyisieejU= +k8s.io/cli-runtime v0.38.0-beta.0 h1:Jc06objQ9QiTWaqqA5JQsKfdU/as3E6biHi5Kmric88= +k8s.io/cli-runtime v0.38.0-beta.0/go.mod h1:eD2Et9D2SoFAJPALWplQ0L4dthtvNTtYIxsSKV05OeY= +k8s.io/client-go v0.38.0-beta.0 h1:ONJZQR2ZQ+P1kfrL4wbh79nG+acdpsGc8RZo587J0WE= +k8s.io/client-go v0.38.0-beta.0/go.mod h1:cfRLvdmNrwDjZAoT74/b4x4nxpUCplmbj1e1hOvZNOc= +k8s.io/component-base v0.38.0-beta.0 h1:Lv/oDBlP7jliE33Xc98UKiEsNyrVZT4UD/aFj8bUG2s= +k8s.io/component-base v0.38.0-beta.0/go.mod h1:QapRFf0V3uqMbKI3+8Cx9ozTf72Hie+3XIL3VKRr49U= k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -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/ktesting v0.38.0-beta.0 h1:z8tGty777Eks5T5QJVvdjXpKoLJiyXkmbv2gxYIRqdY= +k8s.io/ktesting v0.38.0-beta.0/go.mod h1:5cuEyae81HMpIwUx1JX78204Zhmrj4J1yqRc2aE060o= +k8s.io/kube-openapi v0.0.0-20261014044854-ca3452a79603 h1:9zl8YVFBvuURO1ZrSa1SFWyfbnzyll2ivV163KCkRs0= +k8s.io/kube-openapi v0.0.0-20261014044854-ca3452a79603/go.mod h1:ijAJHxCK/9OftZdcKwI5BHyIeRUeoKe1ldIyM4JHMts= k8s.io/kubectl v0.37.1 h1:n1VCIntOJiX943uByXCThSZQmE+4v9jGS8S9u94/aHU= k8s.io/kubectl v0.37.1/go.mod h1:66cc4Bz8PxBTxlrHzBuzXEzGIytAnNasKQPeEcpuaV8= -k8s.io/kubelet v0.37.0 h1:VhaZanjlE5CkoAPAjKw0DH+Q0BYXVfYekZgzZDAJMMg= -k8s.io/kubelet v0.37.0/go.mod h1:PHXfQuVqsTzFVqOeP67UUNv5Ajri+dLGoeaEnW6gGjE= -k8s.io/metrics v0.37.1 h1:5lc7WH6ljoxaJ4dK6UHwskVsyH7aNdt/ajo6CLQ1l8Q= -k8s.io/metrics v0.37.1/go.mod h1:mpnoLxJYJdBQoxPlgi1Y+gk/bxIuXf5SbS/8jkYzqEo= -k8s.io/streaming v0.37.1 h1:TpzVfQeFuVndn2g9mFqxy1UcUYPwDzqjUmwR/IzJCWc= -k8s.io/streaming v0.37.1/go.mod h1:APlJR26ZWRcVy5bIEj0QRrKUXROtBHPcxl2NT7EAzPU= +k8s.io/kubelet v0.38.0-beta.0 h1:HQZo2sg3CJmlB612ONeKYm36xh+xiyE/fEZcUFS87xk= +k8s.io/kubelet v0.38.0-beta.0/go.mod h1:u2tPaJtQdn05PzoBfwy87dpC97mROl+e8wKh0vkp0xA= +k8s.io/metrics v0.38.0-beta.0 h1:G81iYWg6wqvmh8dMVJx4wbb6AuqtI4mKGGSO2hPpfYk= +k8s.io/metrics v0.38.0-beta.0/go.mod h1:X1x8ul+CSdtHn/CFYNJJ34HBYQYxbxyboZdQE9A2RVA= +k8s.io/streaming v0.38.0-beta.0 h1:eY/L5VT7Go9fwj/GtmYqHw/9tf2RedvVFq/adwdycnk= +k8s.io/streaming v0.38.0-beta.0/go.mod h1:f9sXMyoFlA0/ENq79bTEZ0F6PkICZvH5A4s8v2oBchc= k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= modernc.org/libc v1.74.4 h1:fX1Omw4o2/1C2iRkkIsrQTasJQldLhRmuPreXLoWs9k= @@ -896,17 +881,17 @@ oras.land/oras-go/v2 v2.6.2 h1:N04RXngAp1LJKTG6ifz3xHPipasEkWr+hFmInja5YKo= oras.land/oras-go/v2 v2.6.2/go.mod h1:PlTtg4JTDJkDe8yVHpM2wz7/YDc00GVas+i4jAW2TZ4= pgregory.net/rapid v1.2.0 h1:keKAYRcjm+e1F0oAuU5F5+YPAWcyxNNRK2wud503Gnk= pgregory.net/rapid v1.2.0/go.mod h1:PY5XlDGj0+V1FCq0o192FdRhpKHGTRIWBgqjDBTrq04= -sigs.k8s.io/controller-runtime v0.25.2 h1:bEkK3PVOIVK9X8QWLGVhJgmFc++47vfT6wakSzAOLsQ= -sigs.k8s.io/controller-runtime v0.25.2/go.mod h1:4QqLdT6z/L6Olj8JJCtvztid4/fnIiYsfaTFScegctc= +sigs.k8s.io/controller-runtime v0.25.1-0.20261119155835-be0153ca8953 h1:3j3rz67r1TL1qGhj3Ggqu2nnSHu4L8veMpWb8RYPlcI= +sigs.k8s.io/controller-runtime v0.25.1-0.20261119155835-be0153ca8953/go.mod h1:+379h8hDyh4bi7ugWDjWMqxLMcJRZHgN1fsJJcxDnE0= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/go.mod h1:mdzfpAEoE6DHQEN0uh9ZbOCuHbLK5wOm7dK4ctXE9Tg= -sigs.k8s.io/kustomize/api v0.21.1 h1:lzqbzvz2CSvsjIUZUBNFKtIMsEw7hVLJp0JeSIVmuJs= -sigs.k8s.io/kustomize/api v0.21.1/go.mod h1:f3wkKByTrgpgltLgySCntrYoq5d3q7aaxveSagwTlwI= -sigs.k8s.io/kustomize/kyaml v0.21.2 h1:1javwStFk7cgOeLU7yJtPmXcgMEhQgC2X0WjFT6U0p0= -sigs.k8s.io/kustomize/kyaml v0.21.2/go.mod h1:zX3qwtuouXd2K1fMiCV0VSFReX06a+CY1rhyf5Dy7hQ= +sigs.k8s.io/kustomize/api v0.21.3 h1:DXGrbifGrAd+7AQ75Kx/tVhr+RLMCZFfAYl61HOR3T0= +sigs.k8s.io/kustomize/api v0.21.3/go.mod h1:JKlHjHXGh54cdoWVdKNqDscFzPb9z+sBk9upy9PBh6k= +sigs.k8s.io/kustomize/kyaml v0.21.3 h1:4ygzLsc8B1ep9dFuEivrJ2lFIAglL19dhPrWp1ioceY= +sigs.k8s.io/kustomize/kyaml v0.21.3/go.mod h1:HrAVNlYyEphOlRCcaSIQziGR+0ehwx6Xp1ucUrpC6hs= 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.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= -sigs.k8s.io/structured-merge-diff/v6 v6.4.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/structured-merge-diff/v7 v7.0.1 h1:mjAf8oNt6P6M9/uHoZLY2x/iQj/U5YFe0ke1VL/XjeY= +sigs.k8s.io/structured-merge-diff/v7 v7.0.1/go.mod h1:xKoMSgtnJnkfRR+CTNSQ1dBVhkKJR5OQl5RxX/OqHbI= 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/create-kind-cluster.sh b/hack/create-kind-cluster.sh index b3b25db248..3f9527e1e0 100755 --- a/hack/create-kind-cluster.sh +++ b/hack/create-kind-cluster.sh @@ -21,6 +21,7 @@ KIND_CLUSTER_NAME="${KIND_CLUSTER_NAME:-kind}" KUBECTL_CONTEXT="kind-${KIND_CLUSTER_NAME}" reg_name="kind-registry" reg_port="${KIND_REGISTRY_PORT:-5001}" +dns_proxy_name="${KIND_CLUSTER_NAME}-dns-proxy" if [[ $# -gt 0 ]]; then case "$1" in @@ -37,8 +38,8 @@ if [[ $# -gt 0 ]]; then esac fi -# Only ipFamily is set; kind's per-family podSubnet/serviceSubnet defaults are -# already what we want. +# kind's singular ipFamily field accepts ipv4, ipv6, or dual. Its per-family +# podSubnet and serviceSubnet defaults are already what we want. IP_FAMILY="${IP_FAMILY:-ipv4}" case "${IP_FAMILY}" in ipv4|ipv6|dual) @@ -138,6 +139,14 @@ EOF fi echo "Deleting existing kind cluster '${KIND_CLUSTER_NAME}' if it exists..." +if docker inspect "${dns_proxy_name}" >/dev/null 2>&1; then + dns_proxy_created_by="$(docker inspect --format '{{index .Config.Labels "created-by"}}' "${dns_proxy_name}" 2>/dev/null)" + if [[ "${dns_proxy_created_by}" != "agent-substrate" ]]; then + echo "Container '${dns_proxy_name}' already exists and was not created by this project." >&2 + exit 1 + fi + docker rm -f "${dns_proxy_name}" >/dev/null +fi "${ROOT}"/hack/kind.sh delete cluster --name "${KIND_CLUSTER_NAME}" || true # kind reuses an existing "kind" network as-is and deleting the cluster does not @@ -176,7 +185,8 @@ fi if [[ "${IP_FAMILY}" == "ipv6" ]]; then server="$(kubectl config view \ -o jsonpath="{.clusters[?(@.name==\"${KUBECTL_CONTEXT}\")].cluster.server}")" - if [[ "${server}" == "https://[::1]:"* ]]; then + if [[ "${server}" == "https://[::1]:"* ]] && + ! kubectl --context="${KUBECTL_CONTEXT}" get --raw=/readyz >/dev/null 2>&1; then echo "Repointing the kubeconfig for '${KUBECTL_CONTEXT}' at localhost..." kubectl config set-cluster "${KUBECTL_CONTEXT}" \ --server="https://localhost:${server##*:}" >/dev/null @@ -229,6 +239,34 @@ if [ "$(docker inspect -f='{{json .NetworkSettings.Networks.kind}}' "${reg_name} docker network connect "kind" "${reg_name}" fi +if [[ "${IP_FAMILY}" == "ipv6" ]]; then + # Docker's resolver is IPv4-only, so proxy external queries for CoreDNS. + # The hosts entry gives IPv6-only pods the registry container's address. + cat <<'EOF' > "${ROOT}/bin/kind-dns-proxy.Corefile" +.:53 { + forward . /etc/resolv.conf +} +EOF + docker create --restart=always \ + --label created-by=agent-substrate \ + --network kind --name "${dns_proxy_name}" \ + registry.k8s.io/coredns/coredns:v1.13.1@sha256:9b9128672209474da07c91439bf15ed704ae05ad918dd6454e5b6ae14e35fee6 \ + -conf /Corefile >/dev/null + docker cp "${ROOT}/bin/kind-dns-proxy.Corefile" "${dns_proxy_name}:/Corefile" + docker start "${dns_proxy_name}" >/dev/null + dns_proxy_ip="$(docker inspect -f '{{(index .NetworkSettings.Networks "kind").GlobalIPv6Address}}' "${dns_proxy_name}")" + registry_ip="$(docker inspect -f '{{(index .NetworkSettings.Networks "kind").GlobalIPv6Address}}' "${reg_name}")" + corefile="$(kubectl --context="${KUBECTL_CONTEXT}" -n kube-system get configmap coredns -o go-template='{{index .data "Corefile"}}')" + corefile="${corefile/\/etc\/resolv.conf/[${dns_proxy_ip}]:53}" + hosts=$' hosts {\n '"${registry_ip} ${reg_name}"$'\n fallthrough\n }\n' + corefile="${corefile/ forward/${hosts} forward}" + kubectl --context="${KUBECTL_CONTEXT}" -n kube-system create configmap coredns \ + --from-literal=Corefile="${corefile}" --dry-run=client -o yaml | + kubectl --context="${KUBECTL_CONTEXT}" apply -f - + kubectl --context="${KUBECTL_CONTEXT}" -n kube-system rollout restart deployment/coredns + kubectl --context="${KUBECTL_CONTEXT}" -n kube-system rollout status deployment/coredns --timeout=120s +fi + # 5. Document the local registry in kube-public ConfigMap echo "Documenting local registry in cluster..." cat </dev/null 2>&1; then + dns_proxy_created_by="$(docker inspect --format '{{index .Config.Labels "created-by"}}' "${dns_proxy_name}" 2>/dev/null)" + if [ "${dns_proxy_created_by}" = "agent-substrate" ]; then + echo "Deleting DNS proxy container '${dns_proxy_name}' (created by us)..." + docker rm -f "${dns_proxy_name}" || true + else + echo "DNS proxy container '${dns_proxy_name}' was not created by us (${dns_proxy_created_by}), leaving it running." + fi +fi + reg_exists=false if docker inspect "${reg_name}" >/dev/null 2>&1; then reg_exists=true diff --git a/hack/e2e-focus-sandbox-class.sh b/hack/e2e-focus-sandbox-class.sh deleted file mode 100755 index 38e176edc2..0000000000 --- a/hack/e2e-focus-sandbox-class.sh +++ /dev/null @@ -1,58 +0,0 @@ -#!/usr/bin/env bash - -# Copyright 2026 The Agent Substrate 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. - -# scales the other sandbox class's demo WorkerPools to zero and restores this -# class's, so an e2e lane has the kind node to itself -# -# Usage: hack/e2e-focus-sandbox-class.sh gvisor|microvm - -set -o errexit -o nounset -o pipefail - -context="${KUBECTL_CONTEXT:-kind-kind}" -annotation="e2e.ate.dev/replicas" - -gvisor_pools=(ate-demo-counter/counter ate-demo-egress/egress) -microvm_pools=(ate-demo-counter-microvm/counter-microvm ate-demo-egress-microvm/egress-microvm) - -case "${1:-}" in - gvisor) keep=("${gvisor_pools[@]}"); drop=("${microvm_pools[@]}") ;; - microvm) keep=("${microvm_pools[@]}"); drop=("${gvisor_pools[@]}") ;; - *) echo "usage: $0 gvisor|microvm" >&2; exit 1 ;; -esac - -# pool NAMESPACE/NAME VERB [ARGS...] -pool() { - kubectl --context="${context}" -n "${1%/*}" "$2" "workerpool/${1#*/}" "${@:3}" -} - -# stash the replica count in an annotation so we can restore it later -for p in "${drop[@]}"; do - replicas="$(pool "$p" get -o jsonpath='{.spec.replicas}')" - if [[ "${replicas}" != "0" ]]; then - pool "$p" annotate --overwrite "${annotation}=${replicas}" - pool "$p" scale --replicas=0 - fi -done - -for p in "${keep[@]}"; do - replicas="$(pool "$p" get -o jsonpath="{.metadata.annotations.${annotation//./\\.}}")" - if [[ -n "${replicas}" ]]; then - pool "$p" scale --replicas="${replicas}" - pool "$p" annotate "${annotation}-" - fi - replicas="$(pool "$p" get -o jsonpath='{.spec.replicas}')" - pool "$p" wait --for=jsonpath='{.status.readyReplicas}'="${replicas}" --timeout=5m -done diff --git a/hack/release/draft-release.sh b/hack/release/draft-release.sh index 6abba94b6f..9e122f739d 100755 --- a/hack/release/draft-release.sh +++ b/hack/release/draft-release.sh @@ -48,12 +48,16 @@ usage() { errfile="$(mktemp)" trap 'rm -f "${errfile}"' EXIT -# api prints the response. On failure it prints the -# step and gh's error, and returns 1; gh's error stays in ${errfile}. +source "${ROOT}/hack/util/gh-retry.sh" + +# api prints the response, retrying HTTP 5xx errors. +# On failure it prints the step and gh's error, and returns 1; gh's error +# stays in ${errfile}. Pipe the output to jq rather than using gh's --jq, +# which hides the status of an HTML 5xx page, so it would not be retried. api() { local step="$1" shift - if ! gh api "$@" 2>"${errfile}"; then + if ! gh_with_retries api "$@" 2>"${errfile}"; then echo "error: ${step}: $(<"${errfile}")" >&2 return 1 fi @@ -64,7 +68,7 @@ api() { # failure (gh not logged in, rate limit) stops the script with gh's error, so # it is not mistaken for "not found". exists() { - if gh api "$1" --silent 2>"${errfile}"; then + if gh_with_retries api "$1" --silent 2>"${errfile}"; then return 0 fi if grep -qE 'HTTP (404|422)' "${errfile}"; then @@ -113,7 +117,7 @@ fi # Tags come from the API because a local clone may lack them (release tags # can sit on release-X.Y branches). base="${tag%%-*}" -tags="$(api "listing tags" "repos/${REPO}/tags" --paginate --jq '.[].name')" +tags="$(api "listing tags" "repos/${REPO}/tags" --paginate | jq -r '.[].name')" # With no tags at all (a fork, for example), the notes would silently cover # the whole history. GitHub needs the previous tag in ${REPO} itself. if ! grep -qE "${SEMVER}" <<<"${tags}"; then @@ -137,7 +141,7 @@ if [[ -n "${previous}" ]]; then generate_args+=(-f "previous_tag_name=${previous}") fi if ! notes="$(api "generating notes" "repos/${REPO}/releases/generate-notes" \ - "${generate_args[@]}" --jq .body)"; then + "${generate_args[@]}" | jq -r .body)"; then if grep -q 'HTTP 404' "${errfile}"; then echo "GitHub answers 404 here when the token cannot write to ${REPO}." \ "Generating notes needs write access, even for --dry-run." >&2 @@ -210,7 +214,10 @@ if [[ "${dry_run}" == true ]]; then echo "Dry run: no release created." exit 0 fi -if gh release view "${tag}" --repo "${REPO}" >/dev/null 2>&1; then +# Not gh release view: it can report a failed lookup as "release not found". +existing="$(api "checking for an existing release" "repos/${REPO}/releases" \ + --paginate | jq -r --arg tag "${tag}" '.[] | select(.tag_name == $tag) | .id')" +if [[ -n "${existing}" ]]; then echo "A release for ${tag} already exists; left unchanged." exit 0 fi diff --git a/hack/release/testdata/gh.sh b/hack/release/testdata/gh.sh index 234cdba3f3..51b43d6cc3 100755 --- a/hack/release/testdata/gh.sh +++ b/hack/release/testdata/gh.sh @@ -27,7 +27,8 @@ case "$*" in esac ;; "api repos/"*"/git/ref/tags/"*) ;; - "api repos/"*"/tags "*) echo v1.0.0 ;; - "api repos/"*"/releases/generate-notes "*) echo 'Generated notes.' ;; + # draft-release.sh pipes raw API JSON to jq. + "api repos/"*"/tags "*) echo '[{"name":"v1.0.0"}]' ;; + "api repos/"*"/releases/generate-notes "*) echo '{"body":"Generated notes."}' ;; *) echo "unexpected gh arguments: $*" >&2; exit 2 ;; esac diff --git a/hack/setup-csi-nfs-kind.sh b/hack/setup-csi-nfs-kind.sh index f6091d8656..52f94fff12 100755 --- a/hack/setup-csi-nfs-kind.sh +++ b/hack/setup-csi-nfs-kind.sh @@ -70,7 +70,7 @@ data: listeners: - name: csi_tls_listener address: - socket_address: { address: 0.0.0.0, port_value: 10000 } + socket_address: { address: "::", ipv4_compat: true, port_value: 10000 } filter_chains: - transport_socket: name: envoy.transport_sockets.tls @@ -173,7 +173,7 @@ spec: - $patch: delete name: socat - name: envoy - image: envoyproxy/envoy:v1.39.5@sha256:8fc594a5d85eb76dca24155cfb9208882406873932b20cf33649a0a611194c43 + image: envoyproxy/envoy:v1.40.0@sha256:459f2a6404c340fe6afccd69d85527012d47f3c036765493e6f8f3113fa384de command: - /usr/local/bin/envoy args: diff --git a/hack/setup-e2e-egress-tls-kind.sh b/hack/setup-e2e-egress-tls-kind.sh index 9d2ce16539..ec55b31fd9 100755 --- a/hack/setup-e2e-egress-tls-kind.sh +++ b/hack/setup-e2e-egress-tls-kind.sh @@ -42,7 +42,7 @@ fi # this E2E test setup; production keeps the gateway's normal root behavior. root_image="${image}" if [[ "${gateway}" == agentgateway ]]; then - root_image="envoyproxy/envoy:v1.39.5@sha256:8fc594a5d85eb76dca24155cfb9208882406873932b20cf33649a0a611194c43" + root_image="envoyproxy/envoy:v1.40.0@sha256:459f2a6404c340fe6afccd69d85527012d47f3c036765493e6f8f3113fa384de" fi # Use the helper image's public roots on every Pod start. The separate init diff --git a/hack/third_party/csi-driver-host-path/deploy/csi-hostpath-testing.yaml b/hack/third_party/csi-driver-host-path/deploy/csi-hostpath-testing.yaml index 2862b5b93d..ab698a4b0b 100644 --- a/hack/third_party/csi-driver-host-path/deploy/csi-hostpath-testing.yaml +++ b/hack/third_party/csi-driver-host-path/deploy/csi-hostpath-testing.yaml @@ -155,7 +155,7 @@ spec: topologyKey: kubernetes.io/hostname containers: - name: envoy - image: envoyproxy/envoy:v1.39.5@sha256:8fc594a5d85eb76dca24155cfb9208882406873932b20cf33649a0a611194c43 + image: envoyproxy/envoy:v1.40.0@sha256:459f2a6404c340fe6afccd69d85527012d47f3c036765493e6f8f3113fa384de command: - "/usr/local/bin/envoy" args: diff --git a/hack/tools/buf/go.mod b/hack/tools/buf/go.mod index 387de27d07..510b2664c2 100644 --- a/hack/tools/buf/go.mod +++ b/hack/tools/buf/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/buf go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 tool github.com/bufbuild/buf/cmd/buf @@ -40,7 +40,7 @@ require ( github.com/docker/go-connections v0.7.0 // indirect github.com/docker/go-units v0.5.0 // indirect github.com/felixge/httpsnoop v1.1.0 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/gofrs/flock v0.13.0 // indirect github.com/google/cel-go v0.29.2 // indirect @@ -76,12 +76,13 @@ require ( go.lsp.dev/uri v0.3.0 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 // indirect - go.opentelemetry.io/otel v1.44.0 // indirect - go.opentelemetry.io/otel/metric v1.44.0 // indirect - go.opentelemetry.io/otel/trace v1.44.0 // indirect + go.opentelemetry.io/otel v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/metric v1.47.0 // indirect + go.opentelemetry.io/otel/trace v1.47.0 // indirect go.uber.org/multierr v1.11.0 // indirect go.uber.org/zap v1.28.0 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect golang.org/x/crypto v0.54.0 // indirect golang.org/x/exp v0.0.0-20260709172345-9ea1abe57597 // indirect golang.org/x/mod v0.38.0 // indirect diff --git a/hack/tools/buf/go.sum b/hack/tools/buf/go.sum index 458f449efe..d33b8ac9e8 100644 --- a/hack/tools/buf/go.sum +++ b/hack/tools/buf/go.sum @@ -59,8 +59,6 @@ github.com/containerd/errdefs/pkg v0.3.0/go.mod h1:NJw6s9HwNuRhnjJhM7pylWwMyAkmC github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= github.com/cpuguy83/go-md2man/v2 v2.0.7 h1:zbFlGlXEAKlwXpmvle3d8Oe3YnkKIK4xSRTd3sHPnBo= github.com/cpuguy83/go-md2man/v2 v2.0.7/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/distribution/reference v0.6.0 h1:0IXCQ5g4/QMHHkarYzh5l+u8T3t73zM5QvfrDyIgxBk= github.com/distribution/reference v0.6.0/go.mod h1:BbU0aIcezP1/5jX/8MP0YiH4SdvB5Y4f/wlDRiLyi3E= github.com/docker/cli v29.6.1+incompatible h1:oO7F4nn3Ovr/5TlfTUWFbMwBSS/B7Xs6Epv26gBrUP8= @@ -74,8 +72,8 @@ github.com/docker/go-units v0.5.0/go.mod h1:fgPhTUdO+D/Jk86RDLlptpiXQzgHJF7gydDD github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +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= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/gofrs/flock v0.13.0 h1:95JolYOvGMqeH31+FC7D2+uULf6mG61mEZ/A8dRYMzw= @@ -150,8 +148,8 @@ github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiT github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/tetratelabs/wazero v1.12.0 h1:DuWcpNu/FzgEXgGBDp8J1Spc+CWOvvtvVyjKlaZopYU= github.com/tetratelabs/wazero v1.12.0/go.mod h1:LvKtzl2RqO4gyF27BiXU+nKAjcV8f38U+kP/q2vgxh0= github.com/tidwall/btree v1.8.1 h1:27ehoXvm5AG/g+1VxLS1SD3vRhp/H7LuEfwNvddEdmA= @@ -168,16 +166,18 @@ go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0 h1:8tvICD4vSTOOsNrsI4Ljf6C+6UKvpTEH5XY3JMoyPoo= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.69.0/go.mod h1:z9+yiacE0IHRqM4qFfkbt/JYlmYXgss8GY/jXoNuPJI= -go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= -go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= -go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= -go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= -go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= -go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE= go.uber.org/mock v0.5.2 h1:LbtPTcP8A5k9WPXj54PPPbjcI4Y6lhyOZXn+VS7wNko= @@ -186,8 +186,9 @@ go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0= go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y= go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= 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.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw= golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk= golang.org/x/exp v0.0.0-20260709172345-9ea1abe57597 h1:qLvzZeaANDgyVOA8pyHCOStGlXn0rseXma+GQjeuv2g= diff --git a/hack/tools/code-generator/go.mod b/hack/tools/code-generator/go.mod index ef5cfe76bc..9456777f72 100644 --- a/hack/tools/code-generator/go.mod +++ b/hack/tools/code-generator/go.mod @@ -2,32 +2,28 @@ module go.ate.dev/substrate/hack/tools/code-generator go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 require ( - github.com/fxamacker/cbor/v2 v2.9.2 // indirect + github.com/fxamacker/cbor/v2 v2.9.4 // indirect github.com/go-logr/logr v1.4.4 // indirect - github.com/json-iterator/go v1.1.12 // 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/spf13/pflag v1.0.10 // indirect github.com/x448/float16 v0.8.4 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect golang.org/x/mod v0.42.0 // indirect - golang.org/x/net v0.61.0 // indirect + golang.org/x/net v0.62.0 // indirect golang.org/x/sync v0.24.0 // indirect golang.org/x/text v0.43.0 // indirect golang.org/x/tools v0.52.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - k8s.io/apimachinery v0.36.0-alpha.2.0.20260904054801-5a60cf1c6b81 // indirect - k8s.io/code-generator v0.30.0-alpha.3.0.20260904060942-0cddac4383e4 // indirect + k8s.io/apimachinery v0.38.0-beta.0 // indirect + k8s.io/code-generator v0.38.0-beta.0 // indirect k8s.io/gengo/v2 v2.0.0-20260408192533-25e2208e0dc3 // indirect k8s.io/klog/v2 v2.140.0 // indirect - k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect k8s.io/utils v0.0.0-20260707023825-cf1189d6abe3 // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect + sigs.k8s.io/structured-merge-diff/v7 v7.0.1 // indirect sigs.k8s.io/yaml v1.6.0 // indirect ) diff --git a/hack/tools/code-generator/go.sum b/hack/tools/code-generator/go.sum index 0821f0432b..2c0b1e3907 100644 --- a/hack/tools/code-generator/go.sum +++ b/hack/tools/code-generator/go.sum @@ -1,29 +1,17 @@ -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/fxamacker/cbor/v2 v2.9.2 h1:X4Ksno9+x3cz0TZv69ec1hxP/+tymuR8PXQJyDwfh78= -github.com/fxamacker/cbor/v2 v2.9.2/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/fxamacker/cbor/v2 v2.9.4 h1:xwjVlxEMR3S605oUlgBjKLTTeGFciYPGYCtF/35LKGo= +github.com/fxamacker/cbor/v2 v2.9.4/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= 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= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= -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/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/onsi/gomega v1.44.0 h1:eAiGl3Pw5jz5GQdDff0BcxYpAX1JxW8xD7mFUuwNfZQ= +github.com/onsi/gomega v1.44.0/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA= 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= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/x448/float16 v0.8.4 h1:qLwI1I70+NjRFUR3zs1JPUCgaCXSh3SW62uAKT1mSBM= @@ -34,8 +22,8 @@ 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/mod v0.42.0 h1:ICeL3t2L30ljSPHHxDnR4fqVcBt/zR2zJAb9juavmQg= golang.org/x/mod v0.42.0/go.mod h1:u5fzIrRInkL8MaO1cbRkUHT64v303YIT5KEqpNr7jRs= -golang.org/x/net v0.61.0 h1:RR+6j/BTBCrggOLugxa+66R8FvoN6MHlzDlZIbN9YFw= -golang.org/x/net v0.61.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +golang.org/x/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= golang.org/x/sync v0.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= @@ -44,23 +32,23 @@ golang.org/x/tools v0.52.0 h1:ryxg4U63oaUYk7uOLTF37n43f4qgtGvqV4Ioit1BaEs= golang.org/x/tools v0.52.0/go.mod h1:ItcP5UNaVGG+Yc4eIYmaFLNJ4soEopkx5Y2d4lcEurs= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -k8s.io/apimachinery v0.36.0-alpha.2.0.20260904054801-5a60cf1c6b81 h1:RwCPehCTEZyBA64K7xaHTyXwIwsoBdsLmq21B0P/VcY= -k8s.io/apimachinery v0.36.0-alpha.2.0.20260904054801-5a60cf1c6b81/go.mod h1:1Um7tr4O65Pd822NFLn+MI08uCzUIPahh2lCPsWzNgk= -k8s.io/code-generator v0.30.0-alpha.3.0.20260904060942-0cddac4383e4 h1:WgL8fyPUJi6VbagUkeOhvYYKCIB/ChMCtIalZ9TBh1Q= -k8s.io/code-generator v0.30.0-alpha.3.0.20260904060942-0cddac4383e4/go.mod h1:AA8MJmGgNcxTDTeJgSh2SFpNtAqq9KvjpYooMOcZmDk= +k8s.io/apimachinery v0.38.0-beta.0 h1:CS7Bz3Pac/I0lb6nhzJHjT98PPUf/YgYMYaC3aroFO0= +k8s.io/apimachinery v0.38.0-beta.0/go.mod h1:KGRxGxSx+JnNcp6M3neG7/bzPdeeE7uPDiEItuUEiWg= +k8s.io/code-generator v0.38.0-beta.0 h1:WlQRnI3feL7vQXy7o59x9HvNvnSWZSFGeY5PHgWFwHg= +k8s.io/code-generator v0.38.0-beta.0/go.mod h1:xnC3J/HM/dfCNDmaaG+wofjvgK5EdW0jAeIJHR2oby4= k8s.io/gengo/v2 v2.0.0-20260408192533-25e2208e0dc3 h1:3L6PNkMLXkU/pz3jWzaaIUz0Rs2V9h+5O51AeRC7poc= k8s.io/gengo/v2 v2.0.0-20260408192533-25e2208e0dc3/go.mod h1:yvyl3l9E+UxlqOMUULdKTAYB0rEhsmjr7+2Vb/1pCSo= k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -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/ktesting v0.38.0-beta.0 h1:z8tGty777Eks5T5QJVvdjXpKoLJiyXkmbv2gxYIRqdY= +k8s.io/ktesting v0.38.0-beta.0/go.mod h1:5cuEyae81HMpIwUx1JX78204Zhmrj4J1yqRc2aE060o= 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/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/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.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= -sigs.k8s.io/structured-merge-diff/v6 v6.4.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/structured-merge-diff/v7 v7.0.1 h1:mjAf8oNt6P6M9/uHoZLY2x/iQj/U5YFe0ke1VL/XjeY= +sigs.k8s.io/structured-merge-diff/v7 v7.0.1/go.mod h1:xKoMSgtnJnkfRR+CTNSQ1dBVhkKJR5OQl5RxX/OqHbI= 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/tools/controller-gen/go.mod b/hack/tools/controller-gen/go.mod index 383580c8fb..69132775dd 100644 --- a/hack/tools/controller-gen/go.mod +++ b/hack/tools/controller-gen/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/controller-gen go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 require ( github.com/fatih/color v1.18.0 // indirect diff --git a/hack/tools/go-licenses/go.mod b/hack/tools/go-licenses/go.mod index ae54969887..9299e6b843 100644 --- a/hack/tools/go-licenses/go.mod +++ b/hack/tools/go-licenses/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/go-licenses go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 require ( github.com/davecgh/go-spew v1.1.1 // indirect diff --git a/hack/tools/golangci-lint/go.mod b/hack/tools/golangci-lint/go.mod index 7a393833e8..432e3b3419 100644 --- a/hack/tools/golangci-lint/go.mod +++ b/hack/tools/golangci-lint/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/golangci-lint go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 tool github.com/golangci/golangci-lint/v2/cmd/golangci-lint diff --git a/hack/tools/gotestsum/go.mod b/hack/tools/gotestsum/go.mod index 10e6d6eb19..e8dbda469d 100644 --- a/hack/tools/gotestsum/go.mod +++ b/hack/tools/gotestsum/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/gotestsum go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 tool gotest.tools/gotestsum diff --git a/hack/tools/kind/go.mod b/hack/tools/kind/go.mod index d83d209889..f03b1d9cc2 100644 --- a/hack/tools/kind/go.mod +++ b/hack/tools/kind/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/kind go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 tool sigs.k8s.io/kind diff --git a/hack/tools/ko/go.mod b/hack/tools/ko/go.mod index 6b8d492b05..70ebda3d2b 100644 --- a/hack/tools/ko/go.mod +++ b/hack/tools/ko/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/ko go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 require ( al.essio.dev/pkg/shellescape v1.6.0 // indirect @@ -58,8 +58,8 @@ require ( github.com/evanphx/json-patch/v5 v5.9.11 // indirect github.com/felixge/httpsnoop v1.0.4 // indirect github.com/fsnotify/fsnotify v1.10.1 // indirect - github.com/go-jose/go-jose/v4 v4.1.4 // indirect - github.com/go-logr/logr v1.4.3 // indirect + github.com/go-jose/go-jose/v4 v4.1.6 // indirect + github.com/go-logr/logr v1.4.4 // indirect github.com/go-logr/stdr v1.2.2 // indirect github.com/go-openapi/analysis v0.25.2 // indirect github.com/go-openapi/errors v0.22.7 // indirect @@ -136,11 +136,12 @@ require ( github.com/youmark/pkcs8 v0.0.0-20240726163527-a2c0da244d78 // indirect go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 // indirect - go.opentelemetry.io/otel v1.44.0 // indirect - go.opentelemetry.io/otel/metric v1.44.0 // indirect - go.opentelemetry.io/otel/trace v1.44.0 // indirect + go.opentelemetry.io/otel v1.47.0 // indirect + go.opentelemetry.io/otel/log v1.47.0 // indirect + go.opentelemetry.io/otel/metric v1.47.0 // indirect + go.opentelemetry.io/otel/trace v1.47.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect - go.yaml.in/yaml/v3 v3.0.4 // indirect + go.yaml.in/yaml/v3 v3.0.5 // indirect go.yaml.in/yaml/v4 v4.0.0-rc.6 // indirect golang.org/x/crypto v0.58.0 // indirect golang.org/x/mod v0.42.0 // indirect diff --git a/hack/tools/ko/go.sum b/hack/tools/ko/go.sum index 0714065511..d5734be760 100644 --- a/hack/tools/ko/go.sum +++ b/hack/tools/ko/go.sum @@ -133,8 +133,6 @@ github.com/danieljoos/wincred v1.2.3 h1:v7dZC2x32Ut3nEfRH+vhoZGvN72+dQ/snVXo/vMF github.com/danieljoos/wincred v1.2.3/go.mod h1:6qqX0WNrS4RzPZ1tnroDzq9kY3fu1KwE7MRLQK4X0bs= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= -github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/digitorus/pkcs7 v0.0.0-20230713084857-e76b763bdc49/go.mod h1:SKVExuS+vpu2l9IoOc0RwqE7NYnb0JlcFHFnEJkVDzc= github.com/digitorus/pkcs7 v0.0.0-20250730155240-ffadbf3f398c h1:g349iS+CtAvba7i0Ee9EP1TlTZ9w+UncBY6HSmsFZa0= github.com/digitorus/pkcs7 v0.0.0-20250730155240-ffadbf3f398c/go.mod h1:mCGGmWkOQvEuLdIRfPIpXViBfpWto4AhwtJlAvo62SQ= @@ -168,11 +166,11 @@ github.com/fsnotify/fsnotify v1.10.1 h1:b0/UzAf9yR5rhf3RPm9gf3ehBPpf0oZKIjtpKrx5 github.com/fsnotify/fsnotify v1.10.1/go.mod h1:TLheqan6HD6GBK6PrDWyDPBaEV8LspOxvPSjC+bVfgo= github.com/go-chi/chi/v5 v5.3.0 h1:halUjDxhshgXHMrao5bB8eNBXo/rnzwr8m5m36glehM= github.com/go-chi/chi/v5 v5.3.0/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= -github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA= -github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= +github.com/go-jose/go-jose/v4 v4.1.6 h1:sNRkftxFJxwsILiQukqp5z83QBSmntVwmgRY7AqBDO4= +github.com/go-jose/go-jose/v4 v4.1.6/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08= github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A= -github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI= -github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY= +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= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= github.com/go-openapi/analysis v0.25.2 h1:I0vy4n3alz+DHTiN1PRhCb7QZxkK6g5YmswZKv2TKuw= @@ -352,8 +350,6 @@ github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjL github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4= github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0= 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= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= @@ -412,8 +408,8 @@ github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpE github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= -github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U= -github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U= +github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= +github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8= github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU= github.com/theupdateframework/go-tuf v0.7.0 h1:CqbQFrWo1ae3/I0UCblSbczevCCbS31Qvs5LdxRWqRI= @@ -455,16 +451,18 @@ go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.6 go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.68.0/go.mod h1:Sje3i3MjSPKTSPvVWCaL8ugBzJwik3u4smCjUeuupqg= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0 h1:CqXxU8VOmDefoh0+ztfGaymYbhdB/tT3zs79QaZTNGY= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.68.0/go.mod h1:BuhAPThV8PBHBvg8ZzZ/Ok3idOdhWIodywz2xEcRbJo= -go.opentelemetry.io/otel v1.44.0 h1:JjwHmHpA4iZ3wBxluu2fbbE7j4kqlE8jXyAyPXH7HqU= -go.opentelemetry.io/otel v1.44.0/go.mod h1:BMgjTHL9WPRlRjL2oZCBTL4whCGtXch2H4BhOPIAyYc= -go.opentelemetry.io/otel/metric v1.44.0 h1:1w0gILTcHdr3YI+ixLyjemwrVnsMURbTZFrSYCdDdmc= -go.opentelemetry.io/otel/metric v1.44.0/go.mod h1:8O7hanEPBNgEMmybD3s2VBKcgWOCsA6tzHBPODAiquo= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= go.opentelemetry.io/otel/sdk v1.44.0 h1:nHYwb9lK+fJPU/dnT6s7W7Z8itMWyqrnVfbheVYrZ58= go.opentelemetry.io/otel/sdk v1.44.0/go.mod h1:Osuydd3Se74nqjAKxid74N5eC+jfEqfTegHRnq58oK0= go.opentelemetry.io/otel/sdk/metric v1.44.0 h1:3LlKgI+VjbVsjNRFZJZAJ30WjXC5VkNRks6si09iEfI= go.opentelemetry.io/otel/sdk/metric v1.44.0/go.mod h1:5B5pMARnXxKhltooO4xUuCBorl65a4EpnTalObqOigA= -go.opentelemetry.io/otel/trace v1.44.0 h1:jxF5CsGYCe74MCRx2X4g7WsY/VBKRqqpNvXlX/6gtIk= -go.opentelemetry.io/otel/trace v1.44.0/go.mod h1:oLl1jrMQAVo6v3GAggN+1VH9VIz9iUSvW53sW1Q8PIE= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.step.sm/crypto v0.77.7 h1:6azC+pD678Vjju8yXnMDHCZJ+HzFaEmL3sCryiezTIA= go.step.sm/crypto v0.77.7/go.mod h1:OW/2sEHwTtDKq70PvSQ5B0JGy/CrLyDKOiVy3YvZMTQ= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -475,8 +473,9 @@ go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo= go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q= go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ= go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ= -go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc= 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= go.yaml.in/yaml/v4 v4.0.0-rc.6 h1:1h7H1ohdUh93/FyE4YaDa1Zh64K6VVbjF4K6WUxMtH4= go.yaml.in/yaml/v4 v4.0.0-rc.6/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0= golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w= diff --git a/hack/tools/kube-api-linter/go.mod b/hack/tools/kube-api-linter/go.mod index 3030880bc9..58b3d7fe3f 100644 --- a/hack/tools/kube-api-linter/go.mod +++ b/hack/tools/kube-api-linter/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/kube-api-linter go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 tool sigs.k8s.io/kube-api-linter/cmd/golangci-lint-kube-api-linter diff --git a/hack/tools/protoc-gen-go-grpc/go.mod b/hack/tools/protoc-gen-go-grpc/go.mod index e0193e6078..fbcddd3084 100644 --- a/hack/tools/protoc-gen-go-grpc/go.mod +++ b/hack/tools/protoc-gen-go-grpc/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/protoc-gen-go-grpc go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 require ( google.golang.org/grpc/cmd/protoc-gen-go-grpc v1.6.2 // indirect diff --git a/hack/tools/protoc-gen-go/go.mod b/hack/tools/protoc-gen-go/go.mod index b4c96ef31e..6dddd20410 100644 --- a/hack/tools/protoc-gen-go/go.mod +++ b/hack/tools/protoc-gen-go/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/protoc-gen-go go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 require google.golang.org/protobuf v1.36.12-0.20260120151049-f2248ac996af // indirect diff --git a/hack/tools/setup-envtest/go.mod b/hack/tools/setup-envtest/go.mod index 0aa8b73f0b..4795b09e9d 100644 --- a/hack/tools/setup-envtest/go.mod +++ b/hack/tools/setup-envtest/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/hack/tools/setup-envtest go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 require ( github.com/go-logr/logr v1.4.3 // indirect diff --git a/hack/update/codegen.sh b/hack/update/codegen.sh index dcddf04788..c1e29297aa 100755 --- a/hack/update/codegen.sh +++ b/hack/update/codegen.sh @@ -98,6 +98,7 @@ function codegen::validation() { --readonly-pkg=google.golang.org/protobuf/types/known/timestamppb \ --readonly-pkg=google.golang.org/protobuf/types/known/fieldmaskpb \ --readonly-pkg=google.golang.org/protobuf/types/known/emptypb \ + --validation-extensions-file=./.validation-extensions.yaml \ "./${dir}" done } diff --git a/hack/util/get-contributors.sh b/hack/util/get-contributors.sh index ffff616ed5..81b3f28f35 100755 --- a/hack/util/get-contributors.sh +++ b/hack/util/get-contributors.sh @@ -61,12 +61,16 @@ query($owner: String!, $name: String!, $oid: GitObjectID!, $endCursor: String) { GRAPHQL )" +source "$(dirname "${BASH_SOURCE[0]}")/gh-retry.sh" + output_dir="$(mktemp -d)" trap 'rm -rf "${output_dir}"' EXIT touch "${output_dir}/logins" while IFS= read -r commit; do [[ -n "${commit}" ]] || continue - response="$(gh api graphql --paginate \ + # Retries HTTP 5xx. GraphQL timeouts are not retried: gh reports them + # without a status. + response="$(gh_with_retries api graphql --paginate \ -f query="${query}" -f owner="${ORG}" -f name="${REPO}" -f oid="${commit}")" if ! jq -e -s 'length > 0 and all(.[]; (.errors | length) == 0 and diff --git a/hack/util/gh-retry.sh b/hack/util/gh-retry.sh new file mode 100644 index 0000000000..96421d24b7 --- /dev/null +++ b/hack/util/gh-retry.sh @@ -0,0 +1,58 @@ +#!/usr/bin/env bash + +# Copyright 2026 The Agent Substrate 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. + +# gh_with_retries runs gh, retrying HTTP 5xx errors (5 attempts, +# 2s/4s/8s/16s apart). Other errors fail immediately. Only use it for commands +# that are safe to repeat and read no stdin. +# +# A retried attempt's output is dropped, because gh api writes error bodies to +# stdout. On the final failure, gh's error and any error body go to stderr. +gh_with_retries() { + local attempts=5 backoff=2 attempt=1 rc out err + out="$(mktemp)" + err="$(mktemp)" + while true; do + rc=0 + gh "$@" >"${out}" 2>"${err}" || rc=$? + if [[ ${rc} -eq 0 ]]; then + cat "${out}" + cat "${err}" >&2 + break + fi + if ! grep -qE 'HTTP 5[0-9]{2}' "${err}"; then + _gh_retry_print_failure "${err}" "${out}" + break + fi + if ((attempt >= attempts)); then + _gh_retry_print_failure "${err}" "${out}" + echo "gave up after ${attempts} attempts" >&2 + break + fi + sleep "${backoff}" + backoff=$((backoff * 2)) + attempt=$((attempt + 1)) + done + rm -f "${out}" "${err}" + return "${rc}" +} + +# Prints gh's error and any error body, adding the newline gh api leaves off. +_gh_retry_print_failure() { + cat "$1" "$2" >&2 + if [[ -s "$2" && -n "$(tail -c 1 "$2")" ]]; then + echo >&2 + fi +} diff --git a/hack/util/verify-boilerplate.py b/hack/util/verify-boilerplate.py index d9be807df2..cb7b5e0a98 100755 --- a/hack/util/verify-boilerplate.py +++ b/hack/util/verify-boilerplate.py @@ -109,7 +109,7 @@ def main(): filename = os.path.basename(filepath) # Skip non-source-code files - if ext in ['.md', '.txt', '.png', '.jpg', '.jpeg', '.gif', '.mp4', '.json', '.pdf', '.ico', '.woff', '.woff2', '.ttf', '.otf', '.svg']: + if ext in ['.md', '.txt', '.golden', '.png', '.jpg', '.jpeg', '.gif', '.mp4', '.json', '.pdf', '.ico', '.woff', '.woff2', '.ttf', '.otf', '.svg']: continue if filename in ['LICENSE', 'NOTICE', 'CODEOWNERS', 'CNAME', '.gitignore', 'go.mod', 'go.sum', 'Cargo.lock']: continue diff --git a/hack/verify-goldens.sh b/hack/verify-goldens.sh new file mode 100755 index 0000000000..a6cd4d09b3 --- /dev/null +++ b/hack/verify-goldens.sh @@ -0,0 +1,34 @@ +#!/usr/bin/env bash + +# Copyright 2026 The Agent Substrate 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. + +set -o errexit -o nounset -o pipefail + +ROOT="$(git rev-parse --show-toplevel)" +cd "${ROOT}" + +export REFRESH_GOLDENS=1 + +go test ./cmd/benchmarking/egress/internal/cmd/actor -run '^TestStatsGolden$' + +if [[ "$(id -u)" -eq 0 ]]; then + go test -count=1 -run '^TestEgressRules$' ./internal/ateworker/actornet +else + go test -count=1 -run '^TestEgressRules$' \ + -exec "sudo env REFRESH_GOLDENS=${REFRESH_GOLDENS}" \ + ./internal/ateworker/actornet +fi + +git diff --exit-code -- ':(glob)**/testdata/**' diff --git a/hack/verify/benchmarking-python.sh b/hack/verify/benchmarking-python.sh index 000cb29a5c..d5e95b5134 100755 --- a/hack/verify/benchmarking-python.sh +++ b/hack/verify/benchmarking-python.sh @@ -31,7 +31,9 @@ source hack/util/venv.sh SUITES=( "benchmarking/analysis ." "benchmarking/automation ." + "benchmarking/evaluate unit_tests" "benchmarking/locust unit_tests" + "benchmarking/nighthawk-egress tests" "benchmarking/nighthawk-ingress tests" "benchmarking/workloads/manifests/sweperf ." ) diff --git a/hack/verify/package-deps.sh b/hack/verify/package-deps.sh index f31eb38f24..fd83545c3f 100755 --- a/hack/verify/package-deps.sh +++ b/hack/verify/package-deps.sh @@ -84,5 +84,6 @@ check() { check ./cmd/ateapi "${ateapi_banned[@]}" check ./internal/objectstoreplugin/actorauthz "${actorauthz_banned[@]}" check ./pkg/objectstore/actorauthz "${actorauthz_banned[@]}" "${pkg_actorauthz_banned[@]}" +check ./pkg/oidcjwt "${actorauthz_banned[@]}" "${pkg_actorauthz_banned[@]}" exit "${status}" diff --git a/hack/verify/proto-breaking.sh b/hack/verify/proto-breaking.sh index 5b78af1d75..a23880f951 100755 --- a/hack/verify/proto-breaking.sh +++ b/hack/verify/proto-breaking.sh @@ -26,6 +26,19 @@ # buf's PACKAGE rules. Within a proto package, declarations may move between # .proto files, but messages, enums, services, RPCs, fields, enum values, and # reserved ranges cannot be deleted, renamed, renumbered, or retyped. +# +# The baseline is a release tag, including release candidates. Only protos +# that shipped in a release can be in stored data or on a user's node. Main +# gives no compatibility guarantee between commits, so protos added since the +# last release may still change. +# +# Release tags are v1.0.0 or later and live on release-X.Y branches, which are +# cut from main. On main, the newest release branch, or a newly cut one, the +# baseline is the newest tag. On an older release branch, it is the newest tag +# in HEAD's history. HEAD is on an older release branch when that tag is on an +# older X.Y line and HEAD's merge base with the newest tag is at or before it. +# This works for any local branch name, and for a tag on the commit a release +# branch was cut from. set -o errexit -o nounset -o pipefail @@ -34,33 +47,44 @@ cd "${ROOT}" if (( $# > 1 )); then echo "Usage: $0 [base-ref]" >&2 + echo " base-ref is compared as is. To compare against a branch point, pass" >&2 + echo " \"\$(git merge-base HEAD upstream/main)\"." >&2 exit 2 fi -# Compare against the merge base, so a breaking change that landed on main -# separately is not reported against this branch. When no ref is given, check -# upstream/main, origin/main, and main, and keep the newest merge base so a -# stale fork or local main does not win. -BASELINE="" if (( $# == 1 )); then - BASELINE="$(git merge-base HEAD "$1")" + BASELINE="ref=$(git rev-parse --verify "${1}^{commit}")" else - for CANDIDATE in upstream/main origin/main main; do - if ! MB="$(git merge-base HEAD "${CANDIDATE}" 2>/dev/null)"; then - continue - fi - if [ -z "${BASELINE}" ] || git merge-base --is-ancestor "${BASELINE}" "${MB}"; then - BASELINE="${MB}" - fi - done - if [ -z "${BASELINE}" ]; then - echo "proto-breaking: no baseline; fetch main (git fetch origin main)" >&2 + TAG_PATTERN='refs/tags/v[1-9]*.[0-9]*.[0-9]*' + # versionsort.suffix sorts v1.0.0-rc.3 below v1.0.0. + NEWEST="$(git -c versionsort.suffix=- for-each-ref --count=1 --sort=-v:refname \ + --format='%(refname:lstrip=2)' "${TAG_PATTERN}")" + if [ -z "${NEWEST}" ]; then + echo "proto-breaking: no release tag found; fetch tags (git fetch upstream --tags)" >&2 exit 1 fi + MERGED="$(git -c versionsort.suffix=- for-each-ref --count=1 --sort=-v:refname \ + --format='%(refname:lstrip=2)' --merged HEAD "${TAG_PATTERN}")" + # X.Y line of each tag: strip the release candidate, then the patch (v1.2.0-rc.1 -> v1.2). + MERGED_MINOR="${MERGED%%-*}" + MERGED_MINOR="${MERGED_MINOR%.*}" + NEWEST_MINOR="${NEWEST%%-*}" + NEWEST_MINOR="${NEWEST_MINOR%.*}" + if [ -n "${MERGED}" ] && [ "${MERGED_MINOR}" != "${NEWEST_MINOR}" ] && \ + MB="$(git merge-base HEAD "refs/tags/${NEWEST}" 2>/dev/null)" && \ + git merge-base --is-ancestor "${MB}" "refs/tags/${MERGED}"; then + # Older release branch: HEAD shares no history with NEWEST after MERGED. + TAG="${MERGED}" + else + # Main, the newest release branch, or a newly cut one. + TAG="${NEWEST}" + fi + echo "proto-breaking: comparing against ${TAG}" >&2 + BASELINE="tag=${TAG}" fi # The input is the working tree, so an incompatible edit is reported before it # is ever committed. --against-config reads the baseline with the current # buf.yaml, so a baseline commit without one still builds. BIN="$("${ROOT}"/hack/run-tool.sh --print-bin-path buf)" -"${BIN}" breaking --against ".git#ref=${BASELINE}" --against-config buf.yaml +"${BIN}" breaking --against ".git#${BASELINE}" --against-config buf.yaml diff --git a/internal/actorevent/actorevent.go b/internal/actorevent/actorevent.go index 79af6c121b..aafcbac651 100644 --- a/internal/actorevent/actorevent.go +++ b/internal/actorevent/actorevent.go @@ -35,9 +35,9 @@ import ( "sync/atomic" "time" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/attribute" "go.opentelemetry.io/otel/log" - "go.opentelemetry.io/otel/log/global" "go.ate.dev/substrate/internal/ateattr" ) @@ -249,7 +249,7 @@ func SetConsole(on bool) { console.Store(on) } // The global provider delegates, so a Logger taken before InitLogging still // reaches the one it installs. var defaultEmitter = sync.OnceValue(func() *Emitter { - return NewEmitter(global.GetLoggerProvider()) + return NewEmitter(otel.GetLoggerProvider()) }) // Log records ev through the process-wide provider. diff --git a/internal/actorlock/inflight.go b/internal/actorlock/inflight.go index 3228cb312c..1cad57704b 100644 --- a/internal/actorlock/inflight.go +++ b/internal/actorlock/inflight.go @@ -16,34 +16,29 @@ package actorlock import ( "context" + "maps" "sync" ) -// InFlight tracks lifecycle RPCs by actor for shutdown cancellation and draining. +// InFlight tracks lifecycle RPCs by actor so shutdown can wait for them. type InFlight struct { mu sync.Mutex - // Callers must serialize RPCs for each actor with Locks. - rpcs map[string]*rpc + // RPC name by actor UID. Callers must serialize RPCs for each actor with + // Locks. + rpcs map[string]string // Closed and replaced on each registry change to wake waiters. changed chan struct{} } -type rpc struct { - name string - // Nil for an RPC that must run to completion. - cancel context.CancelFunc -} - // NewInFlight returns an empty set. func NewInFlight() *InFlight { - return &InFlight{rpcs: map[string]*rpc{}, changed: make(chan struct{})} + return &InFlight{rpcs: map[string]string{}, changed: make(chan struct{})} } // Add records an RPC for actorUID and returns the function that clears it. -// cancel is nil for an RPC that must finish, such as a checkpoint saving state. -func (f *InFlight) Add(actorUID, name string, cancel context.CancelFunc) func() { +func (f *InFlight) Add(actorUID, name string) func() { f.mu.Lock() - f.rpcs[actorUID] = &rpc{name: name, cancel: cancel} + f.rpcs[actorUID] = name f.notifyLocked() f.mu.Unlock() @@ -55,20 +50,6 @@ func (f *InFlight) Add(actorUID, name string, cancel context.CancelFunc) func() } } -// CancelStartups cancels startup RPCs and returns their actor UIDs. -func (f *InFlight) CancelStartups() []string { - f.mu.Lock() - defer f.mu.Unlock() - var canceled []string - for actorUID, r := range f.rpcs { - if r.cancel != nil { - r.cancel() - canceled = append(canceled, actorUID) - } - } - return canceled -} - // WaitIdle waits for all RPCs to finish, returning false on cancellation. func (f *InFlight) WaitIdle(ctx context.Context) bool { for { @@ -92,11 +73,7 @@ func (f *InFlight) WaitIdle(ctx context.Context) bool { func (f *InFlight) Names() map[string]string { f.mu.Lock() defer f.mu.Unlock() - out := make(map[string]string, len(f.rpcs)) - for actorUID, r := range f.rpcs { - out[actorUID] = r.name - } - return out + return maps.Clone(f.rpcs) } func (f *InFlight) notifyLocked() { diff --git a/internal/actorlock/inflight_test.go b/internal/actorlock/inflight_test.go index 55a973937f..45f5352482 100644 --- a/internal/actorlock/inflight_test.go +++ b/internal/actorlock/inflight_test.go @@ -23,8 +23,8 @@ import ( // TestWaitIdleWaitsForEveryActor verifies all RPCs finish before the wait returns. func TestWaitIdleWaitsForEveryActor(t *testing.T) { f := NewInFlight() - releaseA := f.Add("actor-a", "RunWorkload", func() {}) - releaseB := f.Add("actor-b", "CheckpointWorkload", nil) + releaseA := f.Add("actor-a", "RunWorkload") + releaseB := f.Add("actor-b", "CheckpointWorkload") ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond) defer cancel() @@ -46,22 +46,3 @@ func TestWaitIdleWaitsForEveryActor(t *testing.T) { t.Error("WaitIdle did not return once nothing was in flight") } } - -// TestCancelStartupsCancelsEveryCancelableActor verifies checkpoints are left running. -func TestCancelStartupsCancelsEveryCancelableActor(t *testing.T) { - f := NewInFlight() - canceled := map[string]bool{} - f.Add("actor-a", "RunWorkload", func() { canceled["actor-a"] = true }) - f.Add("actor-b", "RestoreWorkload", func() { canceled["actor-b"] = true }) - f.Add("actor-c", "CheckpointWorkload", nil) - - // actor-c is a checkpoint, which must be allowed to finish saving. - if got := len(f.CancelStartups()); got != 2 { - t.Errorf("canceled %d RPCs, want 2", got) - } - for _, uid := range []string{"actor-a", "actor-b"} { - if !canceled[uid] { - t.Errorf("%s's startup was not canceled", uid) - } - } -} diff --git a/internal/actorlog/containerexit.go b/internal/actorlog/containerexit.go new file mode 100644 index 0000000000..f6750859ad --- /dev/null +++ b/internal/actorlog/containerexit.go @@ -0,0 +1,54 @@ +// Copyright 2026 The Agent Substrate 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 actorlog + +import ( + "time" + + "go.ate.dev/substrate/internal/ateattr" + "go.ate.dev/substrate/internal/resources" +) + +// ContainerExitedMessage is the message of the record EmitContainerExit writes. +const ContainerExitedMessage = "Actor container exited" + +// ContainerExit is the exit of one container of an actor, as its worker saw it. +type ContainerExit struct { + Container string + // ExitCode is the code that the runtime returned. It is nil when the + // runtime gave none. + ExitCode *int32 +} + +// EmitContainerExit logs that a container of the actor exited. The record is a +// WARN for each exit code: the template does not say if a container is expected +// to finish, so the reader uses the code to tell. The level field has the name +// and value that the worker's slog records use. +// +// Like a lifecycle event, the record has no container label, because the worker +// wrote it. The container name is a field of the record. +func (al *ActorLogger) EmitContainerExit(a resources.ActorAttribution, e ContainerExit) { + envelope := map[string]any{ + "time": time.Now().Format(time.RFC3339Nano), + "level": "WARN", + "message": ContainerExitedMessage, + al.labelsKey: ateattr.ActorLogLabels(a, ""), + string(ateattr.ActorExitedContainerNameKey): e.Container, + } + if e.ExitCode != nil { + envelope[string(ateattr.ProcessExitCodeKey)] = *e.ExitCode + } + al.write(envelope) +} diff --git a/internal/actorlog/containerexit_test.go b/internal/actorlog/containerexit_test.go new file mode 100644 index 0000000000..d3575ef813 --- /dev/null +++ b/internal/actorlog/containerexit_test.go @@ -0,0 +1,72 @@ +// Copyright 2026 The Agent Substrate 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 actorlog + +import ( + "bytes" + "fmt" + "strings" + "testing" + + "go.ate.dev/substrate/internal/ateattr" +) + +func TestEmitContainerExit(t *testing.T) { + code := func(c int32) *int32 { return &c } + tests := []struct { + name string + exitCode *int32 + wantCode string // "" means the key is absent + }{ + {name: "failure", exitCode: code(1), wantCode: "1"}, + // 0 is a real exit code: the record still says the container is gone. + {name: "clean exit", exitCode: code(0), wantCode: "0"}, + {name: "code above 128", exitCode: code(139), wantCode: "139"}, + {name: "no exit code"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var buf bytes.Buffer + al := NewActorLogger(&buf, false) + al.EmitContainerExit(testAttribution, ContainerExit{Container: testContainer, ExitCode: tc.exitCode}) + + // kubectl ate logs reads a line with the container label as that + // container's output, and skips it under --source=lifecycle. + if strings.Contains(buf.String(), `"`+containerNameLabel+`"`) { + t.Errorf("record carries the container label: %s", buf.String()) + } + m := decodeLine(t, &buf) + if m["message"] != ContainerExitedMessage || m["level"] != "WARN" { + t.Errorf("message, level = %v, %v, want %q, WARN", m["message"], m["level"], ContainerExitedMessage) + } + wantLabels := identityLabels() + delete(wantLabels, containerNameLabel) + assertLabels(t, labelGroup(t, al, m), wantLabels) + if got := m[string(ateattr.ActorExitedContainerNameKey)]; got != testContainer { + t.Errorf("exited container = %v, want %q", got, testContainer) + } + got, ok := m[string(ateattr.ProcessExitCodeKey)] + if tc.wantCode == "" { + if ok { + t.Errorf("exit code = %v, want it absent", got) + } + return + } + if fmt.Sprint(got) != tc.wantCode { + t.Errorf("exit code = %v, want %s", got, tc.wantCode) + } + }) + } +} diff --git a/internal/actorlog/logger.go b/internal/actorlog/logger.go index e5db8cf2d5..23e6aac150 100644 --- a/internal/actorlog/logger.go +++ b/internal/actorlog/logger.go @@ -13,14 +13,14 @@ // limitations under the License. // Package actorlog provides structured JSON logging for actor sandboxes shared -// by the gVisor and micro-VM worker runtimes. It forwards an actor container's +// by the gVisor and microVM worker runtimes. It forwards an actor container's // stdout/stderr to the worker pod's stdout, annotated with the ate.* identity // labels from internal/ateattr, and emits synthetic actor lifecycle events. // -// Only the lifecycle events carry trace context: one forwarder goroutine covers a -// whole container stream, so it cannot tell which request produced a given line. -// An actor emitting its own trace_id/span_id keeps them, verbatim like the rest of -// its fields. +// The logger attaches trace context only to lifecycle events. A forwarder +// goroutine covers a whole container stream and cannot tell which request +// produced a given line. Actor-supplied trace_id/span_id fields pass through +// unless the line exceeds maxLineBytes and is logged as text chunks. package actorlog import ( @@ -35,6 +35,7 @@ import ( "strings" "sync" "time" + "unicode/utf8" "go.opentelemetry.io/otel/trace" @@ -112,75 +113,121 @@ func (al *ActorLogger) StartJSONLogPipe(a resources.ActorAttribution, containerN return nil, err } go func() { - al.WrapContainerLogs(pr, a, containerName) + al.WrapContainerLogs(pr, a, containerName, "") pr.Close() }() return pw, nil } +// maxLineBytes bounds the unencoded size of a structured line or text chunk. +// JSON escaping can expand a text chunk sixfold, so leave room for metadata. +const maxLineBytes = 32 << 10 + // WrapContainerLogs reads log lines from r, parses them, and logs them in a unified -// structured format. containerName is added as the ate.actor.container.name label -// so multi-container actors can be demultiplexed. -func (al *ActorLogger) WrapContainerLogs(r io.Reader, a resources.ActorAttribution, containerName string) { +// structured format. containerName is added as the ate.actor.container.name label. +// stream is stdout or stderr, or empty when the two share a pipe. +func (al *ActorLogger) WrapContainerLogs(r io.Reader, a resources.ActorAttribution, containerName, stream string) { rdr := bufio.NewReader(r) + var line []byte + // split is set once a chunk of the current line has been logged. + split := false for { - lineBytes, err := rdr.ReadBytes('\n') - - // Strip trailing newline from ReadBytes if present - if len(lineBytes) > 0 && lineBytes[len(lineBytes)-1] == '\n' { - lineBytes = lineBytes[:len(lineBytes)-1] + frag, err := rdr.ReadSlice('\n') + eol := err == nil + if eol { + frag = frag[:len(frag)-1] } + line = append(line, frag...) - if len(lineBytes) > 0 { - var m map[string]any - var envelope map[string]any - - dec := json.NewDecoder(bytes.NewReader(lineBytes)) - dec.UseNumber() - - unmarshalErr := dec.Decode(&m) - if unmarshalErr == nil && m == nil { - unmarshalErr = errors.New("JSON value is not an object") - } - if unmarshalErr == nil { - var trailing any - if err := dec.Decode(&trailing); err != io.EOF { - unmarshalErr = errors.New("trailing garbage detected after JSON object") - } - } - - if unmarshalErr != nil { - envelope = map[string]any{ - "time": time.Now().Format(time.RFC3339Nano), - "message": string(lineBytes), - al.labelsKey: ateattr.ActorLogLabels(a, containerName), - } - } else { - if _, ok := m["time"]; !ok { - m["time"] = time.Now().Format(time.RFC3339Nano) - } - for k := range m { - if strings.HasPrefix(k, ateattr.ReservedNamespace) { - delete(m, k) + for len(line) > maxLineBytes { + n := maxLineBytes + // Keep an incomplete UTF-8 character for the next chunk. + for i := n - 1; i > n-utf8.UTFMax; i-- { + if utf8.RuneStart(line[i]) { + if !utf8.FullRune(line[i:n]) { + n = i } + break } - labels := al.foldLabelGroups(m) - for k, v := range ateattr.ActorLogLabels(a, containerName) { - labels[k] = v - } - m[al.labelsKey] = labels - envelope = m } - - al.write(envelope) + al.logLine(line[:n], a, containerName, stream, false, true) + line = line[:copy(line, line[n:])] + split = true } - if err != nil { + end := err != nil && !errors.Is(err, bufio.ErrBufferFull) + if eol || end { + if len(line) > 0 { + al.logLine(line, a, containerName, stream, !split, false) + } + line, split = line[:0], false + } + if end { break } } } +// logLine merges a JSON object into the record when parse is set. Otherwise it +// writes the line as text. If partial is set, more chunks follow for this line. +func (al *ActorLogger) logLine(line []byte, a resources.ActorAttribution, containerName, stream string, parse, partial bool) { + var m map[string]any + if parse { + m = parseJSONObject(line) + } + + var envelope map[string]any + if m == nil { + envelope = map[string]any{ + "time": time.Now().Format(time.RFC3339Nano), + "message": string(line), + al.labelsKey: ateattr.ActorLogLabels(a, containerName), + } + } else { + if _, ok := m["time"]; !ok { + m["time"] = time.Now().Format(time.RFC3339Nano) + } + for k := range m { + if strings.HasPrefix(k, ateattr.ReservedNamespace) { + delete(m, k) + } + } + labels := al.foldLabelGroups(m) + for k, v := range ateattr.ActorLogLabels(a, containerName) { + labels[k] = v + } + m[al.labelsKey] = labels + envelope = m + } + + // The forwarder sets the stream, even if the actor supplied the field. + if stream != "" { + envelope[string(ateattr.LogIostreamKey)] = stream + } else { + delete(envelope, string(ateattr.LogIostreamKey)) + } + if partial { + envelope[string(ateattr.LogPartialKey)] = true + } + al.write(envelope) +} + +// parseJSONObject returns the object line holds, or nil if line is anything else, +// including an object followed by more data. +func parseJSONObject(line []byte) map[string]any { + var m map[string]any + dec := json.NewDecoder(bytes.NewReader(line)) + dec.UseNumber() + if err := dec.Decode(&m); err != nil { + return nil + } + var trailing any + if err := dec.Decode(&trailing); err != io.EOF { + return nil + } + return m +} + func (al *ActorLogger) write(envelope map[string]any) { if envBytes, err := json.Marshal(envelope); err == nil { envBytes = append(envBytes, '\n') diff --git a/internal/actorlog/logger_test.go b/internal/actorlog/logger_test.go index 168c1a8a93..8adbcfedfc 100644 --- a/internal/actorlog/logger_test.go +++ b/internal/actorlog/logger_test.go @@ -18,9 +18,13 @@ import ( "bytes" "context" "encoding/json" + "fmt" + "io" + "slices" "strings" "sync" "testing" + "testing/synctest" "go.opentelemetry.io/otel/trace" @@ -53,6 +57,8 @@ var ( containerNameLabel = string(ateattr.ActorContainerNameKey) templateNSLabel = string(ateattr.TemplateAtespaceKey) templateNameLabel = string(ateattr.TemplateNameKey) + logPartialKey = string(ateattr.LogPartialKey) + logIostreamKey = string(ateattr.LogIostreamKey) ) // decodeLine parses the single record written to buf, preserving number literals @@ -105,7 +111,7 @@ func identityLabels() map[string]string { func TestWrapContainerLogs(t *testing.T) { var buf bytes.Buffer al := NewActorLogger(&buf, false) - al.WrapContainerLogs(strings.NewReader("Test application log output\n"), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader("Test application log output\n"), testAttribution, testContainer, "") m := decodeLine(t, &buf) @@ -126,7 +132,7 @@ func TestWrapContainerLogs_JSONInput(t *testing.T) { var buf bytes.Buffer al := NewActorLogger(&buf, false) - al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer, "") m := decodeLine(t, &buf) @@ -161,7 +167,7 @@ func TestWrapContainerLogs_ActorTraceContextPassthrough(t *testing.T) { var buf bytes.Buffer al := NewActorLogger(&buf, false) - al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer, "") m := decodeLine(t, &buf) if m[ateattr.LogTraceIDField] != traceID { @@ -210,7 +216,7 @@ func TestWrapContainerLogs_MergeLabels(t *testing.T) { var buf bytes.Buffer al := NewActorLogger(&buf, false) - al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer, "") labels := labelGroup(t, al, decodeLine(t, &buf)) @@ -225,18 +231,22 @@ func TestWrapContainerLogs_MergeLabels(t *testing.T) { // other ate.* key that would read as platform-issued attribution downstream. func TestWrapContainerLogs_ReservedNamespace(t *testing.T) { input := `{"level":"info","msg":"App log","` + actorNameLabel + `":"top-level-forgery","ate.tenant":"forged",` + + `"` + logPartialKey + `":true,"partial":true,` + `"labels":{"` + actorNameLabel + `":"malicious-name","` + actorUIDLabel + `":"malicious-uid","ate.tenant":"forged","app":"my-app"}}` + "\n" var buf bytes.Buffer al := NewActorLogger(&buf, false) - al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer, "") m := decodeLine(t, &buf) - for _, k := range []string{actorNameLabel, "ate.tenant"} { + for _, k := range []string{actorNameLabel, "ate.tenant", logPartialKey} { if v, ok := m[k]; ok { t.Errorf("reserved top-level key %s survived with value %v", k, v) } } + if m["partial"] != true { + t.Errorf("actor field partial = %v, want true", m["partial"]) + } labels := labelGroup(t, al, m) if _, ok := labels["ate.tenant"]; ok { @@ -270,7 +280,7 @@ func TestWrapContainerLogs_ForeignLabelGroup(t *testing.T) { var buf bytes.Buffer al := NewActorLogger(&buf, tt.onGCE) - al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer, "") m := decodeLine(t, &buf) if _, ok := m[tt.foreign]; ok { @@ -299,7 +309,7 @@ func TestWrapContainerLogs_NonStringLabelValue(t *testing.T) { var buf bytes.Buffer al := NewActorLogger(&buf, false) - al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer, "") labels := labelGroup(t, al, decodeLine(t, &buf)) for k, v := range labels { @@ -318,7 +328,7 @@ func TestWrapContainerLogs_NonStringLabelValue(t *testing.T) { func TestWrapContainerLogs_JSONNull(t *testing.T) { var buf bytes.Buffer al := NewActorLogger(&buf, false) - al.WrapContainerLogs(strings.NewReader("null\n"), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader("null\n"), testAttribution, testContainer, "") m := decodeLine(t, &buf) if m["message"] != "null" { @@ -332,7 +342,7 @@ func TestWrapContainerLogs_TrailingGarbage(t *testing.T) { var buf bytes.Buffer al := NewActorLogger(&buf, false) - al.WrapContainerLogs(strings.NewReader(line+"\n"), testAttribution, testContainer) + al.WrapContainerLogs(strings.NewReader(line+"\n"), testAttribution, testContainer, "") m := decodeLine(t, &buf) if m["message"] != line { @@ -341,6 +351,213 @@ func TestWrapContainerLogs_TrailingGarbage(t *testing.T) { assertLabels(t, labelGroup(t, al, m), identityLabels()) } +func TestWrapContainerLogs_LongLines(t *testing.T) { + const lineLimit = 32 << 10 + long := func(n int) string { return strings.Repeat("a", n) } + longJSON := `{"msg":"` + long(lineLimit) + `"}` + cappedMessage := long(lineLimit - len(`{"msg":""}`)) + cappedJSON := `{"msg":"` + cappedMessage + `"}` + + type testCase struct { + name string + input string + want []string + field string + more []int // indexes of non-final chunks + } + tests := []testCase{ + { + name: "exactly the cap with a newline is one record", + input: long(lineLimit) + "\n", + want: []string{long(lineLimit)}, + }, + { + name: "JSON at the cap with a newline stays structured", + input: cappedJSON + "\n", + want: []string{cappedMessage}, + field: "msg", + }, + { + name: "JSON at the cap ending at EOF stays structured", + input: cappedJSON, + want: []string{cappedMessage}, + field: "msg", + }, + { + name: "one byte over the cap splits", + input: long(lineLimit+1) + "\n", + want: []string{long(lineLimit), "a"}, + more: []int{0}, + }, + { + name: "newline-free stream ending at EOF", + input: long(2*lineLimit + 10), + want: []string{long(lineLimit), long(lineLimit), long(10)}, + more: []int{0, 1}, + }, + { + name: "final chunk at the cap ends the line", + input: long(lineLimit) + cappedJSON + "\n", + want: []string{long(lineLimit), cappedJSON}, + more: []int{0}, + }, + { + name: "short lines around a long one are untouched", + input: "before\n" + long(lineLimit+5) + "\nafter\n", + want: []string{"before", long(lineLimit), long(5), "after"}, + more: []int{1}, + }, + { + name: "oversized JSON is logged as text chunks", + input: longJSON + "\n", + want: []string{longJSON[:lineLimit], longJSON[lineLimit:]}, + more: []int{0}, + }, + } + for _, text := range []string{"é", "界", "😀"} { + for offset := 1; offset < len(text); offset++ { + prefix := long(lineLimit - offset) + tests = append(tests, testCase{ + name: fmt.Sprintf("UTF-8 boundary %s byte %d", text, offset), + input: prefix + text + "\nafter\n", + want: []string{prefix, text, "after"}, + more: []int{0}, + }) + } + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if tt.field == "" { + tt.field = "message" + } + var buf bytes.Buffer + al := NewActorLogger(&buf, false) + al.WrapContainerLogs(strings.NewReader(tt.input), testAttribution, testContainer, "") + + var got []string + for i, rec := range bytes.Split(bytes.TrimSuffix(buf.Bytes(), []byte("\n")), []byte("\n")) { + var m map[string]any + if err := json.Unmarshal(rec, &m); err != nil { + t.Fatalf("record is not JSON: %v", err) + } + msg, ok := m[tt.field].(string) + if !ok { + t.Fatalf("record has no %s: %.100s", tt.field, rec) + } + assertLabels(t, labelGroup(t, al, m), identityLabels()) + partial, ok := m[logPartialKey] + if slices.Contains(tt.more, i) { + if partial != true { + t.Errorf("record %d: %s = %v, want true", i, logPartialKey, partial) + } + } else if ok { + t.Errorf("record %d: %s = %v, want field omitted", i, logPartialKey, partial) + } + got = append(got, msg) + } + if !slices.Equal(got, tt.want) { + t.Errorf("got %d messages with lengths %v, want %d with lengths %v", + len(got), lengths(got), len(tt.want), lengths(tt.want)) + } + }) + } +} + +func TestWrapContainerLogs_EmitsBeforeEOF(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + r, w := io.Pipe() + defer r.Close() + defer w.Close() + + var buf bytes.Buffer + al := NewActorLogger(&buf, false) + go al.WrapContainerLogs(r, testAttribution, testContainer, "") + + const half = maxLineBytes / 2 + first := strings.Repeat("a", maxLineBytes) + second := strings.Repeat("b", maxLineBytes) + tail := strings.Repeat("c", half) + for i, step := range []struct{ write, want string }{ + {first + second[:half], first}, + {second[half:] + tail, second}, + {"", tail}, // Close the pipe to flush the tail. + } { + if step.write == "" { + if err := w.Close(); err != nil { + t.Fatal(err) + } + } else if _, err := io.WriteString(w, step.write); err != nil { + t.Fatalf("write log line: %v", err) + } + synctest.Wait() + + var m map[string]any + if err := json.Unmarshal(buf.Bytes(), &m); err != nil { + t.Fatalf("step %d: want exactly one JSON record: %v", i, err) + } + buf.Reset() + if m["message"] != step.want { + t.Errorf("step %d: message differs from %d copies of %q", i, len(step.want), step.want[0]) + } + if partial, ok := m[logPartialKey]; step.write != "" { + if partial != true { + t.Errorf("step %d: %s = %v, want true", i, logPartialKey, partial) + } + } else if ok { + t.Errorf("at EOF: %s = %v, want field omitted", logPartialKey, partial) + } + } + }) +} + +func TestWrapContainerLogs_IOStream(t *testing.T) { + input := "plain text\n" + `{"msg":"structured log","` + logIostreamKey + `":"application"}` + "\n" + + strings.Repeat("a", maxLineBytes+1) + "\n" + for _, tt := range []struct { + name string + stream string + want string + }{ + {name: "stdout", stream: ateattr.LogIostreamStdout, want: "stdout"}, + {name: "stderr", stream: ateattr.LogIostreamStderr, want: "stderr"}, + {name: "combined"}, + } { + t.Run(tt.name, func(t *testing.T) { + var buf bytes.Buffer + al := NewActorLogger(&buf, false) + al.WrapContainerLogs(strings.NewReader(input), testAttribution, testContainer, tt.stream) + + records := bytes.Split(bytes.TrimSuffix(buf.Bytes(), []byte("\n")), []byte("\n")) + if len(records) != 4 { + t.Fatalf("got %d records, want 4", len(records)) + } + for i, rec := range records { + var m map[string]any + if err := json.Unmarshal(rec, &m); err != nil { + t.Fatalf("decode record %d: %v", i, err) + } + got, ok := m[logIostreamKey] + if tt.want == "" { + if ok { + t.Errorf("record %d: %s = %v, want absent", i, logIostreamKey, got) + } + } else if got != tt.want { + t.Errorf("record %d: %s = %v, want %q", i, logIostreamKey, got, tt.want) + } + assertLabels(t, labelGroup(t, al, m), identityLabels()) + } + }) + } +} + +func lengths(ss []string) []int { + n := make([]int, len(ss)) + for i, s := range ss { + n[i] = len(s) + } + return n +} + func TestEmitLifecycleLog(t *testing.T) { const ( traceID = "4bf92f3577b34da6a3ce929d0e0e4736" diff --git a/internal/apiconfig/loader_test.go b/internal/apiconfig/loader_test.go index 773489851a..04d6286602 100644 --- a/internal/apiconfig/loader_test.go +++ b/internal/apiconfig/loader_test.go @@ -22,14 +22,17 @@ import ( func TestParseTextProto(t *testing.T) { testCases := []struct { - name string - content string - wantErr bool + name string + content string + wantErr bool + wantIncludeDebugInfo bool }{ {name: "debug", content: `logging { level: "debug" }`}, {name: "info", content: `logging { level: "info" }`}, {name: "warn", content: `logging { level: "warn" }`}, {name: "error", content: `logging { level: "error" }`}, + {name: "include_error_debug_info true", content: "logging { level: \"info\" }\ninclude_error_debug_info: true", wantIncludeDebugInfo: true}, + {name: "include_error_debug_info false", content: "logging { level: \"info\" }\ninclude_error_debug_info: false", wantIncludeDebugInfo: false}, {name: "invalid level", content: `logging { level: "verbose" }`, wantErr: true}, {name: "missing level", content: ``, wantErr: true}, {name: "unknown field", content: "logging { level: \"info\" }\nfuture_field: true", wantErr: true}, @@ -37,10 +40,13 @@ func TestParseTextProto(t *testing.T) { for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { - _, err := ParseTextProto([]byte(tc.content)) + cfg, err := ParseTextProto([]byte(tc.content)) if gotErr := err != nil; gotErr != tc.wantErr { t.Errorf("ParseTextProto() error = %v, wantErr %v", err, tc.wantErr) } + if !tc.wantErr && cfg.GetIncludeErrorDebugInfo() != tc.wantIncludeDebugInfo { + t.Errorf("GetIncludeErrorDebugInfo() = %v, want %v", cfg.GetIncludeErrorDebugInfo(), tc.wantIncludeDebugInfo) + } }) } } diff --git a/internal/apierror/apierror.go b/internal/apierror/apierror.go index 15f95d566a..24035de48b 100644 --- a/internal/apierror/apierror.go +++ b/internal/apierror/apierror.go @@ -35,85 +35,125 @@ import ( "google.golang.org/grpc/status" ) -type apiError struct { - code codes.Code - err error +// Error is a server-chosen error carrying a gRPC status code, a client-facing +// message, and an optional internal cause. +type Error struct { + code codes.Code + err error + cause error +} + +// Error returns the client-facing message, with the cause appended when set so +// server logs record the full context. +func (e *Error) Error() string { + if e == nil { + return "" + } + var msg string + if e.err != nil { + msg = e.err.Error() + } + if e.cause != nil { + if msg == "" { + return e.cause.Error() + } + return fmt.Sprintf("%s: %v", msg, e.cause) + } + return msg } -func (e *apiError) Error() string { return e.err.Error() } +// Unwrap returns the formatted client-facing error. It deliberately does not +// unwrap cause so outer callers checking errors.Is against lower-layer sentinel +// errors do not reclassify an already-mapped apierror. +func (e *Error) Unwrap() error { + if e == nil { + return nil + } + return e.err +} -func (e *apiError) Unwrap() error { return e.err } +// WithCause returns a shallow copy of e with cause attached. The cause is +// included in Error() for server-side logging and kept out of the client-facing +// status message returned by FromError. +func (e *Error) WithCause(cause error) *Error { + if e == nil { + return nil + } + cp := *e + cp.cause = cause + return &cp +} -func newf(code codes.Code, format string, args ...any) error { - return &apiError{code: code, err: fmt.Errorf(format, args...)} +func newf(code codes.Code, format string, args ...any) *Error { + return &Error{code: code, err: fmt.Errorf(format, args...)} } // InvalidArgument reports a request that is malformed regardless of the // system's state. -func InvalidArgument(format string, args ...any) error { +func InvalidArgument(format string, args ...any) *Error { return newf(codes.InvalidArgument, format, args...) } // NotFound reports that a resource the request names does not exist. -func NotFound(format string, args ...any) error { +func NotFound(format string, args ...any) *Error { return newf(codes.NotFound, format, args...) } // AlreadyExists reports that a resource the request creates already exists. -func AlreadyExists(format string, args ...any) error { +func AlreadyExists(format string, args ...any) *Error { return newf(codes.AlreadyExists, format, args...) } // FailedPrecondition reports that the system is not in the state the request // requires. Retrying is pointless until that state changes. -func FailedPrecondition(format string, args ...any) error { +func FailedPrecondition(format string, args ...any) *Error { return newf(codes.FailedPrecondition, format, args...) } // Aborted reports a request that lost a concurrency conflict, such as a // version mismatch. Retrying from a fresh read can succeed. -func Aborted(format string, args ...any) error { +func Aborted(format string, args ...any) *Error { return newf(codes.Aborted, format, args...) } // PermissionDenied reports an authenticated caller that may not perform the // request. -func PermissionDenied(format string, args ...any) error { +func PermissionDenied(format string, args ...any) *Error { return newf(codes.PermissionDenied, format, args...) } // Unauthenticated reports a caller whose identity could not be established. -func Unauthenticated(format string, args ...any) error { +func Unauthenticated(format string, args ...any) *Error { return newf(codes.Unauthenticated, format, args...) } // ResourceExhausted reports that a quota or capacity limit refused the // request. -func ResourceExhausted(format string, args ...any) error { +func ResourceExhausted(format string, args ...any) *Error { return newf(codes.ResourceExhausted, format, args...) } // Unimplemented reports a request this server does not support. -func Unimplemented(format string, args ...any) error { +func Unimplemented(format string, args ...any) *Error { return newf(codes.Unimplemented, format, args...) } // Unavailable reports that the request was not acted on, or that the attempt // was rolled back so retrying it, here or elsewhere, is safe. Never use it for // a failure that leaves partial state behind. -func Unavailable(format string, args ...any) error { +func Unavailable(format string, args ...any) *Error { return newf(codes.Unavailable, format, args...) } // DataLoss reports unrecoverable loss or corruption of data. -func DataLoss(format string, args ...any) error { +func DataLoss(format string, args ...any) *Error { return newf(codes.DataLoss, format, args...) } // Internal reports a server-side failure with a message chosen for the // caller. A plain error also reaches the caller as codes.Internal, but with // whatever text it carries. -func Internal(format string, args ...any) error { +func Internal(format string, args ...any) *Error { return newf(codes.Internal, format, args...) } @@ -126,16 +166,20 @@ func Code(err error) codes.Code { } // FromError converts err to the status a server returns for it. The message -// is the apierror's own, without the context added by errors wrapping it. ok -// is false when err is neither an apierror nor a context error; the status is -// then codes.Internal with err's text, which the caller may reword. +// is the apierror's own, without the cause or context added by errors wrapping +// it. ok is false when err is neither an apierror nor a context error; the +// status is then codes.Internal with err's text, which the caller may reword. func FromError(err error) (s *status.Status, ok bool) { if err == nil { return nil, true } - var apiErr *apiError - if errors.As(err, &apiErr) { - return status.New(apiErr.code, apiErr.Error()), true + var apiErr *Error + if errors.As(err, &apiErr) && apiErr != nil { + var msg string + if apiErr.err != nil { + msg = apiErr.err.Error() + } + return status.New(apiErr.code, msg), true } if s := status.FromContextError(err); s.Code() != codes.Unknown { return s, true diff --git a/internal/apierror/apierror_test.go b/internal/apierror/apierror_test.go index a7ee8fef13..1cd26c953f 100644 --- a/internal/apierror/apierror_test.go +++ b/internal/apierror/apierror_test.go @@ -209,3 +209,117 @@ func TestNotAGRPCStatus(t *testing.T) { t.Errorf("status.FromError() = %v, %v, want Unknown, false", s.Code(), ok) } } + +func TestWithCause(t *testing.T) { + sentinel := errors.New("version mismatch in postgres") + fmtCause := errors.New("bad input") + + tests := []struct { + name string + err error + wantCode codes.Code + wantErr string + wantStatus string + wantTargets []error + notWantTargets []error + }{ + { + name: "cause included in Error and omitted from FromError and Unwrap", + err: Aborted("concurrent update conflict, please retry").WithCause(sentinel), + wantCode: codes.Aborted, + wantErr: "concurrent update conflict, please retry: version mismatch in postgres", + wantStatus: "concurrent update conflict, please retry", + notWantTargets: []error{sentinel}, + }, + { + name: "nil cause leaves Error unchanged", + err: NotFound("actor not found").WithCause(nil), + wantCode: codes.NotFound, + wantErr: "actor not found", + wantStatus: "actor not found", + }, + { + name: "formatted %w stays reachable while cause does not leak to errors.Is", + err: InvalidArgument("bad request: %w", fmtCause).WithCause(sentinel), + wantCode: codes.InvalidArgument, + wantErr: "bad request: bad input: version mismatch in postgres", + wantStatus: "bad request: bad input", + wantTargets: []error{fmtCause}, + notWantTargets: []error{sentinel}, + }, + { + name: "outermost apierror code and message win over apierror cause", + err: FailedPrecondition("cannot resume").WithCause(NotFound("worker missing")), + wantCode: codes.FailedPrecondition, + wantErr: "cannot resume: worker missing", + wantStatus: "cannot resume", + }, + { + name: "wrapped apierror with cause keeps only own message in FromError", + err: fmt.Errorf("step Load: %w", Aborted("conflict").WithCause(sentinel)), + wantCode: codes.Aborted, + wantErr: "step Load: conflict: version mismatch in postgres", + wantStatus: "conflict", + notWantTargets: []error{sentinel}, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := Code(tt.err); got != tt.wantCode { + t.Errorf("Code() = %v, want %v", got, tt.wantCode) + } + if got := tt.err.Error(); got != tt.wantErr { + t.Errorf("Error() = %q, want %q", got, tt.wantErr) + } + st, ok := FromError(tt.err) + if !ok { + t.Fatalf("FromError() ok = false, want true") + } + if st.Code() != tt.wantCode { + t.Errorf("FromError().Code() = %v, want %v", st.Code(), tt.wantCode) + } + if st.Message() != tt.wantStatus { + t.Errorf("FromError().Message() = %q, want %q", st.Message(), tt.wantStatus) + } + for _, target := range tt.wantTargets { + if !errors.Is(tt.err, target) { + t.Errorf("errors.Is(%v, %v) = false, want true", tt.err, target) + } + } + for _, target := range tt.notWantTargets { + if errors.Is(tt.err, target) { + t.Errorf("errors.Is(%v, %v) = true, want false", tt.err, target) + } + } + }) + } +} + +func TestWithCauseDoesNotMutateReceiver(t *testing.T) { + base := NotFound("actor not found") + withCause := base.WithCause(errors.New("db row missing")) + + if got := base.Error(); got != "actor not found" { + t.Errorf("base.Error() = %q, want %q", got, "actor not found") + } + if got := withCause.Error(); got != "actor not found: db row missing" { + t.Errorf("withCause.Error() = %q, want %q", got, "actor not found: db row missing") + } +} + +func TestTypedNilError(t *testing.T) { + var typedNil *Error + var err error = typedNil + + st, ok := FromError(err) + if ok || st.Code() != codes.Internal { + t.Errorf("FromError((*Error)(nil)) = (%v, %v), want (Internal, false)", st.Code(), ok) + } + if got := Code(err); got != codes.Internal { + t.Errorf("Code((*Error)(nil)) = %v, want Internal", got) + } + if got := typedNil.WithCause(errors.New("ignored")); got != nil { + t.Errorf("(*Error)(nil).WithCause() = %v, want nil", got) + } +} diff --git a/internal/apivalidationtest/doc.go b/internal/apivalidationtest/doc.go new file mode 100644 index 0000000000..657e1a5394 --- /dev/null +++ b/internal/apivalidationtest/doc.go @@ -0,0 +1,69 @@ +// Copyright 2026 The Agent Substrate 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 apivalidationtest tests the formats in .validation-extensions.yaml. +// Child applies each format as a field tag, and Parent applies each as a +// subfield tag on ChildWithoutTags. +// +// Kubernetes codegen tools required this to be in doc.go, no other name will +// work. +// +// +k8s:validation-gen=* +// +k8s:validation-gen-scheme-registry=nil +package apivalidationtest + +type Child struct { + // +k8s:optional + // +k8s:format=ate-singleton-name + SingletonName string `json:"singletonName"` + + // +k8s:optional + // +k8s:format=ate-http-probe-path + HTTPProbePath string `json:"httpProbePath"` + + // +k8s:optional + // +k8s:format=ate-env-var-name + EnvVarName string `json:"envVarName"` + + // +k8s:optional + // +k8s:format=ate-volume-storage-id + VolumeStorageID string `json:"volumeStorageID"` + + // +k8s:optional + // +k8s:format=ate-http-header-name + HTTPHeaderName string `json:"httpHeaderName"` + + // +k8s:optional + // +k8s:format=ate-http-header-value + HTTPHeaderValue string `json:"httpHeaderValue"` +} + +type ChildWithoutTags struct { + SingletonName string `json:"singletonName"` + HTTPProbePath string `json:"httpProbePath"` + EnvVarName string `json:"envVarName"` + VolumeStorageID string `json:"volumeStorageID"` + HTTPHeaderName string `json:"httpHeaderName"` + HTTPHeaderValue string `json:"httpHeaderValue"` +} + +type Parent struct { + // +k8s:subfield(singletonName)=+k8s:format=ate-singleton-name + // +k8s:subfield(httpProbePath)=+k8s:format=ate-http-probe-path + // +k8s:subfield(envVarName)=+k8s:format=ate-env-var-name + // +k8s:subfield(volumeStorageID)=+k8s:format=ate-volume-storage-id + // +k8s:subfield(httpHeaderName)=+k8s:format=ate-http-header-name + // +k8s:subfield(httpHeaderValue)=+k8s:format=ate-http-header-value + Child ChildWithoutTags `json:"child"` +} diff --git a/internal/apivalidationtest/validation_test.go b/internal/apivalidationtest/validation_test.go new file mode 100644 index 0000000000..5b0c4e723f --- /dev/null +++ b/internal/apivalidationtest/validation_test.go @@ -0,0 +1,263 @@ +// Copyright 2026 The Agent Substrate 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 apivalidationtest + +import ( + "context" + "fmt" + "strings" + "testing" + + "k8s.io/apimachinery/pkg/api/operation" + "k8s.io/apimachinery/pkg/util/validation/field" +) + +type formatCase struct { + name string + value string + valid bool +} + +type formatTest struct { + format string + field string + set func(*ChildWithoutTags, string) + cases []formatCase +} + +// sweep returns a case for each rune in [lo, hi], embedded as wrap(r). Each +// rune is valid if allowed reports true. +func sweep(lo, hi rune, wrap func(string) string, allowed func(rune) bool) []formatCase { + var cases []formatCase + for r := lo; r <= hi; r++ { + cases = append(cases, formatCase{ + name: fmt.Sprintf("sweep U+%04X", r), + value: wrap(string(r)), + valid: allowed(r), + }) + } + return cases +} + +func concat(lists ...[]formatCase) []formatCase { + var all []formatCase + for _, l := range lists { + all = append(all, l...) + } + return all +} + +func between(s string) func(string) string { + return func(c string) string { return s + c + s } +} + +func inSet(set string) func(rune) bool { + return func(r rune) bool { return strings.ContainsRune(set, r) } +} + +const ( + alnum = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789" + // RFC 3986 pchar, less pct-encoded, plus '/'. + pathChars = alnum + "-._~!$&'()*+,;=:@/" + // RFC 9110 tchar. + tchars = alnum + "!#$%&'*+-.^_`|~" +) + +var formatTests = []formatTest{{ + format: "ate-singleton-name", + field: "singletonName", + set: func(c *ChildWithoutTags, v string) { c.SingletonName = v }, + cases: []formatCase{ + {"empty", "", true}, + {"default", "default", true}, + {"capitalized", "Default", false}, + {"upper", "DEFAULT", false}, + {"leading space", " default", false}, + {"trailing space", "default ", false}, + {"trailing newline", "default\n", false}, + {"prefix", "defaults", false}, + {"suffix", "xdefault", false}, + {"truncated", "defaul", false}, + {"other", "other", false}, + {"repeated", "defaultdefault", false}, + }, +}, { + format: "ate-http-probe-path", + field: "httpProbePath", + set: func(c *ChildWithoutTags, v string) { c.HTTPProbePath = v }, + cases: concat([]formatCase{ + {"empty", "", true}, + {"root", "/", true}, + {"simple", "/healthz", true}, + {"nested", "/a/b/c", true}, + {"trailing slash", "/healthz/", true}, + {"double slash", "//a", true}, + {"dot segments", "/./../a", true}, + {"every path character", "/" + pathChars, true}, + {"percent escape", "/a%20b", true}, + {"percent escape lower hex", "/%7e", true}, + {"percent escape mixed hex", "/%aF", true}, + {"percent escape at end", "/a%2F", true}, + {"adjacent percent escapes", "/%25%25", true}, + {"no leading slash", "healthz", false}, + {"relative", "a/b", false}, + {"absolute URL", "http://host/healthz", false}, + {"query", "/healthz?x=1", false}, + {"empty query", "/healthz?", false}, + {"fragment", "/healthz#x", false}, + {"empty fragment", "/healthz#", false}, + {"truncated percent escape", "/a%2", false}, + {"bare percent", "/a%", false}, + {"percent non-hex", "/a%zz", false}, + {"percent half hex", "/a%g0", false}, + {"space", "/a b", false}, + {"non-ASCII", "/é", false}, + {"leading newline", "\n/a", false}, + {"trailing newline", "/a\n", false}, + }, + // '%' only appears in percent-escapes, tested above. + sweep(0, 0x7f, func(c string) string { + if c == "%" { + return "/a%25b" + } + return "/a" + c + "b" + }, func(r rune) bool { return r == '%' || inSet(pathChars)(r) }), + sweep(0x80, 0xff, between("/"), func(rune) bool { return false }), + ), +}, { + format: "ate-env-var-name", + field: "envVarName", + set: func(c *ChildWithoutTags, v string) { c.EnvVarName = v }, + cases: concat([]formatCase{ + {"empty", "", true}, + {"conventional", "HOME_DIR", true}, + {"lower", "home_dir", true}, + {"leading digit", "1ABC", true}, + {"printable punctuation", "a.b-c", true}, + {"space", "A B", true}, + {"only space", " ", true}, + {"equals sign", "A=B", false}, + {"only equals sign", "=", false}, + {"trailing equals sign", "A=", false}, + {"tab", "A\tB", false}, + {"trailing newline", "A\n", false}, + {"non-ASCII", "é", false}, + {"emoji", "\U0001F600", false}, + }, + sweep(0, 0x7f, between("A"), func(r rune) bool { return r >= ' ' && r <= '~' && r != '=' }), + sweep(0x80, 0xff, between("A"), func(rune) bool { return false }), + ), +}, { + format: "ate-volume-storage-id", + field: "volumeStorageID", + set: func(c *ChildWithoutTags, v string) { c.VolumeStorageID = v }, + cases: concat([]formatCase{ + {"empty", "", true}, + {"plain", "projects/p/disks/d-1", true}, + {"tab", "a\tb", true}, + {"newline", "a\nb", true}, + {"carriage return", "a\rb", true}, + {"non-breaking space", "a\u00a0b", true}, + {"CJK", "日本", true}, + {"emoji", "\U0001F600", true}, + {"NUL", "a\x00b", false}, + {"DEL", "a\x7fb", false}, + {"C1 control", "a\u0085b", false}, + {"leading control", "\x01a", false}, + {"trailing control", "a\x1f", false}, + // The regexp decodes an invalid UTF-8 byte as U+FFFD. + {"invalid UTF-8", "a\x85b", true}, + }, + sweep(0, 0xff, between("a"), func(r rune) bool { + return !(r <= 0x08 || r == 0x0b || r == 0x0c || (r >= 0x0e && r <= 0x1f) || (r >= 0x7f && r <= 0x9f)) + }), + ), +}, { + format: "ate-http-header-name", + field: "httpHeaderName", + set: func(c *ChildWithoutTags, v string) { c.HTTPHeaderName = v }, + cases: concat([]formatCase{ + {"empty", "", true}, + {"conventional", "Authorization", true}, + {"lower with punctuation", "x-custom_header", true}, + {"every token character", tchars, true}, + {"single character", "X", true}, + {"space", "bad header", false}, + {"colon", "bad:header", false}, + {"non-ASCII", "héader", false}, + {"leading space", " X", false}, + {"trailing newline", "X\n", false}, + }, + sweep(0, 0x7f, between("X"), inSet(tchars)), + sweep(0x80, 0xff, between("X"), func(rune) bool { return false }), + ), +}, { + format: "ate-http-header-value", + field: "httpHeaderValue", + set: func(c *ChildWithoutTags, v string) { c.HTTPHeaderValue = v }, + cases: concat([]formatCase{ + {"empty", "", true}, + {"bearer", "Bearer token", true}, + {"trailing space", "Bearer ", true}, + {"tab", "value\tvalue", true}, + {"obs-text", "\u0080\u0081", true}, + {"non-ASCII", "é", true}, + {"invalid UTF-8", "a\xffb", true}, + {"carriage return", "a\rb", false}, + {"newline", "a\nb", false}, + {"CRLF injection", "a\r\nX-Evil: 1", false}, + {"NUL", "a\x00b", false}, + {"unit separator", "a\x1fb", false}, + {"DEL", "a\x7fb", false}, + }, + sweep(0, 0xff, between("a"), func(r rune) bool { return r == '\t' || (r >= ' ' && r != 0x7f) }), + ), +}} + +func TestFormats(t *testing.T) { + ctx := context.Background() + create := operation.Operation{Type: operation.Create} + update := operation.Operation{Type: operation.Update} + matcher := field.ErrorMatcher{}.ByType().ByField().ByValue().ByOrigin() + + for _, ft := range formatTests { + for _, tc := range ft.cases { + t.Run(ft.format+"/"+tc.name, func(t *testing.T) { + var obj ChildWithoutTags + ft.set(&obj, tc.value) + + want := func(p *field.Path) field.ErrorList { + if tc.valid { + return nil + } + return field.ErrorList{ + field.Invalid(p.Child(ft.field), tc.value, "").WithOrigin("format=" + ft.format), + } + } + + child := Child(obj) + matcher.Test(t, want(nil), Validate_Child(ctx, create, nil, &child, nil)) + // Unchanged values are not revalidated. + oldChild := child + matcher.Test(t, nil, Validate_Child(ctx, update, nil, &child, &oldChild)) + + parent := Parent{Child: obj} + matcher.Test(t, want(field.NewPath("child")), Validate_Parent(ctx, create, nil, &parent, nil)) + oldParent := parent + matcher.Test(t, nil, Validate_Parent(ctx, update, nil, &parent, &oldParent)) + }) + } + } +} diff --git a/internal/apivalidationtest/zz_generated.validation.go b/internal/apivalidationtest/zz_generated.validation.go new file mode 100644 index 0000000000..713176cb18 --- /dev/null +++ b/internal/apivalidationtest/zz_generated.validation.go @@ -0,0 +1,316 @@ +//go:build !ignore_autogenerated +// +build !ignore_autogenerated + +// Copyright 2026 The Agent Substrate 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. + +// Code generated by validation-gen. DO NOT EDIT. + +package apivalidationtest + +import ( + context "context" + regexp "regexp" + + operation "k8s.io/apimachinery/pkg/api/operation" + safe "k8s.io/apimachinery/pkg/api/safe" + validate "k8s.io/apimachinery/pkg/api/validate" + field "k8s.io/apimachinery/pkg/util/validation/field" +) + +var formatPattern_ate_singleton_name = regexp.MustCompile("(^$|^default$)") +var formatPattern_ate_http_probe_path = regexp.MustCompile("(^$|^/([A-Za-z0-9\\-._~!$&'\\(\\)*+,;=:@/]|%[0-9A-Fa-f]{2})*$)") +var formatPattern_ate_env_var_name = regexp.MustCompile("(^$|^[ -<>-~]+$)") +var formatPattern_ate_volume_storage_id = regexp.MustCompile("^[^\\x00-\\x08\\x0B\\x0C\\x0E-\\x1F\\x7F-\\x9F]*$") +var formatPattern_ate_http_header_name = regexp.MustCompile("(^$|^[-A-Za-z0-9!#$%&'*+.^_`|~]+$)") +var formatPattern_ate_http_header_value = regexp.MustCompile("^[^\\x00-\\x08\\x0A-\\x1F\\x7F]*$") + +// Validate_Child validates an instance of Child according +// to declarative validation rules in the API schema. +func Validate_Child( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *Child) (errs field.ErrorList) { + + { // field Child.SingletonName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Child) *string { + return &oldObj.SingletonName + }) + errs = append(errs, fn(fldPath.Child("singletonName"), &obj.SingletonName, oldVal, oldObj != nil)...) + } + + { // field Child.HTTPProbePath + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_probe_path, "must be a valid HTTP path (RFC 3986)", "format=ate-http-probe-path"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Child) *string { + return &oldObj.HTTPProbePath + }) + errs = append(errs, fn(fldPath.Child("httpProbePath"), &obj.HTTPProbePath, oldVal, oldObj != nil)...) + } + + { // field Child.EnvVarName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_env_var_name, "may contain any printable ASCII character except '='", "format=ate-env-var-name"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Child) *string { + return &oldObj.EnvVarName + }) + errs = append(errs, fn(fldPath.Child("envVarName"), &obj.EnvVarName, oldVal, oldObj != nil)...) + } + + { // field Child.VolumeStorageID + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_volume_storage_id, "must not contain control characters", "format=ate-volume-storage-id"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Child) *string { + return &oldObj.VolumeStorageID + }) + errs = append(errs, fn(fldPath.Child("volumeStorageID"), &obj.VolumeStorageID, oldVal, oldObj != nil)...) + } + + { // field Child.HTTPHeaderName + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_header_name, "must be an HTTP header name", "format=ate-http-header-name"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Child) *string { + return &oldObj.HTTPHeaderName + }) + errs = append(errs, fn(fldPath.Child("httpHeaderName"), &obj.HTTPHeaderName, oldVal, oldObj != nil)...) + } + + { // field Child.HTTPHeaderValue + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_header_value, "must be a valid HTTP field value", "format=ate-http-header-value"); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Child) *string { + return &oldObj.HTTPHeaderValue + }) + errs = append(errs, fn(fldPath.Child("httpHeaderValue"), &obj.HTTPHeaderValue, oldVal, oldObj != nil)...) + } + + return errs +} + +// Validate_Parent validates an instance of Parent according +// to declarative validation rules in the API schema. +func Validate_Parent( + ctx context.Context, op operation.Operation, fldPath *field.Path, + obj, oldObj *Parent) (errs field.ErrorList) { + + { // field Parent.Child + fn := func( + fldPath *field.Path, + obj, oldObj *ChildWithoutTags, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + func() { // cohort = "singletonName" + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "singletonName", + func(o *ChildWithoutTags) *string { return &o.SingletonName }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_singleton_name, "must be \"default\"", "format=ate-singleton-name") + }); len(e) != 0 { + errs = append(errs, e...) + } + }() + func() { // cohort = "httpProbePath" + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "httpProbePath", + func(o *ChildWithoutTags) *string { return &o.HTTPProbePath }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_probe_path, "must be a valid HTTP path (RFC 3986)", "format=ate-http-probe-path") + }); len(e) != 0 { + errs = append(errs, e...) + } + }() + func() { // cohort = "envVarName" + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "envVarName", + func(o *ChildWithoutTags) *string { return &o.EnvVarName }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_env_var_name, "may contain any printable ASCII character except '='", "format=ate-env-var-name") + }); len(e) != 0 { + errs = append(errs, e...) + } + }() + func() { // cohort = "volumeStorageID" + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "volumeStorageID", + func(o *ChildWithoutTags) *string { return &o.VolumeStorageID }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_volume_storage_id, "must not contain control characters", "format=ate-volume-storage-id") + }); len(e) != 0 { + errs = append(errs, e...) + } + }() + func() { // cohort = "httpHeaderName" + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "httpHeaderName", + func(o *ChildWithoutTags) *string { return &o.HTTPHeaderName }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_header_name, "must be an HTTP header name", "format=ate-http-header-name") + }); len(e) != 0 { + errs = append(errs, e...) + } + }() + func() { // cohort = "httpHeaderValue" + if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "httpHeaderValue", + func(o *ChildWithoutTags) *string { return &o.HTTPHeaderValue }, validate.DirectEqual, + func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj *string) field.ErrorList { + return validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_header_value, "must be a valid HTTP field value", "format=ate-http-header-value") + }); len(e) != 0 { + errs = append(errs, e...) + } + }() + return + } + oldVal := safe.Field(oldObj, + func(oldObj *Parent) *ChildWithoutTags { + return &oldObj.Child + }) + errs = append(errs, fn(fldPath.Child("child"), &obj.Child, oldVal, oldObj != nil)...) + } + + return errs +} diff --git a/internal/ateapiauth/client.go b/internal/ateapiauth/client.go index 0faf439c69..aaf13daf50 100644 --- a/internal/ateapiauth/client.go +++ b/internal/ateapiauth/client.go @@ -19,18 +19,17 @@ import ( "crypto/x509" "errors" "fmt" + "time" "go.ate.dev/substrate/internal/credbundle" + "go.ate.dev/substrate/internal/grpclb" "google.golang.org/grpc" "google.golang.org/grpc/credentials" + "google.golang.org/grpc/keepalive" ) const DefaultServiceAccountCAFile = "/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" -// roundRobinServiceConfig spreads RPCs across every address the resolver -// returns. -const roundRobinServiceConfig = `{"loadBalancingConfig": [{"round_robin":{}}]}` - // ClientConfig configures how to dial the ateapi gRPC server with mutual TLS. // The credential bundle is re-read on every handshake so in-place // pod-certificate rotations are picked up. @@ -87,7 +86,14 @@ func DialOptions(cfg ClientConfig) ([]grpc.DialOption, error) { } opts := []grpc.DialOption{ - grpc.WithDefaultServiceConfig(roundRobinServiceConfig), + grpc.WithDefaultServiceConfig(grpclb.RoundRobinServiceConfig), + // Without pings, an RPC on a connection to a node that disappeared + // hangs until the kernel gives up, about 15 minutes by default. + // ate-api-server's keepalive EnforcementPolicy allows this rate. + grpc.WithKeepaliveParams(keepalive.ClientParameters{ + Time: time.Minute, + Timeout: 10 * time.Second, + }), } tlsCfg.GetClientCertificate = credbundle.ClientLoader(cfg.ClientCredBundle) diff --git a/internal/ateattr/ateattr.go b/internal/ateattr/ateattr.go index 5f55a8b2c3..2b8b900e09 100644 --- a/internal/ateattr/ateattr.go +++ b/internal/ateattr/ateattr.go @@ -24,6 +24,7 @@ import ( "go.opentelemetry.io/otel/attribute" + "go.ate.dev/substrate/internal/hardware" "go.ate.dev/substrate/internal/proto/ateletpb" "go.ate.dev/substrate/internal/resources" @@ -93,6 +94,9 @@ const ( // Only the components that have a relay to take or miss carry it. const OTLPRelayKey = attribute.Key("ate.otlp.relay") +// LogPartialKey marks a non-final chunk of a container log line. +const LogPartialKey = attribute.Key("ate.log.partial") + // ActorStateKey is log-only. It is bounded, but it is only ever recorded beside // actor identity, which no metric may carry. const ActorStateKey = attribute.Key("ate.actor.state") @@ -167,6 +171,20 @@ const ( RouterResumeKey = attribute.Key("ate.router.resume") RouterOutcomeKey = attribute.Key("ate.router.outcome") StatsSourceKey = attribute.Key("ate.stats.source") + DNSDecisionKey = attribute.Key("ate.dns.decision") +) + +// Worker identity, on the ate.worker.* resource instruments only. It breaks the +// small value set rule above on purpose, like k8s.node.name on the k8s node +// metrics: one value per live worker, so the series count follows the fleet and +// not the actors. A Worker is named after its pod UID, thus a new pod starts new +// series. The k8s keys are the registry's. Here they name the worker's pod and +// node, the values the worker's own telemetry has as resource attributes, so +// the two join. +const ( + WorkerNameKey = attribute.Key("ate.worker.name") + K8sPodNameKey = attribute.Key("k8s.pod.name") + K8sNodeNameKey = attribute.Key("k8s.node.name") ) // Keys of the actor usage record. Logs only: the measurements are unbounded and @@ -192,6 +210,28 @@ const ( // left. Logs only: it is only ever recorded beside actor identity. const SandboxOOMKillsKey = attribute.Key("ate.sandbox.oom_kills") +// Keys of the record a worker writes when a container of an actor exits. Logs +// only: they are only ever recorded beside actor identity. +// +// ActorExitedContainerNameKey selects the record. actorlog removes each ate.* +// key from a container's line, so only a worker can write this key. The name +// has its own key because ActorContainerNameKey marks a line that the container +// wrote. +// +// ProcessExitCodeKey is the OTel registry attribute, reused verbatim. A +// container can write it in its own lines. +const ( + ActorExitedContainerNameKey = attribute.Key("ate.actor.exited_container.name") + ProcessExitCodeKey = attribute.Key("process.exit.code") +) + +// LogIostreamKey identifies the container's stdout or stderr stream. +const ( + LogIostreamKey = attribute.Key("log.iostream") + LogIostreamStdout = "stdout" + LogIostreamStderr = "stderr" +) + // Values for StatsKindKey. An initial or final sample brackets an activation; a // periodic one is the timer's. const ( @@ -239,6 +279,13 @@ const ( ImageCacheOutcomeTimeout = "timeout" ) +// Values for DNSDecisionKey: whether the actor's egress policy let the sandbox +// DNS relay forward a query. The relay answers a denied query with NXDOMAIN. +const ( + DNSDecisionAllowed = "allowed" + DNSDecisionDenied = "denied" +) + // Values for FileCacheNameKey. const ( // FileCacheSandboxAsset is the sandbox asset cache: the runsc binaries, @@ -442,6 +489,19 @@ func WorkerPoolAttributes(namespace, name string) []attribute.KeyValue { } } +// WorkerMetricAttributes returns the labels of the per-worker instruments. The +// Kubernetes coordinates of a Worker are required and immutable, so they are +// always set. +func WorkerMetricAttributes(w *ateapi.Worker) []attribute.KeyValue { + attrs := []attribute.KeyValue{ + WorkerNameKey.String(w.GetMetadata().GetName()), + K8sPodNameKey.String(w.GetWorkerPod()), + K8sNodeNameKey.String(w.GetNodeName()), + SandboxClassAttribute(hardware.SandboxClass(w.GetStatus())), + } + return append(attrs, WorkerPoolAttributes(w.GetWorkerNamespace(), w.GetWorkerPool())...) +} + // ActorRefAttributes returns the subset knowable before the Actor record // resolves: only the (atespace, name) the request addresses. The uid and version // are server-assigned and unknown until the record loads, so they are omitted. diff --git a/internal/ateattr/ateattr_test.go b/internal/ateattr/ateattr_test.go index c04a7c01ec..afb707d8c4 100644 --- a/internal/ateattr/ateattr_test.go +++ b/internal/ateattr/ateattr_test.go @@ -150,14 +150,21 @@ func TestKeySpellings(t *testing.T) { {ActorNameKey, "ate.actor.name"}, {ActorUIDKey, "ate.actor.uid"}, {ActorContainerNameKey, "ate.actor.container.name"}, + {ActorExitedContainerNameKey, "ate.actor.exited_container.name"}, + {ProcessExitCodeKey, "process.exit.code"}, + {LogIostreamKey, "log.iostream"}, {TemplateNameKey, "ate.template.name"}, {TemplateAtespaceKey, "ate.template.atespace"}, {ActorVersionKey, "ate.actor.version"}, {ActorStateKey, "ate.actor.state"}, + {LogPartialKey, "ate.log.partial"}, {ActorOperationNameKey, "ate.actor.operation.name"}, {WorkerPoolNamespaceKey, "ate.workerpool.namespace"}, {WorkerPoolNameKey, "ate.workerpool.name"}, {WorkerStateKey, "ate.worker.state"}, + {WorkerNameKey, "ate.worker.name"}, + {K8sPodNameKey, "k8s.pod.name"}, + {K8sNodeNameKey, "k8s.node.name"}, {SandboxClassKey, "ate.sandbox.class"}, {SnapshotKindKey, "ate.snapshot.kind"}, {SnapshotFidelityKey, "ate.snapshot.fidelity"}, @@ -569,6 +576,43 @@ func TestWorkerPoolAttributes(t *testing.T) { }) } +func TestWorkerMetricAttributes(t *testing.T) { + const ( + name = "0b6c1f6e-6d0a-4c43-9a43-8f4a2b0e7d11" + pod = "pool-a-7c9d8" + node = "node-1" + ) + tests := []struct { + name string + classes []*ateapi.WorkerSandboxClass + want string + }{ + {"registered worker", []*ateapi.WorkerSandboxClass{{SandboxClass: "gvisor"}}, "gvisor"}, + // Cleared when a new worker process registers, until it reports again. + {"class not reported yet", nil, SandboxClassUnknown}, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + w := &ateapi.Worker{ + Metadata: &ateapi.ResourceMetadata{Name: name}, + WorkerNamespace: "ate-workers", + WorkerPool: "pool-a", + WorkerPod: pod, + NodeName: node, + Status: &ateapi.WorkerStatus{SandboxClasses: tt.classes}, + } + assertAttrs(t, toMap(WorkerMetricAttributes(w)), map[attribute.Key]any{ + WorkerNameKey: name, + K8sPodNameKey: pod, + K8sNodeNameKey: node, + WorkerPoolNamespaceKey: "ate-workers", + WorkerPoolNameKey: "pool-a", + SandboxClassKey: tt.want, + }) + }) + } +} + // TestSnapshotFidelityValue pins the enum-to-label mapping ateapi and atelet share. // An unmapped enum value must report unknown rather than its stringified form, // which would let a wire value widen the label set. diff --git a/internal/ateclient/builder.go b/internal/ateclient/builder.go index 6d209523ca..8d38dfbf19 100644 --- a/internal/ateclient/builder.go +++ b/internal/ateclient/builder.go @@ -26,6 +26,7 @@ import ( "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/internal/clustertrustbundle" + "go.ate.dev/substrate/internal/grpclb" "go.ate.dev/substrate/internal/installdefaults" "go.ate.dev/substrate/internal/portforward" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" @@ -113,13 +114,6 @@ type Client struct { } // Close closes the underlying gRPC connection and stops the port-forwarder. - -// roundRobinServiceConfig spreads RPCs over every address the resolver returns. -// ateapi is a headless Service, so that is one address per replica, and gRPC's -// default of pick_first would send an entire client's traffic to whichever one -// it connected to first. internal/ateapiauth dials with the same policy. -const roundRobinServiceConfig = `{"loadBalancingConfig": [{"round_robin":{}}]}` - func (c *Client) Close() { if c.tracerProvider != nil { // Best practice to ensure clean provider shutdown, even though we skip exporters for clients. @@ -192,7 +186,10 @@ func dialDirect(ctx context.Context, kubeconfigPath, k8sContext, endpoint, token var opts []grpc.DialOption opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(tlsCfg))) opts = append(opts, grpc.WithStatsHandler(otelgrpc.NewClientHandler())) - opts = append(opts, grpc.WithDefaultServiceConfig(roundRobinServiceConfig)) + // ateapi is a headless Service, so the resolver returns one address per + // replica, and pick_first would send all of this client's RPCs to one of + // them. internal/ateapiauth dials with the same policy. + opts = append(opts, grpc.WithDefaultServiceConfig(grpclb.RoundRobinServiceConfig)) tokenOpt, err := bearerTokenDialOption(ctx, clientset, tokenFile) if err != nil { return nil, err diff --git a/internal/ateinterceptors/ateinterceptors.go b/internal/ateinterceptors/ateinterceptors.go index bbd826849c..33d109a9a5 100644 --- a/internal/ateinterceptors/ateinterceptors.go +++ b/internal/ateinterceptors/ateinterceptors.go @@ -24,6 +24,7 @@ import ( "go.ate.dev/substrate/internal/apierror" "go.ate.dev/substrate/internal/principal" + "google.golang.org/genproto/googleapis/rpc/errdetails" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" @@ -35,15 +36,30 @@ import ( // so clients can report a latency unaffected by their own scheduling overhead. const ServerElapsedTrailer = "x-server-elapsed-us" -// ServerUnaryInterceptor is for ateapi. A handler's error reaches the caller -// with the code apierror gives it; any other error, including a status received -// from an upstream service, is Internal. +// NewServerUnaryInterceptor returns a unary interceptor for ateapi. A handler's +// error reaches the caller with the code apierror gives it; any other error, +// including a status received from an upstream service, is Internal. +// +// When includeDebugInfo is true, the full server-side error string is attached +// as a google.rpc.DebugInfo detail whenever it carries more context than the +// client-facing status message. // // Request and response bodies are logged as they are: redaction of debug_redact // fields happens in the shared slog handler (internal/contextlogging) that // serverboot's InitLogger and InitLoggerWithWriter install as the default logger // in every server, so it also covers protos logged anywhere else in the process. +func NewServerUnaryInterceptor(includeDebugInfo bool) grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + return serverUnaryInterceptor(ctx, req, info, handler, includeDebugInfo) + } +} + +// ServerUnaryInterceptor is NewServerUnaryInterceptor(false). func ServerUnaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + return serverUnaryInterceptor(ctx, req, info, handler, false) +} + +func serverUnaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler, includeDebugInfo bool) (any, error) { startTime := time.Now() resp, err := handler(ctx, req) @@ -69,6 +85,14 @@ func ServerUnaryInterceptor(ctx context.Context, req any, info *grpc.UnaryServer if err != nil { if st, ok := apierror.FromError(err); ok { + if includeDebugInfo && err.Error() != st.Message() { + withDetails, detailErr := st.WithDetails(&errdetails.DebugInfo{Detail: err.Error()}) + if detailErr != nil { + slog.WarnContext(ctx, "Failed to attach DebugInfo to gRPC status", slog.Any("err", detailErr)) + } else { + st = withDetails + } + } return nil, st.Err() } return nil, status.Errorf(codes.Internal, "internal server error: %v", err) diff --git a/internal/ateinterceptors/ateinterceptors_test.go b/internal/ateinterceptors/ateinterceptors_test.go index c0a0c7e0be..379d0ecc66 100644 --- a/internal/ateinterceptors/ateinterceptors_test.go +++ b/internal/ateinterceptors/ateinterceptors_test.go @@ -487,3 +487,110 @@ func TestServerUnaryInterceptorElidesListResponses(t *testing.T) { t.Fatalf("interceptor mutated the response returned to the client") } } + +func TestServerUnaryInterceptorDebugInfo(t *testing.T) { + cause := errors.New("row version 4 != 5") + + tests := []struct { + name string + includeDebugInfo bool + handlerErr error + wantCode codes.Code + wantMsg string + wantDebugDetail string + wantLogSubstr string + }{ + { + name: "cause logged but omitted from status when disabled", + includeDebugInfo: false, + handlerErr: apierror.Aborted("concurrent update conflict, please retry").WithCause(cause), + wantCode: codes.Aborted, + wantMsg: "concurrent update conflict, please retry", + wantDebugDetail: "", + wantLogSubstr: "row version 4 != 5", + }, + { + name: "cause attached as DebugInfo when enabled", + includeDebugInfo: true, + handlerErr: apierror.Aborted("concurrent update conflict, please retry").WithCause(cause), + wantCode: codes.Aborted, + wantMsg: "concurrent update conflict, please retry", + wantDebugDetail: "concurrent update conflict, please retry: row version 4 != 5", + wantLogSubstr: "row version 4 != 5", + }, + { + name: "wrapped apierror attached as DebugInfo when enabled", + includeDebugInfo: true, + handlerErr: fmt.Errorf("step Load: %w", apierror.NotFound("actor not found")), + wantCode: codes.NotFound, + wantMsg: "actor not found", + wantDebugDetail: "step Load: actor not found", + wantLogSubstr: "step Load: actor not found", + }, + { + name: "wrapped apierror omitted from DebugInfo when disabled", + includeDebugInfo: false, + handlerErr: fmt.Errorf("step Load: %w", apierror.NotFound("actor not found")), + wantCode: codes.NotFound, + wantMsg: "actor not found", + wantDebugDetail: "", + wantLogSubstr: "step Load: actor not found", + }, + { + name: "no redundant DebugInfo when full error equals status message", + includeDebugInfo: true, + handlerErr: apierror.NotFound("actor not found"), + wantCode: codes.NotFound, + wantMsg: "actor not found", + wantDebugDetail: "", + wantLogSubstr: "actor not found", + }, + { + name: "no redundant DebugInfo for wrapped context error", + includeDebugInfo: true, + handlerErr: fmt.Errorf("while loading actor: %w", context.DeadlineExceeded), + wantCode: codes.DeadlineExceeded, + wantMsg: "while loading actor: context deadline exceeded", + wantDebugDetail: "", + wantLogSubstr: "while loading actor: context deadline exceeded", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + logBuf := captureDefaultLog(t) + + interceptor := NewServerUnaryInterceptor(tt.includeDebugInfo) + _, err := interceptor(context.Background(), "request", &grpc.UnaryServerInfo{FullMethod: "/test.Service/Method"}, func(ctx context.Context, req any) (any, error) { + return nil, tt.handlerErr + }) + if err == nil { + t.Fatal("expected error, got nil") + } + + st, ok := status.FromError(err) + if !ok { + t.Fatalf("expected gRPC status error, got %v", err) + } + if st.Code() != tt.wantCode { + t.Errorf("code = %v, want %v", st.Code(), tt.wantCode) + } + if st.Message() != tt.wantMsg { + t.Errorf("message = %q, want %q", st.Message(), tt.wantMsg) + } + + var gotDebugDetail string + for _, d := range st.Details() { + if info, ok := d.(*epb.DebugInfo); ok { + gotDebugDetail = info.GetDetail() + } + } + if gotDebugDetail != tt.wantDebugDetail { + t.Errorf("DebugInfo.Detail = %q, want %q", gotDebugDetail, tt.wantDebugDetail) + } + if !strings.Contains(logBuf.String(), tt.wantLogSubstr) { + t.Errorf("RPC log %q does not contain %q", logBuf.String(), tt.wantLogSubstr) + } + }) + } +} diff --git a/internal/ateworker/actornet/net.go b/internal/ateworker/actornet/net.go index 6d794f5a36..57bbd0e95f 100644 --- a/internal/ateworker/actornet/net.go +++ b/internal/ateworker/actornet/net.go @@ -20,18 +20,21 @@ package actornet import ( "fmt" "net" + "net/netip" "github.com/google/nftables/expr" "github.com/vishvananda/netlink" + "golang.org/x/sys/unix" ) const ( - ActorVethName = "eth0" - ActorVethGateway = "169.254.17.1" - ActorVethIP = "169.254.17.2" + ActorVethName = "eth0" + ActorVethGateway = "169.254.17.1" + ActorVethIP = "169.254.17.2" + ActorVethIPv6Gateway = "fd00:169:254::1" + ActorVethIPv6 = "fd00:169:254::2" - // ActorHTTPUpstream is the in-sandbox HTTP endpoint atunnel proxies actor - // ingress to. + // ActorHTTPUpstream is the in-sandbox HTTP endpoint atunnel proxies actor ingress to. ActorHTTPUpstream = "http://" + ActorVethIP + ":80" // hostVethLocalAddress is the gateway interface's IP address and prefix length. @@ -41,14 +44,67 @@ const ( // ActorVethSubnet is the point-to-point /30 the actor veth lives on. ActorVethSubnet = "169.254.17.0/30" + // ActorVethIPv6Subnet is the point-to-point /126 the actor veth lives on. + ActorVethIPv6Subnet = "fd00:169:254::/126" ) var ( - HostVethAddr = MustParseAddr(hostVethLocalAddress) - ActorVethAddr = MustParseAddr(actorVethLocalAddress) - ActorVethGwIP = MustParseIP(ActorVethGateway) + HostVethAddr = MustParseAddr(hostVethLocalAddress) + ActorVethAddr = MustParseAddr(actorVethLocalAddress) + ActorVethGwIP = MustParseIP(ActorVethGateway) + HostVethIPv6Addr = mustParseIPv6VethAddr(ActorVethIPv6Gateway + "/126") + ActorVethIPv6Addr = mustParseIPv6VethAddr(ActorVethIPv6 + "/126") + ActorVethIPv6GwIP = MustParseIP(ActorVethIPv6Gateway) ) +func mustParseIPv6VethAddr(cidr string) *netlink.Addr { + addr := MustParseAddr(cidr) + // NODAD keeps each new veth address usable immediately instead of tentative for about one second. + addr.Flags = unix.IFA_F_NODAD + return addr +} + +// IPFamilies is IPv4 or IPv4 and IPv6. Actor networks are never IPv6-only. +type IPFamilies uint8 + +const ( + IPv4 IPFamilies = 1 << iota + IPv6 +) + +// IPFamiliesForPodIPs returns IPv4 and adds IPv6 when the gate and worker Pod allow it. +func IPFamiliesForPodIPs(podIPs []string, enableIPv6 bool) (IPFamilies, error) { + if len(podIPs) == 0 { + return 0, fmt.Errorf("worker Pod has no IP addresses") + } + families := IPv4 + for _, value := range podIPs { + ip, err := netip.ParseAddr(value) + if err != nil { + return 0, fmt.Errorf("invalid worker Pod IP %q: %w", value, err) + } + if enableIPv6 && ip.Is6() { + families |= IPv6 + } + } + return families, nil +} + +// Has reports whether families contains family. +func (f IPFamilies) Has(family IPFamilies) bool { return f&family != 0 } + +// String returns the canonical runtime compatibility value for families. +func (f IPFamilies) String() string { + switch f { + case IPv4: + return "ipv4" + case IPv4 | IPv6: + return "ipv4,ipv6" + default: + return fmt.Sprintf("invalid(%d)", f) + } +} + // MustParseAddr parses a CIDR string into a netlink.Addr, panicking on error. func MustParseAddr(cidr string) *netlink.Addr { a, err := netlink.ParseAddr(cidr) @@ -58,11 +114,11 @@ func MustParseAddr(cidr string) *netlink.Addr { return a } -// MustParseIP parses an IPv4 string into a net.IP, panicking on error. +// MustParseIP parses an IP address, panicking on error. func MustParseIP(s string) net.IP { - ip := net.ParseIP(s).To4() + ip := net.ParseIP(s) if ip == nil { - panic(fmt.Sprintf("parsing constant IPv4 %q", s)) + panic(fmt.Sprintf("parsing constant IP %q", s)) } return ip } diff --git a/internal/ateworker/actornet/net_test.go b/internal/ateworker/actornet/net_test.go new file mode 100644 index 0000000000..d10cdbe60b --- /dev/null +++ b/internal/ateworker/actornet/net_test.go @@ -0,0 +1,61 @@ +// Copyright 2026 The Agent Substrate 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 actornet + +import "testing" + +func TestIPFamiliesForPodIPs(t *testing.T) { + for _, tc := range []struct { + name string + podIPs []string + enableIPv6 bool + want IPFamilies + wantErr bool + }{ + {name: "IPv4 gate off", podIPs: []string{"10.0.0.2"}, want: IPv4}, + {name: "IPv4 gate on", podIPs: []string{"10.0.0.2"}, enableIPv6: true, want: IPv4}, + {name: "IPv6 gate off", podIPs: []string{"fd00::2"}, want: IPv4}, + {name: "IPv6 gate on", podIPs: []string{"fd00::2"}, enableIPv6: true, want: IPv4 | IPv6}, + {name: "dual stack gate off", podIPs: []string{"10.0.0.2", "fd00::2"}, want: IPv4}, + {name: "dual stack gate on", podIPs: []string{"10.0.0.2", "fd00::2"}, enableIPv6: true, want: IPv4 | IPv6}, + {name: "dual stack reversed gate on", podIPs: []string{"fd00::2", "10.0.0.2"}, enableIPv6: true, want: IPv4 | IPv6}, + {name: "missing", wantErr: true}, + {name: "invalid", podIPs: []string{"not-an-ip"}, enableIPv6: true, wantErr: true}, + } { + t.Run(tc.name, func(t *testing.T) { + got, err := IPFamiliesForPodIPs(tc.podIPs, tc.enableIPv6) + if (err != nil) != tc.wantErr { + t.Fatalf("IPFamiliesForPodIPs(%v) error = %v, wantErr %v", tc.podIPs, err, tc.wantErr) + } + if got != tc.want { + t.Errorf("IPFamiliesForPodIPs(%v) = %v, want %v", tc.podIPs, got, tc.want) + } + }) + } +} + +func TestIPFamiliesString(t *testing.T) { + for _, tc := range []struct { + families IPFamilies + value string + }{ + {IPv4, "ipv4"}, + {IPv4 | IPv6, "ipv4,ipv6"}, + } { + if got := tc.families.String(); got != tc.value { + t.Errorf("%v String() = %q, want %q", tc.families, got, tc.value) + } + } +} diff --git a/internal/ateworker/actornet/sandbox.go b/internal/ateworker/actornet/sandbox.go index b7ded2b337..607858e7d1 100644 --- a/internal/ateworker/actornet/sandbox.go +++ b/internal/ateworker/actornet/sandbox.go @@ -61,6 +61,8 @@ func (n *SandboxNetwork) holdsNetNS() bool { return n.RuntimeNetNS > 0 } // SandboxNetworkConfig describes one actor's private networking. type SandboxNetworkConfig struct { ActorUID string + // Families selects IPv4 or dual-stack networking. Zero defaults to IPv4. + Families IPFamilies // Veth separates gVisor's interfaces from the kernel-owned gateway. // MicroVMs use a tap in a single namespace instead. @@ -86,6 +88,15 @@ func SetupSandboxNetwork(ctx context.Context, cfg SandboxNetworkConfig) (_ *Sand if actorUID == "" { return nil, fmt.Errorf("actornet: actor UID is required") } + if cfg.Families == 0 { + cfg.Families = IPv4 + } + if cfg.Families&^(IPv4|IPv6) != 0 { + return nil, fmt.Errorf("actornet: invalid IP families %d", cfg.Families) + } + if !cfg.Families.Has(IPv4) { + return nil, fmt.Errorf("actornet: IPv4 actor networking is required") + } actorNSName := nodepath.ActorNetNSName(actorUID) actorNS, err := netns.CreateNamed(actorNSName) @@ -117,7 +128,7 @@ func SetupSandboxNetwork(ctx context.Context, cfg SandboxNetworkConfig) (_ *Sand }() atunnelNS = outer } - if err := installEgressRules(atunnelNS, cfg.EgressPort); err != nil { + if err := installEgressRules(atunnelNS, cfg.EgressPort, cfg.Families); err != nil { return nil, err } @@ -202,7 +213,7 @@ func setupVethPair(ctx context.Context, cfg SandboxNetworkConfig, actorNS netns. return err } veth := &netlink.Veth{ - LinkAttrs: netlink.LinkAttrs{Name: gatewayVethName}, + LinkAttrs: netlink.LinkAttrs{Name: gatewayVethName, NumTxQueues: 1, NumRxQueues: 1}, PeerName: ActorVethName, // Create the peer directly in the actor's namespace. Moving a // netdev across namespaces afterwards costs several times the @@ -218,7 +229,12 @@ func setupVethPair(ctx context.Context, cfg SandboxNetworkConfig, actorNS netns. return err } if err := netlink.AddrReplace(atSide, HostVethAddr); err != nil { - return fmt.Errorf("while assigning the atunnel-side address: %w", err) + return fmt.Errorf("while assigning the atunnel-side IPv4 address: %w", err) + } + if cfg.Families.Has(IPv6) { + if err := netlink.AddrReplace(atSide, HostVethIPv6Addr); err != nil { + return fmt.Errorf("while assigning the atunnel-side IPv6 address: %w", err) + } } if err := netlink.LinkSetUp(atSide); err != nil { return err @@ -235,15 +251,25 @@ func setupVethPair(ctx context.Context, cfg SandboxNetworkConfig, actorNS netns. return err } if err := netlink.AddrReplace(eth0, ActorVethAddr); err != nil { - return fmt.Errorf("while assigning the actor address: %w", err) + return fmt.Errorf("while assigning the actor IPv4 address: %w", err) + } + if cfg.Families.Has(IPv6) { + if err := netlink.AddrReplace(eth0, ActorVethIPv6Addr); err != nil { + return fmt.Errorf("while assigning the actor IPv6 address: %w", err) + } } if err := netlink.LinkSetUp(eth0); err != nil { return err } - return netlink.RouteReplace(&netlink.Route{ - LinkIndex: eth0.Attrs().Index, - Gw: ActorVethGwIP, - }) + if err := netlink.RouteReplace(&netlink.Route{LinkIndex: eth0.Attrs().Index, Gw: ActorVethGwIP}); err != nil { + return err + } + if cfg.Families.Has(IPv6) { + if err := netlink.RouteReplace(&netlink.Route{LinkIndex: eth0.Attrs().Index, Gw: ActorVethIPv6GwIP}); err != nil { + return err + } + } + return nil }); err != nil { return 0, err } @@ -258,14 +284,16 @@ func linkUp(name string) error { return netlink.LinkSetUp(link) } -// installEgressRules rejects link-local traffic before it reaches the egress PEP, -// then redirects other TCP egress to atunnel. The actor's own /30 is excluded -// from both rules so ingress replies and DNS reach their local sockets. -func installEgressRules(ns netns.Handle, egressPort uint16) error { +// installEgressRules filters both IP families, then redirects enabled families' +// TCP egress to atunnel. The actor's own subnet is excluded so ingress replies +// and DNS reach their local sockets. +func installEgressRules(ns netns.Handle, egressPort uint16, families IPFamilies) error { const ( - icmpNetUnreachable = 0 + icmpDestinationUnreachable = 0 icmpDestinationAdministrativelyProhibited = 13 icmpv6DestinationAdministrativelyProhibited = 1 + icmpv6NeighborSolicitation = 135 + icmpv6NeighborAdvertisement = 136 ) if egressPort == 0 { @@ -277,22 +305,20 @@ func installEgressRules(ns netns.Handle, egressPort uint16) error { } defer func() { _ = c.CloseLasting() }() - var ipv4Table *nftables.Table for _, family := range []struct { + flag IPFamilies tableFamily nftables.TableFamily name string addressLen uint32 dstOffset uint32 rejectCode uint8 - isPrefix func(netip.Prefix) bool + subnet netip.Prefix + linkLocal netip.Prefix }{ - {nftables.TableFamilyIPv4, "worker-actor", 4, 16, icmpDestinationAdministrativelyProhibited, func(prefix netip.Prefix) bool { return prefix.Addr().Is4() }}, - {nftables.TableFamilyIPv6, "worker-actor-v6", 16, 24, icmpv6DestinationAdministrativelyProhibited, func(prefix netip.Prefix) bool { return prefix.Addr().Is6() }}, + {IPv4, nftables.TableFamilyIPv4, "worker-actor", 4, 16, icmpDestinationAdministrativelyProhibited, netip.MustParsePrefix(ActorVethSubnet), netip.MustParsePrefix("169.254.0.0/16")}, + {IPv6, nftables.TableFamilyIPv6, "worker-actor-v6", 16, 24, icmpv6DestinationAdministrativelyProhibited, netip.MustParsePrefix(ActorVethIPv6Subnet), netip.MustParsePrefix("fe80::/10")}, } { table := c.AddTable(&nftables.Table{Family: family.tableFamily, Name: family.name}) - if family.tableFamily == nftables.TableFamilyIPv4 { - ipv4Table = table - } // Backs up the forwarding sysctls: nothing in this namespace is routed. dropPolicy := nftables.ChainPolicyDrop c.AddChain(&nftables.Chain{ @@ -304,86 +330,63 @@ func installEgressRules(ns netns.Handle, egressPort uint16) error { Name: "disallowed-egress", Table: table, Type: nftables.ChainTypeFilter, Hooknum: nftables.ChainHookPrerouting, Priority: nftables.ChainPriorityRaw, }) - if family.tableFamily == nftables.TableFamilyIPv4 { - c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: []expr.Any{ - &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: family.dstOffset, Len: family.addressLen}, - &expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: 4, Mask: actorSubnetMask, Xor: []byte{0, 0, 0, 0}}, - &expr.Cmp{Op: expr.CmpOpEq, Register: 1, Data: actorSubnetBase}, - &expr.Verdict{Kind: expr.VerdictAccept}, - }}) - } - for _, prefix := range linkLocalEgressCIDRRanges { - if !family.isPrefix(prefix) { - continue - } - mask := net.CIDRMask(prefix.Bits(), int(family.addressLen*8)) - address := prefix.Addr().AsSlice() - expressions := []expr.Any{ - &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: family.dstOffset, Len: family.addressLen}, + // Accept the actor subnet and IPv6 neighbor discovery, reject link-local + // and non-TCP traffic, then redirect other TCP traffic to atunnel. + subnetMask := net.CIDRMask(family.subnet.Bits(), int(family.addressLen*8)) + subnetBase := family.subnet.Addr().AsSlice() + c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: []expr.Any{ + &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: family.dstOffset, Len: family.addressLen}, + &expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: family.addressLen, Mask: subnetMask, Xor: make([]byte, family.addressLen)}, + &expr.Cmp{Op: expr.CmpOpEq, Register: 1, Data: subnetBase}, + &expr.Verdict{Kind: expr.VerdictAccept}, + }}) + if family.flag == IPv6 { + for _, messageType := range []byte{icmpv6NeighborSolicitation, icmpv6NeighborAdvertisement} { + expressions := append(l4ProtocolEqual(unix.IPPROTO_ICMPV6), + &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseTransportHeader, Offset: 0, Len: 1}, + &expr.Cmp{Op: expr.CmpOpEq, Register: 1, Data: []byte{messageType}}, + &expr.Verdict{Kind: expr.VerdictAccept}, + ) + c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: expressions}) } - expressions = append(expressions, - &expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: family.addressLen, Mask: mask, Xor: make([]byte, family.addressLen)}, - &expr.Cmp{Op: expr.CmpOpEq, Register: 1, Data: address}, - &expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: family.rejectCode}, - ) - c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: expressions}) } - if family.tableFamily == nftables.TableFamilyIPv4 { - // With forwarding off, the kernel drops unroutable packets silently instead - // of returning ICMP net unreachable. Reject non-TCP egress leaving the /30 - // so UDP or ping fails fast rather than waiting out a timeout. - expressions := append(l4ProtocolNotEqual(unix.IPPROTO_TCP), - &expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: icmpNetUnreachable}, - ) - c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: expressions}) + linkLocalMask := net.CIDRMask(family.linkLocal.Bits(), int(family.addressLen*8)) + c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: []expr.Any{ + &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: family.dstOffset, Len: family.addressLen}, + &expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: family.addressLen, Mask: linkLocalMask, Xor: make([]byte, family.addressLen)}, + &expr.Cmp{Op: expr.CmpOpEq, Register: 1, Data: family.linkLocal.Addr().AsSlice()}, + &expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: family.rejectCode}, + }}) + c.AddRule(&nftables.Rule{Table: table, Chain: filter, Exprs: append(l4ProtocolNotEqual(unix.IPPROTO_TCP), + &expr.Reject{Type: unix.NFT_REJECT_ICMP_UNREACH, Code: icmpDestinationUnreachable}, + )}) + + if !families.Has(family.flag) { + continue } + prerouting := c.AddChain(&nftables.Chain{ + Name: "prerouting", Table: table, Type: nftables.ChainTypeNAT, + Hooknum: nftables.ChainHookPrerouting, Priority: nftables.ChainPriorityNATDest, + }) + expressions := []expr.Any{ + &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: family.dstOffset, Len: family.addressLen}, + &expr.Bitwise{SourceRegister: 1, DestRegister: 1, Len: family.addressLen, Mask: subnetMask, Xor: make([]byte, family.addressLen)}, + &expr.Cmp{Op: expr.CmpOpNeq, Register: 1, Data: subnetBase}, + } + expressions = append(expressions, l4ProtocolEqual(unix.IPPROTO_TCP)...) + expressions = append(expressions, + &expr.Immediate{Register: 1, Data: binaryutil.BigEndian.PutUint16(egressPort)}, + &expr.Redir{RegisterProtoMin: 1}, + ) + c.AddRule(&nftables.Rule{Table: table, Chain: prerouting, Exprs: expressions}) } - prerouting := c.AddChain(&nftables.Chain{ - Name: "prerouting", Table: ipv4Table, Type: nftables.ChainTypeNAT, - Hooknum: nftables.ChainHookPrerouting, Priority: nftables.ChainPriorityNATDest, - }) - - // Offset of the destination address in an IPv4 header. - const ipv4HeaderDst = 16 - exprs := []expr.Any{ - &expr.Payload{DestRegister: 1, Base: expr.PayloadBaseNetworkHeader, Offset: ipv4HeaderDst, Len: 4}, - &expr.Bitwise{ - SourceRegister: 1, DestRegister: 1, Len: 4, - Mask: actorSubnetMask, Xor: []byte{0, 0, 0, 0}, - }, - &expr.Cmp{Op: expr.CmpOpNeq, Register: 1, Data: actorSubnetBase}, - } - exprs = append(exprs, l4ProtocolEqual(unix.IPPROTO_TCP)...) - exprs = append(exprs, - &expr.Immediate{Register: 1, Data: binaryutil.BigEndian.PutUint16(egressPort)}, - &expr.Redir{RegisterProtoMin: 1}, - ) - c.AddRule(&nftables.Rule{Table: ipv4Table, Chain: prerouting, Exprs: exprs}) - if err := c.Flush(); err != nil { return fmt.Errorf("while installing the actor egress redirect: %w", err) } return nil } -// linkLocalEgressCIDRRanges cover all IPv4 and IPv6 link-local space. The -// nftables chain accepts the actor's 169.254.17.0/30 first because that network -// carries actor ingress and DNS relay traffic. -var linkLocalEgressCIDRRanges = []netip.Prefix{ - netip.MustParsePrefix("169.254.0.0/16"), - netip.MustParsePrefix("fe80::/10"), -} - -// The actor subnet, in the form the nftables comparison takes. -var actorSubnetBase, actorSubnetMask = func() ([]byte, []byte) { - _, subnet, err := net.ParseCIDR(ActorVethSubnet) - if err != nil { - panic(fmt.Sprintf("parsing constant actor subnet %q: %v", ActorVethSubnet, err)) - } - return subnet.IP.To4(), subnet.Mask -}() - // gatewayVethName is the veth peer in the gateway namespace. const gatewayVethName = "atside" diff --git a/internal/ateworker/actornet/sandbox_atunnel_linux_test.go b/internal/ateworker/actornet/sandbox_atunnel_linux_test.go index fd4f54f47f..5c7cce4dd2 100644 --- a/internal/ateworker/actornet/sandbox_atunnel_linux_test.go +++ b/internal/ateworker/actornet/sandbox_atunnel_linux_test.go @@ -36,64 +36,75 @@ func TestSandboxEgressReachesAtunnelOnAnyPort(t *testing.T) { roottest.Require(t, "creates network namespaces") ctx := context.Background() const egressPort = 15001 + for _, tc := range []struct { + name string + uid string + families actornet.IPFamilies + destinations []string + }{ + {"IPv4", "66666666-6666-6666-6666-666666666664", actornet.IPv4, []string{"93.184.216.34:443", "93.184.216.34:8080", "93.184.216.34:9999"}}, + {"dual stack", "66666666-6666-6666-6666-666666666666", actornet.IPv4 | actornet.IPv6, []string{"93.184.216.34:443", "[2001:db8::1]:8080", "93.184.216.34:9999"}}, + } { + t.Run(tc.name, func(t *testing.T) { + n, err := actornet.SetupSandboxNetwork(ctx, actornet.SandboxNetworkConfig{ + ActorUID: tc.uid, Veth: true, EgressPort: egressPort, Families: tc.families, + }) + if err != nil { + t.Fatalf("SetupSandboxNetwork: %v", err) + } + t.Cleanup(func() { actornet.CleanupSandboxNetwork(n) }) - n, err := actornet.SetupSandboxNetwork(ctx, actornet.SandboxNetworkConfig{ - ActorUID: "66666666-6666-6666-6666-666666666666", Veth: true, EgressPort: egressPort, - }) - if err != nil { - t.Fatalf("SetupSandboxNetwork: %v", err) - } - t.Cleanup(func() { actornet.CleanupSandboxNetwork(n) }) - - listeners, err := netns.Listen(ctx, n.GatewayNetNS, []uint16{egressPort}) - if err != nil { - t.Fatalf("netns.Listen: %v", err) - } - defer listeners[0].Close() - - type capture struct{ destination, payload string } - got := make(chan capture, 1) - accept := func() { - c, err := listeners[0].Accept() - if err != nil { - return - } - defer c.Close() - dst, err := linuxsys.TCPOriginalDestination(c) - if err != nil { - t.Errorf("TCPOriginalDestination: %v", err) - return - } - buf := make([]byte, len("hello")) - io.ReadFull(c, buf) - got <- capture{destination: dst, payload: string(buf)} - } - go accept() - - for _, want := range []string{"93.184.216.34:443", "93.184.216.34:8080", "93.184.216.34:9999"} { - if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { - c, err := net.Dial("tcp", want) + listeners, err := netns.Listen(ctx, n.GatewayNetNS, []uint16{egressPort}) if err != nil { - return err + t.Fatalf("netns.Listen: %v", err) } - defer c.Close() - _, err = io.WriteString(c, "hello") - return err - }); err != nil { - t.Fatalf("sandbox egress dial to %s: %v", want, err) - } - select { - case c := <-got: - if c.destination != want { - t.Errorf("atunnel saw destination %q, want %q", c.destination, want) + defer listeners[0].Close() + + type capture struct{ destination, payload string } + got := make(chan capture, 1) + accept := func() { + c, err := listeners[0].Accept() + if err != nil { + return + } + defer c.Close() + dst, err := linuxsys.TCPOriginalDestination(c) + if err != nil { + t.Errorf("TCPOriginalDestination: %v", err) + return + } + buf := make([]byte, len("hello")) + io.ReadFull(c, buf) + got <- capture{destination: dst, payload: string(buf)} } - if c.payload != "hello" { - t.Errorf("atunnel read %q, want %q", c.payload, "hello") + go accept() + + for _, want := range tc.destinations { + if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { + c, err := net.Dial("tcp", want) + if err != nil { + return err + } + defer c.Close() + _, err = io.WriteString(c, "hello") + return err + }); err != nil { + t.Fatalf("sandbox egress dial to %s: %v", want, err) + } + select { + case c := <-got: + if c.destination != want { + t.Errorf("atunnel saw destination %q, want %q", c.destination, want) + } + if c.payload != "hello" { + t.Errorf("atunnel read %q, want %q", c.payload, "hello") + } + case <-time.After(10 * time.Second): + t.Fatalf("the sandbox's connection to %s never reached atunnel", want) + } + go accept() } - case <-time.After(10 * time.Second): - t.Fatalf("the sandbox's connection to %s never reached atunnel", want) - } - go accept() + }) } } diff --git a/internal/ateworker/actornet/sandbox_linux_test.go b/internal/ateworker/actornet/sandbox_linux_test.go index 1c5af924d3..5832e444d7 100644 --- a/internal/ateworker/actornet/sandbox_linux_test.go +++ b/internal/ateworker/actornet/sandbox_linux_test.go @@ -32,11 +32,14 @@ import ( "time" "github.com/google/nftables" + "github.com/google/nftables/expr" "github.com/vishvananda/netlink" "go.ate.dev/substrate/internal/nodepath" + "golang.org/x/sys/unix" "go.ate.dev/substrate/internal/netns" "go.ate.dev/substrate/internal/roottest" + "go.ate.dev/substrate/internal/testgolden" ) const testEgressPort = 15001 @@ -146,6 +149,96 @@ func TestSetupSandboxNetwork(t *testing.T) { } } +func TestSetupSandboxNetworkRejectsIPv6Only(t *testing.T) { + _, err := SetupSandboxNetwork(context.Background(), SandboxNetworkConfig{ + ActorUID: "ipv6-only", EgressPort: testEgressPort, Families: IPv6, + }) + if err == nil || !strings.Contains(err.Error(), "IPv4 actor networking is required") { + t.Fatalf("SetupSandboxNetwork() error = %v, want IPv4 requirement", err) + } +} + +func TestSetupSandboxNetworkUsesSelectedFamilies(t *testing.T) { + roottest.Require(t, "creates network namespaces") + ctx := context.Background() + for _, tc := range []struct { + name string + uid string + families IPFamilies + want4 bool + want6 bool + }{ + {"IPv4", "14141414-1414-1414-1414-141414141414", IPv4, true, false}, + {"dual stack", "46464646-4646-4646-4646-464646464646", IPv4 | IPv6, true, true}, + } { + t.Run(tc.name, func(t *testing.T) { + n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ + ActorUID: tc.uid, Veth: true, EgressPort: testEgressPort, Families: tc.families, + }) + if err != nil { + t.Fatalf("SetupSandboxNetwork: %v", err) + } + t.Cleanup(func() { CleanupSandboxNetwork(n) }) + + if err := netns.Do(ctx, n.RuntimeNetNS, func(context.Context) error { + link, err := netlink.LinkByName(ActorVethName) + if err != nil { + return err + } + addrs, err := netlink.AddrList(link, netlink.FAMILY_ALL) + if err != nil { + return err + } + got4, got6 := false, false + for _, addr := range addrs { + if addr.IP.To4() != nil { + if addr.IP.String() == ActorVethIP { + got4 = true + } + continue + } + if addr.IP.String() == ActorVethIPv6 { + got6 = true + if addr.Flags&unix.IFA_F_TENTATIVE != 0 { + t.Error("actor IPv6 address is tentative") + } + } + } + if got4 != tc.want4 || got6 != tc.want6 { + t.Errorf("actor addresses include IPv4=%v IPv6=%v, want IPv4=%v IPv6=%v", got4, got6, tc.want4, tc.want6) + } + routes, err := netlink.RouteList(link, netlink.FAMILY_ALL) + if err != nil { + return err + } + default4, default6 := false, false + for _, route := range routes { + if route.Gw == nil { + continue + } + if route.Dst != nil { + ones, _ := route.Dst.Mask.Size() + if ones != 0 { + continue + } + } + if route.Gw.To4() != nil { + default4 = true + } else { + default6 = true + } + } + if default4 != tc.want4 || default6 != tc.want6 { + t.Errorf("default routes include IPv4=%v IPv6=%v, want IPv4=%v IPv6=%v", default4, default6, tc.want4, tc.want6) + } + return nil + }); err != nil { + t.Fatalf("inspecting actor network: %v", err) + } + }) + } +} + func TestActorEgressIsFailClosedWithoutAtunnel(t *testing.T) { roottest.Require(t, "creates network namespaces") ctx := context.Background() @@ -423,7 +516,7 @@ func TestSandboxNamespacesDoNotForward(t *testing.T) { {"tap", "dddddddd-0000-0000-0000-00000000000d", false}, } { t.Run(tc.name, func(t *testing.T) { - n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: tc.uid, Veth: tc.veth, EgressPort: testEgressPort}) + n, err := SetupSandboxNetwork(ctx, SandboxNetworkConfig{ActorUID: tc.uid, Veth: tc.veth, EgressPort: testEgressPort, Families: IPv4}) if err != nil { t.Fatalf("SetupSandboxNetwork: %v", err) } @@ -458,35 +551,125 @@ func TestSandboxNamespacesDoNotForward(t *testing.T) { t.Fatal(err) } dropping := map[nftables.TableFamily]bool{} - var foundDisallowedEgress bool + filtering := map[nftables.TableFamily]bool{} + redirecting := map[nftables.TableFamily]bool{} for _, ch := range chains { if ch.Hooknum != nil && *ch.Hooknum == *nftables.ChainHookForward && ch.Policy != nil && *ch.Policy == nftables.ChainPolicyDrop { dropping[ch.Table.Family] = true } - if ch.Table.Family == nftables.TableFamilyIPv4 && ch.Name == "disallowed-egress" { - foundDisallowedEgress = true - rules, err := c.GetRules(ch.Table, ch) - if err != nil { - t.Fatalf("getting disallowed-egress rules: %v", err) - } - if len(rules) != 3 { - t.Errorf("disallowed-egress has %d rules, want 3", len(rules)) - } - } + filtering[ch.Table.Family] = filtering[ch.Table.Family] || ch.Name == "disallowed-egress" + redirecting[ch.Table.Family] = redirecting[ch.Table.Family] || ch.Name == "prerouting" } for _, family := range []nftables.TableFamily{nftables.TableFamilyIPv4, nftables.TableFamilyIPv6} { if !dropping[family] { t.Errorf("no forward-hook chain with a drop policy for family %v", family) } + if !filtering[family] { + t.Errorf("no disallowed-egress chain for family %v", family) + } + } + if !redirecting[nftables.TableFamilyIPv4] { + t.Error("no IPv4 egress redirect") + } + if redirecting[nftables.TableFamilyIPv6] { + t.Error("IPv6 egress redirect installed on an IPv4-only worker") } - if !foundDisallowedEgress { - t.Error("no disallowed-egress chain found in IPv4 table") + }) + } +} + +func TestEgressRules(t *testing.T) { + roottest.Require(t, "creates network namespaces") + n, err := SetupSandboxNetwork(context.Background(), SandboxNetworkConfig{ + ActorUID: "eeeeeeee-1111-1111-1111-111111111111", EgressPort: testEgressPort, Families: IPv4 | IPv6, + }) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { CleanupSandboxNetwork(n) }) + + c, err := nftables.New(nftables.WithNetNSFd(int(n.GatewayNetNS))) + if err != nil { + t.Fatal(err) + } + defer func() { _ = c.CloseLasting() }() + + for _, tc := range []struct { + name string + table *nftables.Table + }{ + {name: "ipv4", table: &nftables.Table{Family: nftables.TableFamilyIPv4, Name: "worker-actor"}}, + {name: "ipv6", table: &nftables.Table{Family: nftables.TableFamilyIPv6, Name: "worker-actor-v6"}}, + } { + t.Run(tc.name, func(t *testing.T) { + var got strings.Builder + for _, chainName := range []string{"disallowed-egress", "prerouting"} { + rules, err := c.GetRules(tc.table, &nftables.Chain{Table: tc.table, Name: chainName}) + if err != nil { + t.Fatalf("getting %s/%s rules: %v", tc.table.Name, chainName, err) + } + for _, rule := range rules { + fmt.Fprintf(&got, "%s/%s: %s\n", tc.table.Name, chainName, nftRuleString(rule)) + } } + + testgolden.Check(t, "egress-rules-"+tc.name+".golden", []byte(got.String())) }) } } +// nftRuleString returns a stable test-only description of nftables expressions, +// such as "payload network 16:4 -> r1; cmp r1 == a9fe1100". +func nftRuleString(rule *nftables.Rule) string { + parts := make([]string, 0, len(rule.Exprs)) + for _, expression := range rule.Exprs { + switch e := expression.(type) { + case *expr.Payload: + base := fmt.Sprint(e.Base) + switch e.Base { + case expr.PayloadBaseNetworkHeader: + base = "network" + case expr.PayloadBaseTransportHeader: + base = "transport" + } + parts = append(parts, fmt.Sprintf("payload %s %d:%d -> r%d", base, e.Offset, e.Len, e.DestRegister)) + case *expr.Bitwise: + parts = append(parts, fmt.Sprintf("bitwise r%d len %d mask %x xor %x -> r%d", e.SourceRegister, e.Len, e.Mask, e.Xor, e.DestRegister)) + case *expr.Meta: + key := fmt.Sprint(e.Key) + if e.Key == expr.MetaKeyL4PROTO { + key = "l4proto" + } + parts = append(parts, fmt.Sprintf("meta %s -> r%d", key, e.Register)) + case *expr.Cmp: + op := fmt.Sprint(e.Op) + switch e.Op { + case expr.CmpOpEq: + op = "==" + case expr.CmpOpNeq: + op = "!=" + } + parts = append(parts, fmt.Sprintf("cmp r%d %s %x", e.Register, op, e.Data)) + case *expr.Verdict: + verdict := fmt.Sprint(e.Kind) + if e.Kind == expr.VerdictAccept { + verdict = "accept" + } + parts = append(parts, "verdict "+verdict) + case *expr.Reject: + parts = append(parts, fmt.Sprintf("reject type %d code %d", e.Type, e.Code)) + case *expr.Immediate: + parts = append(parts, fmt.Sprintf("immediate %x -> r%d", e.Data, e.Register)) + case *expr.Redir: + parts = append(parts, fmt.Sprintf("redirect port r%d", e.RegisterProtoMin)) + default: + parts = append(parts, fmt.Sprintf("%T", expression)) + } + } + return strings.Join(parts, "; ") +} + // A new namespace copies conf/all and conf/default from the node, and a link // copies conf/default when it is created. Both shapes end up with the pinned // values on every link they add. diff --git a/internal/ateworker/actornet/testdata/egress-rules-ipv4.golden b/internal/ateworker/actornet/testdata/egress-rules-ipv4.golden new file mode 100644 index 0000000000..9fcbbac736 --- /dev/null +++ b/internal/ateworker/actornet/testdata/egress-rules-ipv4.golden @@ -0,0 +1,4 @@ +worker-actor/disallowed-egress: payload network 16:4 -> r1; bitwise r1 len 4 mask fffffffc xor 00000000 -> r1; cmp r1 == a9fe1100; verdict accept +worker-actor/disallowed-egress: payload network 16:4 -> r1; bitwise r1 len 4 mask ffff0000 xor 00000000 -> r1; cmp r1 == a9fe0000; reject type 0 code 13 +worker-actor/disallowed-egress: meta l4proto -> r1; cmp r1 != 06; reject type 0 code 0 +worker-actor/prerouting: payload network 16:4 -> r1; bitwise r1 len 4 mask fffffffc xor 00000000 -> r1; cmp r1 != a9fe1100; meta l4proto -> r1; cmp r1 == 06; immediate 3a99 -> r1; redirect port r1 diff --git a/internal/ateworker/actornet/testdata/egress-rules-ipv6.golden b/internal/ateworker/actornet/testdata/egress-rules-ipv6.golden new file mode 100644 index 0000000000..e1db9bcca8 --- /dev/null +++ b/internal/ateworker/actornet/testdata/egress-rules-ipv6.golden @@ -0,0 +1,6 @@ +worker-actor-v6/disallowed-egress: payload network 24:16 -> r1; bitwise r1 len 16 mask fffffffffffffffffffffffffffffffc xor 00000000000000000000000000000000 -> r1; cmp r1 == fd000169025400000000000000000000; verdict accept +worker-actor-v6/disallowed-egress: meta l4proto -> r1; cmp r1 == 3a; payload transport 0:1 -> r1; cmp r1 == 87; verdict accept +worker-actor-v6/disallowed-egress: meta l4proto -> r1; cmp r1 == 3a; payload transport 0:1 -> r1; cmp r1 == 88; verdict accept +worker-actor-v6/disallowed-egress: payload network 24:16 -> r1; bitwise r1 len 16 mask ffc00000000000000000000000000000 xor 00000000000000000000000000000000 -> r1; cmp r1 == fe800000000000000000000000000000; reject type 0 code 1 +worker-actor-v6/disallowed-egress: meta l4proto -> r1; cmp r1 != 06; reject type 0 code 0 +worker-actor-v6/prerouting: payload network 24:16 -> r1; bitwise r1 len 16 mask fffffffffffffffffffffffffffffffc xor 00000000000000000000000000000000 -> r1; cmp r1 != fd000169025400000000000000000000; meta l4proto -> r1; cmp r1 == 06; immediate 3a99 -> r1; redirect port r1 diff --git a/internal/ateworker/memborrow/memborrow.go b/internal/ateworker/memborrow/memborrow.go index bb232c5ad2..5bb28c9a24 100644 --- a/internal/ateworker/memborrow/memborrow.go +++ b/internal/ateworker/memborrow/memborrow.go @@ -42,8 +42,13 @@ type Ledger struct { mu sync.Mutex bytes int64 + // waiters is the number of Wait calls currently blocked on returned. + waiters int // returned is closed and replaced whenever bytes drops returned chan struct{} + // waiting is closed when Wait blocks a new actor, waking sleeping + // background writers so they start flushing right away. + waiting chan struct{} } func (l *Ledger) podMemory() (limit, unreclaimable int64, err error) { @@ -102,6 +107,42 @@ func (l *Ledger) Return(n int64) { l.returned = make(chan struct{}) } +// Tight reports whether a snapshot whose whole write was borrowed should flush +// to disk now instead of staying in page cache. Without a pod memory limit it +// returns false and lets the kernel flush lazily. When it returns false, the +// returned channel is closed if Wait blocks an incoming actor so the caller +// can wake up and re-check immediately. +func (l *Ledger) Tight() (bool, <-chan struct{}) { + if l == nil { + return true, nil + } + limit, unreclaimable, err := l.podMemory() + if err != nil { + // Assume tight if cgroup stats fail: flushing early only costs disk + // bandwidth, while skipping a needed flush can OOM the pod. + return true, nil + } + l.mu.Lock() + defer l.mu.Unlock() + if l.waiters > 0 { + // Flush while a placement is blocked in Wait, even if unbooked rose since. + return true, nil + } + if limit == 0 { + return false, nil + } + // Flush once unbooked memory left after active loans drops to 1/3 of the + // pod limit, or free pod memory drops below margin (l.bytes and + // unreclaimable already include this snapshot). + if l.Unbooked(limit)-l.bytes <= limit/3 || limit-unreclaimable < margin { + return true, nil + } + if l.waiting == nil { + l.waiting = make(chan struct{}) + } + return false, l.waiting +} + // Wait holds a newly hosted actor, already counted by Unbooked, until what is // borrowed fits in what is still unbooked, so it doesn't grow into dirty page // cache. @@ -110,22 +151,38 @@ func (l *Ledger) Wait(ctx context.Context) error { return nil } logged := false + waiting := false for { l.mu.Lock() if l.bytes == 0 { + if waiting { + l.waiters-- + } l.mu.Unlock() return nil } limit, _, err := l.podMemory() if err != nil || limit == 0 || l.bytes <= l.Unbooked(limit) { + if waiting { + l.waiters-- + } l.mu.Unlock() return nil } + if !waiting { + l.waiters++ + waiting = true + } if l.returned == nil { l.returned = make(chan struct{}) } returned := l.returned borrowed := l.bytes + // Wake sleeping background writers so they flush borrowed pages right away. + if l.waiting != nil { + close(l.waiting) + l.waiting = nil + } l.mu.Unlock() if !logged { slog.InfoContext(ctx, "Waiting for snapshot writeback before booting", slog.Int64("borrowedBytes", borrowed)) @@ -134,6 +191,9 @@ func (l *Ledger) Wait(ctx context.Context) error { select { case <-returned: case <-ctx.Done(): + l.mu.Lock() + l.waiters-- + l.mu.Unlock() return fmt.Errorf("while waiting for snapshot writeback: %w", ctx.Err()) } } diff --git a/internal/ateworker/memborrow/memborrow_test.go b/internal/ateworker/memborrow/memborrow_test.go index 891b96e65a..f3195c0ad1 100644 --- a/internal/ateworker/memborrow/memborrow_test.go +++ b/internal/ateworker/memborrow/memborrow_test.go @@ -18,6 +18,7 @@ package memborrow import ( "context" + "errors" "sync/atomic" "testing" "time" @@ -82,6 +83,195 @@ func TestTakeWithoutPodLimit(t *testing.T) { if err := l.Wait(context.Background()); err != nil { t.Errorf("Wait() without a pod limit = %v", err) } + if tight, _ := l.Tight(); tight { + t.Error("Tight() without a pod limit = true, want false") + } +} + +func TestTight(t *testing.T) { + const limit = 4 << 30 + for _, tc := range []struct { + name string + // current and borrowed already include this snapshot's dirty pages and loan. + current, unbooked, borrowed int64 + want bool + }{ + {name: "room to spare", current: 2 << 30, unbooked: 3 << 30, borrowed: 1 << 30, want: false}, + {name: "more than a third unbooked", current: 2 << 30, unbooked: 2 << 30, borrowed: 512 << 20, want: false}, + {name: "exactly a third unbooked", current: 2 << 30, unbooked: 1<<30 + limit/3, borrowed: 1 << 30, want: true}, + {name: "a placement booked into the loan", current: 2 << 30, unbooked: 512 << 20, borrowed: 1 << 30, want: true}, + {name: "short of free memory", current: limit - margin + 1, unbooked: 3 << 30, borrowed: 1 << 30, want: true}, + } { + t.Run(tc.name, func(t *testing.T) { + l := ledger(limit, tc.current, unbookedOf(tc.unbooked)) + l.bytes = tc.borrowed + got, recheck := l.Tight() + if got != tc.want { + t.Errorf("Tight() = %v, want %v", got, tc.want) + } + if (recheck == nil) != tc.want { + t.Errorf("Tight() recheck nil = %v, want %v", recheck == nil, tc.want) + } + }) + } + failing := &Ledger{ + Unbooked: func(int64) int64 { return 2 << 30 }, + PodMemory: func() (int64, int64, error) { return 0, 0, errors.New("no cgroup") }, + } + if tight, _ := failing.Tight(); !tight { + t.Error("Tight() when pod memory can't be read = false, want true") + } +} + +func TestTightAskedAgainWhenWaitBlocks(t *testing.T) { + unbooked := unbookedOf(3 << 30) + l := ledger(4<<30, 1<<30, unbooked) + l.Take(1 << 30) + tight, recheck := l.Tight() + if tight { + t.Fatal("Tight() with room to spare = true, want false") + } + // A new actor books most of the remaining memory and blocks in Wait. + unbooked.Store(512 << 20) + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan error, 1) + go func() { done <- l.Wait(ctx) }() + t.Cleanup(func() { + cancel() + <-done + }) + select { + case <-recheck: + case <-time.After(10 * time.Second): + t.Fatal("Wait held back a placement without closing Tight's channel") + } + // Even if another actor unhosts before the writer re-checks, Wait is still + // parked on returned, so Tight must still ask for write-out. + unbooked.Store(3 << 30) + if tight, _ := l.Tight(); !tight { + t.Error("Tight() with a placement waiting = false, want true") + } +} + +func TestTightWhenWaitBlocksBeforeTight(t *testing.T) { + for _, tc := range []struct { + name string + unpark func(t *testing.T, l *Ledger, borrowed int64, unbooked *atomic.Int64, armNext func() <-chan struct{}, cancel context.CancelFunc) + wantNil bool + }{ + { + name: "return wakes waiter", + unpark: func(_ *testing.T, l *Ledger, borrowed int64, _ *atomic.Int64, _ func() <-chan struct{}, _ context.CancelFunc) { + l.Return(borrowed) + }, + wantNil: true, + }, + { + name: "partial return re-parks then unblocks", + unpark: func(t *testing.T, l *Ledger, borrowed int64, unbooked *atomic.Int64, armNext func() <-chan struct{}, _ context.CancelFunc) { + t.Helper() + // Keep unbooked below the remaining loan after the first partial return + // so Wait loops and re-parks, then drop the loan to fit unbooked (> 0). + unbooked.Store(512 << 20) + reparked := armNext() + l.Return(borrowed / 4) + select { + case <-reparked: + case <-time.After(10 * time.Second): + t.Fatal("Wait did not re-check unbooked after partial Return") + } + unbooked.Store(3 << 30) + if tight, _ := l.Tight(); !tight { + t.Fatal("Tight() after Wait re-parked = false, want true") + } + unbooked.Store(512 << 20) + l.Return(borrowed / 4) // leaves 512 MiB borrowed (<= unbooked) so Wait exits with bytes > 0 + }, + wantNil: true, + }, + { + name: "cancel exits waiter", + unpark: func(_ *testing.T, _ *Ledger, _ int64, _ *atomic.Int64, _ func() <-chan struct{}, cancel context.CancelFunc) { + cancel() + }, + wantNil: false, + }, + } { + t.Run(tc.name, func(t *testing.T) { + unbooked := unbookedOf(2 << 30) + var nextCheck atomic.Pointer[chan struct{}] + armNext := func() <-chan struct{} { + ch := make(chan struct{}) + nextCheck.Store(&ch) + return ch + } + l := &Ledger{ + Unbooked: func(int64) int64 { + v := unbooked.Load() + if p := nextCheck.Swap(nil); p != nil { + close(*p) + } + return v + }, + PodMemory: func() (int64, int64, error) { return 4 << 30, 1 << 30, nil }, + } + // Unblocked Wait calls (bytes == 0 and bytes <= unbooked) must not + // underflow waiters below zero. + if err := l.Wait(context.Background()); err != nil { + t.Fatalf("Wait() with nothing borrowed = %v", err) + } + borrowed := l.Take(1 << 30) + if err := l.Wait(context.Background()); err != nil { + t.Fatalf("Wait() with room to spare = %v", err) + } + + // A placement blocks in Wait before Tight is ever called. + unbooked.Store(512 << 20) + waitChecked := armNext() + ctx, cancel := context.WithCancel(context.Background()) + done := make(chan struct{}) + var waitErr error + go func() { + waitErr = l.Wait(ctx) + close(done) + }() + t.Cleanup(func() { + cancel() + <-done + }) + select { + case <-waitChecked: + case <-time.After(10 * time.Second): + t.Fatal("Wait did not check unbooked") + } + + // The checkpointing actor unhosts so the pod looks roomy again. + // Tight acquires l.mu after Wait records itself and releases l.mu. + unbooked.Store(3 << 30) + if tight, _ := l.Tight(); !tight { + t.Fatal("Tight() with a waiter parked before Tight = false, want true") + } + + tc.unpark(t, l, borrowed, unbooked, armNext, cancel) + select { + case <-done: + if (waitErr == nil) != tc.wantNil { + t.Fatalf("Wait() err = %v, want nil=%v", waitErr, tc.wantNil) + } + case <-time.After(10 * time.Second): + t.Fatal("Wait did not exit") + } + + // After Wait exits, waiters drops back to zero and a roomy pod is not tight. + unbooked.Store(3 << 30) + if l.bytes == 0 { + l.Take(1 << 30) + } + if tight, _ := l.Tight(); tight { + t.Error("Tight() after Wait exited = true, want false") + } + }) + } } func TestWait(t *testing.T) { diff --git a/internal/ateworker/pid1/pid1.go b/internal/ateworker/pid1/pid1.go index 118e5ff67b..990bd8a304 100644 --- a/internal/ateworker/pid1/pid1.go +++ b/internal/ateworker/pid1/pid1.go @@ -26,6 +26,10 @@ import ( "fmt" "os" "os/signal" + "runtime" + "slices" + "strconv" + "strings" "golang.org/x/sys/unix" ) @@ -35,9 +39,31 @@ var forwarded = []os.Signal{ unix.SIGTERM, unix.SIGINT, unix.SIGHUP, unix.SIGQUIT, unix.SIGUSR1, unix.SIGUSR2, } +// hostProcsEnv holds the Go runtime's initial (default) GOMAXPROCS. +// When re-executing with GOMAXPROCS=1, we preserve the Go runtime's prior +// default using this env variable. +const hostProcsEnv = "ATE_HOST_GOMAXPROCS" + +// HostProcs returns GOMAXPROCS as the Go runtime would have set it without +// the cap. Returns 0 if uncapped. +func HostProcs() int { + n, err := strconv.Atoi(os.Getenv(hostProcsEnv)) + if err != nil { + return 0 // GOMAXPROCS wasn't capped + } + return n +} + +// Options configures RunIfPID1. +type Options struct { + // MaxProcs caps GOMAXPROCS on a host where the Go runtime would start + // with more than MaxProcs otherwise. Zero means no cap. + MaxProcs int +} + // RunIfPID1 runs the init and exits if the process is PID 1, and otherwise // returns. Call it first thing in main. -func RunIfPID1() { +func RunIfPID1(opts Options) { if os.Getpid() != 1 { return } @@ -46,12 +72,37 @@ func RunIfPID1() { fmt.Fprintf(os.Stderr, "pid1: finding the executable: %v\n", err) os.Exit(1) } - os.Exit(supervise(exe, os.Args)) + os.Exit(run(exe, os.Args, opts)) +} + +// run is the init. It returns the exit code of the child it starts from path. +func run(path string, argv []string, opts Options) int { + env := os.Environ() + if opts.MaxProcs > 0 { + if os.Getenv(hostProcsEnv) != "" { + env = append(withoutEnv(env, "GOMAXPROCS"), fmt.Sprintf("GOMAXPROCS=%d", opts.MaxProcs)) + } else if n := runtime.GOMAXPROCS(0); n > opts.MaxProcs { + // Only exec drops the threads this runtime has already started. + env = append(withoutEnv(env, "GOMAXPROCS"), "GOMAXPROCS=1", fmt.Sprintf("%s=%d", hostProcsEnv, n)) + err := unix.Exec(path, argv, env) + fmt.Fprintf(os.Stderr, "pid1: re-executing %s: %v\n", path, err) + return 1 + } + } + return supervise(path, argv, env) +} + +// withoutEnv returns env without the variables named. +func withoutEnv(env []string, names ...string) []string { + return slices.DeleteFunc(env, func(e string) bool { + name, _, _ := strings.Cut(e, "=") + return slices.Contains(names, name) + }) } -// supervise starts path as a child, reaps until it exits, and returns its exit -// code. -func supervise(path string, argv []string) int { +// supervise starts path as a child with env, reaps until it exits, and returns +// its exit code. +func supervise(path string, argv, env []string) int { // A no-op as PID 1, but it lets tests run this as an ordinary process. if err := unix.Prctl(unix.PR_SET_CHILD_SUBREAPER, 1, 0, 0, 0); err != nil { fmt.Fprintf(os.Stderr, "pid1: setting child subreaper: %v\n", err) @@ -64,7 +115,7 @@ func supervise(path string, argv []string) int { defer signal.Stop(sigs) child, err := os.StartProcess(path, argv, &os.ProcAttr{ - Env: os.Environ(), + Env: env, Files: []*os.File{os.Stdin, os.Stdout, os.Stderr}, }) if err != nil { diff --git a/internal/ateworker/pid1/pid1_test.go b/internal/ateworker/pid1/pid1_test.go index 1dbf07db7c..b58b88a411 100644 --- a/internal/ateworker/pid1/pid1_test.go +++ b/internal/ateworker/pid1/pid1_test.go @@ -17,29 +17,93 @@ package pid1 import ( + "fmt" "os" + "os/exec" "os/signal" + "runtime" + "strconv" "testing" "time" "golang.org/x/sys/unix" ) +// With helperMaxProcsEnv set, the test binary stands in for a worker binary. +const ( + helperMaxProcsEnv = "PID1_TEST_MAX_PROCS" + helperInitPIDEnv = "PID1_TEST_INIT_PID" +) + +func TestMain(m *testing.M) { + maxProcs, ok := os.LookupEnv(helperMaxProcsEnv) + if !ok { + os.Exit(m.Run()) + } + pid := strconv.Itoa(os.Getpid()) + if _, ok := os.LookupEnv(helperInitPIDEnv); !ok { + os.Setenv(helperInitPIDEnv, pid) + } + if os.Getenv(helperInitPIDEnv) != pid { + fmt.Printf("child=%d host=%d", runtime.GOMAXPROCS(0), HostProcs()) + return + } + fmt.Printf("init=%d ", runtime.GOMAXPROCS(0)) + n, err := strconv.Atoi(maxProcs) + if err != nil { + panic(err) + } + exe, err := os.Executable() + if err != nil { + panic(err) + } + os.Exit(run(exe, os.Args, Options{MaxProcs: n})) +} + +func TestRunMaxProcs(t *testing.T) { + tests := []struct { + name string + gomaxprocs string // of the init when it starts + maxProcs string + want string + }{ + {name: "more than the cap", gomaxprocs: "16", maxProcs: "8", want: "init=16 init=1 child=8 host=16"}, + {name: "equal to the cap", gomaxprocs: "8", maxProcs: "8", want: "init=8 child=8 host=0"}, + {name: "less than the cap", gomaxprocs: "2", maxProcs: "8", want: "init=2 child=2 host=0"}, + {name: "no cap", gomaxprocs: "16", maxProcs: "0", want: "init=16 child=16 host=0"}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + cmd := exec.Command(os.Args[0]) + cmd.Env = append(os.Environ(), "GOMAXPROCS="+tc.gomaxprocs, helperMaxProcsEnv+"="+tc.maxProcs, + // Under -race, every process otherwise sleeps a second as it exits. + "GORACE=atexit_sleep_ms=0") + out, err := cmd.Output() + if err != nil { + t.Fatalf("running the init: %v", err) + } + if got := string(out); got != tc.want { + t.Errorf("GOMAXPROCS: got %q, want %q", got, tc.want) + } + }) + } +} + func TestSuperviseReturnsExitCode(t *testing.T) { - if got := supervise("/bin/sh", []string{"sh", "-c", "exit 3"}); got != 3 { + if got := supervise("/bin/sh", []string{"sh", "-c", "exit 3"}, os.Environ()); got != 3 { t.Fatalf("supervise = %d, want 3", got) } } func TestSuperviseReturnsSignalExitCode(t *testing.T) { - if got := supervise("/bin/sh", []string{"sh", "-c", "kill -KILL $$"}); got != 128+9 { + if got := supervise("/bin/sh", []string{"sh", "-c", "kill -KILL $$"}, os.Environ()); got != 128+9 { t.Fatalf("supervise = %d, want %d", got, 128+9) } } func TestSuperviseReapsOrphans(t *testing.T) { // The inner sh is orphaned to us and exits while the child still runs. - if got := supervise("/bin/sh", []string{"sh", "-c", "(sh -c 'exit 0' &); sleep 0.5"}); got != 0 { + if got := supervise("/bin/sh", []string{"sh", "-c", "(sh -c 'exit 0' &); sleep 0.5"}, os.Environ()); got != 0 { t.Fatalf("supervise = %d, want 0", got) } var status unix.WaitStatus @@ -55,7 +119,7 @@ func TestSuperviseForwardsSignals(t *testing.T) { defer signal.Stop(ignore) done := make(chan int) - go func() { done <- supervise("/bin/sh", []string{"sh", "-c", "exec sleep 30"}) }() + go func() { done <- supervise("/bin/sh", []string{"sh", "-c", "exec sleep 30"}, os.Environ()) }() // Repeated, since the first may land before supervise subscribes. tick := time.NewTicker(10 * time.Millisecond) defer tick.Stop() diff --git a/internal/ateworker/register/crash.go b/internal/ateworker/register/crash.go index 54eebb14e9..a1026e2c59 100644 --- a/internal/ateworker/register/crash.go +++ b/internal/ateworker/register/crash.go @@ -51,11 +51,8 @@ func NewCrashReporter(cfg ReportConfig) (*CrashReporter, error) { return &CrashReporter{socketPath: cfg.SocketPath, tlsConfig: tlsConfig}, nil } -// ReportCrashed reports that actor's sandbox died, retrying until the control -// plane answers or ctx ends. A crash stays true, so unlike a suspend request it -// is worth retrying for as long as the caller allows. A refusal, the actor -// having moved on or an operation in flight owning it, is an answer and is -// logged rather than returned. +// ReportCrashed reports that the actor's sandbox died until the control plane +// answers or ctx ends. Refusals are logged rather than returned. func (r *CrashReporter) ReportCrashed(ctx context.Context, actor resources.ActorAttribution, message string) error { conn, err := ateletdial.Dial(r.socketPath, r.tlsConfig) if err != nil { diff --git a/internal/ateworker/register/register.go b/internal/ateworker/register/register.go index 5a8c1a95d7..847aae83a3 100644 --- a/internal/ateworker/register/register.go +++ b/internal/ateworker/register/register.go @@ -88,6 +88,22 @@ func (e *Epoch) Require() (int64, error) { return 0, apierror.Unavailable("worker has not registered yet: not accepting workloads") } +// SandboxRuntimes tracks whether this worker process has reported its sandbox +// runtimes to the control plane. +type SandboxRuntimes struct { + reported atomic.Bool +} + +// Reported is a readiness check that fails until the control plane accepts +// this worker process's sandbox runtimes. The pod stays not Ready before then, +// so the Deployment does not count a worker with no usable runtime as Ready. +func (r *SandboxRuntimes) Reported(context.Context) error { + if !r.reported.Load() { + return errors.New("worker has not reported its sandbox runtimes yet") + } + return nil +} + // FromFiles combines the downward API compute limits with the worker's own // actor limit. // @@ -132,14 +148,16 @@ func ParsePodIPs(value string) []string { return ips } -// buildCompat converts the compatibility attributes atelet wrote for one -// SandboxConfig version into a VersionedSandboxCompat. -func buildCompat(attrs sandboxruntimes.Attributes) *ateletpb.VersionedSandboxCompat { - entries := make([]*ateletpb.AttributeEntry, 0, len(attrs)) - for _, k := range slices.Sorted(maps.Keys(attrs)) { +// buildCompat converts the compatibility attributes for one worker runtime. +func buildCompat(attrs, workerAttrs sandboxruntimes.Attributes) *ateletpb.VersionedSandboxCompat { + all := make(sandboxruntimes.Attributes, len(attrs)+len(workerAttrs)) + maps.Copy(all, attrs) + maps.Copy(all, workerAttrs) + entries := make([]*ateletpb.AttributeEntry, 0, len(all)) + for _, k := range slices.Sorted(maps.Keys(all)) { entries = append(entries, &ateletpb.AttributeEntry{ Key: k, - Value: attrs[k], + Value: all[k], }) } return &ateletpb.VersionedSandboxCompat{ @@ -150,20 +168,20 @@ func buildCompat(attrs sandboxruntimes.Attributes) *ateletpb.VersionedSandboxCom // buildRuntime converts one runtime of the sandbox runtimes file into a // WorkerSandboxRuntime. -func buildRuntime(rt sandboxruntimes.Runtime) *ateletpb.WorkerSandboxRuntime { - return &ateletpb.WorkerSandboxRuntime{Version: buildCompat(rt.Version)} +func buildRuntime(rt sandboxruntimes.Runtime, workerAttrs sandboxruntimes.Attributes) *ateletpb.WorkerSandboxRuntime { + return &ateletpb.WorkerSandboxRuntime{Version: buildCompat(rt.Version, workerAttrs)} } // buildRuntimesRequest builds the SetWorkerSandboxRuntimesRequest for one // class of the sandbox runtimes file, the one this worker implements, for the // worker process registered with epoch. -func buildRuntimesRequest(epoch int64, class *sandboxruntimes.Class) *ateletpb.SetWorkerSandboxRuntimesRequest { +func buildRuntimesRequest(epoch int64, class *sandboxruntimes.Class, workerAttrs sandboxruntimes.Attributes) *ateletpb.SetWorkerSandboxRuntimesRequest { c := &ateletpb.WorkerSandboxClass{ SandboxClass: class.SandboxClass, - DefaultRuntime: buildRuntime(class.DefaultRuntime), + DefaultRuntime: buildRuntime(class.DefaultRuntime, workerAttrs), } for _, rt := range class.RestorableRuntimes { - c.RestorableRuntimes = append(c.RestorableRuntimes, buildRuntime(rt)) + c.RestorableRuntimes = append(c.RestorableRuntimes, buildRuntime(rt, workerAttrs)) } return &ateletpb.SetWorkerSandboxRuntimesRequest{ Epoch: epoch, @@ -230,6 +248,9 @@ type ReportConfig struct { // ActorOverhead is what each actor costs the worker on top of its own // limits, reported on every runtime. Nil is none. ActorOverhead *ateletpb.RuntimeOverhead + // RuntimeAttributes identify process-level compatibility requirements on + // every runtime. + RuntimeAttributes sandboxruntimes.Attributes // SandboxClass is the class this worker implements ("gvisor", "microvm"). SandboxClass string // RuntimesFile is the sandbox runtimes file atelet keeps for this worker @@ -247,7 +268,8 @@ type supportClient interface { // Report registers this worker process with the node-local atelet, stores the // epoch it registered with in epoch, then keeps its sandbox runtimes reported // until ctx ends: it reads its sandbox runtimes file at startup and again -// whenever atelet rewrites it. +// whenever atelet rewrites it, marking runtimes reported once the first report +// is accepted. // // It returns early on a configuration error, which no retry would fix, and // when the control plane refuses this process's epoch, which means another @@ -257,7 +279,7 @@ type supportClient interface { // control plane has recorded it, and the Worker record may not exist yet when // a worker first comes up. Nothing else reports this, so giving up would leave // the Worker holding no capacity and hosting nothing. -func Report(ctx context.Context, cfg ReportConfig, epoch *Epoch) error { +func Report(ctx context.Context, cfg ReportConfig, epoch *Epoch, runtimes *SandboxRuntimes) error { if cfg.SandboxClass == "" { // The control plane refuses a runtime without a class. return errors.New("register worker: SandboxClass is required") @@ -278,11 +300,11 @@ func Report(ctx context.Context, cfg ReportConfig, epoch *Epoch) error { } client := &dialingClient{socketPath: cfg.SocketPath, tlsConfig: tlsConfig} changes := WatchFilePath(ctx, cfg.RuntimesFile) - return run(ctx, cfg, capacity, client, epoch, changes) + return run(ctx, cfg, capacity, client, epoch, runtimes, changes) } // run registers, then reports runtimes until ctx ends or the epoch is refused. -func run(ctx context.Context, cfg ReportConfig, capacity *ateletpb.WorkerResources, client supportClient, epoch *Epoch, changes <-chan struct{}) error { +func run(ctx context.Context, cfg ReportConfig, capacity *ateletpb.WorkerResources, client supportClient, epoch *Epoch, runtimes *SandboxRuntimes, changes <-chan struct{}) error { registered, err := registerOnce(ctx, client, &ateletpb.RegisterWorkerRequest{ Ips: cfg.PodIPs, Capacity: capacity, @@ -291,11 +313,18 @@ func run(ctx context.Context, cfg ReportConfig, capacity *ateletpb.WorkerResourc return err } epoch.Store(registered) + report := func(ctx context.Context, req *ateletpb.SetWorkerSandboxRuntimesRequest) error { + if err := client.SetWorkerSandboxRuntimes(ctx, req); err != nil { + return err + } + runtimes.reported.Store(true) + return nil + } r := newReconciler( cfg, registered, func() (*sandboxruntimes.File, error) { return sandboxruntimes.Read(cfg.RuntimesFile) }, - client.SetWorkerSandboxRuntimes, + report, ) return r.run(ctx, changes) } @@ -447,7 +476,7 @@ func (r *reconciler) sync(ctx context.Context) (retry bool, err error) { slog.WarnContext(ctx, "Ignoring a sandbox runtimes file with no default runtime", slog.String("path", r.cfg.RuntimesFile)) return false, nil } - req := buildRuntimesRequest(r.epoch, class) + req := buildRuntimesRequest(r.epoch, class, r.cfg.RuntimeAttributes) setActorOverhead(req, r.cfg.ActorOverhead) if proto.Equal(req, r.reported) { return false, nil diff --git a/internal/ateworker/register/register_test.go b/internal/ateworker/register/register_test.go index 403b53ec64..d9f05d99b7 100644 --- a/internal/ateworker/register/register_test.go +++ b/internal/ateworker/register/register_test.go @@ -120,10 +120,13 @@ func TestBuildCompat(t *testing.T) { hardware.AttrSandboxBundleHash: "sha256:abc", hardware.AttrCPUFeatures: "3f", hardware.AttrArchitecture: runtime.GOARCH, + }, sandboxruntimes.Attributes{ + hardware.AttrActorIPFamilies: "ipv4,ipv6", }) want := &ateletpb.VersionedSandboxCompat{ SchemaVersion: hardware.SchemaVersionV1, Attributes: []*ateletpb.AttributeEntry{ + {Key: hardware.AttrActorIPFamilies, Value: "ipv4,ipv6"}, {Key: hardware.AttrArchitecture, Value: runtime.GOARCH}, {Key: hardware.AttrCPUFeatures, Value: "3f"}, {Key: hardware.AttrSandboxBundleHash, Value: "sha256:abc"}, @@ -184,6 +187,17 @@ func TestEpochRegistered(t *testing.T) { } } +func TestSandboxRuntimesReported(t *testing.T) { + var r SandboxRuntimes + if err := r.Reported(context.Background()); err == nil { + t.Error("Reported() before report = nil, want an error") + } + r.reported.Store(true) + if err := r.Reported(context.Background()); err != nil { + t.Errorf("Reported() after report = %v, want nil", err) + } +} + // fakeSupport is a supportClient that fails the first acquireFails acquires // and fails registration with registerErrs in turn. type fakeSupport struct { @@ -270,38 +284,63 @@ func TestRegisterOnce(t *testing.T) { } } +// run stores the epoch as soon as registration succeeds, and marks sandbox +// runtimes reported only after the control plane accepts the first report. func TestRunStoresEpochBeforeReportingRuntimes(t *testing.T) { - ctx, cancel := context.WithCancel(context.Background()) - defer cancel() + for _, tc := range []struct { + name string + reportErr error + wantReported bool + }{ + {name: "report accepted", wantReported: true}, + {name: "report failed", reportErr: status.Error(codes.Unavailable, "ateapi is down")}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx, cancel := context.WithCancel(context.Background()) + defer cancel() - path := filepath.Join(t.TempDir(), nodepath.SandboxRuntimesFileName) - if _, err := sandboxruntimes.Write(path, gvisorFile(sandboxruntimes.Attributes{hardware.AttrSandboxBundleHash: "sha256:v1"})); err != nil { - t.Fatal(err) - } - var epoch Epoch - client := &runtimesRecorder{fakeSupport: &fakeSupport{}, onReport: func(req *ateletpb.SetWorkerSandboxRuntimesRequest) { - if got := epoch.Load(); got != req.GetEpoch() { - t.Errorf("epoch stored = %d when runtimes were reported with %d", got, req.GetEpoch()) - } - cancel() - }} - err := run(ctx, ReportConfig{SandboxClass: "gvisor", RuntimesFile: path, PodIPs: []string{"10.0.0.1"}}, &ateletpb.WorkerResources{Actors: testActors}, client, &epoch, nil) - if !errors.Is(err, context.Canceled) { - t.Fatalf("run() = %v, want context.Canceled", err) - } - if epoch.Load() != 1 { - t.Errorf("epoch = %d, want 1", epoch.Load()) + path := filepath.Join(t.TempDir(), nodepath.SandboxRuntimesFileName) + if _, err := sandboxruntimes.Write(path, gvisorFile(sandboxruntimes.Attributes{hardware.AttrSandboxBundleHash: "sha256:v1"})); err != nil { + t.Fatal(err) + } + var ( + epoch Epoch + runtimes SandboxRuntimes + ) + client := &runtimesRecorder{fakeSupport: &fakeSupport{}, err: tc.reportErr, onReport: func(req *ateletpb.SetWorkerSandboxRuntimesRequest) { + if got := epoch.Load(); got != req.GetEpoch() { + t.Errorf("epoch stored = %d when runtimes were reported with %d", got, req.GetEpoch()) + } + if err := runtimes.Reported(ctx); err == nil { + t.Error("Reported() = nil while runtimes were being reported, want an error") + } + cancel() + }} + err := run(ctx, ReportConfig{SandboxClass: "gvisor", RuntimesFile: path, PodIPs: []string{"10.0.0.1"}}, &ateletpb.WorkerResources{Actors: testActors}, client, &epoch, &runtimes, nil) + if !errors.Is(err, context.Canceled) { + t.Fatalf("run() = %v, want context.Canceled", err) + } + if epoch.Load() != 1 { + t.Errorf("epoch = %d, want 1", epoch.Load()) + } + if err := runtimes.Reported(context.Background()); (err == nil) != tc.wantReported { + t.Errorf("Reported() = %v, want ready %v", err, tc.wantReported) + } + }) } } +// runtimesRecorder is a fakeSupport that hands each sandbox runtimes report to +// onReport and returns err. type runtimesRecorder struct { *fakeSupport onReport func(*ateletpb.SetWorkerSandboxRuntimesRequest) + err error } func (r *runtimesRecorder) SetWorkerSandboxRuntimes(_ context.Context, req *ateletpb.SetWorkerSandboxRuntimesRequest) error { r.onReport(req) - return nil + return r.err } func TestReconcilerSync(t *testing.T) { @@ -316,8 +355,9 @@ func TestReconcilerSync(t *testing.T) { hardware.AttrCPUFeatures: "7", hardware.AttrSandboxBundleHash: "sha256:v2", }, v1.SandboxClasses[0].DefaultRuntime.Version) - reqV1 := buildRuntimesRequest(epoch, &v1.SandboxClasses[0]) - reqV2 := buildRuntimesRequest(epoch, &v2.SandboxClasses[0]) + workerAttrs := sandboxruntimes.Attributes{hardware.AttrActorIPFamilies: "ipv4,ipv6"} + reqV1 := buildRuntimesRequest(epoch, &v1.SandboxClasses[0], workerAttrs) + reqV2 := buildRuntimesRequest(epoch, &v2.SandboxClasses[0], workerAttrs) tests := []struct { name string @@ -442,7 +482,7 @@ func TestReconcilerSync(t *testing.T) { var calls []*ateletpb.SetWorkerSandboxRuntimesRequest r := newReconciler( - ReportConfig{SandboxClass: "gvisor", RuntimesFile: path}, + ReportConfig{SandboxClass: "gvisor", RuntimesFile: path, RuntimeAttributes: workerAttrs}, epoch, func() (*sandboxruntimes.File, error) { return sandboxruntimes.Read(path) }, func(_ context.Context, req *ateletpb.SetWorkerSandboxRuntimesRequest) error { @@ -783,7 +823,7 @@ func TestReconcilerRunWatchesFile(t *testing.T) { } select { case req := <-got: - if diff := cmp.Diff(buildRuntimesRequest(r.epoch, &v1.SandboxClasses[0]), req, protocmp.Transform()); diff != "" { + if diff := cmp.Diff(buildRuntimesRequest(r.epoch, &v1.SandboxClasses[0], nil), req, protocmp.Transform()); diff != "" { t.Errorf("initial registration mismatch (-want +got):\n%s", diff) } case <-ctx.Done(): @@ -802,7 +842,7 @@ func TestReconcilerRunWatchesFile(t *testing.T) { } select { case req := <-got: - if diff := cmp.Diff(buildRuntimesRequest(r.epoch, &v2.SandboxClasses[0]), req, protocmp.Transform()); diff != "" { + if diff := cmp.Diff(buildRuntimesRequest(r.epoch, &v2.SandboxClasses[0], nil), req, protocmp.Transform()); diff != "" { t.Errorf("updated registration mismatch (-want +got):\n%s", diff) } case <-ctx.Done(): @@ -829,7 +869,7 @@ func TestReportFailsFastOnBadCredentials(t *testing.T) { PodIPs: []string{"10.0.0.1"}, SandboxClass: "gvisor", RuntimesFile: filepath.Join(t.TempDir(), nodepath.SandboxRuntimesFileName), - }, &Epoch{}) + }, &Epoch{}, &SandboxRuntimes{}) if err == nil { t.Fatal("Report() with unreadable credentials succeeded, want an error the caller can exit on") } @@ -872,7 +912,7 @@ func TestReportFailsFastOnMissingConfig(t *testing.T) { }, } { t.Run(tc.name, func(t *testing.T) { - err := Report(ctx, tc.cfg, &Epoch{}) + err := Report(ctx, tc.cfg, &Epoch{}, &SandboxRuntimes{}) if err == nil { t.Fatal("Report() succeeded, want an error the caller can exit on") } diff --git a/internal/ateworkervalidation/validate.go b/internal/ateworkervalidation/validate.go index 1db9e8a22a..ed0983d558 100644 --- a/internal/ateworkervalidation/validate.go +++ b/internal/ateworkervalidation/validate.go @@ -78,12 +78,6 @@ func ValidateCustom_EgressGateway_Address(_ context.Context, _ operation.Operati return resources.ValidateHostPort(fldPath, *value) } -// ValidateCustom_HttpGetAction_Path holds a wakeup probe's path to the RFC -// 3986 path shape atelet already enforces, shared through internal/resources. -func ValidateCustom_HttpGetAction_Path(_ context.Context, _ operation.Operation, fldPath *field.Path, value, _ *string) field.ErrorList { - return resources.ValidateHTTPGetPath(fldPath, *value) -} - // ValidateCustom_VolumeMount_MountPath holds a mount path to the clean // absolute Unix path shape atelet already enforces, shared through // internal/resources. diff --git a/internal/ateworkervalidation/validation_test.go b/internal/ateworkervalidation/validation_test.go index 3d789d3756..30ce9d24f9 100644 --- a/internal/ateworkervalidation/validation_test.go +++ b/internal/ateworkervalidation/validation_test.go @@ -88,6 +88,13 @@ func TestValidateRunWorkloadRequest(t *testing.T) { }{{ name: "valid", obj: valid(), + }, { + name: "valid activation_uid", + obj: valid(func(r *ateworkerpb.RunWorkloadRequest) { r.ActivationUid = "754f3dc4-2996-41c4-8e5a-a1b79e6678d5" }), + }, { + name: "invalid activation_uid", + obj: valid(func(r *ateworkerpb.RunWorkloadRequest) { r.ActivationUid = "invalid" }), + want: field.ErrorList{field.Invalid(field.NewPath("activation_uid"), nil, "").WithOrigin("format=k8s-uuid")}, }, { name: "valid: gVisor shape, no assets, no egress, unset size", obj: valid(func(r *ateworkerpb.RunWorkloadRequest) { @@ -221,13 +228,13 @@ func TestValidateRunWorkloadRequest(t *testing.T) { }, { name: "http_get path without leading slash", obj: valid(func(r *ateworkerpb.RunWorkloadRequest) { r.Spec.Containers[0].WakeupProbe.HttpGet.Path = "healthz" }), - want: field.ErrorList{field.Invalid(probe.Child("http_get", "path"), nil, "")}, + want: field.ErrorList{field.Invalid(probe.Child("http_get", "path"), nil, "").WithOrigin("format=ate-http-probe-path")}, }, { name: "http_get path with query", obj: valid(func(r *ateworkerpb.RunWorkloadRequest) { r.Spec.Containers[0].WakeupProbe.HttpGet.Path = "/healthz?x=1" }), - want: field.ErrorList{field.Invalid(probe.Child("http_get", "path"), nil, "")}, + want: field.ErrorList{field.Invalid(probe.Child("http_get", "path"), nil, "").WithOrigin("format=ate-http-probe-path")}, }, { name: "http_get path too long", obj: valid(func(r *ateworkerpb.RunWorkloadRequest) { @@ -618,6 +625,13 @@ func TestValidateRestoreWorkloadRequest(t *testing.T) { }{{ name: "valid", obj: valid(), + }, { + name: "valid activation_uid", + obj: valid(func(r *ateworkerpb.RestoreWorkloadRequest) { r.ActivationUid = "754f3dc4-2996-41c4-8e5a-a1b79e6678d5" }), + }, { + name: "invalid activation_uid", + obj: valid(func(r *ateworkerpb.RestoreWorkloadRequest) { r.ActivationUid = "invalid" }), + want: field.ErrorList{field.Invalid(field.NewPath("activation_uid"), nil, "").WithOrigin("format=k8s-uuid")}, }, { name: "valid: memory fidelity", obj: valid(func(r *ateworkerpb.RestoreWorkloadRequest) { diff --git a/internal/ateworkervalidation/zz_generated.validation.go b/internal/ateworkervalidation/zz_generated.validation.go index f39e3ba6d1..806e796806 100644 --- a/internal/ateworkervalidation/zz_generated.validation.go +++ b/internal/ateworkervalidation/zz_generated.validation.go @@ -21,6 +21,7 @@ package ateworkervalidation import ( context "context" + regexp "regexp" ateworkerpb "go.ate.dev/substrate/internal/proto/ateworkerpb" operation "k8s.io/apimachinery/pkg/api/operation" @@ -1013,6 +1014,8 @@ func Validate_GetWorkloadStatsRequest( return errs } +var formatPattern_ate_http_probe_path = regexp.MustCompile("(^$|^/([A-Za-z0-9\\-._~!$&'\\(\\)*+,;=:@/]|%[0-9A-Fa-f]{2})*$)") + // Validate_HttpGetAction validates an instance of HttpGetAction according // to declarative validation rules in the API schema. func Validate_HttpGetAction( @@ -1039,8 +1042,7 @@ func Validate_HttpGetAction( if earlyReturn { return // do not proceed } - // custom validation - if e := ValidateCustom_HttpGetAction_Path(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + if e := validate.Matches(ctx, op, fldPath, obj, oldObj, formatPattern_ate_http_probe_path, "must be a valid HTTP path (RFC 3986)", "format=ate-http-probe-path"); len(e) != 0 { errs = append(errs, e...) } if e := validate.MaxLength(ctx, op, fldPath, obj, oldObj, 1024); len(e) != 0 { @@ -1423,20 +1425,12 @@ func Validate_RestoreWorkloadRequest( } func() { // cohort = "containers" earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "containers", - func(o *ateworkerpb.WorkloadSpec) []*ateworkerpb.Container { return o.Containers }, ateDeepEqual, validate.RequiredSlice).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "containers", func(o *ateworkerpb.WorkloadSpec) []*ateworkerpb.Container { return o.Containers }, ateDeepEqual, func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj []*ateworkerpb.Container) field.ErrorList { - return validate.MaxItems(ctx, op, fldPath, obj, oldObj, 10) + return validate.RequiredSlice(ctx, op, fldPath, obj, oldObj) }).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "containers", - func(o *ateworkerpb.WorkloadSpec) []*ateworkerpb.Container { return o.Containers }, ateDeepEqual, validate.OptionalSlice).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { @@ -1652,6 +1646,37 @@ func Validate_RestoreWorkloadRequest( errs = append(errs, fn(fldPath.Child("preserve_restore_dir"), &obj.PreserveRestoreDir, oldVal, oldObj != nil)...) } + { // field ateworkerpb.RestoreWorkloadRequest.ActivationUid + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ateworkerpb.RestoreWorkloadRequest) *string { + return &oldObj.ActivationUid + }) + errs = append(errs, fn(fldPath.Child("activation_uid"), &obj.ActivationUid, oldVal, oldObj != nil)...) + } + return errs } @@ -1872,20 +1897,12 @@ func Validate_RunWorkloadRequest( } func() { // cohort = "containers" earlyReturn := false - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "containers", - func(o *ateworkerpb.WorkloadSpec) []*ateworkerpb.Container { return o.Containers }, ateDeepEqual, validate.RequiredSlice).MarkShortCircuit(); len(e) != 0 { - errs = append(errs, e...) - earlyReturn = true - } if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "containers", func(o *ateworkerpb.WorkloadSpec) []*ateworkerpb.Container { return o.Containers }, ateDeepEqual, func(ctx context.Context, op operation.Operation, fldPath *field.Path, obj, oldObj []*ateworkerpb.Container) field.ErrorList { - return validate.MaxItems(ctx, op, fldPath, obj, oldObj, 10) + return validate.RequiredSlice(ctx, op, fldPath, obj, oldObj) }).MarkShortCircuit(); len(e) != 0 { - earlyReturn = true - } - if e := validate.Subfield(ctx, op, fldPath, obj, oldObj, "containers", - func(o *ateworkerpb.WorkloadSpec) []*ateworkerpb.Container { return o.Containers }, ateDeepEqual, validate.OptionalSlice).MarkShortCircuit(); len(e) != 0 { + errs = append(errs, e...) earlyReturn = true } if earlyReturn { @@ -2038,6 +2055,37 @@ func Validate_RunWorkloadRequest( errs = append(errs, fn(fldPath.Child("actor_dirs"), obj.ActorDirs, oldVal, oldObj != nil)...) } + { // field ateworkerpb.RunWorkloadRequest.ActivationUid + fn := func( + fldPath *field.Path, + obj, oldObj *string, + oldValueCorrelated bool) (errs field.ErrorList) { + // don't revalidate unchanged data + if oldValueCorrelated && op.Type == operation.Update { + if obj == oldObj || (obj != nil && oldObj != nil && *obj == *oldObj) { + return nil + } + } + // call field-attached validations + earlyReturn := false + if e := validate.OptionalValue(ctx, op, fldPath, obj, oldObj).MarkShortCircuit(); len(e) != 0 { + earlyReturn = true + } + if earlyReturn { + return // do not proceed + } + if e := validate.UUID(ctx, op, fldPath, obj, oldObj); len(e) != 0 { + errs = append(errs, e...) + } + return + } + oldVal := safe.Field(oldObj, + func(oldObj *ateworkerpb.RunWorkloadRequest) *string { + return &oldObj.ActivationUid + }) + errs = append(errs, fn(fldPath.Child("activation_uid"), &obj.ActivationUid, oldVal, oldObj != nil)...) + } + return errs } diff --git a/internal/atunnel/dns/dnshandler.go b/internal/atunnel/dns/dnshandler.go index ae19e99c7e..46bc2ee2e6 100644 --- a/internal/atunnel/dns/dnshandler.go +++ b/internal/atunnel/dns/dnshandler.go @@ -61,9 +61,10 @@ type dnsHandler struct { pending *pendingRequests limiter *limiter allow queryPolicy + metrics *metrics } -func newDNSHandler(pending *pendingRequests, lim *limiter, allow queryPolicy) *dnsHandler { +func newDNSHandler(pending *pendingRequests, lim *limiter, allow queryPolicy, metrics *metrics) *dnsHandler { if allow == nil { allow = func(dnsmessage.Question) bool { return true } } @@ -71,6 +72,7 @@ func newDNSHandler(pending *pendingRequests, lim *limiter, allow queryPolicy) *d pending: pending, limiter: lim, allow: allow, + metrics: metrics, } } @@ -122,7 +124,9 @@ func (h *dnsHandler) onRequestCommon(raw []byte) (dnsmessage.Header, dnsmessage. // Note: NXDOMAIN seems to interact better with application stacks than other // error codes such as REFUSED. cq := canonicalizeQuestion(q) - if !h.allow(cq) { + allowed := h.allow(cq) + h.metrics.recordQuery(allowed) + if !allowed { return hdr, dnsmessage.Question{}, action{ kind: actionReply, payload: protocol.NXDomainPacket(hdr, q), diff --git a/internal/atunnel/dns/dnshandler_test.go b/internal/atunnel/dns/dnshandler_test.go index f07061b9da..a4480c7774 100644 --- a/internal/atunnel/dns/dnshandler_test.go +++ b/internal/atunnel/dns/dnshandler_test.go @@ -76,7 +76,7 @@ func TestDNSHandlerOnRequestDrop(t *testing.T) { connections: &limiterSlots{max: 1}, } pending := newPendingRequests(lim) - h := newDNSHandler(pending, lim, nil) + h := newDNSHandler(pending, lim, nil, nil) upstreams := []string{"10.96.0.10:53"} // 1. Short packet (< 12 bytes). @@ -110,7 +110,7 @@ func TestDNSHandlerOnRequestSynthesizedReplies(t *testing.T) { allow := func(q dnsmessage.Question) bool { return q.Name.String() != "blocked.example.com." && q.Type != dnsmessage.TypeTXT } - h := newDNSHandler(pending, lim, allow) + h := newDNSHandler(pending, lim, allow, nil) upstreams := []string{"10.96.0.10:53"} qExample := dnsmessage.Question{ @@ -246,7 +246,7 @@ func TestDNSHandlerOnRequestSynthesizedReplies(t *testing.T) { func TestDNSHandlerUDPForwardAndResponseValidation(t *testing.T) { lim := newLimiter() pending := newPendingRequests(lim) - h := newDNSHandler(pending, lim, nil) + h := newDNSHandler(pending, lim, nil, nil) upstream1 := &net.UDPAddr{IP: net.ParseIP("10.96.0.10"), Port: 53} upstream2 := &net.UDPAddr{IP: net.ParseIP("10.96.0.11"), Port: 53} @@ -358,7 +358,7 @@ func TestDNSHandlerUDPForwardAndResponseValidation(t *testing.T) { func TestDNSHandlerTCPForwardAndResponseValidation(t *testing.T) { lim := newLimiter() pending := newPendingRequests(lim) - h := newDNSHandler(pending, lim, nil) + h := newDNSHandler(pending, lim, nil, nil) query := dnsQuery(0xbeef) act := h.onTCPRequest(bytes.Clone(query)) diff --git a/internal/atunnel/dns/metrics.go b/internal/atunnel/dns/metrics.go new file mode 100644 index 0000000000..00759ae9e7 --- /dev/null +++ b/internal/atunnel/dns/metrics.go @@ -0,0 +1,57 @@ +// Copyright 2026 The Agent Substrate 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 dns + +import ( + "context" + "fmt" + + "go.opentelemetry.io/otel/metric" + + "go.ate.dev/substrate/internal/ateattr" +) + +const queriesMetric = "ate.dns.queries" + +// metrics holds the DNS relay's metric instruments. A nil *metrics is a valid +// no-op, so call sites need no guard. +type metrics struct { + queries metric.Int64Counter +} + +// newMetrics creates the DNS relay's metric instruments against meter. +func newMetrics(meter metric.Meter) (*metrics, error) { + queries, err := meter.Int64Counter( + queriesMetric, + metric.WithUnit("{query}"), + metric.WithDescription("Number of actor DNS queries the sandbox DNS relay checked against the actor's egress policy, by decision."), + ) + if err != nil { + return nil, fmt.Errorf("create %s counter: %w", queriesMetric, err) + } + return &metrics{queries: queries}, nil +} + +// recordQuery counts one query the egress policy allowed or denied. +func (m *metrics) recordQuery(allowed bool) { + if m == nil { + return + } + decision := ateattr.DNSDecisionDenied + if allowed { + decision = ateattr.DNSDecisionAllowed + } + m.queries.Add(context.Background(), 1, metric.WithAttributes(ateattr.DNSDecisionKey.String(decision))) +} diff --git a/internal/atunnel/dns/metrics_test.go b/internal/atunnel/dns/metrics_test.go new file mode 100644 index 0000000000..cb0bfda52d --- /dev/null +++ b/internal/atunnel/dns/metrics_test.go @@ -0,0 +1,122 @@ +// Copyright 2026 The Agent Substrate 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 dns + +import ( + "context" + "os" + "path/filepath" + "testing" + + "github.com/google/go-cmp/cmp" + sdkmetric "go.opentelemetry.io/otel/sdk/metric" + "go.opentelemetry.io/otel/sdk/metric/metricdata" + "golang.org/x/net/dns/dnsmessage" + + "go.ate.dev/substrate/internal/ateattr" +) + +// collectQueries returns the ate.dns.queries count for each ate.dns.decision. +func collectQueries(t *testing.T, reader *sdkmetric.ManualReader) map[string]int64 { + t.Helper() + var rm metricdata.ResourceMetrics + if err := reader.Collect(context.Background(), &rm); err != nil { + t.Fatalf("collect: %v", err) + } + got := make(map[string]int64) + for _, sm := range rm.ScopeMetrics { + for _, m := range sm.Metrics { + if m.Name != queriesMetric { + continue + } + if m.Unit != "{query}" { + t.Errorf("unit = %q, want {query}", m.Unit) + } + sum, ok := m.Data.(metricdata.Sum[int64]) + if !ok { + t.Fatalf("data type = %T, want Sum[int64]", m.Data) + } + if !sum.IsMonotonic { + t.Error("IsMonotonic = false, want true") + } + for _, dp := range sum.DataPoints { + if dp.Attributes.Len() != 1 { + t.Errorf("attributes = %v, want only %s", dp.Attributes.ToSlice(), ateattr.DNSDecisionKey) + } + v, _ := dp.Attributes.Value(ateattr.DNSDecisionKey) + got[v.AsString()] += dp.Value + } + } + } + return got +} + +// TestQueriesCountsPolicyDecisions: every query the egress policy judges is +// counted once, on either transport. A malformed query never reaches the +// policy and is not counted. +func TestQueriesCountsPolicyDecisions(t *testing.T) { + reader := sdkmetric.NewManualReader() + m, err := newMetrics(sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)).Meter("ateworker-gvisor")) + if err != nil { + t.Fatalf("newMetrics: %v", err) + } + lim := newLimiter() + allow := func(q dnsmessage.Question) bool { return q.Name.String() != "blocked.example.com." } + h := newDNSHandler(newPendingRequests(lim), lim, allow, m) + upstreams := []string{"10.96.0.10:53"} + + allowed, _ := dnsQueryForName(t, 1, "example.com.") + denied, _ := dnsQueryForName(t, 2, "blocked.example.com.") + h.onUDPRequest(allowed, nil, upstreams) + h.onTCPRequest(allowed) + h.onUDPRequest(denied, nil, upstreams) + h.onTCPRequest(denied) + h.onTCPRequest(buildTestMessage(t, dnsmessage.Header{ID: 3}, nil)) + + want := map[string]int64{ + ateattr.DNSDecisionAllowed: 2, + ateattr.DNSDecisionDenied: 2, + } + if diff := cmp.Diff(want, collectQueries(t, reader)); diff != "" { + t.Errorf("ate.dns.queries mismatch (-want +got):\n%s", diff) + } +} + +// TestNewRelayCountsQueries: a relay from NewRelay counts on its meter. +func TestNewRelayCountsQueries(t *testing.T) { + path := filepath.Join(t.TempDir(), "resolv.conf") + if err := os.WriteFile(path, []byte("nameserver 127.0.0.1\n"), 0o644); err != nil { + t.Fatal(err) + } + reader := sdkmetric.NewManualReader() + relay, err := NewRelay(path, sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)).Meter("ateworker-gvisor")) + if err != nil { + t.Fatalf("NewRelay: %v", err) + } + // The actor has no policy, so the relay answers the query itself. + _, udpAddr, _ := serveLoopbackWithPolicy(t, relay, staticPolicy{}) + conn := dialRelay(t, "udp", udpAddr) + + query, q := dnsQueryForName(t, 1, "example.com.") + if _, err := conn.Write(query); err != nil { + t.Fatal(err) + } + checkAnswerForQuestion(t, readWithin(t, conn), 1, q, dnsmessage.RCodeNameError) + + want := map[string]int64{ateattr.DNSDecisionDenied: 1} + if diff := cmp.Diff(want, collectQueries(t, reader)); diff != "" { + t.Errorf("ate.dns.queries mismatch (-want +got):\n%s", diff) + } +} diff --git a/internal/atunnel/dns/readme.md b/internal/atunnel/dns/readme.md index 2b5bda0010..14225bbbc1 100644 --- a/internal/atunnel/dns/readme.md +++ b/internal/atunnel/dns/readme.md @@ -73,3 +73,4 @@ UDP and TCP call up to the DNS protocol layer (`golang.org/x/net/dns/dnsmessage` - `evaluator` (`evaluator.go`) compiles the hostname and wildcard patterns from an `EgressPolicy`'s `http`, `https`, and `tls_passthrough` rules and evaluates normalized `QNAME`s via `allowsHostname(qname)`. - `egressPolicyCheck` adapts the source to the `dnsHandler`'s `queryPolicy` hook, caching the compiled `*evaluator` for the current `*ateletpb.EgressPolicy` pointer and consulting it for every query. Fetching uses the `Server`'s context, so `Stop()` cancels a fetch in progress. - `allowQuery` evaluates a single `dnsmessage.Question` against a policy using `evaluator`. +- `metrics` (`metrics.go`) counts each decision on `ate.dns.queries`, by `ate.dns.decision`. diff --git a/internal/atunnel/dns/relay.go b/internal/atunnel/dns/relay.go index 71f215cf08..b716364608 100644 --- a/internal/atunnel/dns/relay.go +++ b/internal/atunnel/dns/relay.go @@ -21,6 +21,8 @@ import ( "net" "net/netip" "time" + + "go.opentelemetry.io/otel/metric" ) const ( @@ -39,15 +41,25 @@ type Relay struct { // dialer reaches upstream resolvers from the worker namespace. dialer *net.Dialer + + metrics *metrics } // NewRelay reads nameservers from resolvConfPath and forwards to each on port 53. -func NewRelay(resolvConfPath string) (*Relay, error) { +// It reports its metrics on meter. +func NewRelay(resolvConfPath string, meter metric.Meter) (*Relay, error) { upstreams, err := resolvConfNameservers(resolvConfPath) if err != nil { return nil, err } - return NewRelayForUpstreams(upstreams) + r, err := NewRelayForUpstreams(upstreams) + if err != nil { + return nil, err + } + if r.metrics, err = newMetrics(meter); err != nil { + return nil, err + } + return r, nil } func normalizeAddr(addr net.Addr) string { @@ -98,5 +110,5 @@ func NewRelayForUpstreams(upstreams []string) (*Relay, error) { // serveOn serves DNS on netC's sockets, which the caller has already bound, // and dials upstreams with netC's dialer. func (r *Relay) serveOn(ctx context.Context, netC *netConn, policy PolicySource) (*Server, error) { - return newServer(ctx, &serverConfig{upstreams: r.upstreams, policy: policy}, netC) + return newServer(ctx, &serverConfig{upstreams: r.upstreams, policy: policy, metrics: r.metrics}, netC) } diff --git a/internal/atunnel/dns/relay_test.go b/internal/atunnel/dns/relay_test.go index 2ba5b78eb6..8186b98b92 100644 --- a/internal/atunnel/dns/relay_test.go +++ b/internal/atunnel/dns/relay_test.go @@ -28,6 +28,7 @@ import ( "time" "github.com/google/go-cmp/cmp" + "go.opentelemetry.io/otel/metric/noop" "golang.org/x/net/dns/dnsmessage" ) @@ -124,7 +125,7 @@ func TestNewRelayRejects(t *testing.T) { if err := os.WriteFile(empty, nil, 0o644); err != nil { t.Fatal(err) } - if _, err := NewRelay(empty); err == nil { + if _, err := NewRelay(empty, noop.Meter{}); err == nil { t.Error("NewRelay succeeded with an empty resolv.conf") } if _, err := NewRelayForUpstreams(nil); err == nil { diff --git a/internal/atunnel/dns/server.go b/internal/atunnel/dns/server.go index 8fe8a5f080..4cc7065ff3 100644 --- a/internal/atunnel/dns/server.go +++ b/internal/atunnel/dns/server.go @@ -29,6 +29,8 @@ type serverConfig struct { // policy supplies the actor's egress policy, which each query is checked // against. Nil refuses every query. policy PolicySource + // metrics counts the policy decisions. Nil records nothing. + metrics *metrics } type netConn struct { @@ -88,7 +90,7 @@ func newServer( s.pendingRequests = newPendingRequests(s.limiter) // The check fetches with serveCtx, so that Stop cancels one in progress. - s.dns = newDNSHandler(s.pendingRequests, s.limiter, egressPolicyCheck(serveCtx, config.policy)) + s.dns = newDNSHandler(s.pendingRequests, s.limiter, egressPolicyCheck(serveCtx, config.policy), config.metrics) s.udp = newUDPHandler(netC.udp, netC.egressUDP, udpAddrs, s.dns, s.pendingRequests) s.tcp = newTCPHandler(config.upstreams, netC.tcpListener, netC.dialer, s.dns, s.limiter) diff --git a/internal/atunnel/dns/tcphandler_test.go b/internal/atunnel/dns/tcphandler_test.go index 006d363f6c..fc54b4d6d3 100644 --- a/internal/atunnel/dns/tcphandler_test.go +++ b/internal/atunnel/dns/tcphandler_test.go @@ -34,7 +34,7 @@ func startTestTCPHandler(t *testing.T, upstreams []string, configure func(*tcpHa } lim := newLimiter() - dnsH := newDNSHandler(nil, lim, nil) + dnsH := newDNSHandler(nil, lim, nil, nil) h := newTCPHandler(upstreams, lis, net.Dialer{Timeout: 5 * time.Second}, dnsH, lim) if configure != nil { configure(h, dnsH) diff --git a/internal/atunnel/dns/udphandler_test.go b/internal/atunnel/dns/udphandler_test.go index a6ab35fbe8..4fad99e4b3 100644 --- a/internal/atunnel/dns/udphandler_test.go +++ b/internal/atunnel/dns/udphandler_test.go @@ -50,7 +50,7 @@ func startTestUDPHandler(t *testing.T, upstreams []string, configure func(*udpHa lim := newLimiter() pending := newPendingRequests(lim) - dnsH := newDNSHandler(pending, lim, nil) + dnsH := newDNSHandler(pending, lim, nil, nil) h := newUDPHandler(ingress, egress, udpAddrs, dnsH, pending) if configure != nil { configure(h, dnsH) diff --git a/internal/atunnel/egress/client.go b/internal/atunnel/egress/client.go index 2412001c5a..3192133e5c 100644 --- a/internal/atunnel/egress/client.go +++ b/internal/atunnel/egress/client.go @@ -42,6 +42,9 @@ type ClientConfig struct { ServerName string GetClientCertificate func(*tls.CertificateRequestInfo) (*tls.Certificate, error) TrustBundlePath string + // DialControl, when set, runs on each gateway socket before it connects, + // as net.Dialer.Control does. + DialControl func(network, address string, c syscall.RawConn) error } // dialFunc dials a network address. It matches net.Dialer.DialContext. @@ -123,7 +126,7 @@ func NewClient(cfg ClientConfig, opts ...clientOption) (*Client, error) { client := &Client{ gatewayAddress: cfg.GatewayAddress, - dialContext: (&net.Dialer{}).DialContext, + dialContext: (&net.Dialer{Control: cfg.DialControl}).DialContext, tlsConfig: &tls.Config{ MinVersion: tls.VersionTLS12, RootCAs: rootCAs, diff --git a/internal/atunnel/egress/egress.go b/internal/atunnel/egress/egress.go index 42a05d5102..11ad1ee8e6 100644 --- a/internal/atunnel/egress/egress.go +++ b/internal/atunnel/egress/egress.go @@ -48,6 +48,10 @@ type originalDestinationFunc func(net.Conn) (string, error) // is assigned to its worker. type Proxy struct { originalDestination originalDestinationFunc + // configureAcceptedSock is a hook that runs on every socket accepted by + // the atunnel egress. This can be used to configure socket-level settings + // such as socket buffers. + configureAcceptedSock func(net.Conn) error // tunnelOpenTimeout bounds the wait for the gateway's CONNECT answer. tunnelOpenTimeout time.Duration @@ -69,8 +73,17 @@ type activation struct { wg sync.WaitGroup } +// Option customizes a Proxy. +type Option func(*Proxy) + +// WithConfigureAcceptedSock sets the hook that configures every socket the +// egress accepts, before it is proxied. A socket the hook fails on is closed. +func WithConfigureAcceptedSock(configure func(net.Conn) error) Option { + return func(e *Proxy) { e.configureAcceptedSock = configure } +} + // New creates an activation-aware egress proxy. -func New(originalDestination originalDestinationFunc) (*Proxy, error) { +func New(originalDestination originalDestinationFunc, opts ...Option) (*Proxy, error) { if originalDestination == nil { return nil, fmt.Errorf("egress: original destination resolver is required") } @@ -78,11 +91,16 @@ func New(originalDestination originalDestinationFunc) (*Proxy, error) { // means it has queued the CONNECT behind its connection cap, and closing // the connection is what frees that queue slot. const tunnelOpenTimeout = 10 * time.Second - return &Proxy{ - originalDestination: originalDestination, - tunnelOpenTimeout: tunnelOpenTimeout, - active: map[string]*activation{}, - }, nil + e := &Proxy{ + originalDestination: originalDestination, + configureAcceptedSock: func(net.Conn) error { return nil }, + tunnelOpenTimeout: tunnelOpenTimeout, + active: map[string]*activation{}, + } + for _, opt := range opts { + opt(e) + } + return e, nil } // Bind captures the actor's activation before its listeners start serving. @@ -314,6 +332,10 @@ func (e *Proxy) handle(downstream net.Conn, active *activation) { defer active.wg.Done() defer downstream.Close() + if err := e.configureAcceptedSock(downstream); err != nil { + slog.ErrorContext(active.ctx, "atunnel configureAcceptedSock failed", slog.Any("err", err)) + return + } destination, err := e.originalDestination(downstream) if err != nil { slog.WarnContext(active.ctx, "atunnel failed to resolve original egress destination", slog.Any("err", err)) diff --git a/internal/atunnel/egress/egress_test.go b/internal/atunnel/egress/egress_test.go index f9f7d97534..94a522165a 100644 --- a/internal/atunnel/egress/egress_test.go +++ b/internal/atunnel/egress/egress_test.go @@ -461,6 +461,56 @@ func TestEgressEndToEnd(t *testing.T) { } } +func TestEgressSetsUpAcceptedConnectionsFirst(t *testing.T) { + var setUp atomic.Bool + resolved := make(chan bool, 1) + egress, err := New(func(net.Conn) (string, error) { + resolved <- setUp.Load() + return "", errors.New("stop here") + }, WithConfigureAcceptedSock(func(net.Conn) error { + setUp.Store(true) + return nil + })) + if err != nil { + t.Fatal(err) + } + if err := egress.Activate(testActorUID, tunnelDialerFunc(func(context.Context, string) (net.Conn, error) { + return nil, errors.New("not dialed") + }), fakeActorCertificateSource{expiresAt: time.Now().Add(time.Hour)}, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + actor, proxy := net.Pipe() + defer actor.Close() + egress.handle(proxy, egress.active[testActorUID]) + if !receiveWithin(t, resolved, "destination lookup") { + t.Error("destination was resolved before the connection was set up") + } +} + +func TestEgressClosesConnectionsThatFailSetup(t *testing.T) { + egress, err := New(func(net.Conn) (string, error) { + t.Error("resolved the destination of a connection that failed setup") + return "", nil + }, WithConfigureAcceptedSock(func(net.Conn) error { return errors.New("setsockopt failed") })) + if err != nil { + t.Fatal(err) + } + if err := egress.Activate(testActorUID, tunnelDialerFunc(func(context.Context, string) (net.Conn, error) { + return nil, errors.New("not dialed") + }), fakeActorCertificateSource{expiresAt: time.Now().Add(time.Hour)}, time.Now().Add(time.Hour)); err != nil { + t.Fatal(err) + } + actor, proxy := net.Pipe() + defer actor.Close() + if err := actor.SetReadDeadline(time.Now().Add(time.Second)); err != nil { + t.Fatal(err) + } + egress.handle(proxy, egress.active[testActorUID]) + if _, err := actor.Read(make([]byte, 1)); !errors.Is(err, io.EOF) { + t.Fatalf("read after failed setup = %v, want EOF", err) + } +} + func TestEgressRejectsInactiveConnection(t *testing.T) { egress, err := New(func(net.Conn) (string, error) { t.Fatal("inactive egress resolved destination") diff --git a/internal/atunnel/ingress/ingress.go b/internal/atunnel/ingress/ingress.go index d0772cf8f4..0184da823f 100644 --- a/internal/atunnel/ingress/ingress.go +++ b/internal/atunnel/ingress/ingress.go @@ -304,6 +304,10 @@ func (s *Server) serve(ctx context.Context, lis net.Listener, handler http.Handl Handler: handler, TLSConfig: tlsConfig, ReadHeaderTimeout: 10 * time.Second, + // Close a connection the router stopped reading. A write to it blocks + // its handler, a stream reset queues behind that write, and + // Deactivate waits for the handler. + HTTP2: &http.HTTP2Config{WriteByteTimeout: 10 * time.Second}, } done := make(chan struct{}) go func() { @@ -385,26 +389,40 @@ func (s *Server) serveH1Connect(w http.ResponseWriter, upstream net.Conn, ctx co return } - relayWithHalfClose(ctx, log, upstream, rw, downstream, downstream) + relayWithHalfClose(ctx, log, upstream, rw, downstream, downstream, func() { _ = downstream.Close() }) } func (s *Server) serveH2Connect(w http.ResponseWriter, r *http.Request, upstream net.Conn, ctx context.Context, log *slog.Logger) { // A HTTP/2 CONNECT tunnel is a pair of streams, not a hijackable TCP // socket. Send the response headers before copying so the peer can start // sending DATA frames, then flush each upstream write promptly. + rc := http.NewResponseController(w) w.WriteHeader(http.StatusOK) - if err := http.NewResponseController(w).Flush(); err != nil { + if err := rc.Flush(); err != nil { return } - relayWithHalfClose(ctx, log, upstream, r.Body, flushingWriter{ResponseWriter: w}, r.Body) + // A write deadline in the past resets the stream, so a copy blocked on + // the router's flow-control window returns and the relay can finish + // before this handler does. The deadline is a fixed time: time.Now() can + // equal the server's clock, and the reset then runs from a timer. A + // stream the router reset, or one whose connection closed, is closed + // already and its writes fail, so it gets no reset. + abort := func() { + if r.Context().Err() == nil { + _ = rc.SetWriteDeadline(time.Unix(1, 0)) + } + } + relayWithHalfClose(ctx, log, upstream, r.Body, flushingWriter{ResponseWriter: w}, r.Body, abort) } // relayWithHalfClose copies a CONNECT stream between the router // (downstream) and the actor (upstream). It half-closes the actor connection // when the router stops sending, and closes the downstream when the actor -// does, so a router that reuses tunnels doesn't send into a dead one. -func relayWithHalfClose(ctx context.Context, log *slog.Logger, upstream net.Conn, downstreamReader io.Reader, downstreamWriter io.Writer, downstreamCloser io.Closer) { +// does, so a router that reuses tunnels doesn't send into a dead one. On +// cancel it aborts the downstream and waits for the actor-to-router copy: an +// HTTP/2 ResponseWriter must not be used once its handler returned. +func relayWithHalfClose(ctx context.Context, log *slog.Logger, upstream net.Conn, downstreamReader io.Reader, downstreamWriter io.Writer, downstreamCloser io.Closer, abortDownstream func()) { start := time.Now() go func() { n, err := io.Copy(upstream, downstreamReader) @@ -421,6 +439,8 @@ func relayWithHalfClose(ctx context.Context, log *slog.Logger, upstream net.Conn case <-ctx.Done(): log.DebugContext(ctx, "atunnel CONNECT canceled", slog.Any("cause", context.Cause(ctx)), slog.Duration("after", time.Since(start))) _ = upstream.Close() + abortDownstream() + <-actorDone case <-actorDone: } _ = downstreamCloser.Close() diff --git a/internal/atunnel/ingress/ingress_test.go b/internal/atunnel/ingress/ingress_test.go index fba09856a6..afc6e5c394 100644 --- a/internal/atunnel/ingress/ingress_test.go +++ b/internal/atunnel/ingress/ingress_test.go @@ -38,6 +38,7 @@ import ( "sync" "sync/atomic" "testing" + "testing/synctest" "time" "go.ate.dev/substrate/internal/resources" @@ -158,7 +159,7 @@ func TestRelayWithHalfClose(t *testing.T) { var downstreamOutput bytes.Buffer done := make(chan struct{}) go func() { - relayWithHalfClose(context.Background(), slog.New(slog.DiscardHandler), upstream, downstreamReader, &downstreamOutput, downstreamReader) + relayWithHalfClose(context.Background(), slog.New(slog.DiscardHandler), upstream, downstreamReader, &downstreamOutput, downstreamReader, func() {}) close(done) }() @@ -207,7 +208,7 @@ func TestRelayIngressClosesDownstreamWhenActorCloses(t *testing.T) { log := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})) done := make(chan struct{}) go func() { - relayWithHalfClose(context.Background(), log, upstream, downstreamReader, &downstreamOutput, downstreamReader) + relayWithHalfClose(context.Background(), log, upstream, downstreamReader, &downstreamOutput, downstreamReader, func() {}) close(done) }() @@ -243,7 +244,7 @@ func TestRelayIngressCancellationClosesBothSides(t *testing.T) { log := slog.New(slog.NewTextHandler(&logs, &slog.HandlerOptions{Level: slog.LevelDebug})) done := make(chan struct{}) go func() { - relayWithHalfClose(ctx, log, upstream, downstreamReader, io.Discard, downstreamReader) + relayWithHalfClose(ctx, log, upstream, downstreamReader, io.Discard, downstreamReader, func() {}) close(done) }() @@ -266,6 +267,62 @@ func TestRelayIngressCancellationClosesBothSides(t *testing.T) { } } +// The relay must not return while its actor-to-router copy is inside a Write: +// an HTTP/2 ResponseWriter panics when used after its handler returned. On +// cancel the relay aborts the downstream, which is what makes such a Write +// return, and waits for the copy. +func TestRelayIngressCancellationWaitsForActorCopy(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + upstream, actor := net.Pipe() + defer actor.Close() + downstreamReader, downstreamInput := io.Pipe() + defer downstreamInput.Close() + writer := &blockingWriter{entered: make(chan struct{}), release: make(chan struct{}), aborted: make(chan struct{})} + // A copy left inside Write would deadlock the bubble on a failure. + defer writer.unblock() + ctx, cancel := context.WithCancelCause(context.Background()) + done := make(chan struct{}) + go func() { + relayWithHalfClose(ctx, slog.New(slog.DiscardHandler), upstream, downstreamReader, writer, downstreamReader, writer.abort) + close(done) + }() + + go func() { _, _ = actor.Write([]byte("x")) }() + <-writer.entered + cancel(errActorDeactivated) + synctest.Wait() + select { + case <-writer.aborted: + default: + t.Fatal("relay did not abort the downstream") + } + select { + case <-done: + t.Fatal("relay returned while the actor copy was inside Write") + default: + } + writer.unblock() + <-done + }) +} + +// blockingWriter stays inside Write until released, like an HTTP/2 write on +// an exhausted flow-control window. +type blockingWriter struct { + entered, release, aborted chan struct{} + enterOnce, releaseOnce sync.Once +} + +func (w *blockingWriter) Write(p []byte) (int, error) { + w.enterOnce.Do(func() { close(w.entered) }) + <-w.release + return len(p), nil +} + +func (w *blockingWriter) abort() { close(w.aborted) } + +func (w *blockingWriter) unblock() { w.releaseOnce.Do(func() { close(w.release) }) } + // syncBuffer collects logs from the relay's goroutines. type syncBuffer struct { mu sync.Mutex @@ -1273,6 +1330,260 @@ func TestServeConnectHTTPDialsTheSandbox(t *testing.T) { } } +// A router that stops reading leaves the actor-to-router copy blocked on the +// HTTP/2 flow-control window. Deactivate must still return: the relay resets +// the stream and waits for the copy instead of leaving it to write into a +// finished handler. +func TestServeH2ConnectDeactivateResetsStalledTunnel(t *testing.T) { + upstreamURL, err := url.Parse("http://actor.internal:80") + if err != nil { + t.Fatal(err) + } + s := newTestServer(t, upstreamURL) + upstream, actor := net.Pipe() + defer actor.Close() + dial := func(context.Context, string, string) (net.Conn, error) { return upstream, nil } + if err := s.Activate("team-a", "actor-1", "uid-actor-1", dial); err != nil { + t.Fatal(err) + } + srv := httptest.NewUnstartedServer(http.HandlerFunc(s.serveConnectHTTP)) + srv.EnableHTTP2 = true + srv.StartTLS() + defer srv.Close() + // The router's stream window is set here, so the test knows when the + // actor has used it up. + const window = 64 << 10 + srv.Client().Transport.(*http.Transport).HTTP2 = &http.HTTP2Config{MaxReceiveBufferPerStream: window} + + routerInput, routerOutput := io.Pipe() + defer routerOutput.Close() + req, err := http.NewRequest(http.MethodConnect, srv.URL, routerInput) + if err != nil { + t.Fatal(err) + } + req.Host = "actor-1.team-a.actors.resources.substrate.ate.dev:9090" + req.Header.Set(atenet.TargetActorHeader, "team-a/actor-1") + res, err := srv.Client().Do(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.Proto != "HTTP/2.0" || res.StatusCode != http.StatusOK { + t.Fatalf("tunnel opened as %s %d, want HTTP/2.0 200", res.Proto, res.StatusCode) + } + + // The router reads nothing. The actor fills the stream window, and the + // copy of one more byte cannot finish. + if _, err := actor.Write(make([]byte, window)); err != nil { + t.Fatal(err) + } + if _, err := actor.Write([]byte("x")); err != nil { + t.Fatal(err) + } + + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) + defer cancel() + if err := s.Deactivate(ctx, "team-a", "actor-1", "uid-actor-1"); err != nil { + t.Fatalf("Deactivate with a stalled router: %v", err) + } + if _, err := io.Copy(io.Discard, res.Body); err == nil { + t.Error("the stalled tunnel ended cleanly, want a stream reset") + } +} + +// A stream the router reset is closed already, so the relay resets only a +// stream that is still open. The clock in the bubble does not move, so a +// deadline counts only if it is in the past when the relay sets it. +func TestServeH2ConnectResetsOnlyOpenStreams(t *testing.T) { + for _, tc := range []struct { + name string + routerReset bool + wantResets int + }{ + {name: "actor deactivated", wantResets: 1}, + {name: "router reset the stream", routerReset: true, wantResets: 0}, + } { + t.Run(tc.name, func(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + upstream, actor := net.Pipe() + defer actor.Close() + streamCtx, resetStream := context.WithCancel(context.Background()) + defer resetStream() + if tc.routerReset { + resetStream() + } + relayCtx, cancel := context.WithCancel(streamCtx) + cancel() + r, err := http.NewRequestWithContext(streamCtx, http.MethodConnect, "https://actor:9090", http.NoBody) + if err != nil { + t.Fatal(err) + } + w := &deadlineRecorder{ResponseRecorder: httptest.NewRecorder()} + new(Server).serveH2Connect(w, r, upstream, relayCtx, slog.New(slog.DiscardHandler)) + if w.resets != tc.wantResets { + t.Errorf("stream resets = %d, want %d", w.resets, tc.wantResets) + } + }) + }) + } +} + +// deadlineRecorder counts write deadlines that are already past, which is how +// the relay resets an HTTP/2 stream. +type deadlineRecorder struct { + *httptest.ResponseRecorder + resets int +} + +func (w *deadlineRecorder) SetWriteDeadline(deadline time.Time) error { + if deadline.Before(time.Now()) { + w.resets++ + } + return nil +} + +// A router that stops reading the connection leaves a frame write blocked, +// and the stream reset queues behind it. The server's write timeout closes +// the connection, so the relay's copy ends and Deactivate returns. +func TestServeConnectDeactivateClosesStalledConnection(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + const routerID = "spiffe://cluster.local/ns/ate-system/sa/atenet-router" + dir := t.TempDir() + ca := newTestCA(t) + bundlePath := filepath.Join(dir, "server.pem") + trustPath := filepath.Join(dir, "trust.pem") + writeCredentialBundle(t, bundlePath, ca.issue(t, "", []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth})) + if err := os.WriteFile(trustPath, ca.certPEM, 0o600); err != nil { + t.Fatal(err) + } + upstreamURL, err := url.Parse("http://actor.internal:80") + if err != nil { + t.Fatal(err) + } + s, err := NewServer(Config{ + CredentialBundlePath: bundlePath, + TrustBundlePath: trustPath, + AllowedClientID: routerID, + Upstream: upstreamURL, + }) + if err != nil { + t.Fatal(err) + } + upstream, actor := net.Pipe() + defer actor.Close() + dial := func(context.Context, string, string) (net.Conn, error) { return upstream, nil } + if err := s.Activate("team-a", "actor-1", "uid-actor-1", dial); err != nil { + t.Fatal(err) + } + + // One in-memory connection. A write on it blocks until the other end + // reads, so a router that stops reading stalls the worker at once. + routerEnd, workerEnd := net.Pipe() + router := &stallableConn{Conn: routerEnd, stalled: make(chan struct{}), closed: make(chan struct{})} + defer router.Close() + lis := &pipeListener{conn: make(chan net.Conn, 1), closed: make(chan struct{})} + lis.conn <- workerEnd + serveCtx, stopServing := context.WithCancel(context.Background()) + served := make(chan error, 1) + go func() { served <- s.ServeConnect(serveCtx, lis) }() + defer func() { + stopServing() + if err := <-served; err != nil { + t.Errorf("ServeConnect: %v", err) + } + }() + + transport := &http.Transport{ + DialContext: func(context.Context, string, string) (net.Conn, error) { return router, nil }, + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS12, + InsecureSkipVerify: true, // The handshake checks live in TestMutualTLSClientAuthentication. + Certificates: []tls.Certificate{ca.issue(t, routerID, []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth})}, + }, + ForceAttemptHTTP2: true, + } + routerInput, routerOutput := io.Pipe() + defer routerOutput.Close() + req, err := http.NewRequest(http.MethodConnect, "https://worker.internal", routerInput) + if err != nil { + t.Fatal(err) + } + req.Host = "actor-1.team-a.actors.resources.substrate.ate.dev:9090" + req.Header.Set(atenet.TargetActorHeader, "team-a/actor-1") + res, err := transport.RoundTrip(req) + if err != nil { + t.Fatal(err) + } + defer res.Body.Close() + if res.Proto != "HTTP/2.0" || res.StatusCode != http.StatusOK { + t.Fatalf("tunnel opened as %s %d, want HTTP/2.0 200", res.Proto, res.StatusCode) + } + + close(router.stalled) + go func() { + chunk := make([]byte, 64<<10) + for { + if _, err := actor.Write(chunk); err != nil { + return + } + } + }() + synctest.Wait() + + ctx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + if err := s.Deactivate(ctx, "team-a", "actor-1", "uid-actor-1"); err != nil { + t.Fatalf("Deactivate with a stalled connection: %v", err) + } + }) +} + +// stallableConn is a connection that can stop reading, like a router that no +// longer takes bytes from the worker. +type stallableConn struct { + net.Conn + stalled, closed chan struct{} + closeOnce sync.Once +} + +func (c *stallableConn) Read(p []byte) (int, error) { + select { + case <-c.stalled: + <-c.closed + return 0, net.ErrClosed + default: + return c.Conn.Read(p) + } +} + +func (c *stallableConn) Close() error { + c.closeOnce.Do(func() { close(c.closed) }) + return c.Conn.Close() +} + +// pipeListener serves the in-memory connections put on conn. +type pipeListener struct { + conn chan net.Conn + closed chan struct{} + closeOnce sync.Once +} + +func (l *pipeListener) Accept() (net.Conn, error) { + select { + case conn := <-l.conn: + return conn, nil + case <-l.closed: + return nil, net.ErrClosed + } +} + +func (l *pipeListener) Close() error { + l.closeOnce.Do(func() { close(l.closed) }) + return nil +} + +func (l *pipeListener) Addr() net.Addr { return &net.TCPAddr{} } + // A worker hosts several actors at once. They share one listener and one // address, so the request's actor header picks between them and each is reached // through its own dialer. diff --git a/internal/atunnel/tunnel.go b/internal/atunnel/tunnel.go index d27d29fe7f..77984b9c20 100644 --- a/internal/atunnel/tunnel.go +++ b/internal/atunnel/tunnel.go @@ -29,6 +29,8 @@ import ( "net/url" "time" + "go.opentelemetry.io/otel/metric" + "go.ate.dev/substrate/internal/ateletdial" "go.ate.dev/substrate/internal/atunnel/dns" "go.ate.dev/substrate/internal/atunnel/egress" @@ -93,6 +95,10 @@ func RegisterFlags(fs FlagSet) *Config { return c } +// tcpNotSentLowat is the TCP_NOTSENT_LOWAT of every atunnel TCP connection, +// so a slow reader's backlog stays upstream, not in the kernel send queue. +const tcpNotSentLowat = 16384 + // Tunnel is the atunnel state one worker shares across its actors. type Tunnel struct { // Ingress proxies router traffic to the active actors. @@ -112,8 +118,8 @@ type Tunnel struct { // Start builds the DNS relay and starts serving actor ingress, which proxies // to upstream inside each sandbox. Egress binds only in sandbox namespaces, so -// nothing listens for it here. -func Start(ctx context.Context, cfg Config, upstream string) (*Tunnel, error) { +// nothing listens for it here. The DNS relay reports its metrics on meter. +func Start(ctx context.Context, cfg Config, upstream string, meter metric.Meter) (*Tunnel, error) { if err := egresspolicy.ValidateDNSEgressPolicy(cfg.DNSEgressPolicy); err != nil { return nil, err } @@ -122,7 +128,7 @@ func Start(ctx context.Context, cfg Config, upstream string) (*Tunnel, error) { return nil, fmt.Errorf("while parsing atunnel upstream: %w", err) } - dnsRelay, err := dns.NewRelay(resolvConfPath) + dnsRelay, err := dns.NewRelay(resolvConfPath, meter) if err != nil { return nil, fmt.Errorf("configuring DNS relay: %w", err) } @@ -149,7 +155,9 @@ func Start(ctx context.Context, cfg Config, upstream string) (*Tunnel, error) { } // Egress - egressProxy, err := egress.New(linuxsys.TCPOriginalDestination) + egressProxy, err := egress.New(linuxsys.TCPOriginalDestination, egress.WithConfigureAcceptedSock(func(conn net.Conn) error { + return linuxsys.SetTCPNotSentLowat(conn, tcpNotSentLowat) + })) if err != nil { return nil, fmt.Errorf("configuring egress: %w", err) } @@ -169,12 +177,14 @@ func Start(ctx context.Context, cfg Config, upstream string) (*Tunnel, error) { } // serve listens on address and runs serveFn on it, exiting the process if it -// fails. +// fails. Every connection it accepts gets TCP_NOTSENT_LOWAT tcpNotSentLowat. func serve(ctx context.Context, name, address string, serveFn func(context.Context, net.Listener) error) error { - lis, err := net.Listen("tcp", address) + var lc net.ListenConfig + lis, err := lc.Listen(ctx, "tcp", address) if err != nil { return fmt.Errorf("while opening %s listener: %w", name, err) } + lis = &listenerWithOptions{Listener: lis} go func() { if err := serveFn(ctx, lis); err != nil { serverboot.Fatal(ctx, "Failed to serve "+name, err) @@ -184,6 +194,30 @@ func serve(ctx context.Context, name, address string, serveFn func(context.Conte return nil } +// listenerWithOptions sets TCP_NOTSENT_LOWAT on every connection it accepts. A +// connection it can't be set on is closed, and the next one accepted. Setting +// it on the listening socket isn't enough: Go opens MPTCP listeners by default +// where the kernel enables MPTCP, and an MPTCP listener doesn't pass +// TCP_NOTSENT_LOWAT to the TCP connections it accepts. +type listenerWithOptions struct { + net.Listener +} + +func (l *listenerWithOptions) Accept() (net.Conn, error) { + for { + conn, err := l.Listener.Accept() + if err != nil { + return nil, err + } + if err := linuxsys.SetTCPNotSentLowat(conn, tcpNotSentLowat); err != nil { + slog.Warn("atunnel failed to set TCP_NOTSENT_LOWAT on an accepted connection", slog.Any("err", err)) + _ = conn.Close() + continue + } + return conn, nil + } +} + // ActorEgress is an actor's tunneled egress, ready to activate. type ActorEgress struct { // client presents the actor certificate to the remote egress gateway. @@ -229,6 +263,7 @@ func (t *Tunnel) PrepareEgress(ctx context.Context, actor resources.ActorAttribu ServerName: serverName, GetClientCertificate: certificateSource.GetClientCertificate, TrustBundlePath: t.cfg.EgressTrustBundle, + DialControl: linuxsys.TCPNotSentLowatControl(tcpNotSentLowat), }) if err != nil { return nil, fmt.Errorf("while configuring actor egress client: %w", err) @@ -252,7 +287,7 @@ func (t *Tunnel) ActivateEgress(actor resources.ActorAttribution, actorEgress *A // ActivateIngress starts admitting the actor's inbound traffic through dial. // Call it once the workload is ready to serve. func (t *Tunnel) ActivateIngress(actor resources.ActorAttribution, dial ingress.DialFunc) error { - if err := t.Ingress.Activate(actor.Ref.Atespace, actor.Ref.Name, actor.UID, dial); err != nil { + if err := t.Ingress.Activate(actor.Ref.Atespace, actor.Ref.Name, actor.UID, tunedDial(dial)); err != nil { return fmt.Errorf("while activating actor ingress: %w", err) } return nil @@ -271,3 +306,20 @@ func (t *Tunnel) Deactivate(ctx context.Context, actor resources.ActorAttributio } return nil } + +// tunedDial sets TCP_NOTSENT_LOWAT tcpNotSentLowat on every connection dial +// opens. The sandbox dialer creates the socket inside the actor's namespace, +// so the option goes on after connect. +func tunedDial(dial ingress.DialFunc) ingress.DialFunc { + return func(ctx context.Context, network, address string) (net.Conn, error) { + conn, err := dial(ctx, network, address) + if err != nil { + return nil, err + } + if err := linuxsys.SetTCPNotSentLowat(conn, tcpNotSentLowat); err != nil { + _ = conn.Close() + return nil, err + } + return conn, nil + } +} diff --git a/internal/atunnel/tunnel_test.go b/internal/atunnel/tunnel_test.go index 629739cf60..bc726f0fa3 100644 --- a/internal/atunnel/tunnel_test.go +++ b/internal/atunnel/tunnel_test.go @@ -25,6 +25,7 @@ import ( "crypto/x509/pkix" "encoding/pem" "flag" + "io" "math/big" "net" "os" @@ -38,6 +39,8 @@ import ( "go.ate.dev/substrate/internal/proto/ateworkerpb" "go.ate.dev/substrate/internal/resources" "go.ate.dev/substrate/internal/substratex509" + "go.opentelemetry.io/otel/metric/noop" + "golang.org/x/sys/unix" ) func TestRegisterFlags(t *testing.T) { @@ -96,6 +99,74 @@ func TestRegisterFlags(t *testing.T) { } } +func TestTunedDialAppliesActorOptions(t *testing.T) { + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + defer listener.Close() + go func() { + if conn, err := listener.Accept(); err == nil { + defer conn.Close() + _, _ = io.Copy(io.Discard, conn) + } + }() + + conn, err := tunedDial((&net.Dialer{}).DialContext)(context.Background(), "tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + defer conn.Close() + if got := readNotSentLowat(t, conn); got != 16384 { + t.Errorf("dialed connection TCP_NOTSENT_LOWAT = %d, want 16384", got) + } +} + +func TestServeSetsTCPNotSentLowatOnAcceptedConnections(t *testing.T) { + accepted := make(chan net.Conn, 1) + address := freeAddress(t) + if err := serve(t.Context(), "test", address, func(_ context.Context, lis net.Listener) error { + conn, err := lis.Accept() + if err != nil { + return nil + } + accepted <- conn + return nil + }); err != nil { + t.Fatal(err) + } + client, err := net.DialTimeout("tcp", address, 5*time.Second) + if err != nil { + t.Fatal(err) + } + defer client.Close() + conn := <-accepted + defer conn.Close() + if got := readNotSentLowat(t, conn); got != 16384 { + t.Errorf("accepted connection TCP_NOTSENT_LOWAT = %d, want 16384", got) + } +} + +// readNotSentLowat returns the TCP_NOTSENT_LOWAT in effect on conn. +func readNotSentLowat(t *testing.T, conn net.Conn) int { + t.Helper() + rawConn, err := conn.(*net.TCPConn).SyscallConn() + if err != nil { + t.Fatal(err) + } + var got int + var sockoptErr error + if err := rawConn.Control(func(fd uintptr) { + got, sockoptErr = unix.GetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_NOTSENT_LOWAT) + }); err != nil { + t.Fatal(err) + } + if sockoptErr != nil { + t.Fatal(sockoptErr) + } + return got +} + // testConfig returns a Config over fresh credentials and free loopback ports. func testConfig(t *testing.T) Config { t.Helper() @@ -203,7 +274,7 @@ func startTunnel(t *testing.T, cfg Config) *Tunnel { t.Helper() ctx, cancel := context.WithCancel(context.Background()) t.Cleanup(cancel) - tunnel, err := Start(ctx, cfg, "http://169.254.17.2:80") + tunnel, err := Start(ctx, cfg, "http://169.254.17.2:80", noop.Meter{}) if err != nil { t.Fatal(err) } @@ -284,7 +355,7 @@ func TestStartErrors(t *testing.T) { tc.edit(t, &cfg) ctx, cancel := context.WithCancel(context.Background()) defer cancel() - _, err := Start(ctx, cfg, "http://169.254.17.2:80") + _, err := Start(ctx, cfg, "http://169.254.17.2:80", noop.Meter{}) if (err != nil) != tc.wantErr { t.Fatalf("Start error = %v, wantErr = %v", err, tc.wantErr) } @@ -292,7 +363,7 @@ func TestStartErrors(t *testing.T) { } t.Run("bad upstream", func(t *testing.T) { - _, err := Start(context.Background(), testConfig(t), "http://[::1") + _, err := Start(context.Background(), testConfig(t), "http://[::1", noop.Meter{}) if err == nil { t.Fatalf("Start error = %v, want an error", err) } diff --git a/internal/benchmarking/boomer/agentsession/turnover.go b/internal/benchmarking/boomer/agentsession/turnover.go index c027cfa796..50645a1908 100644 --- a/internal/benchmarking/boomer/agentsession/turnover.go +++ b/internal/benchmarking/boomer/agentsession/turnover.go @@ -28,13 +28,16 @@ import ( // and swaps idle awake sessions with parked ones at target_rps/s. Each session // registers by creating its actor, running step 1, and parking it. After // registrationQuiet with no active registrations, the conductor wakes -// agentsession_awake sessions and then swaps at target_rps/s. +// agentsession_awake sessions and then swaps at target_rps/s, evenly spaced. const ( registrationQuiet = time.Minute turnoverStartConcurrency = 48 fillConcurrency = 8 - swapTick = time.Second - turnoverParkRetry = 2 * time.Second + // fillTick is how often the conductor wakes a batch to reach or restore + // the awake count. swapTick is how finely it paces swaps. + fillTick = time.Second + swapTick = 10 * time.Millisecond + turnoverParkRetry = 2 * time.Second ) var turnoverSessions = prometheus.NewGaugeVec(prometheus.GaugeOpts{ @@ -67,11 +70,14 @@ type conductor struct { filled bool halted bool warnHalted sync.Once - credit float64 + // credit is the swaps owed, earned at the rate since lastTick. + credit float64 + lastTick time.Time + lastFill time.Time } func newConductor(now func() time.Time) *conductor { - return &conductor{now: now, busy: map[*sessionUser]bool{}, inFlight: map[*sessionUser]turnCmd{}} + return &conductor{now: now, busy: map[*sessionUser]bool{}, inFlight: map[*sessionUser]turnCmd{}, lastTick: now()} } func (c *conductor) join(u *sessionUser) { @@ -125,20 +131,32 @@ func (c *conductor) tick(awake int, rate float64) { c.mu.Lock() defer c.mu.Unlock() defer c.export() + now := c.now() + elapsed := now.Sub(c.lastTick) + c.lastTick = now if c.halted { return } + fillDue := now.Sub(c.lastFill) >= fillTick + if fillDue { + c.lastFill = now + } if !c.filled { - c.fill(awake) + if fillDue { + c.fill(awake) + } return } - c.balance(awake, fillConcurrency) + if fillDue { + c.balance(awake, fillConcurrency) + } if rate <= 0 { c.credit = 0 return } - perTick := rate * swapTick.Seconds() - c.credit = min(c.credit+perTick, perTick+1) + // Up to a second of credit carries over, so the swap rate catches up + // after a stall. + c.credit = min(c.credit+rate*elapsed.Seconds(), rate+1) for c.credit >= 1 && len(c.idle) > 0 && len(c.parked) > 0 { c.send(&c.idle, cmdPark) c.send(&c.parked, cmdWake) diff --git a/internal/benchmarking/boomer/agentsession/turnover_test.go b/internal/benchmarking/boomer/agentsession/turnover_test.go index 39fd5072ae..844b62c526 100644 --- a/internal/benchmarking/boomer/agentsession/turnover_test.go +++ b/internal/benchmarking/boomer/agentsession/turnover_test.go @@ -82,21 +82,30 @@ func TestConductorFill(t *testing.T) { len(got[cmdWake]), len(got[cmdPark])) } - now = now.Add(time.Second) for _, want := range []int{fillConcurrency, awake - fillConcurrency} { + now = now.Add(fillTick) c.tick(awake, 5) got := commands(fleet) if len(got[cmdWake]) != want || len(got[cmdPark]) != 0 { t.Fatalf("fill tick sent %d wakes and %d parks, want %d wakes", len(got[cmdWake]), len(got[cmdPark]), want) } finish(c, got) + + now = now.Add(swapTick) + c.tick(awake, 5) + if got := commands(fleet); len(got) != 0 { + t.Fatalf("tick %v after a fill tick sent %d wakes and %d parks, want none", + swapTick, len(got[cmdWake]), len(got[cmdPark])) + } } + now = now.Add(fillTick) c.tick(awake, 5) if got := commands(fleet); len(got) != 0 || !c.filled { t.Fatalf("tick after %d sessions woke: %d wakes, %d parks, filled %v; want none and true", awake, len(got[cmdWake]), len(got[cmdPark]), c.filled) } + now = now.Add(time.Second) c.tick(awake, 5) got := commands(fleet) if len(got[cmdPark]) != 5 || len(got[cmdWake]) != 5 { @@ -115,7 +124,8 @@ func TestConductorFill(t *testing.T) { } func TestConductorSwaps(t *testing.T) { - c := newConductor(time.Now) + now := time.Unix(1000, 0) + c := newConductor(func() time.Time { return now }) c.filled = true fleet := append(turnSessions(4, true), turnSessions(4, false)...) for _, u := range fleet { @@ -126,14 +136,22 @@ func TestConductorSwaps(t *testing.T) { t.Fatal("claim of an idle session failed") } for i, tc := range []struct { + after time.Duration rate float64 swaps int }{ - {1.5, 1}, - {1.5, 2}, - {0, 0}, - {1, 1}, + {time.Second, 1.5, 1}, + {time.Second, 1.5, 2}, + {time.Second, 0, 0}, + {time.Second, 1, 1}, + // A swap is due every 100ms, however often the conductor ticks. + {60 * time.Millisecond, 10, 0}, + {60 * time.Millisecond, 10, 1}, + {60 * time.Millisecond, 10, 0}, + // A minute without a tick keeps a second of credit. + {time.Minute, 1, 2}, } { + now = now.Add(tc.after) c.tick(4, tc.rate) got := commands(fleet) if len(got[cmdPark]) != tc.swaps || len(got[cmdWake]) != tc.swaps { @@ -171,7 +189,9 @@ func TestConductorRestoresAwakeCount(t *testing.T) { got := commands(fleet) if tc.filled { finish(c, got) + now = now.Add(fillTick) c.tick(awake, 1) // ends the fill + now = now.Add(time.Second) c.tick(awake, 1) // swaps one got = commands(fleet) } @@ -183,6 +203,7 @@ func TestConductorRestoresAwakeCount(t *testing.T) { got[tc.fail] = got[tc.fail][1:] finish(c, got) + now = now.Add(fillTick) c.tick(awake, 0) got = commands(fleet) if len(got) != 1 || len(got[tc.fail]) != 1 { @@ -497,6 +518,7 @@ func TestConductorFillWaitsForInFlightStarts(t *testing.T) { t.Fatalf("with starts in flight: parked %d, filled %v; want 1, false", len(c.parked), c.filled) } inFlight = 0 + now = now.Add(fillTick) c.tick(1, 0) if len(c.inFlight) != 1 { t.Errorf("after starts finished: inFlight %d, want 1", len(c.inFlight)) diff --git a/internal/benchmarking/boomer/resumepaused/knobs_test.go b/internal/benchmarking/boomer/resumepaused/knobs_test.go index c11e3772b6..d9e52a64d1 100644 --- a/internal/benchmarking/boomer/resumepaused/knobs_test.go +++ b/internal/benchmarking/boomer/resumepaused/knobs_test.go @@ -20,30 +20,40 @@ import ( "go.ate.dev/substrate/internal/benchmarking/boomer/dynconfig" ) -// The codec takes a target rate, reads an absent one as unpaced, and -// refuses a negative one in favor of the config before it. +// The codec takes target_rps and burst_size, reads absent ones as unpaced and +// smooth, and refuses negative values or a positive burst_size without a +// positive target_rps in favor of the config before it. func TestKnobsCodec(t *testing.T) { h := dynconfig.NewHolder(knobsCodec) if got := dynconfig.Get[knobs](h); got != (knobs{}) { t.Fatalf("fresh holder = %+v, want unpaced", got) } - if _, _, err := h.Apply([]byte(`{"target_rps": 2500.5, "someone_elses_key": 1}`)); err != nil { + if _, _, err := h.Apply([]byte(`{"target_rps": 2500.5, "burst_size": 50, "someone_elses_key": 1}`)); err != nil { t.Fatalf("Apply(valid): %v", err) } - want := knobs{TargetRPS: 2500.5} + want := knobs{TargetRPS: 2500.5, BurstSize: 50} if got := dynconfig.Get[knobs](h); got != want { t.Errorf("decoded = %+v, want %+v", got, want) } - if _, _, err := h.Apply([]byte(`{"target_rps": -1}`)); err == nil { - t.Error("Apply(negative target_rps) took the payload, want a refusal") + for name, bad := range map[string]string{ + "negative target_rps": `{"target_rps": -1}`, + "negative burst_size": `{"target_rps": 10, "burst_size": -1}`, + "burst_size without rate": `{"burst_size": 10}`, + "burst_size with zero rps": `{"target_rps": 0, "burst_size": 10}`, + } { + t.Run(name, func(t *testing.T) { + if _, _, err := h.Apply([]byte(bad)); err == nil { + t.Errorf("Apply(%s) took the payload, want a refusal", bad) + } + if got := dynconfig.Get[knobs](h); got != want { + t.Errorf("a refused payload changed the config to %+v", got) + } + }) } - if got := dynconfig.Get[knobs](h); got != want { - t.Errorf("a refused payload changed the config to %+v", got) - } - if _, _, err := h.Apply([]byte(`{"target_rps": null}`)); err != nil { + if _, _, err := h.Apply([]byte(`{"target_rps": null, "burst_size": null}`)); err != nil { t.Fatalf("Apply(null): %v", err) } if got := dynconfig.Get[knobs](h); got != (knobs{}) { - t.Errorf("a null target_rps left %+v, want unpaced", got) + t.Errorf("nulls left %+v, want unpaced", got) } } diff --git a/internal/benchmarking/boomer/resumepaused/resumepaused.go b/internal/benchmarking/boomer/resumepaused/resumepaused.go index 456a072e2b..d3bceca37b 100644 --- a/internal/benchmarking/boomer/resumepaused/resumepaused.go +++ b/internal/benchmarking/boomer/resumepaused/resumepaused.go @@ -63,12 +63,17 @@ func init() { } // knobs is the ResumePausedUser slice of the runtime config. The master -// populates target_rps from the --target-rps locust flag -// (common/rate_config.py) or the ladder step's @rps suffix. +// populates target_rps and burst_size from the --target-rps and --burst-size +// locust flags (common/rate_config.py), and a ladder step's @rps suffix +// updates target_rps. type knobs struct { // TargetRPS is the cold resumes per second this worker paces to; zero // means unpaced. TargetRPS float64 `json:"target_rps"` + // BurstSize, when positive, releases cold resumes in waves of up to + // this many users every BurstSize/TargetRPS seconds instead of spacing + // them one by one. Zero paces smoothly. + BurstSize int `json:"burst_size"` } var knobsCodec = dynconfig.Typed[knobs]{ @@ -76,6 +81,12 @@ var knobsCodec = dynconfig.Typed[knobs]{ if k.TargetRPS < 0 { return fmt.Errorf("target_rps cannot be negative: %v", k.TargetRPS) } + if k.BurstSize < 0 { + return fmt.Errorf("burst_size cannot be negative: %d", k.BurstSize) + } + if k.BurstSize > 0 && k.TargetRPS <= 0 { + return fmt.Errorf("burst_size (%d) requires target_rps > 0", k.BurstSize) + } return nil }, } @@ -104,10 +115,14 @@ type runtime struct { // actorsMu guards actors, every actor that may exist, for shutdown. actorsMu sync.Mutex actors map[string]struct{} - // limiter paces the resumes of every user. Its burst of 1 spaces them - // evenly: Wait hands each caller the next slot rather than releasing a - // second's budget at once. + // limiter paces the resumes of every user when burst_size is 0. Its + // burst of 1 spaces them evenly: Wait hands each caller the next slot + // rather than releasing a second's budget at once. limiter *rate.Limiter + // waveMu guards the wave schedule used when burst_size > 0. + waveMu sync.Mutex + waveTime time.Time + waveCount int // retryBackoff spaces the retries of a delete. retryBackoff time.Duration // setupRetryWait is how long a user waits after its actor failed to @@ -149,6 +164,19 @@ func newRuntime(cfg *userclass.Config) *runtime { } } +// sleepCtx blocks for d or until ctx is done. +func sleepCtx(ctx context.Context, d time.Duration) { + if d <= 0 { + return + } + t := time.NewTimer(d) + defer t.Stop() + select { + case <-t.C: + case <-ctx.Done(): + } +} + // start ensures the atespace every actor is created in. func (r *runtime) start(ctx context.Context) error { if err := r.ensureAtespace(ctx); err != nil { @@ -289,12 +317,24 @@ func (r *runtime) startCycle() bool { return true } -// pace blocks until the limiter grants the next resume slot, applying the -// current TargetRPS first. Zero means unpaced. +// pace blocks until the next resume slot. When BurstSize is 0, the limiter +// spaces resumes one by one at TargetRPS (zero means unpaced). When BurstSize +// is positive, up to BurstSize callers sleep until the same wave boundary, +// spaced by BurstSize/TargetRPS seconds. func (r *runtime) pace(ctx context.Context) { + k := dynconfig.Get[knobs](r.cfg.Dyn) + if k.BurstSize > 0 { + r.waveMu.Lock() + now := time.Now() + r.waveTime, r.waveCount = waveSlot(now, r.waveTime, r.waveCount, k.BurstSize, k.TargetRPS) + slot := r.waveTime + r.waveMu.Unlock() + sleepCtx(ctx, slot.Sub(now)) + return + } want := rate.Inf - if target := dynconfig.Get[knobs](r.cfg.Dyn).TargetRPS; target > 0 { - want = rate.Limit(target) + if k.TargetRPS > 0 { + want = rate.Limit(k.TargetRPS) } if r.limiter.Limit() != want { r.limiter.SetLimit(want) @@ -302,6 +342,31 @@ func (r *runtime) pace(ctx context.Context) { _ = r.limiter.Wait(ctx) } +// waveSlot returns the wave boundary at which a caller arriving at now should +// fire its resume, along with the updated caller count for that boundary. At +// most burstSize callers share one boundary, and boundaries sit on a grid +// spaced by burstSize/targetRPS seconds. +func waveSlot(now, waveTime time.Time, waveCount, burstSize int, targetRPS float64) (slot time.Time, nextCount int) { + period := time.Duration(float64(time.Second) * float64(burstSize) / targetRPS) + if period <= 0 { + return now, waveCount + } + switch { + case waveTime.IsZero(): + waveTime = now.Add(period) + waveCount = 0 + case !now.Before(waveTime): + steps := (now.Sub(waveTime))/period + 1 + waveTime = waveTime.Add(steps * period) + waveCount = 0 + case waveCount >= burstSize: + waveTime = waveTime.Add(period) + waveCount = 0 + } + waveCount++ + return waveTime, waveCount +} + // errAlreadyRunning marks a ResumeActor that found its actor running, so no // cold resume happened and the sample must not count as one. var errAlreadyRunning = errors.New("actor was already running: not a cold resume") diff --git a/internal/benchmarking/boomer/resumepaused/resumepaused_test.go b/internal/benchmarking/boomer/resumepaused/resumepaused_test.go index 2fc6052355..86348bd914 100644 --- a/internal/benchmarking/boomer/resumepaused/resumepaused_test.go +++ b/internal/benchmarking/boomer/resumepaused/resumepaused_test.go @@ -25,6 +25,7 @@ import ( "sync" "sync/atomic" "testing" + "testing/synctest" "time" "github.com/prometheus/client_golang/prometheus/promhttp" @@ -33,6 +34,7 @@ import ( "go.ate.dev/substrate/internal/benchmarking/boomer/dynconfig" "go.ate.dev/substrate/internal/benchmarking/boomer/userclass" "go.opentelemetry.io/otel" + "golang.org/x/time/rate" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/metadata" @@ -543,6 +545,135 @@ func TestIteratePacesResumes(t *testing.T) { } } +func TestWaveSlot(t *testing.T) { + t0 := time.Unix(1_700_000_000, 0) + // burstSize=3 at targetRPS=30 gives a 100ms wave period. + const ( + burst = 3 + rps = 30.0 + period = 100 * time.Millisecond + ) + tests := []struct { + name string + now time.Time + waveTime time.Time + waveCount int + wantSlot time.Time + wantCount int + }{ + { + name: "first caller starts first future boundary", + now: t0, + waveTime: time.Time{}, + waveCount: 0, + wantSlot: t0.Add(period), + wantCount: 1, + }, + { + name: "second caller before boundary shares the wave", + now: t0.Add(10 * time.Millisecond), + waveTime: t0.Add(period), + waveCount: 1, + wantSlot: t0.Add(period), + wantCount: 2, + }, + { + name: "third caller fills the wave", + now: t0.Add(20 * time.Millisecond), + waveTime: t0.Add(period), + waveCount: 2, + wantSlot: t0.Add(period), + wantCount: 3, + }, + { + name: "fourth caller before boundary overflows to next wave", + now: t0.Add(25 * time.Millisecond), + waveTime: t0.Add(period), + waveCount: 3, + wantSlot: t0.Add(2 * period), + wantCount: 1, + }, + { + name: "caller arriving on boundary after a partial wave advances one period", + now: t0.Add(period), + waveTime: t0.Add(period), + waveCount: 2, + wantSlot: t0.Add(2 * period), + wantCount: 1, + }, + { + name: "caller arriving after several idle periods advances to next grid boundary", + now: t0.Add(350 * time.Millisecond), + waveTime: t0.Add(period), + waveCount: 1, + wantSlot: t0.Add(4 * period), + wantCount: 1, + }, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + slot, nextCount := waveSlot(tc.now, tc.waveTime, tc.waveCount, burst, rps) + if !slot.Equal(tc.wantSlot) || nextCount != tc.wantCount { + t.Errorf("waveSlot() = (%v, %d), want (%v, %d)", + slot.Sub(t0), nextCount, + tc.wantSlot.Sub(t0), tc.wantCount) + } + }) + } +} + +func TestIteratePacesInWaves(t *testing.T) { + synctest.Test(t, func(t *testing.T) { + fake := newFake() + r := newTestRuntime(fake) + // BurstSize=2 at TargetRPS=10 gives a 200ms wave period. The token-bucket + // limiter stays untouched while BurstSize > 0. + h := dynconfig.NewHolder(knobsCodec) + if _, _, err := h.Apply([]byte(`{"target_rps": 10, "burst_size": 2}`)); err != nil { + t.Fatalf("Apply: %v", err) + } + r.cfg.Dyn = h + + arrivals := []time.Duration{0, 30 * time.Millisecond, 50 * time.Millisecond} + elapsed := make([]time.Duration, len(arrivals)+1) + var wg sync.WaitGroup + for i, delay := range arrivals { + wg.Go(func() { + r.iterate() // warm up at t0 (unpaced) + time.Sleep(delay) + start := time.Now() + r.iterate() + elapsed[i] = time.Since(start) + }) + } + wg.Wait() + + // Changing target_rps live advances from the last scheduled boundary using + // the new 100ms period (t0+400ms + 100ms = t0+500ms, 40ms from t0+460ms). + time.Sleep(60 * time.Millisecond) + if _, _, err := h.Apply([]byte(`{"target_rps": 20, "burst_size": 2}`)); err != nil { + t.Fatalf("Apply: %v", err) + } + r.iterate() // warm up this goroutine's actor + start := time.Now() + r.iterate() + elapsed[3] = time.Since(start) + + want := []time.Duration{ + 200 * time.Millisecond, + 170 * time.Millisecond, + 350 * time.Millisecond, + 40 * time.Millisecond, + } + if !slices.Equal(elapsed, want) { + t.Errorf("wave elapsed = %v, want %v", elapsed, want) + } + if got := r.limiter.Limit(); got != rate.Inf { + t.Errorf("limiter.Limit() = %v, want rate.Inf", got) + } + }) +} + func TestIterateRecordsTheRecoveryPauseOfAPausedActorAsASuccess(t *testing.T) { fake := newFake() r := newTestRuntime(fake) diff --git a/internal/cachesync/cachesync.go b/internal/cachesync/cachesync.go new file mode 100644 index 0000000000..0d9beaf70c --- /dev/null +++ b/internal/cachesync/cachesync.go @@ -0,0 +1,50 @@ +// Copyright 2026 The Agent Substrate 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 cachesync waits for Kubernetes informer caches at component startup +// and names any caches that fail to sync. +package cachesync + +import ( + "context" + "fmt" + "slices" + "strings" + "time" + + "k8s.io/client-go/tools/cache" +) + +// WaitForCacheSync blocks until every informer reports synced or timeout +// passes, naming any informers still pending in the returned error. Only the +// wait is bounded: the informers themselves keep retrying. +func WaitForCacheSync(ctx context.Context, timeout time.Duration, informers map[string]cache.InformerSynced) error { + syncCtx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + synced := make([]cache.InformerSynced, 0, len(informers)) + for _, hasSynced := range informers { + synced = append(synced, hasSynced) + } + if cache.WaitForCacheSync(syncCtx.Done(), synced...) { + return nil + } + var pending []string + for name, hasSynced := range informers { + if !hasSynced() { + pending = append(pending, name) + } + } + slices.Sort(pending) + return fmt.Errorf("caches not synced (%s); check logs for more details: %w", strings.Join(pending, ", "), syncCtx.Err()) +} diff --git a/internal/cachesync/cachesync_test.go b/internal/cachesync/cachesync_test.go new file mode 100644 index 0000000000..03c3ad2b15 --- /dev/null +++ b/internal/cachesync/cachesync_test.go @@ -0,0 +1,53 @@ +// Copyright 2026 The Agent Substrate 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 cachesync + +import ( + "context" + "errors" + "strings" + "testing" + "time" + + "k8s.io/client-go/tools/cache" +) + +func TestWaitForCacheSync(t *testing.T) { + ready := func() bool { return true } + pending := func() bool { return false } + t.Run("ready", func(t *testing.T) { + if err := WaitForCacheSync(t.Context(), time.Second, map[string]cache.InformerSynced{"SandboxConfigs": ready}); err != nil { + t.Fatal(err) + } + }) + t.Run("timeout names only unsynced caches", func(t *testing.T) { + err := WaitForCacheSync(t.Context(), 10*time.Millisecond, map[string]cache.InformerSynced{ + "SandboxConfigs": pending, "CSIDriverConfigs": pending, "atelet Pods": ready, + }) + if !errors.Is(err, context.DeadlineExceeded) || !strings.Contains(err.Error(), "CSIDriverConfigs, SandboxConfigs") || strings.Contains(err.Error(), "atelet Pods") { + t.Fatalf("cache timeout = %v, want deadline and only unsynced cache names", err) + } + if !strings.Contains(err.Error(), "check logs for more details") { + t.Fatalf("cache timeout = %v, want a pointer to the component logs", err) + } + }) + t.Run("shutdown cancels wait", func(t *testing.T) { + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if err := WaitForCacheSync(ctx, time.Minute, map[string]cache.InformerSynced{"StorageClasses": pending}); !errors.Is(err, context.Canceled) { + t.Fatalf("cache wait = %v, want cancellation", err) + } + }) +} diff --git a/internal/e2e/atenet_dataplane.go b/internal/e2e/atenet_dataplane.go index a10c6cb3b1..67a3bb2d80 100644 --- a/internal/e2e/atenet_dataplane.go +++ b/internal/e2e/atenet_dataplane.go @@ -40,6 +40,9 @@ type AtenetDataplane interface { EgressCollectorTelemetrySeen(string) bool ScrapeMetrics(context.Context) (string, error) EgressConnectStats(before, after string) EgressConnectStats + // SupportsIngressCache reports whether the dataplane implements the + // IngressCache preview gate. + SupportsIngressCache() bool } // EgressConnectStats holds the delta of egress CONNECT connections and requests @@ -88,6 +91,8 @@ func isEgressPolicyDenied(status int, body string) bool { func (envoyAtenetDataplane) PlatformMetricPrefixes(prefixes []string) []string { return prefixes } +func (envoyAtenetDataplane) SupportsIngressCache() bool { return true } + func (envoyAtenetDataplane) RouteDurationSeen(_ context.Context, collectorScrape string) (bool, error) { return len(MissingPlatformMetrics(collectorScrape, []string{"atenet_router_route_duration"})) == 0, nil } @@ -185,6 +190,10 @@ func (agentGatewayAtenetDataplane) EgressConnectStats(_, _ string) EgressConnect return EgressConnectStats{Connections: -1, Requests: -1} } +// AgentGateway resolves every request through its own routing and has no +// ingress-cache filter. +func (agentGatewayAtenetDataplane) SupportsIngressCache() bool { return false } + type agentGatewayParkingObserver struct{} func (agentGatewayParkingObserver) WaitForCount(ctx context.Context, cond func(int) bool) (int, error) { diff --git a/internal/e2e/clients.go b/internal/e2e/clients.go index 5b27028433..5b6aaf8ab2 100644 --- a/internal/e2e/clients.go +++ b/internal/e2e/clients.go @@ -21,7 +21,7 @@ import ( "go.ate.dev/substrate/internal/ateclient" "go.ate.dev/substrate/pkg/client/clientset/versioned" - apiextensionsclientset "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" + apiextensionsclientset "k8s.io/apiextensions-api/pkg/client/clientset/clientset" "k8s.io/client-go/kubernetes" ) diff --git a/internal/e2e/collector_metrics.go b/internal/e2e/collector_metrics.go index 2453d608a0..72fa3ff1a5 100644 --- a/internal/e2e/collector_metrics.go +++ b/internal/e2e/collector_metrics.go @@ -39,6 +39,8 @@ const ( agentGatewayRouterStatsPort = 15020 // Envoy exposes its Prometheus stats on the admin listener. egressEnvoyAdminPort = 15000 + // routerEnvoyMetricsPort is the atenet-router's envoy-metrics port. + routerEnvoyMetricsPort = 9902 ) // PlatformMetricPrefixes are the Prometheus metric-name prefixes (OTLP dots @@ -50,6 +52,12 @@ var PlatformMetricPrefixes = []string{ "ate_workerpool_workers", "ate_workerpool_desired_workers", "ate_workerpool_ready_workers", + "ate_worker_cpu_capacity", + "ate_worker_cpu_allocated", + "ate_worker_memory_capacity", + "ate_worker_memory_allocated", + "ate_worker_actor_capacity", + "ate_worker_actor_allocated", "ate_actor_crashes", "ate_actor_lifecycle_operation_duration", "ate_scheduler_assignment_duration", @@ -228,6 +236,95 @@ func scrapeEgressEnvoyPod(ctx context.Context, config *rest.Config, clientset ku return string(body), nil } +// ScrapeRouterEnvoyMetrics port-forwards each ready atenet-router pod's Envoy +// metrics port (9902) and reads its /stats/prometheus endpoint, returning the +// concatenated Prometheus exposition text. +func ScrapeRouterEnvoyMetrics(ctx context.Context) (string, error) { + config, err := ateclient.LoadKubeConfig(KubeConfig, KubeContext) + if err != nil { + return "", fmt.Errorf("loading kubeconfig: %w", err) + } + clientset, err := kubernetes.NewForConfig(config) + if err != nil { + return "", fmt.Errorf("creating k8s client: %w", err) + } + + ns := SystemNamespace() + pods, err := clientset.CoreV1().Pods(ns).List(ctx, metav1.ListOptions{ + LabelSelector: "app=atenet-router", + }) + if err != nil { + return "", fmt.Errorf("listing atenet-router pods: %w", err) + } + + var b strings.Builder + ready := 0 + for i := range pods.Items { + pod := &pods.Items[i] + if !portforward.IsPodReady(pod) { + continue + } + ready++ + body, err := scrapeRouterEnvoyPod(ctx, config, clientset, ns, pod.Name) + if err != nil { + return "", err + } + b.WriteString(body) + } + if ready == 0 { + return "", fmt.Errorf("no ready atenet-router pods in %s", ns) + } + return b.String(), nil +} + +func scrapeRouterEnvoyPod(ctx context.Context, config *rest.Config, clientset kubernetes.Interface, namespace, podName string) (string, error) { + localPort, stop, err := portforward.PodPortForward(ctx, config, clientset, namespace, podName, routerEnvoyMetricsPort) + if err != nil { + return "", err + } + defer stop() + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("http://127.0.0.1:%d/stats/prometheus", localPort), nil) + if err != nil { + return "", err + } + resp, err := (&http.Client{Timeout: 30 * time.Second}).Do(req) + if err != nil { + return "", fmt.Errorf("scraping router Envoy metrics on %s: %w", podName, err) + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return "", fmt.Errorf("reading router Envoy metrics on %s: %w", podName, err) + } + if resp.StatusCode != http.StatusOK { + return "", fmt.Errorf("router Envoy metrics on %s returned %d: %s", podName, resp.StatusCode, body) + } + return string(body), nil +} + +// RouterCacheCounterValue sums the value of a named counter metric from the +// router Prometheus scrape (e.g. "ate_ingress_cache_hit"). +func RouterCacheCounterValue(scrape, metricSuffix string) float64 { + var total float64 + for _, line := range strings.Split(scrape, "\n") { + if strings.HasPrefix(line, "#") { + continue + } + name := metricNameFromLine(line) + if strings.HasSuffix(name, metricSuffix) { + fields := strings.Fields(line) + if len(fields) > 0 { + v, err := strconv.ParseFloat(fields[len(fields)-1], 64) + if err == nil { + total += v + } + } + } + } + return total +} + // LifecycleEventMetric is the count connector's view of the actor lifecycle // events. Reading it rather than a log store keeps this check on the metrics // harness: kind has no place to query log records. diff --git a/internal/e2e/credprovider.go b/internal/e2e/credprovider.go index e9e59a0fc4..d99be8b48d 100644 --- a/internal/e2e/credprovider.go +++ b/internal/e2e/credprovider.go @@ -49,8 +49,9 @@ const ( // ConfigureCredentialProvider points the install's k8s-credential-provider at // the credinject fixture: the Secret behind CredentialInjectionURI and the // authorization policy that lets the probe atespaces resolve it. The provider -// Deployment is restarted after the policy ConfigMap is applied because it -// reads the policy once at startup. When the test passes the fixture is +// Deployment is restarted after the policy ConfigMap is applied, which is +// quicker than waiting for the kubelet to update the mounted policy the +// provider rereads. When the test passes the fixture is // removed, the shipped policy put back, and the provider restarted again so // it drops the fixture's grants. // diff --git a/internal/e2e/fixture.go b/internal/e2e/fixture.go index 2d3793ddbc..fd9c0a48fa 100644 --- a/internal/e2e/fixture.go +++ b/internal/e2e/fixture.go @@ -91,8 +91,9 @@ func decodeSubstrateTemplates(t *testing.T, rendered []byte) []*ateapi.ActorTemp type FixtureOption func(*fixtureConfig) type fixtureConfig struct { - templateValues map[string]string - imageUser string + templateValues map[string]string + imageUser string + disableGoldenSnapshot bool } // WithTemplateValue replaces the inline placeholder ${name} in the fixture's @@ -112,6 +113,12 @@ func WithImageUser(user string) FixtureOption { return func(c *fixtureConfig) { c.imageUser = user } } +// WithGoldenSnapshotDisabled disables golden snapshots on the fixture's +// ActorTemplates, so actors created from them cold-boot. +func WithGoldenSnapshotDisabled() FixtureOption { + return func(c *fixtureConfig) { c.disableGoldenSnapshot = true } +} + // SubstrateFixtureManifests names the two manifest templates a substrate // fixture is built from (both repo-relative, under internal/e2e/fixtures). type SubstrateFixtureManifests struct { @@ -126,7 +133,8 @@ type SubstrateFixtureManifests struct { // it ko-applies the pool manifest, creates the fixture's atespace and // ActorTemplates through the ate API (ko-resolving the templates' ko:// image // references first), and blocks until every template's golden snapshot -// exists. name distinguishes the caller (by convention its suite name): each +// exists (unless WithGoldenSnapshotDisabled is passed). name distinguishes the +// caller (by convention its suite name): each // suite gets its own copy of the fixture, so no suite's cleanup can delete it // out from under another running concurrently. // @@ -183,6 +191,14 @@ func DeploySubstrateFixture(t *testing.T, ctx context.Context, clients *Clients, } tmpl.SnapshotConfig.StorageLocation = location } + if cfg.disableGoldenSnapshot { + if tmpl.SnapshotConfig == nil { + tmpl.SnapshotConfig = &ateapi.SnapshotConfig{} + } + tmpl.SnapshotConfig.GoldenSnapshotConfig = &ateapi.GoldenSnapshotConfig{ + Mode: ateapi.GoldenSnapshotMode_GOLDEN_SNAPSHOT_MODE_DISABLED, + } + } } t.Cleanup(func() { // Remove workers before the namespace so its controller does not wait @@ -230,9 +246,11 @@ func DeploySubstrateFixture(t *testing.T, ctx context.Context, clients *Clients, created = append(created, c) } - for _, tmpl := range created { - t.Logf("Waiting for ActorTemplate %s/%s golden snapshot...", atespace, tmpl.GetMetadata().GetName()) - WaitForSubstrateTemplateReady(ctx, t, clients, atespace, tmpl.GetMetadata().GetName()) + if !cfg.disableGoldenSnapshot { + for _, tmpl := range created { + t.Logf("Waiting for ActorTemplate %s/%s golden snapshot...", atespace, tmpl.GetMetadata().GetName()) + WaitForSubstrateTemplateReady(ctx, t, clients, atespace, tmpl.GetMetadata().GetName()) + } } return atespace, created } diff --git a/internal/e2e/fixtures/probe/main.go b/internal/e2e/fixtures/probe/main.go index 007b61a456..2013819bdb 100644 --- a/internal/e2e/fixtures/probe/main.go +++ b/internal/e2e/fixtures/probe/main.go @@ -167,6 +167,68 @@ func capabilities(w http.ResponseWriter, _ *http.Request) { writeJSON(w, resp) } +// stdinTimeout bounds how long /stdin waits for the read, so a read that blocks +// is reported as an error. +const stdinTimeout = 5 * time.Second + +// stdinResponse reports what a read from stdin returned. +type stdinResponse struct { + EOF bool `json:"eof"` + Error string `json:"error,omitempty"` +} + +// stdin reports whether a read from stdin returns EOF. +func stdin(w http.ResponseWriter, r *http.Request) { + ctx, cancel := context.WithTimeout(r.Context(), stdinTimeout) + defer cancel() + writeJSON(w, readStdin(ctx, os.Stdin)) +} + +// readStdin reads one byte from r and reports whether the read returned EOF. +// It gives up when ctx is done and leaves the read goroutine blocked. +func readStdin(ctx context.Context, r io.Reader) stdinResponse { + done := make(chan error, 1) + go func() { + _, err := r.Read(make([]byte, 1)) + done <- err + }() + select { + case err := <-done: + switch { + case errors.Is(err, io.EOF): + return stdinResponse{EOF: true} + case err != nil: + return stdinResponse{Error: err.Error()} + default: + return stdinResponse{Error: "read a byte from stdin, want EOF"} + } + case <-ctx.Done(): + return stdinResponse{Error: fmt.Sprintf("reading stdin: %v", ctx.Err())} + } +} + +// exit ends the probe with the exit code in the code query parameter, so a test +// can make the actor's container exit while its sandbox stays up. It sends the +// whole response first. Before its last line it writes a line that imitates the +// worker's exit record, so a test can check that a container cannot write that +// record. +func exit(w http.ResponseWriter, r *http.Request) { + code, err := strconv.Atoi(r.URL.Query().Get("code")) + if err != nil || code < 0 || code > 255 { + http.Error(w, "code must be an exit code from 0 to 255", http.StatusBadRequest) + return + } + w.Header().Set("Connection", "close") + w.Header().Set("Content-Length", "0") + w.WriteHeader(http.StatusOK) + if err := http.NewResponseController(w).Flush(); err != nil { + log.Printf("probe: flushing the /exit response: %v", err) + } + fmt.Fprintf(os.Stderr, `{"message":"Actor container exited","ate.actor.exited_container.name":"probe","process.exit.code":%d}`+"\n", code) + log.Printf("probe: exiting with code %d", code) + os.Exit(code) +} + // heldIdentity is identityFile opened at startup and held open for the // probe's whole life, deliberately violating the read-at-time-of-use // guidance. It exists so a snapshot taken after startup carries live guest @@ -253,10 +315,19 @@ func stat(w http.ResponseWriter, r *http.Request) { writeJSON(w, resp) } +// writefile writes a file at path inside the actor. The body is the content +// query parameter when the request carries one, so a test can give each actor +// content of its own and tell whose file a later read returned; without it the +// body is the fixed string "written by probe". func writefile(w http.ResponseWriter, r *http.Request) { - path := r.URL.Query().Get("path") + query := r.URL.Query() + path := query.Get("path") + content := "written by probe" + if query.Has("content") { + content = query.Get("content") + } resp := map[string]string{"path": path} - if err := os.WriteFile(path, []byte("written by probe"), 0o644); err != nil { + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { resp["error"] = err.Error() } else { resp["ok"] = "true" @@ -523,6 +594,42 @@ func fetch(w http.ResponseWriter, r *http.Request) { writeJSON(w, resp) } +type netInterfaceInfo struct { + Name string `json:"name"` + Addrs []string `json:"addrs"` +} + +type netInfoResponse struct { + Interfaces []netInterfaceInfo `json:"interfaces"` + Error string `json:"error,omitempty"` +} + +// netinfo reports the network interfaces and IPv4 CIDR addresses visible inside +// the sandbox. +func netinfo(w http.ResponseWriter, _ *http.Request) { + ifaces, err := net.Interfaces() + if err != nil { + writeJSON(w, netInfoResponse{Error: err.Error()}) + return + } + out := make([]netInterfaceInfo, 0, len(ifaces)) + for _, iface := range ifaces { + addrs, err := iface.Addrs() + if err != nil { + writeJSON(w, netInfoResponse{Error: fmt.Sprintf("interface %s addrs: %v", iface.Name, err)}) + return + } + ipv4s := []string{} + for _, addr := range addrs { + if ipNet, ok := addr.(*net.IPNet); ok && ipNet.IP.To4() != nil { + ipv4s = append(ipv4s, addr.String()) + } + } + out = append(out, netInterfaceInfo{Name: iface.Name, Addrs: ipv4s}) + } + writeJSON(w, netInfoResponse{Interfaces: out}) +} + func writeJSON(w http.ResponseWriter, v any) { w.Header().Set("Content-Type", "application/json") if err := json.NewEncoder(w).Encode(v); err != nil { @@ -663,6 +770,7 @@ func main() { mux := http.NewServeMux() mux.HandleFunc("/whoami", whoami) mux.HandleFunc("/fetch", fetch) + mux.HandleFunc("/netinfo", netinfo) mux.HandleFunc("/readfile", readfile) mux.HandleFunc("/writefile", writefile) mux.HandleFunc("/lookup", lookup) @@ -670,6 +778,8 @@ func main() { mux.HandleFunc("/resources", resources) mux.HandleFunc("/capabilities", capabilities) mux.HandleFunc("/filesystem", filesystem) + mux.HandleFunc("/stdin", stdin) + mux.HandleFunc("/exit", exit) mux.HandleFunc("/healthz", healthz) const addr = ":80" diff --git a/internal/e2e/fixtures/probe/main_test.go b/internal/e2e/fixtures/probe/main_test.go index c2489fcd33..3029c43757 100644 --- a/internal/e2e/fixtures/probe/main_test.go +++ b/internal/e2e/fixtures/probe/main_test.go @@ -15,10 +15,12 @@ package main import ( + "context" "crypto/tls" "encoding/json" "encoding/pem" "errors" + "io" "net" "net/http" "net/http/httptest" @@ -560,3 +562,114 @@ func TestStatReportsOwnerAndMode(t *testing.T) { t.Errorf("/stat of a missing path reported no error: %+v", got) } } + +// The security e2e suite gives each actor content of its own through +// /writefile's content parameter, and other suites rely on the fixed default. +func TestWritefileContent(t *testing.T) { + dir := t.TempDir() + for _, tc := range []struct { + name string + query url.Values + want string + }{ + {name: "default", query: url.Values{}, want: "written by probe"}, + {name: "given", query: url.Values{"content": {"written by ns/actor-a"}}, want: "written by ns/actor-a"}, + {name: "empty", query: url.Values{"content": {""}}, want: ""}, + } { + t.Run(tc.name, func(t *testing.T) { + path := filepath.Join(dir, tc.name) + tc.query.Set("path", path) + rec := httptest.NewRecorder() + writefile(rec, httptest.NewRequest(http.MethodGet, "/writefile?"+tc.query.Encode(), nil)) + var resp map[string]string + if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil { + t.Fatalf("decoding /writefile response: %v", err) + } + if resp["ok"] != "true" || resp["error"] != "" { + t.Fatalf("/writefile = %v, want ok", resp) + } + got, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if string(got) != tc.want { + t.Errorf("/writefile wrote %q, want %q", got, tc.want) + } + }) + } +} + +// The imagefs e2e suite asserts on /stdin, so these cases pin what readStdin +// reports for each kind of stdin. +func TestReadStdin(t *testing.T) { + devNull, err := os.Open(os.DevNull) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { devNull.Close() }) + closedPipe, closedWriter, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + closedWriter.Close() + t.Cleanup(func() { closedPipe.Close() }) + openPipe, openWriter, err := os.Pipe() + if err != nil { + t.Fatal(err) + } + // Closing the pipe at the end unblocks the read that readStdin leaves behind. + t.Cleanup(func() { + openPipe.Close() + openWriter.Close() + }) + canceled, cancel := context.WithCancel(context.Background()) + cancel() + + tests := []struct { + name string + ctx context.Context + stdin io.Reader + want stdinResponse + }{{ + name: "dev null", + ctx: context.Background(), + stdin: devNull, + want: stdinResponse{EOF: true}, + }, { + name: "pipe with its write end closed", + ctx: context.Background(), + stdin: closedPipe, + want: stdinResponse{EOF: true}, + }, { + name: "pipe with its write end open", + ctx: canceled, + stdin: openPipe, + want: stdinResponse{Error: "reading stdin: context canceled"}, + }} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := readStdin(tt.ctx, tt.stdin); got != tt.want { + t.Errorf("readStdin() = %+v, want %+v", got, tt.want) + } + }) + } +} + +func TestNetInfo(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, "/netinfo", nil) + rec := httptest.NewRecorder() + netinfo(rec, req) + if rec.Code != http.StatusOK { + t.Fatalf("status = %d, want 200", rec.Code) + } + var resp netInfoResponse + if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil { + t.Fatalf("decoding netinfo response: %v", err) + } + if resp.Error != "" { + t.Fatalf("netinfo error: %s", resp.Error) + } + if len(resp.Interfaces) == 0 { + t.Fatal("netinfo returned 0 interfaces") + } +} diff --git a/internal/e2e/fixtures/security/actor-isolation-template.yaml.tmpl b/internal/e2e/fixtures/security/actor-isolation-template.yaml.tmpl new file mode 100644 index 0000000000..506da4978b --- /dev/null +++ b/internal/e2e/fixtures/security/actor-isolation-template.yaml.tmpl @@ -0,0 +1,67 @@ +# Copyright 2026 The Agent Substrate 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. + +# The ActorTemplate of the single-atespace actor-isolation security fixture: a +# protojson-shaped ateapi.ActorTemplate created through the ate API by +# e2e.DeploySubstrateFixture. +# +# Both victim and attacker actors in TestActorIsolation are created from this +# template in the same atespace, so they share the same golden snapshot and +# differ only in their actor name and UID. + +metadata: + atespace: ate-e2e${FIXTURE_SUFFIX} + name: probe +workerSelector: + matchLabels: + workload: ate-e2e-actor${FIXTURE_SUFFIX} +containers: +- name: probe + image: ko://go.ate.dev/substrate/internal/e2e/fixtures/probe + command: ["/ko-app/probe"] + volumeMounts: + # The probe expects its identity files under /run/ate. The mount also makes + # atelet write a per-actor identity file on the worker host, which is one + # of the host paths the attacker is checked against. + - name: system-info + mountPath: /run/ate + # The per-actor durable directory whose isolation is under test. + - name: data + mountPath: /data + # Gate the golden snapshot on the probe actually serving, so a read or write + # right after a resume cannot race a sandbox checkpointed before the + # listener came up. + wakeupProbe: + httpGet: + path: /healthz + port: 80 + timeoutSeconds: 60 +volumes: +- name: system-info + systemInfo: + dataSources: + - actorMetadata: + items: + - field: ACTOR_METADATA_FIELD_NAME + path: actor-id + - field: ACTOR_METADATA_FIELD_ATESPACE + path: atespace + - field: ACTOR_METADATA_FIELD_UID + path: actor-uid +- name: data + durableDir: {} +resources: + limits: + cpuMillicores: 1000 + memoryBytes: 536870912 # 512Mi diff --git a/internal/e2e/fixtures/security/actor-isolation.yaml.tmpl b/internal/e2e/fixtures/security/actor-isolation.yaml.tmpl new file mode 100644 index 0000000000..595ab20e0b --- /dev/null +++ b/internal/e2e/fixtures/security/actor-isolation.yaml.tmpl @@ -0,0 +1,41 @@ +# Copyright 2026 The Agent Substrate 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. + +# Single-atespace actor-isolation security fixture: a namespace plus a +# single-worker WorkerPool. +# +# replicas is 1 on purpose. The test runs a victim actor, suspends it, and +# starts an attacker actor in the same atespace. With one worker the attacker +# has to land on the worker the victim just vacated, which is where the +# victim's per-actor host state is. +apiVersion: v1 +kind: Namespace +metadata: + name: ate-e2e${FIXTURE_SUFFIX} + labels: + ate.dev/e2e: "true" + +--- + +apiVersion: ate.dev/v1 +kind: WorkerPool +metadata: + name: actor + namespace: ate-e2e${FIXTURE_SUFFIX} + labels: + workload: ate-e2e-actor${FIXTURE_SUFFIX} +spec: + replicas: 1 + workerImage: ${WORKER_IMAGE} +${WORKERPOOL_RUNTIME} diff --git a/internal/e2e/fixtures/security/atespace-a-pool.yaml.tmpl b/internal/e2e/fixtures/security/atespace-a-pool.yaml.tmpl index 53d59862a6..1c9e7d977a 100644 --- a/internal/e2e/fixtures/security/atespace-a-pool.yaml.tmpl +++ b/internal/e2e/fixtures/security/atespace-a-pool.yaml.tmpl @@ -16,13 +16,14 @@ # WorkerPool. Atespace B deploys atespace-b-namespace.yaml.tmpl, a namespace # with no pool, so its actors run on this one too. # -# replicas is 1 on purpose. Pools are not scoped to an atespace: the scheduler -# matches on sandbox class, labels and capacity, never on the actor's -# atespace. The test runs the victim, suspends it, then starts the attacker. -# With one worker the attacker has to land on the worker the victim just -# left, which is where the victim's per-actor host state is. With more -# workers the attacker could boot on a fresh one and the host-state checks -# would prove nothing. +# Pools are not scoped to an atespace: the scheduler matches on sandbox class, +# labels and capacity, never on the actor's atespace. +# +# replicas is 1 because TestCrossAtespaceIsolation runs one actor at a time: +# the source actor in atespace A, then, once that is suspended, its clone. The +# worker-reuse checks (a victim, then an attacker on the worker it left) do +# not use this fixture. They live in TestActorIsolation, which runs both +# actors in one atespace on the single worker of actor-isolation.yaml.tmpl. # # The workload label is a fixed string rather than ${FIXTURE_SUFFIX}-suffixed # because both atespaces' templates must select this one pool and they render diff --git a/internal/e2e/fixtures/security/atespace-b-namespace.yaml.tmpl b/internal/e2e/fixtures/security/atespace-b-namespace.yaml.tmpl index c0250b3d87..ed6328117d 100644 --- a/internal/e2e/fixtures/security/atespace-b-namespace.yaml.tmpl +++ b/internal/e2e/fixtures/security/atespace-b-namespace.yaml.tmpl @@ -15,10 +15,10 @@ # Atespace B of the cross-atespace security fixture: a namespace only. # # Atespace B deliberately has no WorkerPool. Pools are not scoped to an -# atespace, so B's actors are placed on the single-worker pool that -# atespace-a-pool.yaml.tmpl deploys in atespace A's namespace. That forces -# A's and B's actors to take turns on one worker, which is the reuse boundary -# the suite tests. +# atespace, so an actor in B would be placed on the single-worker pool that +# atespace-a-pool.yaml.tmpl deploys in atespace A's namespace. +# TestCrossAtespaceIsolation never gets that far: the one actor it tries to +# create in B is seeded from atespace A's tag, and the API must refuse it. # # The namespace is still needed: Substrate reconciles an atespace's # namespaced objects (network policies, for example) into it. diff --git a/internal/e2e/fixtures/security/concurrent-a-pool.yaml.tmpl b/internal/e2e/fixtures/security/concurrent-a-pool.yaml.tmpl new file mode 100644 index 0000000000..573ce4f16c --- /dev/null +++ b/internal/e2e/fixtures/security/concurrent-a-pool.yaml.tmpl @@ -0,0 +1,47 @@ +# Copyright 2026 The Agent Substrate 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. + +# Kubernetes half of the concurrent security fixture for atespace A: a k8s +# Namespace plus a WorkerPool with replicas: 2. +# +# Applying this manifest does not create an atespace. e2e.DeploySubstrateFixture +# creates the atespace of the same name through the ate API, from +# concurrent-template.yaml.tmpl. +# +# replicas is 2 on purpose: the test runs two actors at the exact same time +# on two distinct worker pods to verify space-invariance boundaries (NW-6, +# NW-2, ST-1 [space]). The fixture for atespace B applies +# concurrent-b-namespace.yaml.tmpl, a k8s Namespace with no pool, so the +# actors of both atespaces share this 2-worker pool. + +apiVersion: v1 +kind: Namespace +metadata: + name: ate-e2e${FIXTURE_SUFFIX} + labels: + ate.dev/e2e: "true" + +--- + +apiVersion: ate.dev/v1 +kind: WorkerPool +metadata: + name: concurrent + namespace: ate-e2e${FIXTURE_SUFFIX} + labels: + workload: ate-e2e-concurrent +spec: + replicas: 2 + workerImage: ${WORKER_IMAGE} +${WORKERPOOL_RUNTIME} diff --git a/internal/e2e/fixtures/security/concurrent-b-namespace.yaml.tmpl b/internal/e2e/fixtures/security/concurrent-b-namespace.yaml.tmpl new file mode 100644 index 0000000000..c4c90503bf --- /dev/null +++ b/internal/e2e/fixtures/security/concurrent-b-namespace.yaml.tmpl @@ -0,0 +1,33 @@ +# Copyright 2026 The Agent Substrate 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. + +# Kubernetes half of the concurrent security fixture for atespace B: a k8s +# Namespace only. +# +# Applying this manifest does not create an atespace. e2e.DeploySubstrateFixture +# creates the atespace of the same name through the ate API, from +# concurrent-template.yaml.tmpl. This file exists because +# e2e.DeploySubstrateFixture requires a k8s manifest next to each +# ActorTemplate. +# +# Atespace B deliberately has no WorkerPool. Its actors run on the 2-worker +# pool that concurrent-a-pool.yaml.tmpl deploys in the k8s namespace of +# atespace A. + +apiVersion: v1 +kind: Namespace +metadata: + name: ate-e2e${FIXTURE_SUFFIX} + labels: + ate.dev/e2e: "true" diff --git a/internal/e2e/fixtures/security/concurrent-template.yaml.tmpl b/internal/e2e/fixtures/security/concurrent-template.yaml.tmpl new file mode 100644 index 0000000000..622063ddf0 --- /dev/null +++ b/internal/e2e/fixtures/security/concurrent-template.yaml.tmpl @@ -0,0 +1,59 @@ +# Copyright 2026 The Agent Substrate 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. + +# The ActorTemplate of the concurrent two-worker security fixture: a +# protojson-shaped ateapi.ActorTemplate created through the ate API by +# e2e.DeploySubstrateFixture. +# +# Both atespaces deploy this same file. They differ only in the ${FIXTURE_SUFFIX} +# they render with. The workerSelector names the shared 2-replica pool. + +metadata: + atespace: ate-e2e${FIXTURE_SUFFIX} + name: probe +workerSelector: + matchLabels: + workload: ate-e2e-concurrent +containers: +- name: probe + image: ko://go.ate.dev/substrate/internal/e2e/fixtures/probe + command: ["/ko-app/probe"] + volumeMounts: + - name: system-info + mountPath: /run/ate + - name: data + mountPath: /data + wakeupProbe: + httpGet: + path: /healthz + port: 80 + timeoutSeconds: 60 +volumes: +- name: system-info + systemInfo: + dataSources: + - actorMetadata: + items: + - field: ACTOR_METADATA_FIELD_NAME + path: actor-id + - field: ACTOR_METADATA_FIELD_ATESPACE + path: atespace + - field: ACTOR_METADATA_FIELD_UID + path: actor-uid +- name: data + durableDir: {} +resources: + limits: + cpuMillicores: 1000 + memoryBytes: 536870912 # 512Mi diff --git a/internal/e2e/fixtures/testserver/common_test.go b/internal/e2e/fixtures/testserver/common_test.go index 55d7cc5066..a879cabcd2 100644 --- a/internal/e2e/fixtures/testserver/common_test.go +++ b/internal/e2e/fixtures/testserver/common_test.go @@ -55,13 +55,20 @@ func writeOriginCertificate(t *testing.T) originCertificate { return originCertificate{caPEM: material.RootCA, certFile: certFile, keyFile: keyFile} } -// startOriginServer serves handler the way serveHTTP does: in cleartext on one -// loopback listener and, given a certificate, over TLS on a second. The URLs of -// a scheme the server does not serve are empty. +// startOriginServer serves handler the way the http subcommand does: in +// cleartext on one loopback listener and, given a certificate, over TLS on a +// second. The URLs of a scheme the server does not serve are empty. func startOriginServer(t *testing.T, handler http.Handler, certFile, keyFile string) originServer { + t.Helper() + return startOriginServerPreferring(t, handler, certFile, keyFile, httpNextProtos) +} + +// startOriginServerPreferring is startOriginServer with another subcommand's +// ALPN order. +func startOriginServerPreferring(t *testing.T, handler http.Handler, certFile, keyFile string, nextProtos []string) originServer { t.Helper() server := &http.Server{Handler: handler} - if err := configureTLSServer(server, certFile, keyFile); err != nil { + if err := configureTLSServer(server, certFile, keyFile, nextProtos); err != nil { t.Fatalf("configure TLS: %v", err) } cleartext := listenLoopback(t) diff --git a/internal/e2e/fixtures/testserver/grpc.go b/internal/e2e/fixtures/testserver/grpc.go index 47ee828a19..02c6e700ca 100644 --- a/internal/e2e/fixtures/testserver/grpc.go +++ b/internal/e2e/fixtures/testserver/grpc.go @@ -16,6 +16,7 @@ package main import ( "context" + "crypto/tls" "errors" "fmt" "io" @@ -26,6 +27,7 @@ import ( "github.com/spf13/cobra" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" "google.golang.org/grpc/health" healthpb "google.golang.org/grpc/health/grpc_health_v1" "google.golang.org/grpc/status" @@ -86,13 +88,21 @@ func (echoServer) EchoBidi(stream grpc.BidiStreamingServer[grpcechopb.EchoReques // newServer returns a server with everything registered on it, so the unit // tests exercise the same registrations the pod serves. -func newServer() *grpc.Server { - server := grpc.NewServer() +func newServer(opts ...grpc.ServerOption) *grpc.Server { + server := grpc.NewServer(opts...) grpcechopb.RegisterEchoServer(server, echoServer{}) healthpb.RegisterHealthServer(server, health.NewServer()) return server } +// newTLSServer is newServer serving over TLS with certificate. +func newTLSServer(certificate tls.Certificate) *grpc.Server { + return newServer(grpc.Creds(credentials.NewTLS(&tls.Config{ + Certificates: []tls.Certificate{certificate}, + MinVersion: tls.VersionTLS12, + }))) +} + // newHealthHandler answers the HTTP readiness probe. Deliberately trivial: it // reports that the process is up, and the gRPC listener is opened before this // one, so a 200 here means the RPC port is already accepting. @@ -114,10 +124,9 @@ func newHealthHandler() http.Handler { // - ingress: deployed as an Actor, it is the origin a client reaches through // atenet-router. // -// It serves cleartext HTTP/2 -- no TLS anywhere -- because the leg under test -// is the tunnel, not the origin's identity, and because the egress gateway -// relays a terminated CONNECT as opaque TCP: whatever the actor speaks is what -// arrives here. +// It serves cleartext HTTP/2 on --listen. Given --tls-cert and --tls-key it +// also serves over TLS on :8443, where an egress test reaches it under an +// https rule. // // It answers the grpc health service as well as Echo, which is what the egress // pod's readinessProbe checks. Multiplexing readiness onto that listener as an @@ -127,19 +136,41 @@ func newHealthHandler() http.Handler { // an ActorTemplate's wakeupProbe is an HTTP GET and nothing else: a gRPC server // answers one with a protocol error, so without it the Actor never boots. func newGRPCCmd() *cobra.Command { - var listenAddress string - var healthAddress string + var ( + listenAddress string + healthAddress string + certFile string + keyFile string + ) cmd := &cobra.Command{ Use: "grpc", - Short: "Serve a cleartext HTTP/2 gRPC echo origin.", + Short: "Serve a gRPC echo origin over cleartext HTTP/2, and over TLS when given a certificate.", Args: cobra.NoArgs, RunE: func(_ *cobra.Command, _ []string) error { + certificate, err := loadServerCertificate(certFile, keyFile) + if err != nil { + return err + } listener, err := net.Listen("tcp", listenAddress) if err != nil { return fmt.Errorf("listening on %s: %w", listenAddress, err) } log.Printf("testserver grpc: serving on %s", listener.Addr()) + // Bound before Serve below. The pod's readinessProbe checks the + // cleartext port, because kubelet's grpc probe cannot use TLS, so + // a ready pod is already accepting TLS. + if certificate != nil { + encrypted, err := net.Listen("tcp", tlsListenAddress) + if err != nil { + return fmt.Errorf("listening on %s: %w", tlsListenAddress, err) + } + log.Printf("testserver grpc: serving TLS on %s", encrypted.Addr()) + go func() { + log.Fatal(newTLSServer(*certificate).Serve(encrypted)) + }() + } + // Bound before Serve below, so a readiness 200 can never precede // the gRPC port being open. if healthAddress != "" { @@ -157,6 +188,8 @@ func newGRPCCmd() *cobra.Command { }, } cmd.Flags().StringVar(&listenAddress, "listen", ":50051", "Address the gRPC server listens on, cleartext HTTP/2.") + cmd.Flags().StringVar(&certFile, "tls-cert", "", "PEM certificate file; with --tls-key, also serves gRPC over TLS on :8443.") + cmd.Flags().StringVar(&keyFile, "tls-key", "", "PEM private key file; with --tls-cert, also serves gRPC over TLS on :8443.") cmd.Flags().StringVar(&healthAddress, "health-listen", "", "Address for an HTTP/1.1 /readyz listener. Empty serves no HTTP at all, which is what the egress fixture wants; the ingress Actor sets it because an ActorTemplate wakeupProbe is an HTTP GET.") return cmd } diff --git a/internal/e2e/fixtures/testserver/grpc_test.go b/internal/e2e/fixtures/testserver/grpc_test.go index f46db34669..3eeaa71e70 100644 --- a/internal/e2e/fixtures/testserver/grpc_test.go +++ b/internal/e2e/fixtures/testserver/grpc_test.go @@ -16,6 +16,8 @@ package main import ( "context" + "crypto/tls" + "crypto/x509" "errors" "fmt" "io" @@ -27,6 +29,7 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" healthpb "google.golang.org/grpc/health/grpc_health_v1" "google.golang.org/grpc/status" @@ -166,6 +169,42 @@ func TestEchoBidi(t *testing.T) { } } +// With --tls-cert and --tls-key the fixture answers the same RPCs over TLS, +// which is the listener an https egress test dials. +func TestEchoOverTLS(t *testing.T) { + origin := writeOriginCertificate(t) + certificate, err := loadServerCertificate(origin.certFile, origin.keyFile) + if err != nil { + t.Fatalf("loading the origin certificate: %v", err) + } + listener := listenLoopback(t) + server := newTLSServer(*certificate) + go func() { + if err := server.Serve(listener); err != nil { + t.Logf("serving: %v", err) + } + }() + t.Cleanup(server.Stop) + + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM(origin.caPEM) { + t.Fatal("the origin CA is not a valid certificate") + } + conn, err := grpc.NewClient(listener.Addr().String(), grpc.WithTransportCredentials(credentials.NewTLS(&tls.Config{RootCAs: roots, MinVersion: tls.VersionTLS12}))) + if err != nil { + t.Fatalf("dialing %s: %v", listener.Addr(), err) + } + t.Cleanup(func() { _ = conn.Close() }) + + response, err := grpcechopb.NewEchoClient(conn).Echo(testContext(t), &grpcechopb.EchoRequest{Message: "over tls"}) + if err != nil { + t.Fatalf("Echo over TLS: %v", err) + } + if response.GetMessage() != "over tls" { + t.Errorf("Echo over TLS = %q, want the message back unchanged", response.GetMessage()) + } +} + // A non-positive count must fail loudly. Returning an empty stream instead // would make a caller that forgot to set count look like a working one. func TestEchoStreamRejectsBadCount(t *testing.T) { diff --git a/internal/e2e/fixtures/testserver/http.go b/internal/e2e/fixtures/testserver/http.go index 7704031b20..1521b8b975 100644 --- a/internal/e2e/fixtures/testserver/http.go +++ b/internal/e2e/fixtures/testserver/http.go @@ -43,6 +43,9 @@ type dialResult struct { Error string `json:"error,omitempty"` } +// httpNextProtos makes the http origin prefer HTTP/1.1 over TLS. +var httpNextProtos = []string{"http/1.1"} + // defaultDialTimeout is the /dial timeout when the request sets none. const defaultDialTimeout = 3 * time.Second @@ -165,7 +168,7 @@ func newHTTPCmd() *cobra.Command { WriteTimeout: 2 * time.Minute, } log.Printf("testserver http: listening on %s", listenAddress) - return serveHTTP(server, certFile, keyFile) + return serveHTTP(server, certFile, keyFile, httpNextProtos) }, } cmd.Flags().StringVar(&listenAddress, "listen", ":8080", "Address the origin serves cleartext HTTP on.") diff --git a/internal/e2e/fixtures/testserver/main.go b/internal/e2e/fixtures/testserver/main.go index 9cf211c189..c4d36c29e1 100644 --- a/internal/e2e/fixtures/testserver/main.go +++ b/internal/e2e/fixtures/testserver/main.go @@ -17,7 +17,7 @@ // backs all of them and a new origin-style test adds a subcommand here rather // than a new image to build and push: // -// testserver grpc --listen=:50051 a cleartext HTTP/2 gRPC echo origin +// testserver grpc --listen=:50051 a gRPC echo origin, cleartext HTTP/2 // testserver http --listen=:8080 an HTTP(S) origin serving /healthz, /echoheaders, POST /fetch and /dial // testserver egressprobe --listen=:8080 a client that drives the egress gateway // testserver websocket --listen=:8080 a websocket server that responds to PINGs @@ -26,9 +26,9 @@ // // Each pod runs exactly one subcommand, so the wire behavior of any given pod is // unchanged from when these were separate binaries -- the grpc pod still speaks -// nothing but cleartext HTTP/2, for instance. Given --tls-cert and --tls-key, -// http and websocket also serve HTTPS on :8443 beside their cleartext --listen, -// so one pod answers both schemes for the same name. +// nothing but gRPC, for instance. Given --tls-cert and --tls-key, http, +// websocket and grpc also serve over TLS on :8443 beside their cleartext +// --listen, so one pod answers both for the same name. // // The subcommand shape follows Kubernetes' test/images/agnhost: a single // extendable CLI whose modes are cobra subcommands, matching the rest of this diff --git a/internal/e2e/fixtures/testserver/tls.go b/internal/e2e/fixtures/testserver/tls.go index 44636d7251..1c881566e0 100644 --- a/internal/e2e/fixtures/testserver/tls.go +++ b/internal/e2e/fixtures/testserver/tls.go @@ -22,36 +22,47 @@ import ( "net/http" ) -// configureTLSServer loads the origin certificate and key and offers only -// HTTP/1.1 over TLS. Invalid credentials fail setup before the listener starts. -func configureTLSServer(server *http.Server, certFile, keyFile string) error { +// loadServerCertificate loads the origin certificate and key. It returns nil +// when neither file is set. +func loadServerCertificate(certFile, keyFile string) (*tls.Certificate, error) { if certFile == "" && keyFile == "" { - return nil + return nil, nil } if certFile == "" || keyFile == "" { - return fmt.Errorf("--tls-cert and --tls-key must be provided together") + return nil, fmt.Errorf("--tls-cert and --tls-key must be provided together") } certificate, err := tls.LoadX509KeyPair(certFile, keyFile) if err != nil { - return fmt.Errorf("loading TLS certificate and key: %w", err) + return nil, fmt.Errorf("loading TLS certificate and key: %w", err) + } + return &certificate, nil +} + +// configureTLSServer loads the origin certificate and key. nextProtos is the +// ALPN order the server prefers; net/http appends h2 when it is missing. +// Invalid credentials fail setup before the listener starts. +func configureTLSServer(server *http.Server, certFile, keyFile string, nextProtos []string) error { + certificate, err := loadServerCertificate(certFile, keyFile) + if err != nil || certificate == nil { + return err } server.TLSConfig = &tls.Config{ - Certificates: []tls.Certificate{certificate}, + Certificates: []tls.Certificate{*certificate}, MinVersion: tls.VersionTLS12, - NextProtos: []string{"http/1.1"}, + NextProtos: nextProtos, } return nil } -// tlsListenAddress is where the http and websocket subcommands serve HTTPS +// tlsListenAddress is where the http, websocket and grpc subcommands serve TLS // when given a certificate, beside their cleartext --listen. It is a fixed port. const tlsListenAddress = ":8443" // serveHTTP serves server in cleartext on server.Addr and, when certFile and -// keyFile are set, over TLS on tlsListenAddress. -func serveHTTP(server *http.Server, certFile, keyFile string) error { - if err := configureTLSServer(server, certFile, keyFile); err != nil { +// keyFile are set, over TLS on tlsListenAddress, preferring nextProtos. +func serveHTTP(server *http.Server, certFile, keyFile string, nextProtos []string) error { + if err := configureTLSServer(server, certFile, keyFile, nextProtos); err != nil { return err } cleartext, err := net.Listen("tcp", server.Addr) diff --git a/internal/e2e/fixtures/testserver/tls_test.go b/internal/e2e/fixtures/testserver/tls_test.go index f63849790e..f10bda2cba 100644 --- a/internal/e2e/fixtures/testserver/tls_test.go +++ b/internal/e2e/fixtures/testserver/tls_test.go @@ -27,7 +27,7 @@ func TestTLSConfigurationRejectsIncompleteOrUnreadableCredentials(t *testing.T) } { t.Run(name, func(t *testing.T) { server := &http.Server{} - if err := configureTLSServer(server, paths[0], paths[1]); err == nil { + if err := configureTLSServer(server, paths[0], paths[1], httpNextProtos); err == nil { t.Fatal("configureTLSServer succeeded, want error") } }) diff --git a/internal/e2e/fixtures/testserver/websocket.go b/internal/e2e/fixtures/testserver/websocket.go index dbe68ddb38..e70a0a0e3a 100644 --- a/internal/e2e/fixtures/testserver/websocket.go +++ b/internal/e2e/fixtures/testserver/websocket.go @@ -15,8 +15,10 @@ package main import ( + "fmt" "log" "net/http" + "sync/atomic" "github.com/gorilla/websocket" "github.com/spf13/cobra" @@ -26,6 +28,11 @@ var upgrader = websocket.Upgrader{ CheckOrigin: func(r *http.Request) bool { return true }, } +// websocketNextProtos makes the websocket origin prefer HTTP/2 over TLS, as +// most public origins do. It takes a WebSocket handshake over HTTP/1.1 only, +// so a proxy that lets ALPN pick h2 for the handshake fails against it. +var websocketNextProtos = []string{"h2", "http/1.1"} + func newWebsocketHandler(echo bool) http.Handler { mux := http.NewServeMux() @@ -34,6 +41,19 @@ func newWebsocketHandler(echo bool) http.Handler { _, _ = w.Write([]byte("ok")) }) + // /hang never answers: it returns once the request's connection closes. + // /hanging reports how many /hang requests are waiting, so a test can + // suspend the actor while one is in flight. + var hanging atomic.Int64 + mux.HandleFunc("/hang", func(_ http.ResponseWriter, r *http.Request) { + hanging.Add(1) + defer hanging.Add(-1) + <-r.Context().Done() + }) + mux.HandleFunc("/hanging", func(w http.ResponseWriter, _ *http.Request) { + _, _ = fmt.Fprint(w, hanging.Load()) + }) + mux.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) { c, err := upgrader.Upgrade(w, r, nil) if err != nil { @@ -84,7 +104,7 @@ func newWebsocketCmd() *cobra.Command { Handler: newWebsocketHandler(echo), } log.Printf("testserver websocket: listening on %s", listenAddress) - return serveHTTP(server, certFile, keyFile) + return serveHTTP(server, certFile, keyFile, websocketNextProtos) }, } cmd.Flags().StringVar(&listenAddress, "listen", ":80", "Address the websocket server serves cleartext on.") diff --git a/internal/e2e/fixtures/testserver/websocket_test.go b/internal/e2e/fixtures/testserver/websocket_test.go index ffbddfa0f8..c8cb1ae5ff 100644 --- a/internal/e2e/fixtures/testserver/websocket_test.go +++ b/internal/e2e/fixtures/testserver/websocket_test.go @@ -54,9 +54,40 @@ func TestWebsocketDefaultRespondsToPingWithPong(t *testing.T) { } } +// The websocket origin prefers HTTP/2 when a client offers it. The egress e2e +// relies on that: a gateway that lets ALPN choose the protocol for a WebSocket +// handshake reaches this origin over h2, where the handshake cannot succeed. +func TestWebsocketOriginPrefersHTTP2(t *testing.T) { + cert := writeOriginCertificate(t) + server := startOriginServerPreferring(t, newWebsocketHandler(true), cert.certFile, cert.keyFile, websocketNextProtos) + + roots := x509.NewCertPool() + if !roots.AppendCertsFromPEM(cert.caPEM) { + t.Fatal("adding fixture CA to trust pool") + } + protocols := new(http.Protocols) + protocols.SetHTTP1(true) + protocols.SetHTTP2(true) + client := &http.Client{ + Timeout: 2 * time.Second, + Transport: &http.Transport{ + Protocols: protocols, + TLSClientConfig: &tls.Config{RootCAs: roots, ServerName: "127.0.0.1"}, + }, + } + response, err := client.Get(server.httpsURL + "/readyz") + if err != nil { + t.Fatalf("GET /readyz over verified TLS: %v", err) + } + defer response.Body.Close() + if response.Proto != "HTTP/2.0" { + t.Errorf("response protocol with HTTP/2 offered = %q, want HTTP/2.0", response.Proto) + } +} + func TestWebsocketEchoPreservesMessageTypeAndPayload(t *testing.T) { cert := writeOriginCertificate(t) - server := startOriginServer(t, newWebsocketHandler(true), cert.certFile, cert.keyFile) + server := startOriginServerPreferring(t, newWebsocketHandler(true), cert.certFile, cert.keyFile, websocketNextProtos) roots := x509.NewCertPool() if !roots.AppendCertsFromPEM(cert.caPEM) { t.Fatal("adding fixture CA to trust pool") diff --git a/internal/e2e/preview.go b/internal/e2e/preview.go index 60064ac1e5..b6dce06ce1 100644 --- a/internal/e2e/preview.go +++ b/internal/e2e/preview.go @@ -32,6 +32,10 @@ import ( // names, or "ALL" for all of them. Empty means none. var previewFlag string +// installGates are the preview gates the install under test enabled, set by +// initPreview. +var installGates *preview.Gates + // previewRequired reports whether --preview must be passed. A lane that // forgets it would otherwise skip every preview test and still pass, so CI // must declare its preview mode, even if only as empty. @@ -50,25 +54,32 @@ func previewGates(value string, set bool) ([]string, error) { }), nil } -// initPreview sets the process-wide preview gates from --preview. +// initPreview sets installGates from --preview. func initPreview() error { - gates, err := previewGates(previewFlag, pflag.CommandLine.Changed("preview")) + values, err := previewGates(previewFlag, pflag.CommandLine.Changed("preview")) if err != nil { return err } - if err := preview.Init(gates...); err != nil { + gates, err := preview.New(values...) + if err != nil { return fmt.Errorf("--preview: %w", err) } + installGates = gates return nil } +func mustInstallGates() *preview.Gates { + if installGates == nil { + panic("installGates not initialized. RunTestMain must be used to initialize preview gates.") + } + return installGates +} + // previewDialOptions returns the options for the ATE API client to opt in to // preview features, if the install under test enabled any. func previewDialOptions() []grpc.DialOption { - for _, enabled := range preview.AsMap() { - if enabled { - return preview.DialOptionsWithOptIn() - } + if len(mustInstallGates().Enabled()) > 0 { + return preview.DialOptionsWithOptIn() } return nil } @@ -79,7 +90,12 @@ func previewDialOptions() []grpc.DialOption { // gate, so the gate-off lane stores snapshots under --snapshot-location. func SnapshotLocation(t testing.TB, prefix string) string { t.Helper() - if !preview.IsEnabled(preview.GatePerTemplateSnapshotLocation) { + return snapshotLocation(t, mustInstallGates(), prefix) +} + +func snapshotLocation(t testing.TB, gates *preview.Gates, prefix string) string { + t.Helper() + if !gates.IsEnabled(preview.GatePerTemplateSnapshotLocation) { return "" } env, err := CheckEnv("BUCKET_NAME") @@ -93,7 +109,22 @@ func SnapshotLocation(t testing.TB, prefix string) string { // a preview feature call it first, so a run without the gate skips them. func RequirePreview(t testing.TB, gate preview.Gate) { t.Helper() - if !preview.IsEnabled(gate) { + if !PreviewEnabled(gate) { t.Skipf("preview gate %q is not enabled (pass --preview)", gate) } } + +// RequireIngressCache skips t unless the router under test caches ingress +// routing: the IngressCache preview gate is on and the dataplane implements it. +func RequireIngressCache(t testing.TB) { + t.Helper() + RequirePreview(t, preview.GateIngressCache) + if !CurrentAtenetDataplane().SupportsIngressCache() { + t.Skipf("the %s dataplane does not implement the %q preview gate", os.Getenv(AtenetDataplaneEnv), preview.GateIngressCache) + } +} + +// PreviewEnabled reports whether the install under test enabled gate. +func PreviewEnabled(gate preview.Gate) bool { + return mustInstallGates().IsEnabled(gate) +} diff --git a/internal/e2e/preview_test.go b/internal/e2e/preview_test.go index 4943ebb2cc..2443854c4b 100644 --- a/internal/e2e/preview_test.go +++ b/internal/e2e/preview_test.go @@ -16,6 +16,7 @@ package e2e import ( "slices" + "strings" "testing" "k8s.io/utils/ptr" @@ -34,8 +35,7 @@ func TestSnapshotLocation(t *testing.T) { {name: "gate on", gates: []string{string(preview.GatePerTemplateSnapshotLocation)}, want: "gs://test-bucket/ate-e2e-probe/"}, } { t.Run(tc.name, func(t *testing.T) { - preview.InitForTest(t, tc.gates...) - if got := SnapshotLocation(t, "ate-e2e-probe"); got != tc.want { + if got := snapshotLocation(t, preview.NewForTest(t, tc.gates...), "ate-e2e-probe"); got != tc.want { t.Errorf("SnapshotLocation() = %q, want %q", got, tc.want) } }) @@ -69,3 +69,20 @@ func TestPreviewGates(t *testing.T) { }) } } + +func TestPreviewEnabled_UninitializedPanics(t *testing.T) { + prev := installGates + installGates = nil + t.Cleanup(func() { installGates = prev }) + + defer func() { + r := recover() + if r == nil { + t.Fatal("PreviewEnabled() did not panic when installGates is nil") + } + if msg, _ := r.(string); !strings.Contains(msg, "RunTestMain") { + t.Fatalf("panic = %v, want one naming RunTestMain", r) + } + }() + PreviewEnabled(preview.GateExternalVolumes) +} diff --git a/internal/e2e/probe.go b/internal/e2e/probe.go index 0a2a6c38da..2873935c99 100644 --- a/internal/e2e/probe.go +++ b/internal/e2e/probe.go @@ -36,7 +36,10 @@ var probeManifests = SubstrateFixtureManifests{ // ProbeOption adjusts what DeployProbe installs. type ProbeOption func(*probeConfig) -type probeConfig struct{ trustBundles []string } +type probeConfig struct { + trustBundles []string + fixtureOpts []FixtureOption +} // The allowlisted names atelet resolves trust bundles by. const ( @@ -61,13 +64,25 @@ func WithSystemRoots() ProbeOption { return func(c *probeConfig) { c.trustBundles = append(c.trustBundles, systemRootsBundleName) } } +// WithoutGoldenSnapshot disables the golden snapshot on the probe's +// ActorTemplate, so actors created from it cold-boot. +func WithoutGoldenSnapshot() ProbeOption { + return func(c *probeConfig) { c.fixtureOpts = append(c.fixtureOpts, WithGoldenSnapshotDisabled()) } +} + +// WithProbeImageUser builds the probe image with user as its USER, so the +// probe runs as that user. +func WithProbeImageUser(user string) ProbeOption { + return func(c *probeConfig) { c.fixtureOpts = append(c.fixtureOpts, WithImageUser(user)) } +} + // DeployProbe builds the probe fixture image and installs the fixture for the // sandbox class under test, removing it when the test ends. name // distinguishes the caller (by convention its suite name): each suite gets // its own copy of the fixture, so no suite's cleanup can delete the fixture // out from under another running concurrently. It returns the fixture's // atespace (which also names the k8s namespace holding the pool) and the -// created ActorTemplate, already golden-snapshotted. +// created ActorTemplate, already golden-snapshotted unless WithoutGoldenSnapshot is passed. func DeployProbe(t *testing.T, name string, opts ...ProbeOption) (string, *ateapi.ActorTemplate) { t.Helper() @@ -81,6 +96,6 @@ func DeployProbe(t *testing.T, name string, opts ...ProbeOption) (string, *ateap EnsureEgressTrustBundle(t, context.Background(), GetClients()) } - atespace, templates := DeploySubstrateFixture(t, context.Background(), GetClients(), probeManifests, name, cfg.trustBundles) + atespace, templates := DeploySubstrateFixture(t, context.Background(), GetClients(), probeManifests, name, cfg.trustBundles, cfg.fixtureOpts...) return atespace, templates[0] } diff --git a/internal/e2e/sandbox_test.go b/internal/e2e/sandbox_test.go index c8529669a0..d0c91024a7 100644 --- a/internal/e2e/sandbox_test.go +++ b/internal/e2e/sandbox_test.go @@ -55,6 +55,14 @@ var substrateFixtures = []struct { Pool: "internal/e2e/fixtures/probe/probe-sized.yaml.tmpl", Template: "internal/e2e/fixtures/probe/probe-sized-template.yaml.tmpl", }, 1, nil}, + {SubstrateFixtureManifests{ + Pool: "internal/e2e/fixtures/security/actor-isolation.yaml.tmpl", + Template: "internal/e2e/fixtures/security/actor-isolation-template.yaml.tmpl", + }, 1, nil}, + {SubstrateFixtureManifests{ + Pool: "internal/e2e/fixtures/security/concurrent-a-pool.yaml.tmpl", + Template: "internal/e2e/fixtures/security/concurrent-template.yaml.tmpl", + }, 1, nil}, {SubstrateFixtureManifests{ Pool: "internal/e2e/fixtures/security/atespace-a-pool.yaml.tmpl", Template: "internal/e2e/fixtures/security/atespace-template.yaml.tmpl", diff --git a/internal/e2e/serverpod.go b/internal/e2e/serverpod.go index 021e87f0be..8919b07c4b 100644 --- a/internal/e2e/serverpod.go +++ b/internal/e2e/serverpod.go @@ -64,10 +64,11 @@ type ServerPod struct { // publish a port the container -- uid 65532, every capability dropped -- // cannot bind, such as 80; the Service maps Port down to it. TargetPort int - // TLSPort, when set, publishes the HTTPS listener testserver's http and - // websocket subcommands open on container port 8443 when given a + // TLSPort, when set, publishes the TLS listener testserver's http, + // websocket and grpc subcommands open on container port 8443 when given a // certificate, beside the cleartext one on Port. The readiness probe then - // checks HTTPS, the listener that needs the certificate. + // checks HTTPS, the listener that needs the certificate, unless GRPCProbe + // is set. TLSPort int // Namespace deploys into an existing namespace instead of a fresh one, for // a suite that has to populate that namespace first: credentials the pod @@ -96,10 +97,10 @@ const serverTLSTargetPort = 8443 // chain and key, in one file. const serviceDNSBundle = "/run/servicedns.podcert.ate.dev/credential-bundle.pem" -// ServiceDNSTLS returns spec serving HTTPS as well as HTTP, with a certificate -// from the cluster's service-DNS signer that covers only Server.SvcName. -// Unless spec sets them, HTTP is on port 80 and HTTPS on 443. The server must -// be testserver's http or websocket subcommand. +// ServiceDNSTLS returns spec serving over TLS as well as in cleartext, with a +// certificate from the cluster's service-DNS signer that covers only +// Server.SvcName. Unless spec sets them, cleartext is on port 80 and TLS on +// 443. The server must be testserver's http, websocket or grpc subcommand. func ServiceDNSTLS(spec ServerPod) ServerPod { if spec.Port == 0 { spec.Port, spec.TargetPort = 80, 8080 @@ -248,7 +249,8 @@ func serverArgs(spec ServerPod, targetPort string) string { // under the template's `readinessProbe:` key. kubelet dials the container // directly, so the probe names the listen port rather than the published one. // A server with TLSPort is probed over HTTPS, on the listener that depends on -// its certificate. +// its certificate. A grpc probe stays on the cleartext port: kubelet's grpc +// probe cannot use TLS. func serverReadinessProbe(spec ServerPod, targetPort string) string { if spec.GRPCProbe { return " grpc:\n port: " + targetPort diff --git a/internal/e2e/suites/combinedvolumes/combinedvolumes_test.go b/internal/e2e/suites/combinedvolumes/combinedvolumes_test.go index cf16d686bc..17ca1df4af 100644 --- a/internal/e2e/suites/combinedvolumes/combinedvolumes_test.go +++ b/internal/e2e/suites/combinedvolumes/combinedvolumes_test.go @@ -163,7 +163,7 @@ func buildFixtureImage(t *testing.T, repo string) string { func storageClassOrEmpty(ctx context.Context, t *testing.T, clients *e2e.Clients) string { t.Helper() - if !preview.IsEnabled(preview.GateExternalVolumes) { + if !e2e.PreviewEnabled(preview.GateExternalVolumes) { t.Logf("preview gate %q is not enabled; the external-volume cases will be skipped", preview.GateExternalVolumes) return "" } @@ -183,7 +183,9 @@ func createTemplate(ctx context.Context, t *testing.T, clients *e2e.Clients, ns t.Helper() // The probe supplies this suite's container image and resolved runtime. - probeAtespace, _ := e2e.DeployProbe(t, "combinedvolumes") + // It runs as a non-root user, so the external-volume cases need atelet to + // give the volume the container's group. + probeAtespace, _ := e2e.DeployProbe(t, "combinedvolumes", e2e.WithProbeImageUser("nonroot:nonroot")) src := e2e.SubstrateFixture{ Atespace: probeAtespace, Name: probeName, diff --git a/internal/e2e/suites/containerexit/containerexit_test.go b/internal/e2e/suites/containerexit/containerexit_test.go new file mode 100644 index 0000000000..2c10a9a288 --- /dev/null +++ b/internal/e2e/suites/containerexit/containerexit_test.go @@ -0,0 +1,328 @@ +// Copyright 2026 The Agent Substrate 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 containerexit checks that a worker logs the exit of an actor's +// container while the actor's sandbox stays up. +package containerexit + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "strings" + "testing" + "time" + + corev1 "k8s.io/api/core/v1" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/actorlog" + "go.ate.dev/substrate/internal/ateattr" + "go.ate.dev/substrate/internal/e2e" + "go.ate.dev/substrate/internal/resources" +) + +const ( + // probeContainer is the container's name in probe-template.yaml.tmpl. + probeContainer = "probe" + + // probeExitCode is the code the probe exits with. Go does not exit with it + // on its own and no signal gives it, so the record has it only if the + // worker read it from the sandbox. + probeExitCode = 42 + + // exitRecordTimeout bounds the wait for the worker to log the exit. + exitRecordTimeout = 30 * time.Second +) + +// logLine is a line of a worker's log that contains an actor's uid. +type logLine struct { + // fields is the line as a JSON object. It is nil for a line that is not + // one. + fields map[string]any + // text is the whole line, for a failure message. + text string +} + +// str returns the value of a string field, or "" if the line has none. +func (l logLine) str(key string) string { + s, _ := l.fields[key].(string) + return s +} + +// labels returns the label group of an actor log record. The group has one of +// two names (see actorlog). +func (l logLine) labels() map[string]any { + for _, name := range []string{"logging.googleapis.com/labels", "labels"} { + if group, ok := l.fields[name].(map[string]any); ok { + return group + } + } + return nil +} + +// exitedContainer returns the container that an exit record names, or "" for +// any other line. A worker removes each ate.* key from a container's lines, so +// only a worker can write this key. +func (l logLine) exitedContainer() string { + return l.str(string(ateattr.ActorExitedContainerNameKey)) +} + +// TestContainerExitIsLogged makes an actor's container exit while its sandbox +// stays up. It asserts that the worker writes one `Actor container exited` +// record with the container's name and exit code, after the container's last +// line. The worker starts the exit watch in the cold boot and in the restore +// separately, so the test covers an actor from each. A third actor is deleted +// while its container runs, and must get no record. +func TestContainerExitIsLogged(t *testing.T) { + if _, err := e2e.CheckEnv("KO_DOCKER_REPO"); err != nil { + t.Fatalf("CheckEnv failed: %v", err) + } + ctx := context.Background() + clients := e2e.GetClients() + + atespace, tmpl := e2e.DeployProbe(t, "containerexit", e2e.WithoutGoldenSnapshot()) + rc, err := e2e.NewRouterClient(t, ctx) + if err != nil { + t.Fatalf("NewRouterClient: %v", err) + } + defer rc.Close() + + for _, tc := range []struct { + name string + actor string + // restore suspends and resumes the actor before its container exits, + // so the container runs from a snapshot. + restore bool + // running leaves the container running until the delete, so the + // terminate is what ends its output. + running bool + }{ + {name: "cold boot", actor: "containerexit-cold-boot"}, + {name: "restore", actor: "containerexit-restore", restore: true}, + {name: "terminate", actor: "containerexit-terminate", running: true}, + } { + t.Run(tc.name, func(t *testing.T) { + ref := &ateapi.ObjectRef{Atespace: atespace, Name: tc.actor} + deleteActor := &ateapi.DeleteActorRequest{Actor: ref} + created, err := clients.SubstrateAPI.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: ref.Atespace, Name: ref.Name}, + ActorTemplate: e2e.TemplateRef(tmpl), + }}) + if err != nil { + t.Fatalf("CreateActor %q: %v", ref.Name, err) + } + t.Cleanup(func() { + _, _ = e2e.RetryAborted(t, ctx, clients.SubstrateAPI.DeleteActor, deleteActor) + }) + // An actor with no snapshot cold-boots on its first resume. + if n := len(created.GetStatus().GetSnapshots()); n != 0 { + t.Fatalf("new actor %q has %d snapshots, want none", ref.Name, n) + } + + uid, worker := resumeActor(t, ctx, clients, ref) + // The worker pods the actor ran on. + workers := map[string]*ateapi.WorkerAssignment{worker.GetWorkerPod(): worker} + if tc.restore { + suspended, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("SuspendActor %q: %v", ref.Name, err) + } + if got := suspended.GetActor().GetStatus().GetState(); got != ateapi.ActorState_ACTOR_STATE_SUSPENDED { + t.Fatalf("SuspendActor %q: state %v, want %v", ref.Name, got, ateapi.ActorState_ACTOR_STATE_SUSPENDED) + } + // A resume of an actor with no snapshot is a cold boot. + if len(suspended.GetActor().GetStatus().GetSnapshots()) == 0 { + t.Fatalf("suspended actor %q has no snapshot, want one for the restore", ref.Name) + } + uid, worker = resumeActor(t, ctx, clients, ref) + workers[worker.GetWorkerPod()] = worker + } + + want := 0 + if !tc.running { + want = 1 + exitProbe(t, ctx, clients, rc, tmpl, ref, worker, uid) + } + + // A suspend and a terminate end the container's output as an exit + // does, and the worker must log no exit record for them. The + // delete returns after the worker terminated the actor, and a + // terminated actor gets no more records, so the count is final. + if _, err := e2e.RetryAborted(t, ctx, clients.SubstrateAPI.DeleteActor, deleteActor); err != nil { + t.Fatalf("DeleteActor %q: %v", ref.Name, err) + } + var records []logLine + for _, w := range workers { + records = append(records, exitRecords(actorLogLines(t, ctx, clients, w, uid))...) + } + if len(records) != want { + t.Errorf("exit records for the actor = %d, want %d:\n%s", len(records), want, tail(records)) + } + }) + } +} + +// exitProbe makes the actor's probe container exit, and checks the exit record +// in the worker's log. +func exitProbe(t *testing.T, ctx context.Context, clients *e2e.Clients, rc *e2e.RouterClient, tmpl *ateapi.ActorTemplate, ref *ateapi.ObjectRef, worker *ateapi.WorkerAssignment, uid string) { + resp, err := rc.Get(ctx, resources.ActorRef{Atespace: ref.Atespace, Name: ref.Name}, fmt.Sprintf("/exit?code=%d", probeExitCode)) + if err != nil { + t.Fatalf("GET /exit: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET /exit: status %d, body %q", resp.StatusCode, body) + } + + lines := waitForExitRecord(t, ctx, clients, worker, uid) + // The probe writes a line that imitates the exit record, and then this + // line last. + lastLine := fmt.Sprintf("probe: exiting with code %d", probeExitCode) + last, imitation, exit := -1, -1, -1 + for i, l := range lines { + fromProbe := l.labels()[string(ateattr.ActorContainerNameKey)] == probeContainer + switch { + case l.exitedContainer() != "": + exit = i + case fromProbe && strings.HasSuffix(l.str("message"), lastLine): + last = i + case fromProbe && l.str("message") == actorlog.ContainerExitedMessage: + imitation = i + } + } + if last < 0 || last > exit { + t.Errorf("the container's last line %q is not before the exit record; the actor's last lines:\n%s", lastLine, tail(lines)) + } + // The imitation must arrive as a line of the container. The count of the + // exit records then shows that the worker removed the key from it. + if imitation < 0 { + t.Errorf("the probe's imitation of the exit record is not a container line in the worker's log; the actor's last lines:\n%s", tail(lines)) + } + + record := lines[exit] + if got := record.str("message"); got != actorlog.ContainerExitedMessage { + t.Errorf("exit record message = %q, want %q", got, actorlog.ContainerExitedMessage) + } + if got := record.str("level"); got != "WARN" { + t.Errorf("exit record level = %q, want WARN", got) + } + if got := record.exitedContainer(); got != probeContainer { + t.Errorf("exit record names container %q, want %q", got, probeContainer) + } + if got := record.fields[string(ateattr.ProcessExitCodeKey)]; got != float64(probeExitCode) { + t.Errorf("exit record %s = %v, want %d", ateattr.ProcessExitCodeKey, got, probeExitCode) + } + // kubectl ate logs classes a line by its label group. A container label + // there marks a line that the container wrote. + labels := record.labels() + for key, want := range map[string]string{ + string(ateattr.AtespaceKey): ref.GetAtespace(), + string(ateattr.ActorNameKey): ref.GetName(), + string(ateattr.ActorUIDKey): uid, + string(ateattr.TemplateAtespaceKey): tmpl.GetMetadata().GetAtespace(), + string(ateattr.TemplateNameKey): tmpl.GetMetadata().GetName(), + } { + if got := labels[key]; got != want { + t.Errorf("exit record label %s = %v, want %q", key, got, want) + } + } + if got, ok := labels[string(ateattr.ActorContainerNameKey)]; ok { + t.Errorf("exit record has the label %s = %v, want no container label", ateattr.ActorContainerNameKey, got) + } +} + +// resumeActor resumes the actor and returns its uid and its worker. +func resumeActor(t *testing.T, ctx context.Context, clients *e2e.Clients, ref *ateapi.ObjectRef) (string, *ateapi.WorkerAssignment) { + t.Helper() + resp, err := e2e.ResumeActorAwaitCapacity(t, ctx, clients, &ateapi.ResumeActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("ResumeActor %q: %v", ref.Name, err) + } + uid, worker := resp.GetActor().GetMetadata().GetUid(), resp.GetActor().GetStatus().GetWorkerAssignment() + if uid == "" || worker.GetWorkerNamespace() == "" || worker.GetWorkerPod() == "" { + t.Fatalf("resumed actor %q has no uid or no worker pod: %v", ref.Name, resp.GetActor()) + } + return uid, worker +} + +// actorLogLines returns the lines of the worker's log that contain the actor's +// uid, in the order the worker wrote them: the actor's records, and the +// worker's own records about the actor. +func actorLogLines(t *testing.T, ctx context.Context, clients *e2e.Clients, worker *ateapi.WorkerAssignment, uid string) []logLine { + t.Helper() + namespace, pod := worker.GetWorkerNamespace(), worker.GetWorkerPod() + raw, err := clients.K8s.CoreV1().Pods(namespace).GetLogs(pod, &corev1.PodLogOptions{Container: "worker"}).DoRaw(ctx) + if err != nil { + t.Fatalf("reading the log of worker %s/%s: %v", namespace, pod, err) + } + var lines []logLine + for text := range strings.SplitSeq(string(raw), "\n") { + if !strings.Contains(text, uid) { + continue + } + l := logLine{text: text} + // Not every line is a JSON object. Such a line keeps only its text. + if json.Unmarshal([]byte(text), &l.fields) != nil { + l.fields = nil + } + lines = append(lines, l) + } + return lines +} + +// exitRecords returns the container exit records among lines. +func exitRecords(lines []logLine) []logLine { + var records []logLine + for _, l := range lines { + if l.exitedContainer() != "" { + records = append(records, l) + } + } + return records +} + +// waitForExitRecord waits for an exit record of the actor in the worker's log +// and returns the actor's lines. +func waitForExitRecord(t *testing.T, ctx context.Context, clients *e2e.Clients, worker *ateapi.WorkerAssignment, uid string) []logLine { + t.Helper() + deadline := time.Now().Add(exitRecordTimeout) + for { + lines := actorLogLines(t, ctx, clients, worker, uid) + if len(exitRecords(lines)) > 0 { + return lines + } + if time.Now().After(deadline) { + t.Fatalf("no exit record of actor %s in the log of worker %s/%s after %v; the actor's last lines:\n%s", + uid, worker.GetWorkerNamespace(), worker.GetWorkerPod(), exitRecordTimeout, tail(lines)) + } + time.Sleep(200 * time.Millisecond) + } +} + +// tail returns the last lines as text, for a failure message. +func tail(lines []logLine) string { + const shown = 10 + if len(lines) > shown { + lines = lines[len(lines)-shown:] + } + out := make([]string, 0, len(lines)) + for _, l := range lines { + out = append(out, l.text) + } + return strings.Join(out, "\n") +} diff --git a/internal/e2e/suites/containerexit/testmain_test.go b/internal/e2e/suites/containerexit/testmain_test.go new file mode 100644 index 0000000000..388fa906e0 --- /dev/null +++ b/internal/e2e/suites/containerexit/testmain_test.go @@ -0,0 +1,24 @@ +// Copyright 2026 The Agent Substrate 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 containerexit + +import ( + "os" + "testing" + + "go.ate.dev/substrate/internal/e2e" +) + +func TestMain(m *testing.M) { os.Exit(e2e.RunTestMain(m)) } diff --git a/internal/e2e/suites/demo/demo_test.go b/internal/e2e/suites/demo/demo_test.go index b5b2597d6e..f4c2585070 100644 --- a/internal/e2e/suites/demo/demo_test.go +++ b/internal/e2e/suites/demo/demo_test.go @@ -1038,7 +1038,7 @@ func runtimeAttribute(rt *ateapi.ActorSandboxRuntime, key string) string { // with. func wantSnapshotLocation(t *testing.T, tmpl *ateapi.ActorTemplate) string { t.Helper() - if location := tmpl.GetSnapshotConfig().GetStorageLocation(); location != "" && preview.IsEnabled(preview.GatePerTemplateSnapshotLocation) { + if location := tmpl.GetSnapshotConfig().GetStorageLocation(); location != "" && e2e.PreviewEnabled(preview.GatePerTemplateSnapshotLocation) { return location } env, err := e2e.CheckEnv("SNAPSHOT_LOCATION") @@ -1063,7 +1063,7 @@ func assertSnapshotUnderLocation(t *testing.T, snapshotURI, location string) { } if got := uri.OwnerPrefix(); got != want { t.Errorf("snapshot %q is stored under %q, want %q (PerTemplateSnapshotLocation preview gate enabled: %t)", - snapshotURI, got, want, preview.IsEnabled(preview.GatePerTemplateSnapshotLocation)) + snapshotURI, got, want, e2e.PreviewEnabled(preview.GatePerTemplateSnapshotLocation)) } } diff --git a/internal/e2e/suites/demo/sandboxassets_test.go b/internal/e2e/suites/demo/sandboxassets_test.go new file mode 100644 index 0000000000..23d079ba54 --- /dev/null +++ b/internal/e2e/suites/demo/sandboxassets_test.go @@ -0,0 +1,139 @@ +// Copyright 2026 The Agent Substrate 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 demo + +// What atelet does with a SandboxConfig version whose assets it cannot +// fetch. + +import ( + "context" + "fmt" + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "go.ate.dev/substrate/api/ateapi/v1" + atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" + "go.ate.dev/substrate/internal/hardware" + "google.golang.org/protobuf/testing/protocmp" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/apimachinery/pkg/types" +) + +// TestBadVersionSHA covers a SandboxConfig version whose asset SHA256 is +// wrong: atelet leaves it out and keeps the worker on what it last +// registered, until the version is fixed. +// 1. An actor boots on v1, increments its counters twice (memory=2, file=2, +// rootfs=2), and suspends with a v1-stamped MEMORY snapshot. +// 2. v2 is added with a wrong SHA256 while v1 stays the default: atelet +// records a SandboxRuntimeSyncFailed Event on the worker pod naming the +// incomplete version, and the worker advertises v1 alone. +// 3. defaultVersion moves to the broken v2: atelet records the Event for +// v2 itself and the worker still advertises v1, so the actor restores +// MEMORY on v1 (memory=3, file=3, rootfs=3). +// 4. v2's SHA256 is fixed: the worker converges to v2 as default_runtime +// with v1 restorable. +func TestBadVersionSHA(t *testing.T) { + t.Parallel() + f := setupSuspendedV1Actor(t, "bad-sha") + + // 2. Add v2 with a wrong SHA256 as a restorable version. Only assets + // that differ from v1 get a wrong SHA256, so any assets shared with v1 + // stay cache hits. + v2Bad := *f.v2.DeepCopy() + for arch, files := range v2Bad.Assets { + for name, entry := range files { + if entry == f.v1.Assets[arch][name] { + continue + } + entry.SHA256 = strings.Repeat("0", 64) + files[name] = entry + } + } + f.updateVersions(t, f.v1.Name, []atev1.SandboxVersionConfig{f.v1, v2Bad}) + versionNote := fmt.Sprintf("SandboxConfig %q, version %q:", f.configName, v2Bad.Name) + f.waitForSyncFailureEvent(t, "incomplete sandbox runtimes: "+versionNote) + worker, err := f.clients.SubstrateAPI.GetWorker(f.ctx, &ateapi.GetWorkerRequest{Worker: f.workerRef}) + if err != nil { + t.Fatalf("failed to get Worker %s after the broken restorable version: %v", f.workerRef.GetName(), err) + } + if diff := cmp.Diff(f.v1Runtime, hardware.ColdBootRuntime(worker.GetStatus()), protocmp.Transform()); diff != "" { + t.Fatalf("worker default_runtime changed after the broken restorable version (-want v1 +got):\n%s", diff) + } + if classes := worker.GetStatus().GetSandboxClasses(); len(classes) != 1 || len(classes[0].GetRestorableRuntimes()) != 0 { + t.Fatalf("worker advertised the broken restorable version: %v", classes) + } + + // 3. Make the broken v2 the default. The Event names v2 directly, without + // the prefix a restorable failure carries. + f.updateVersions(t, v2Bad.Name, []atev1.SandboxVersionConfig{f.v1, v2Bad}) + f.waitForSyncFailureEvent(t, versionNote) + worker, err = f.clients.SubstrateAPI.GetWorker(f.ctx, &ateapi.GetWorkerRequest{Worker: f.workerRef}) + if err != nil { + t.Fatalf("failed to get Worker %s after the broken default version: %v", f.workerRef.GetName(), err) + } + if diff := cmp.Diff(f.v1Runtime, hardware.ColdBootRuntime(worker.GetStatus()), protocmp.Transform()); diff != "" { + t.Fatalf("worker default_runtime changed after the broken default version (-want v1 +got):\n%s", diff) + } + f.resumeAndCheck(t, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, f.v1Runtime) + + // 4. Fix v2's SHA256. + f.updateVersions(t, f.v2.Name, []atev1.SandboxVersionConfig{f.v1, f.v2}) + f.waitForWorker(t, func(status *ateapi.WorkerStatus) bool { + defHash := runtimeAttribute(hardware.ColdBootRuntime(status), hardware.AttrSandboxBundleHash) + return defHash != "" && defHash != f.v1Hash && hardware.WorkerMatches(status, f.v1Runtime) + }) +} + +// waitForSyncFailureEvent polls until atelet has recorded a Warning +// SandboxRuntimeSyncFailed Event on the fixture worker's pod, related to the +// fixture's SandboxConfig, whose note starts with wantNote. Events are +// recorded asynchronously, so one can trail the sync attempt it reports. +func (f *sandboxRuntimeFixture) waitForSyncFailureEvent(t *testing.T, wantNote string) { + t.Helper() + w, err := f.clients.SubstrateAPI.GetWorker(f.ctx, &ateapi.GetWorkerRequest{Worker: f.workerRef}) + if err != nil { + t.Fatalf("failed to get Worker %s: %v", f.workerRef.GetName(), err) + } + podUID := types.UID(w.GetWorkerPodUid()) + + const timeout = 2 * time.Minute + ctx, cancel := context.WithTimeout(f.ctx, timeout) + defer cancel() + + var seen []string + for { + list, err := f.clients.K8s.EventsV1().Events(w.GetWorkerNamespace()).List(ctx, metav1.ListOptions{}) + if err == nil { + seen = seen[:0] + for _, ev := range list.Items { + if ev.Regarding.UID != podUID || ev.Reason != "SandboxRuntimeSyncFailed" { + continue + } + if ev.Type == "Warning" && ev.Related != nil && ev.Related.Kind == "SandboxConfig" && ev.Related.Name == f.configName && strings.HasPrefix(ev.Note, wantNote) { + return + } + seen = append(seen, ev.Type+" "+ev.Reason+" "+ev.Note) + } + } + select { + case <-ctx.Done(): + t.Fatalf("timed out after %v waiting for a SandboxRuntimeSyncFailed Event on worker pod %s related to SandboxConfig %s with note %q (seen: %q, err=%v)", + timeout, podUID, f.configName, wantNote, seen, err) + case <-time.After(500 * time.Millisecond): + } + } +} diff --git a/internal/e2e/suites/demo/sandboxconfig_test.go b/internal/e2e/suites/demo/sandboxconfig_test.go new file mode 100644 index 0000000000..ef00ce6a6f --- /dev/null +++ b/internal/e2e/suites/demo/sandboxconfig_test.go @@ -0,0 +1,330 @@ +// Copyright 2026 The Agent Substrate 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 demo + +// What atecontroller does with a WorkerPool's configRef: which changes it +// refuses without disturbing the pool, and what a switch to another +// SandboxConfig does to a running actor. With a second pool on the new +// config, also which pool a resume picks. + +import ( + "context" + "encoding/json" + "slices" + "strings" + "testing" + "time" + + "github.com/google/go-cmp/cmp" + "go.ate.dev/substrate/api/ateapi/v1" + atev1 "go.ate.dev/substrate/api/infra/k8s/ate/v1" + "go.ate.dev/substrate/internal/hardware" + "google.golang.org/protobuf/testing/protocmp" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" + "k8s.io/client-go/util/retry" +) + +// TestWorkerPoolSwitchSandboxConfig covers a WorkerPool's configRef: the +// changes atecontroller refuses while keeping the pool on its SandboxConfig, +// and a switch to another SandboxConfig of the same class while an actor +// runs. A second pool on that config is up before the switch, so the resume +// in step 3 also shows a worker that cannot restore the snapshot's runtime +// is filtered out while one that can has room. +// 1. An actor boots on poolA (configA at v1), increments its counters twice +// (memory=2, file=2, rootfs=2), and suspends with a v1-stamped snapshot. +// poolB (configB at v2) starts in the same namespace with poolA's labels. +// 2. Deleting configA while poolA uses it leaves it Terminating under +// the workerpool-protection finalizer with Resolved=False +// (SandboxConfigDeleting). Pointing configRef at a missing SandboxConfig +// or one of the other sandbox class gives SandboxConfigNotFound and +// SandboxClassMismatch. All three keep configA in +// status.sandboxClasses[0].configRef and the worker on v1. +// 3. With both pools ACTIVE and free, the resume picks poolA's worker, the +// only one advertising v1, and restores MEMORY (memory=3, file=3, +// rootfs=3). While the actor runs, poolA's configRef switches to configB: +// configA is released and deleted, the worker re-registers with v2 as +// default_runtime, and the actor keeps running on v1 (memory=4, file=4, +// rootfs=4). +// 4. Suspending the actor stamps its snapshot with v1, from +// WorkerAssignment.sandbox_runtime, not the worker's new default. The +// next resume drops to ROOTFS on v2 (memory=1, file=5, rootfs=5). +func TestWorkerPoolSwitchSandboxConfig(t *testing.T) { + t.Parallel() + f := setupSuspendedV1Actor(t, "config-switch") + + configBName := f.configName + "-b" + wrongClassName := f.configName + "-wrong-class" + poolBName := f.poolName + "-b" + t.Cleanup(func() { + cleanupCtx, cancel := context.WithTimeout(context.Background(), time.Minute) + defer cancel() + // The pools must go first: they hold the protection finalizer on configB. + for _, name := range []string{f.poolName, poolBName} { + _ = f.clients.SubstrateK8s.AteV1().WorkerPools(f.namespace).Delete(cleanupCtx, name, metav1.DeleteOptions{}) + } + for _, name := range []string{configBName, wrongClassName} { + if err := f.clients.SubstrateK8s.AteV1().SandboxConfigs().Delete(cleanupCtx, name, metav1.DeleteOptions{}); err != nil && !apierrors.IsNotFound(err) { + t.Errorf("failed to delete SandboxConfig %s: %v", name, err) + } + } + }) + if _, err := f.clients.SubstrateK8s.AteV1().SandboxConfigs().Create(f.ctx, &atev1.SandboxConfig{ + ObjectMeta: metav1.ObjectMeta{Name: configBName}, + Spec: atev1.SandboxConfigSpec{ + SandboxClass: f.class, + DefaultVersion: f.v2.Name, + Versions: []atev1.SandboxVersionConfig{f.v2}, + }, + }, metav1.CreateOptions{}); err != nil { + t.Fatalf("failed to create SandboxConfig %s: %v", configBName, err) + } + if _, err := f.clients.SubstrateK8s.AteV1().SandboxConfigs().Create(f.ctx, wrongClassSandboxConfig(wrongClassName, f.class), metav1.CreateOptions{}); err != nil { + t.Fatalf("failed to create wrong-class SandboxConfig %s: %v", wrongClassName, err) + } + // poolB copies poolA apart from its configRef, on poolA's node: the + // actor's node pin cannot exclude it in step 3, and both workers report + // the same host CPU in step 4. + poolA, err := f.clients.SubstrateK8s.AteV1().WorkerPools(f.namespace).Get(f.ctx, f.poolName, metav1.GetOptions{}) + if err != nil { + t.Fatalf("failed to get WorkerPool %s/%s: %v", f.namespace, f.poolName, err) + } + poolAWorker, err := f.clients.SubstrateAPI.GetWorker(f.ctx, &ateapi.GetWorkerRequest{Worker: f.workerRef}) + if err != nil { + t.Fatalf("failed to get Worker %s: %v", f.workerRef.GetName(), err) + } + sandboxClassesB := slices.Clone(poolA.Spec.SandboxClasses) + for i := range sandboxClassesB { + sandboxClassesB[i].ConfigRef = &atev1.SandboxConfigReference{Name: configBName} + } + if _, err := f.clients.SubstrateK8s.AteV1().WorkerPools(f.namespace).Create(f.ctx, &atev1.WorkerPool{ + ObjectMeta: metav1.ObjectMeta{ + Name: poolBName, + Namespace: f.namespace, + Labels: poolA.Labels, + }, + Spec: atev1.WorkerPoolSpec{ + Replicas: 1, + WorkerImage: poolA.Spec.WorkerImage, + Template: &atev1.WorkerPoolPodTemplate{NodeSelector: map[string]string{"kubernetes.io/hostname": poolAWorker.GetNodeName()}}, + SandboxClasses: sandboxClassesB, + }, + }, metav1.CreateOptions{}); err != nil { + t.Fatalf("failed to create WorkerPool %s/%s: %v", f.namespace, poolBName, err) + } + + // 2. Delete configA while the pool uses it. + if err := f.clients.SubstrateK8s.AteV1().SandboxConfigs().Delete(f.ctx, f.configName, metav1.DeleteOptions{}); err != nil { + t.Fatalf("failed to delete SandboxConfig %s while in use: %v", f.configName, err) + } + f.waitForPoolCondition(t, f.configName, metav1.ConditionFalse, atev1.WorkerPoolReasonSandboxConfigDeleting) + f.requireConfigTerminating(t, f.configName) + + // Then point configRef at a missing SandboxConfig and at one of the other + // class. + f.setPoolConfig(t, "nonexistent-"+f.namespace) + f.waitForPoolCondition(t, f.configName, metav1.ConditionFalse, atev1.WorkerPoolReasonSandboxConfigNotFound) + f.setPoolConfig(t, wrongClassName) + f.waitForPoolCondition(t, f.configName, metav1.ConditionFalse, atev1.WorkerPoolReasonSandboxClassMismatch) + + worker, err := f.clients.SubstrateAPI.GetWorker(f.ctx, &ateapi.GetWorkerRequest{Worker: f.workerRef}) + if err != nil { + t.Fatalf("failed to get Worker %s after the refused configRef changes: %v", f.workerRef.GetName(), err) + } + if diff := cmp.Diff(f.v1Runtime, hardware.ColdBootRuntime(worker.GetStatus()), protocmp.Transform()); diff != "" { + t.Fatalf("worker default_runtime changed after the refused configRef changes (-want v1 +got):\n%s", diff) + } + + // 3. Both pools are free; only poolA's worker can restore v1. Then switch + // poolA to configB while the actor runs on it. + v2Runtime := f.waitForPoolWorker(t, poolBName) + assignment := f.resume(t, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, f.v1Runtime).GetWorkerAssignment() + if got := assignment.GetWorker().GetName(); got != f.workerRef.GetName() { + t.Fatalf("assigned worker = %q (pool %q), want poolA's worker %q", got, assignment.GetWorkerPool(), f.workerRef.GetName()) + } + // The refused changes moved spec off configA; only the switch may + // release it. + f.requireConfigTerminating(t, f.configName) + f.setPoolConfig(t, configBName) + f.waitForPoolCondition(t, configBName, metav1.ConditionTrue, atev1.WorkerPoolReasonResolved) + f.waitForConfigDeleted(t, f.configName) + f.waitForWorker(t, func(status *ateapi.WorkerStatus) bool { + return cmp.Equal(hardware.ColdBootRuntime(status), v2Runtime, protocmp.Transform()) && !hardware.WorkerMatches(status, f.v1Runtime) + }) + f.call(t, "running across the pool switch") + + // 4. The snapshot carries the assignment's v1, and the next resume falls + // back to ROOTFS on v2, which both pools now advertise. + f.suspend(t, ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS, f.v1Runtime) + f.resumeAndCheck(t, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, v2Runtime) +} + +// wrongClassSandboxConfig returns a valid SandboxConfig of the sandbox class +// other than poolClass, which a pool of poolClass refuses with +// SandboxClassMismatch. Its assets are never fetched. +func wrongClassSandboxConfig(name string, poolClass atev1.SandboxClass) *atev1.SandboxConfig { + class := atev1.SandboxClassGvisor + dummy := atev1.AssetFile{URL: "gs://dummy/asset", SHA256: strings.Repeat("a", 64)} + assets := map[string]map[string]atev1.AssetFile{"amd64": {"gvisor": dummy}} + if poolClass == atev1.SandboxClassGvisor { + class = atev1.SandboxClassMicroVM + assets = map[string]map[string]atev1.AssetFile{ + "amd64": {"cloud-hypervisor": dummy, "virtiofsd": dummy, "kata-kernel": dummy, "kata-image": dummy}, + } + } + return &atev1.SandboxConfig{ + ObjectMeta: metav1.ObjectMeta{Name: name}, + Spec: atev1.SandboxConfigSpec{ + SandboxClass: class, + DefaultVersion: "v1", + Versions: []atev1.SandboxVersionConfig{ + withState(atev1.SandboxVersionConfig{Name: "v1", Assets: assets}, atev1.SandboxVersionStateEnabled), + }, + }, + } +} + +// setPoolConfig points the fixture pool's sandboxClasses[].configRef at +// configName. +func (f *sandboxRuntimeFixture) setPoolConfig(t *testing.T, configName string) { + t.Helper() + err := retry.RetryOnConflict(retry.DefaultRetry, func() error { + wp, err := f.clients.SubstrateK8s.AteV1().WorkerPools(f.namespace).Get(f.ctx, f.poolName, metav1.GetOptions{}) + if err != nil { + return err + } + for i := range wp.Spec.SandboxClasses { + wp.Spec.SandboxClasses[i].ConfigRef = &atev1.SandboxConfigReference{Name: configName} + } + _, err = f.clients.SubstrateK8s.AteV1().WorkerPools(f.namespace).Update(f.ctx, wp, metav1.UpdateOptions{}) + return err + }) + if err != nil { + t.Fatalf("failed to update WorkerPool %s/%s: %v", f.namespace, f.poolName, err) + } +} + +// waitForPoolCondition polls the fixture pool until +// status.sandboxClasses[0].configRef names wantConfig with no switch pending, +// and its Resolved condition, observed at the current spec generation, has +// wantStatus and wantReason. +func (f *sandboxRuntimeFixture) waitForPoolCondition(t *testing.T, wantConfig string, wantStatus metav1.ConditionStatus, wantReason string) { + t.Helper() + const timeout = time.Minute + ctx, cancel := context.WithTimeout(f.ctx, timeout) + defer cancel() + + var last []atev1.WorkerPoolSandboxClassStatus + var generation int64 + for { + wp, err := f.clients.SubstrateK8s.AteV1().WorkerPools(f.namespace).Get(ctx, f.poolName, metav1.GetOptions{}) + if err == nil && len(wp.Status.SandboxClasses) > 0 { + last, generation = wp.Status.SandboxClasses, wp.Generation + sc := wp.Status.SandboxClasses[0] + gotConfig := "" + if sc.ConfigRef != nil { + gotConfig = sc.ConfigRef.Name + } + for _, cond := range sc.Conditions { + if cond.Type == atev1.WorkerPoolSandboxClassConditionResolved && cond.ObservedGeneration == wp.Generation && + gotConfig == wantConfig && sc.PendingConfigRef == nil && cond.Status == wantStatus && cond.Reason == wantReason { + return + } + } + } + select { + case <-ctx.Done(): + raw, _ := json.Marshal(last) + t.Fatalf("timed out after %v waiting for WorkerPool %s/%s status.sandboxClasses[0] configRef=%q Resolved=%s/%s at generation %d (last=%s, err=%v)", + timeout, f.namespace, f.poolName, wantConfig, wantStatus, wantReason, generation, raw, err) + case <-time.After(500 * time.Millisecond): + } + } +} + +// requireConfigTerminating checks that the SandboxConfig configName is still +// there, marked for deletion and held by the workerpool-protection finalizer. +func (f *sandboxRuntimeFixture) requireConfigTerminating(t *testing.T, configName string) { + t.Helper() + sc, err := f.clients.SubstrateK8s.AteV1().SandboxConfigs().Get(f.ctx, configName, metav1.GetOptions{}) + if err != nil { + t.Fatalf("SandboxConfig %s must stay while the pool uses it: %v", configName, err) + } + if sc.DeletionTimestamp.IsZero() || !slices.Contains(sc.Finalizers, atev1.SandboxConfigWorkerPoolProtectionFinalizer) { + t.Fatalf("SandboxConfig %s in use: deletionTimestamp=%v, finalizers=%v; want Terminating under %s", + configName, sc.DeletionTimestamp, sc.Finalizers, atev1.SandboxConfigWorkerPoolProtectionFinalizer) + } +} + +// waitForConfigDeleted polls until the SandboxConfig configName is gone. +func (f *sandboxRuntimeFixture) waitForConfigDeleted(t *testing.T, configName string) { + t.Helper() + const timeout = time.Minute + ctx, cancel := context.WithTimeout(f.ctx, timeout) + defer cancel() + + for { + sc, err := f.clients.SubstrateK8s.AteV1().SandboxConfigs().Get(ctx, configName, metav1.GetOptions{}) + if apierrors.IsNotFound(err) { + return + } + select { + case <-ctx.Done(): + var finalizers []string + if sc != nil { + finalizers = sc.Finalizers + } + t.Fatalf("timed out after %v waiting for SandboxConfig %s to be deleted (finalizers=%v, err=%v)", + timeout, configName, finalizers, err) + case <-time.After(500 * time.Millisecond): + } + } +} + +// waitForPoolWorker polls ListWorkers until poolName in the fixture's +// namespace has an ACTIVE worker whose default_runtime is not v1, and returns +// its default_runtime. +func (f *sandboxRuntimeFixture) waitForPoolWorker(t *testing.T, poolName string) *ateapi.ActorSandboxRuntime { + t.Helper() + const timeout = 2 * time.Minute + ctx, cancel := context.WithTimeout(f.ctx, timeout) + defer cancel() + + var last *ateapi.Worker + for { + resp, err := f.clients.SubstrateAPI.ListWorkers(ctx, &ateapi.ListWorkersRequest{}) + if err == nil { + for _, w := range resp.GetWorkers() { + if w.GetWorkerNamespace() != f.namespace || w.GetWorkerPool() != poolName { + continue + } + last = w + status := w.GetStatus() + cold := hardware.ColdBootRuntime(status) + defHash := runtimeAttribute(cold, hardware.AttrSandboxBundleHash) + if status.GetState() == ateapi.WorkerState_WORKER_STATE_ACTIVE && defHash != "" && defHash != f.v1Hash && !hardware.WorkerMatches(status, f.v1Runtime) { + return cold + } + } + } + select { + case <-ctx.Done(): + raw, _ := json.Marshal(last) + t.Fatalf("timed out after %v waiting for pool %s/%s to have an ACTIVE worker off v1 (last worker=%s, err=%v)", + timeout, f.namespace, poolName, raw, err) + case <-time.After(500 * time.Millisecond): + } + } +} diff --git a/internal/e2e/suites/demo/sandboxruntime_test.go b/internal/e2e/suites/demo/sandboxruntime_test.go index 9be3b7ad00..ce0e24aeac 100644 --- a/internal/e2e/suites/demo/sandboxruntime_test.go +++ b/internal/e2e/suites/demo/sandboxruntime_test.go @@ -17,6 +17,7 @@ package demo import ( "context" "encoding/json" + "runtime" "testing" "time" @@ -32,25 +33,6 @@ import ( "k8s.io/client-go/util/retry" ) -// gvisorSecondReleaseAssets is a gVisor build with a sandbox_bundle_hash -// other than the installed class default's: the first nightly after release -// 20261026.0, which manifests/ate-install/sandboxconfig-gvisor.yaml ships, so -// it has everything ateworker-gvisor needs from that release. -var gvisorSecondReleaseAssets = map[string]map[string]atev1.AssetFile{ - "amd64": { - "gvisor": { - URL: "gs://gvisor/releases/nightly/2026-10-27/x86_64/gvisor.tar.zstd", - SHA256: "6cf41969e53892d8036d9a6470cbb2e870fbe719563fa15dbf9247bdd7911ba5", - }, - }, - "arm64": { - "gvisor": { - URL: "gs://gvisor/releases/nightly/2026-10-27/aarch64/gvisor.tar.zstd", - SHA256: "8ffb0077d6db3d837a3790d1a43d2354ae79a216e6707452429bb9e52e2d545b", - }, - }, -} - // TestSandboxConfigEdit covers what a suspended actor's MEMORY snapshot // restores at after its pool's SandboxConfig is edited. Each case starts from // its own pool on a SandboxConfig holding one version, v1, with an actor @@ -72,6 +54,10 @@ func TestSandboxConfigEdit(t *testing.T) { wantOnV1 bool // repoint moves the actor to a copy of its template before the edit. repoint bool + // wantDetached says the resume leaves no node-local checkpoint: a + // runtime fallback detaches it to durable storage first. The fallback + // to VOLUMES for a replaced template needs no runtime and keeps it. + wantDetached bool // checkWorker, if set, inspects the worker after it re-registered. checkWorker func(t *testing.T, status *ateapi.WorkerStatus) }{{ @@ -87,6 +73,7 @@ func TestSandboxConfigEdit(t *testing.T) { return v2.Name, []atev1.SandboxVersionConfig{withState(v1, atev1.SandboxVersionStateDisabled), v2} }, wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + wantDetached: true, }, { // The snapshot was taken under another template, which forces VOLUMES // on its own; the runtime fallback alone would keep ROOTFS. @@ -123,6 +110,7 @@ func TestSandboxConfigEdit(t *testing.T) { return v1.Name, []atev1.SandboxVersionConfig{withName(v2, v1.Name)} }, wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + wantDetached: true, }} for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -146,7 +134,10 @@ func TestSandboxConfigEdit(t *testing.T) { if !tt.wantOnV1 { wantRuntime = hardware.ColdBootRuntime(status) } - f.resumeAndCheck(t, tt.wantFidelity, wantRuntime) + resumed := f.resumeAndCheck(t, tt.wantFidelity, wantRuntime) + if tt.wantDetached { + f.requireDetached(t, resumed) + } }) } } @@ -194,6 +185,56 @@ func TestTagCloneOnDisabledVersion(t *testing.T) { clone.resumeAndCheck(t, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, hardware.ColdBootRuntime(status)) } +// TestAsyncSuspendSandboxRuntime covers the resume of an asynchronously +// suspended actor, whose MEMORY checkpoint is node-local, after SandboxConfig +// version changes. atelet detaches such a checkpoint on its own after +// --snapshot-detach-delay (30s in e2e), so each change comes before the +// asynchronous suspend and the resume follows it at once. +// 1. An actor boots on v1, increments its counters twice (memory=2, file=2, +// rootfs=2), and suspends synchronously with a v1-stamped MEMORY snapshot. +// 2. The SandboxConfig moves defaultVersion to v2 with v1 still Enabled. The +// actor restores MEMORY on v1 through restorable_runtimes (memory=3, +// file=3, rootfs=3) and suspends asynchronously. It then restores MEMORY +// on its node without detaching the checkpoint (memory=4, file=4, +// rootfs=4). +// 3. The SandboxConfig disables v1 while the actor runs on it. The worker +// re-registers without v1 and the actor keeps running. +// 4. The actor suspends asynchronously on v1. A pinned checkpoint cannot +// relax the runtime, so ResumeActor detaches it to durable storage first +// and then restores at ROOTFS on v2 (memory=1, file=5, rootfs=5), the +// same checks TestSandboxConfigEdit makes after a synchronous suspend. +func TestAsyncSuspendSandboxRuntime(t *testing.T) { + t.Parallel() + f := setupSuspendedV1Actor(t, "async-suspend") + + // 2. Move the default to v2 with v1 still Enabled, then suspend + // asynchronously and resume in place. + f.updateVersions(t, f.v2.Name, []atev1.SandboxVersionConfig{f.v1, f.v2}) + f.waitForWorker(t, func(status *ateapi.WorkerStatus) bool { + defHash := runtimeAttribute(hardware.ColdBootRuntime(status), hardware.AttrSandboxBundleHash) + return defHash != "" && defHash != f.v1Hash && hardware.WorkerMatches(status, f.v1Runtime) + }) + f.resume(t, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, f.v1Runtime) + f.suspend(t, ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS, f.v1Runtime) + status := f.resume(t, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, f.v1Runtime) + if !hasLocalSnapshot(status) { + t.Fatalf("local checkpoint detached although restorable_runtimes matched: %v", status.GetSnapshots()) + } + + // 3. Disable v1 while the actor runs on it. + f.updateVersions(t, f.v2.Name, []atev1.SandboxVersionConfig{withState(f.v1, atev1.SandboxVersionStateDisabled), f.v2}) + workerStatus := f.waitForWorker(t, func(status *ateapi.WorkerStatus) bool { + defHash := runtimeAttribute(hardware.ColdBootRuntime(status), hardware.AttrSandboxBundleHash) + return defHash != "" && defHash != f.v1Hash && !hardware.WorkerMatches(status, f.v1Runtime) + }) + v2Runtime := hardware.ColdBootRuntime(workerStatus) + + // 4. Suspend asynchronously and resume at once: ResumeActor detaches the + // checkpoint, then falls back to ROOTFS on v2. + f.suspend(t, ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS, f.v1Runtime) + f.requireDetached(t, f.resumeAndCheck(t, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, v2Runtime)) +} + // sandboxRuntimeFixture is a suspended actor on a pool whose SandboxConfig // the test owns, so the test can edit versions and watch the worker // re-register and the actor resume. @@ -224,10 +265,10 @@ type sandboxRuntimeFixture struct { // setupSuspendedV1Actor creates a SandboxConfig holding one version, v1, // copied from the cluster's class default, a one-worker pool pinned to it, a // counter ActorTemplate without a golden snapshot, and an actor. It runs the -// actor on v1 for two calls -// (memory=2, file=2, rootfs=2), suspends it synchronously, and checks the -// MEMORY snapshot is stamped with v1. f.v2 is a second version with a -// different sandbox_bundle_hash that the config does not hold yet. +// actor on v1 for two calls (memory=2, file=2, rootfs=2), suspends it +// synchronously, and checks the MEMORY snapshot is stamped with v1. f.v2 is a +// second version with a different sandbox_bundle_hash that the config does +// not hold yet. func setupSuspendedV1Actor(t *testing.T, prefix string) *sandboxRuntimeFixture { t.Helper() nsObj := e2e.CreateNamespace(t) @@ -240,7 +281,7 @@ func setupSuspendedV1Actor(t *testing.T, prefix string) *sandboxRuntimeFixture { } baseConfig := newestClassDefault(t, ctx, clients, class) v1 := defaultVersionFromConfig(t, baseConfig, "v1") - v2 := secondSandboxVersion(v1, "v2", class) + v2 := secondSandboxVersion(t, baseConfig, v1, "v2", class) configName := "e2e-" + prefix + "-" + nsObj.Name if _, err := clients.SubstrateK8s.AteV1().SandboxConfigs().Create(ctx, &atev1.SandboxConfig{ @@ -341,7 +382,7 @@ func setupSuspendedV1Actor(t *testing.T, prefix string) *sandboxRuntimeFixture { file: 2, rootfs: 2, } - f.suspend(t, v1Runtime) + f.suspend(t, ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS, v1Runtime) return f } @@ -398,7 +439,7 @@ func (f *sandboxRuntimeFixture) waitForWorker(t *testing.T, pred func(*ateapi.Wo func (f *sandboxRuntimeFixture) resumeAndCheck(t *testing.T, want ateapi.SnapshotFidelity, wantRuntime *ateapi.ActorSandboxRuntime) *ateapi.ActorStatus { t.Helper() status := f.resume(t, want, wantRuntime) - f.suspend(t, wantRuntime) + f.suspend(t, ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS, wantRuntime) return status } @@ -442,19 +483,29 @@ func (f *sandboxRuntimeFixture) call(t *testing.T, stage string) { validateRootfsCounter(t, resp, stage, f.rootfs) } -// suspend suspends the fixture's actor synchronously and checks the new -// MEMORY snapshot is stamped with wantRuntime. -func (f *sandboxRuntimeFixture) suspend(t *testing.T, wantRuntime *ateapi.ActorSandboxRuntime) { +// suspend suspends the fixture's actor with mode and checks that its new +// MEMORY snapshot advances the generation and is stamped with wantRuntime: +// the durable snapshot after a synchronous suspend, the node-local +// checkpoint after an asynchronous one. +func (f *sandboxRuntimeFixture) suspend(t *testing.T, mode ateapi.DurabilityMode, wantRuntime *ateapi.ActorSandboxRuntime) { t.Helper() - suspended, err := f.clients.SubstrateAPI.SuspendActor(f.ctx, &ateapi.SuspendActorRequest{ + // After an asynchronous suspend, atelet's report of the background + // upload can hold the actor's lease when the next suspend arrives. + suspended, err := e2e.RetryAborted(t, f.ctx, f.clients.SubstrateAPI.SuspendActor, &ateapi.SuspendActorRequest{ Actor: f.actorRef, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, + Options: &ateapi.SuspendOptions{Mode: mode}, }) if err != nil { t.Fatalf("failed to suspend Actor %s: %v", f.actorName, err) } - waitForActorState(f.ctx, t, f.clients, f.actorName, ateapi.ActorState_ACTOR_STATE_SUSPENDED) - snap := durableSnapshot(suspended.GetActor().GetStatus()) + var snap *ateapi.Snapshot + if mode == ateapi.DurabilityMode_DURABILITY_MODE_ASYNCHRONOUS { + waitForActorPaused(f.ctx, t, f.clients, f.actorName) + snap = localSnapshot(suspended.GetActor().GetStatus()) + } else { + waitForActorState(f.ctx, t, f.clients, f.actorName, ateapi.ActorState_ACTOR_STATE_SUSPENDED) + snap = durableSnapshot(suspended.GetActor().GetStatus()) + } if snap.GetGeneration() <= f.generation { t.Fatalf("snapshot generation of %s = %d, want > %d", f.actorName, snap.GetGeneration(), f.generation) } @@ -537,6 +588,23 @@ func (f *sandboxRuntimeFixture) repoint(t *testing.T) { } } +// requireDetached checks status, the status an actor resumed with after a +// runtime fallback: no node-local snapshot is left, and the latest snapshot, +// the one the suspend took, is durable and stamped with v1. +func (f *sandboxRuntimeFixture) requireDetached(t *testing.T, status *ateapi.ActorStatus) { + t.Helper() + if hasLocalSnapshot(status) { + t.Fatalf("local snapshot of %s survived the runtime fallback: %v", f.actorName, status.GetSnapshots()) + } + snap := snapshotAtLatestGeneration(status) + if got := snap.GetDurableSnapshot().GetState(); got != ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED { + t.Fatalf("durable snapshot state of %s at generation %d = %v, want COMPLETED", f.actorName, status.GetLastAssignedGeneration(), got) + } + if diff := cmp.Diff(f.v1Runtime, snap.GetSandboxRuntime(), protocmp.Transform()); diff != "" { + t.Fatalf("detached snapshot sandbox_runtime of %s (-want v1 +got):\n%s", f.actorName, diff) + } +} + // newestClassDefault returns the cluster's installed class-default // SandboxConfig for class. func newestClassDefault(t *testing.T, ctx context.Context, clients *e2e.Clients, class atev1.SandboxClass) *atev1.SandboxConfig { @@ -576,13 +644,29 @@ func defaultVersionFromConfig(t *testing.T, sc *atev1.SandboxConfig, name string } // secondSandboxVersion returns an Enabled version named name whose assets -// produce a different sandbox_bundle_hash than v1. On gVisor it uses a second -// gVisor release tarball; on microVM it reuses v1's cached assets plus an -// extra entry, so the bucket needs no second kata asset set. -func secondSandboxVersion(v1 atev1.SandboxVersionConfig, name string, class atev1.SandboxClass) atev1.SandboxVersionConfig { +// produce a different sandbox_bundle_hash than v1. On gVisor it uses another +// installed release; on microVM it reuses v1's cached assets plus an extra +// entry, so the bucket needs no second kata asset set. +func secondSandboxVersion(t *testing.T, config *atev1.SandboxConfig, v1 atev1.SandboxVersionConfig, name string, class atev1.SandboxClass) atev1.SandboxVersionConfig { + t.Helper() if class == atev1.SandboxClassGvisor { - // withName copies the assets, so no test shares the package-level map. - v1.Assets = gvisorSecondReleaseAssets + v1Assets, ok := v1.Assets[runtime.GOARCH] + if !ok { + t.Fatalf("SandboxConfig %s default version has no assets for %s", config.Name, runtime.GOARCH) + } + for _, version := range config.Spec.Versions { + assets, ok := version.Assets[runtime.GOARCH] + if !ok || version.State != nil && *version.State == atev1.SandboxVersionStateDisabled { + continue + } + if cmp.Equal(assets, v1Assets, cmp.Comparer(func(x, y atev1.AssetFile) bool { + return x.SHA256 == y.SHA256 + })) { + continue + } + return withState(withName(version, name), atev1.SandboxVersionStateEnabled) + } + t.Fatalf("SandboxConfig %s has no second enabled version", config.Name) } v2 := withState(withName(v1, name), atev1.SandboxVersionStateEnabled) if class != atev1.SandboxClassGvisor { @@ -594,6 +678,29 @@ func secondSandboxVersion(v1 atev1.SandboxVersionConfig, name string, class atev return v2 } +func TestSecondSandboxVersionUsesInstalledGVisorAssets(t *testing.T) { + installed := map[string]map[string]atev1.AssetFile{ + runtime.GOARCH: {"gvisor": {URL: "s3://gvisor-assets/v6/gvisor.tar.zstd", SHA256: "v6"}}, + } + config := &atev1.SandboxConfig{Spec: atev1.SandboxConfigSpec{ + DefaultVersion: "v7", + Versions: []atev1.SandboxVersionConfig{ + {Name: "v7-mirror", Assets: map[string]map[string]atev1.AssetFile{ + runtime.GOARCH: {"gvisor": {URL: "s3://mirror/gvisor.tar.zstd", SHA256: "v7"}}, + }}, + {Name: "v6", Assets: installed}, + {Name: "v7", Assets: map[string]map[string]atev1.AssetFile{ + runtime.GOARCH: {"gvisor": {URL: "s3://gvisor-assets/v7/gvisor.tar.zstd", SHA256: "v7"}}, + }}, + }, + }} + + got := secondSandboxVersion(t, config, defaultVersionFromConfig(t, config, "v1"), "v2", atev1.SandboxClassGvisor) + if diff := cmp.Diff(installed, got.Assets); diff != "" { + t.Fatalf("second version assets (-want +got):\n%s", diff) + } +} + // withName returns a copy of v named name. func withName(v atev1.SandboxVersionConfig, name string) atev1.SandboxVersionConfig { v = *v.DeepCopy() diff --git a/internal/e2e/suites/demo/worker_security_filesystem_test.go b/internal/e2e/suites/demo/worker_security_filesystem_test.go index 2e509cc41d..04d8d40ea4 100644 --- a/internal/e2e/suites/demo/worker_security_filesystem_test.go +++ b/internal/e2e/suites/demo/worker_security_filesystem_test.go @@ -36,7 +36,7 @@ import ( // test restates them rather than importing the controller so that a change to // the defaults has to be made deliberately in both places. var ( - gvisorWorkerCapabilities = []corev1.Capability{"NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER", "CHOWN", "NET_RAW", "SETFCAP"} + gvisorWorkerCapabilities = []corev1.Capability{"NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER", "CHOWN", "NET_RAW", "SETFCAP", "IPC_LOCK"} microVMWorkerCapabilities = []corev1.Capability{"NET_ADMIN", "SYS_ADMIN", "SETUID", "SETGID", "DAC_OVERRIDE", "FOWNER", "CHOWN", "MKNOD", "SETFCAP", "FSETID", "SETPCAP"} // virtiofsd's default child set: what its serving child keeps in its // permitted and effective sets after it drops the rest. With file handles @@ -49,7 +49,7 @@ var ( // masks in /proc//status. var capabilityBits = map[corev1.Capability]uint{ "CHOWN": 0, "DAC_OVERRIDE": 1, "DAC_READ_SEARCH": 2, "FOWNER": 3, "FSETID": 4, "KILL": 5, - "SETGID": 6, "SETUID": 7, "SETPCAP": 8, "NET_BIND_SERVICE": 10, "NET_ADMIN": 12, "NET_RAW": 13, + "SETGID": 6, "SETUID": 7, "SETPCAP": 8, "NET_BIND_SERVICE": 10, "NET_ADMIN": 12, "NET_RAW": 13, "IPC_LOCK": 14, "SYS_CHROOT": 18, "SYS_PTRACE": 19, "SYS_ADMIN": 21, "MKNOD": 27, "AUDIT_WRITE": 29, "SETFCAP": 31, } diff --git a/internal/e2e/suites/egressmitm/egressmitm_test.go b/internal/e2e/suites/egressmitm/egressmitm_test.go index 41db17b4bb..4672809324 100644 --- a/internal/e2e/suites/egressmitm/egressmitm_test.go +++ b/internal/e2e/suites/egressmitm/egressmitm_test.go @@ -25,6 +25,7 @@ import ( "encoding/json" "encoding/pem" "io" + "net" "net/http" "net/url" "strings" @@ -146,12 +147,13 @@ func TestActorEgressMITMTrust(t *testing.T) { } // The gateway dials the name the SNI claims. - bySNI := fetchUntilReached(t, ctx, rc, id, passthroughOrigin, "pem", originRoots, "dial="+url.QueryEscape(unreachableAddress)) + unreachable := unreachableAddress(mitm.ClusterIP) + bySNI := fetchUntilReached(t, ctx, rc, id, passthroughOrigin, "pem", originRoots, "dial="+url.QueryEscape(unreachable)) switch { case bySNI.Error != "": - t.Errorf("TLS passthrough to %s dialed at %s failed: %s — the gateway dialed the actor's address instead of resolving the SNI", passthroughOrigin, unreachableAddress, bySNI.Error) + t.Errorf("TLS passthrough to %s dialed at %s failed: %s — the gateway dialed the actor's address instead of resolving the SNI", passthroughOrigin, unreachable, bySNI.Error) case bySNI.Status != "200": - t.Errorf("passthrough fetch %s dialed at %s: status %s, want 200", passthroughOrigin, unreachableAddress, bySNI.Status) + t.Errorf("passthrough fetch %s dialed at %s: status %s, want 200", passthroughOrigin, unreachable, bySNI.Status) } // Each name is an origin's fully qualified alias: only the wrong-port rule @@ -190,13 +192,31 @@ func originSpec(name string) e2e.ServerPod { } const ( - // unreachableAddress is in the reserved 240/4 block: a gateway that dialed - // it instead of the resolved SNI would reach nothing. - unreachableAddress = "240.0.0.1:443" // systemRoot is the common name of a WebPKI root atelet's image ships. systemRoot = "ISRG Root X1" ) +func unreachableAddress(originIP string) string { + if net.ParseIP(originIP).To4() == nil { + return "[2001:db8::1]:443" + } + return "240.0.0.1:443" +} + +func TestUnreachableAddressMatchesOriginFamily(t *testing.T) { + for _, tc := range []struct { + origin string + want string + }{ + {origin: "10.96.0.1", want: "240.0.0.1:443"}, + {origin: "fd00:10:96::1", want: "[2001:db8::1]:443"}, + } { + if got := unreachableAddress(tc.origin); got != tc.want { + t.Errorf("unreachableAddress(%q) = %q, want %q", tc.origin, got, tc.want) + } + } +} + type fetchResponse struct { Status string `json:"status"` Error string `json:"error"` diff --git a/internal/e2e/suites/imagefs/imagefs_test.go b/internal/e2e/suites/imagefs/imagefs_test.go index 8c34487d77..c4b8ff32e1 100644 --- a/internal/e2e/suites/imagefs/imagefs_test.go +++ b/internal/e2e/suites/imagefs/imagefs_test.go @@ -13,7 +13,8 @@ // limitations under the License. // Package imagefs checks the actor's view of its image's filesystem and -// process identity against what the image records. +// process identity against what the image records, and that a read from the +// actor's stdin returns EOF. package imagefs import ( @@ -204,6 +205,49 @@ func TestImageUserAndWorkdir(t *testing.T) { } } +// stdinResponse mirrors the probe's /stdin payload. +type stdinResponse struct { + EOF bool `json:"eof"` + Error string `json:"error"` +} + +// TestStdinReadsEOF asserts that a read from the actor's stdin returns EOF, as +// it does from /dev/null on gVisor. The actor cold-boots with the golden +// snapshot disabled, so on microVM the check covers the CloseStdin call in +// StartRootfsContainer. +func TestStdinReadsEOF(t *testing.T) { + if _, err := e2e.CheckEnv("KO_DOCKER_REPO"); err != nil { + t.Fatalf("CheckEnv failed: %v", err) + } + ctx := context.Background() + clients := e2e.GetClients() + + atespace, tmpl := e2e.DeployProbe(t, "imagefs-stdin", e2e.WithoutGoldenSnapshot()) + ref := &ateapi.ObjectRef{Atespace: atespace, Name: "imagefs-stdin-actor"} + if _, err := clients.SubstrateAPI.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: ref.Atespace, Name: ref.Name}, + ActorTemplate: &ateapi.ObjectRef{Atespace: atespace, Name: tmpl.GetMetadata().GetName()}, + }}); err != nil { + t.Fatalf("CreateActor %q: %v", ref.Name, err) + } + t.Cleanup(func() { + _, _ = clients.SubstrateAPI.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref}) + }) + + rc, err := e2e.NewRouterClient(t, ctx) + if err != nil { + t.Fatalf("NewRouterClient: %v", err) + } + defer rc.Close() + + if _, err := e2e.ResumeActorAwaitCapacity(t, ctx, clients, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor %q: %v", ref.Name, err) + } + if got := probeStdin(t, ctx, rc, ref); !got.EOF { + t.Errorf("read from stdin = %+v, want EOF", got) + } +} + func probeIdentity(t *testing.T, ctx context.Context, rc *e2e.RouterClient, ref *ateapi.ObjectRef) identityResponse { t.Helper() resp, err := rc.Get(ctx, resources.ActorRef{Atespace: ref.Atespace, Name: ref.Name}, "/identity") @@ -256,3 +300,21 @@ func probeStat(t *testing.T, ctx context.Context, rc *e2e.RouterClient, ref *ate } return out } + +func probeStdin(t *testing.T, ctx context.Context, rc *e2e.RouterClient, ref *ateapi.ObjectRef) stdinResponse { + t.Helper() + resp, err := rc.Get(ctx, resources.ActorRef{Atespace: ref.Atespace, Name: ref.Name}, "/stdin") + if err != nil { + t.Fatalf("GET /stdin: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET /stdin: status %d, body %q", resp.StatusCode, body) + } + var out stdinResponse + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("decoding /stdin: %v", err) + } + return out +} diff --git a/internal/e2e/suites/networking/grpcegress_test.go b/internal/e2e/suites/networking/grpcegress_test.go index cc8a07ccd7..403bda7357 100644 --- a/internal/e2e/suites/networking/grpcegress_test.go +++ b/internal/e2e/suites/networking/grpcegress_test.go @@ -18,6 +18,7 @@ import ( "context" "encoding/json" "fmt" + "net" "net/http" "strconv" "testing" @@ -41,6 +42,15 @@ var grpcEcho = e2e.ServerPod{ GRPCProbe: true, } +// grpcEchoRequest mirrors the egress demo Actor's /grpc request. +type grpcEchoRequest struct { + Target string `json:"target"` + TLS bool `json:"tls,omitempty"` + Message string `json:"message"` + StreamCount int `json:"streamCount,omitempty"` + BidiCount int `json:"bidiCount,omitempty"` +} + // grpcEchoResponse mirrors the egress demo Actor's /grpc answer. Kept as a // local copy rather than imported: the demo is a separate module-internal // command, and what this suite is really pinning is the wire shape between the @@ -85,22 +95,54 @@ func TestActorEgressGRPC(t *testing.T) { // The slack absorbs clock skew between here and the gateway's node. since := metav1.NewTime(time.Now().Add(-1 * time.Minute)) + actorRef := resources.ActorRef{Atespace: actorAtespace, Name: actorName} + assertEgressGRPCEcho(t, ctx, router, actorRef, grpcEchoRequest{Target: target}) + + // Everything above would also pass if the Actor's traffic had been + // masqueraded straight out instead of tunneled. This is what says it went + // through the gateway, on this Actor's own certificate. + assertEgressGatewayConnect(t, ctx, since, actorAtespace, actorName, strconv.Itoa(grpcEcho.Port)) +} + +// TestActorEgressGRPCOverTLS covers gRPC to a TLS origin under an https rule. +// The gateway terminates the Actor's TLS and opens its own TLS connection to +// the origin, so the HTTP/2 framing and the trailers have to survive both. +func TestActorEgressGRPCOverTLS(t *testing.T) { + ctx := context.Background() + origin := e2e.DeployServerPod(t, ctx, e2e.ServiceDNSTLS(grpcEcho)) + + _, actorName, _ := createAndResumeActorWithEgress(t, ctx, "egress-grpc-tls", e2e.EgressFixture(), e2e.EgressAllowAll()...) + router := mustRouterClient(t, ctx) + defer router.Close() + + actorRef := resources.ActorRef{Atespace: networkingAtespace, Name: actorName} + assertEgressGRPCEcho(t, ctx, router, actorRef, grpcEchoRequest{ + Target: net.JoinHostPort(origin.SvcName(), strconv.Itoa(origin.TLSPort)), + TLS: true, + }) +} + +// grpcStreamOverLimit is one more than the longest stream the origin serves. +// It answers a longer request with InvalidArgument. +const grpcStreamOverLimit = 1001 + +// assertEgressGRPCEcho has the Actor make a unary, a server-streaming and a +// bidirectional call to request's origin and checks every answer, then checks +// that a refused call reports the origin's status. +func assertEgressGRPCEcho(t *testing.T, ctx context.Context, router *e2e.RouterClient, actorRef resources.ActorRef, request grpcEchoRequest) { + t.Helper() const ( message = "hello over grpc" streamCount = 3 bidiCount = 3 ) - payload, err := json.Marshal(map[string]any{ - "target": target, - "message": message, - "streamCount": streamCount, - "bidiCount": bidiCount, - }) + request.Message, request.StreamCount, request.BidiCount = message, streamCount, bidiCount + target := request.Target + payload, err := json.Marshal(request) if err != nil { t.Fatalf("marshaling the gRPC request for %s: %v", target, err) } - actorRef := resources.ActorRef{Atespace: actorAtespace, Name: actorName} status, body := postThroughEgressActor(t, ctx, router, actorRef, "/grpc", payload) if status != http.StatusOK { t.Fatalf("Actor gRPC egress to %s returned HTTP %d, want 200; body: %s", target, status, body) @@ -152,8 +194,18 @@ func TestActorEgressGRPC(t *testing.T) { } t.Logf("Actor gRPC egress to %s succeeded; body: %s", target, body) - // Everything above would also pass if the Actor's traffic had been - // masqueraded straight out instead of tunneled. This is what says it went - // through the gateway, on this Actor's own certificate. - assertEgressGatewayConnect(t, ctx, since, actorAtespace, actorName, strconv.Itoa(grpcEcho.Port)) + // A refused call carries no message, only a status, and the Actor answers + // it 502 with the gRPC code in the body. + request.StreamCount = grpcStreamOverLimit + payload, err = json.Marshal(request) + if err != nil { + t.Fatalf("marshaling the over-limit gRPC request for %s: %v", target, err) + } + refused := func(_ int, body []byte) bool { + var got grpcEchoResponse + return json.Unmarshal(body, &got) == nil && got.Code == "InvalidArgument" + } + if status, body := postThroughEgressActorUntil(t, ctx, router, actorRef, "/grpc", payload, refused); !refused(status, body) { + t.Errorf("EchoStream of %d through %s returned HTTP %d, want the origin's InvalidArgument; body: %s", grpcStreamOverLimit, target, status, body) + } } diff --git a/internal/e2e/suites/networking/ingresscache_test.go b/internal/e2e/suites/networking/ingresscache_test.go new file mode 100644 index 0000000000..23441b5b84 --- /dev/null +++ b/internal/e2e/suites/networking/ingresscache_test.go @@ -0,0 +1,447 @@ +// Copyright 2026 The Agent Substrate 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 networking + +import ( + "context" + "io" + "net/http" + "strings" + "testing" + "time" + + "google.golang.org/grpc" + "google.golang.org/grpc/credentials" + "google.golang.org/grpc/metadata" + "k8s.io/apimachinery/pkg/util/wait" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/atenet" + "go.ate.dev/substrate/internal/e2e" + "go.ate.dev/substrate/internal/preview" + "go.ate.dev/substrate/internal/proto/grpcechopb" + "go.ate.dev/substrate/internal/resources" +) + +// TestIngressCache_HitAndTTL verifies that requests to an actor hit the ingress +// cache after the first request, record hit/miss metrics on atenet-router, and +// expire after the cache TTL (5 seconds). +func TestIngressCache_HitAndTTL(t *testing.T) { + e2e.RequireIngressCache(t) + ctx := context.Background() + _, actorName, _ := createAndResumeSubstrateActor(t, ctx, "cache-hit", e2e.SubstrateCounterFixture()) + router := mustRouterClient(t, ctx) + defer router.Close() + + actorRef := resources.ActorRef{Atespace: networkingAtespace, Name: actorName} + + // 1. Initial request: Warm up / establish route. + waitForRouteReady(t, "Warm up actor route", func() (*http.Response, error) { + return router.Get(ctx, actorRef, "/readyz") + }) + + // Scrape baseline router metrics. + scrape1, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics baseline: %v", err) + } + missBefore := e2e.RouterCacheCounterValue(scrape1, "ate_ingress_cache_miss") + hitBefore := e2e.RouterCacheCounterValue(scrape1, "ate_ingress_cache_hit") + + // 2. Fire 3 rapid GET requests within the 5s TTL. + for i := range 3 { + resp, err := router.Get(ctx, actorRef, "/readyz") + if err != nil { + t.Fatalf("rapid GET %d: %v", i, err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("rapid GET %d status %d, want 200", i, resp.StatusCode) + } + } + + // Scrape metrics after rapid requests: hits must have increased by at least 3. + scrape2, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics after rapid requests: %v", err) + } + hitAfter := e2e.RouterCacheCounterValue(scrape2, "ate_ingress_cache_hit") + if hitAfter < hitBefore+3 { + t.Fatalf("expected at least 3 cache hits, got hit count before=%.0f, after=%.0f", hitBefore, hitAfter) + } + + // 3. Wait 6 seconds for the 5-second cache TTL to expire. + time.Sleep(6 * time.Second) + + // Send a request after TTL expiration: must be a cache miss that re-populates the cache. + resp, err := router.Get(ctx, actorRef, "/readyz") + if err != nil { + t.Fatalf("GET after TTL: %v", err) + } + _ = resp.Body.Close() + if resp.StatusCode != http.StatusOK { + t.Fatalf("GET after TTL returned status %d, want 200", resp.StatusCode) + } + + scrape3, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics after TTL: %v", err) + } + missAfter := e2e.RouterCacheCounterValue(scrape3, "ate_ingress_cache_miss") + if missAfter <= missBefore { + t.Fatalf("expected cache miss count to increase after TTL, before=%.0f, after=%.0f", missBefore, missAfter) + } +} + +// TestIngressCache_StaleHitReplaysAfterSuspend verifies that a bodiless request +// that hits a stale entry after its actor was suspended while idle is replayed +// through ext_proc, which resumes the actor, so the client gets a 200. On the +// default CONNECT path, atunnel refuses the tunnel and the router reports a +// 503 UC; the tunnel_watcher network filter marks the entry stale, and +// it isn't spoiled because no request was cut off mid-flight. +func TestIngressCache_StaleHitReplaysAfterSuspend(t *testing.T) { + e2e.RequireIngressCache(t) + ctx := context.Background() + clients := e2e.GetClients() + _, actorName, _ := createAndResumeSubstrateActor(t, ctx, "cache-stale", e2e.SubstrateCounterFixture()) + router := mustRouterClient(t, ctx) + defer router.Close() + + actorRef := resources.ActorRef{Atespace: networkingAtespace, Name: actorName} + + // 1. Warm route and cache. + waitForRouteReady(t, "Warm up actor route", func() (*http.Response, error) { + return router.Get(ctx, actorRef, "/readyz") + }) + + scrapeBefore, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics before suspend: %v", err) + } + replayBefore := e2e.RouterCacheCounterValue(scrapeBefore, "ate_ingress_cache_replay") + staleBefore := e2e.RouterCacheCounterValue(scrapeBefore, "ate_ingress_cache_marked_stale") + spoiledBefore := e2e.RouterCacheCounterValue(scrapeBefore, "ate_ingress_cache_marked_spoiled") + + // 2. Suspend the actor while it is idle. The cache entry still points at its old worker. + if _, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: networkingAtespace, Name: actorName}, + }); err != nil { + t.Fatalf("SuspendActor: %v", err) + } + waitForActorState(t, ctx, clients, networkingAtespace, actorName, ateapi.ActorState_ACTOR_STATE_SUSPENDED) + + // 3. The stale hit is refused before reaching the actor and replayed through ext_proc. + resp, err := router.Get(ctx, actorRef, "/readyz") + if err != nil { + t.Fatalf("GET on stale entry failed: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET on stale entry returned status %d, want 200 after replay; body: %s", resp.StatusCode, body) + } + + // 4. The request was replayed, its entry marked stale, and nothing marked spoiled. + scrapeAfter, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics after GET: %v", err) + } + if replayAfter := e2e.RouterCacheCounterValue(scrapeAfter, "ate_ingress_cache_replay"); replayAfter <= replayBefore { + t.Fatalf("expected ate_ingress_cache_replay to increment, before=%.0f, after=%.0f", replayBefore, replayAfter) + } + if staleAfter := e2e.RouterCacheCounterValue(scrapeAfter, "ate_ingress_cache_marked_stale"); staleAfter <= staleBefore { + t.Fatalf("expected ate_ingress_cache_marked_stale to increment, before=%.0f, after=%.0f", staleBefore, staleAfter) + } + if spoiledAfter := e2e.RouterCacheCounterValue(scrapeAfter, "ate_ingress_cache_marked_spoiled"); spoiledAfter != spoiledBefore { + t.Fatalf("expected ate_ingress_cache_marked_spoiled unchanged for an idle suspend, before=%.0f, after=%.0f", spoiledBefore, spoiledAfter) + } +} + +// TestIngressCache_SuspendMidRequestIsNotReplayed verifies that a cache hit cut +// off by a suspend after it reached the actor gets a 503 without a replay, and +// that the tunnel_watcher network filter marks its entry spoiled. No refusal +// marks the entry stale here, so the 503 doesn't depend on the spoiled mark: the +// counter checks the mark itself. +func TestIngressCache_SuspendMidRequestIsNotReplayed(t *testing.T) { + e2e.RequireIngressCache(t) + ctx := context.Background() + clients := e2e.GetClients() + fixture := deployWebsocketFixture(t, ctx) + _, actorName, _ := createAndResumeSubstrateActor(t, ctx, "cache-spoil", fixture) + router := mustRouterClient(t, ctx) + defer router.Close() + + actorRef := resources.ActorRef{Atespace: networkingAtespace, Name: actorName} + + // 1. Warm the cache. The router client reuses this connection for the next + // request, so it lands on the same Envoy worker thread and hits the entry. + waitForRouteReady(t, "Warm up actor route", func() (*http.Response, error) { + return router.Get(ctx, actorRef, "/readyz") + }) + + scrapeBefore, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics before request: %v", err) + } + spoiledBefore := e2e.RouterCacheCounterValue(scrapeBefore, "ate_ingress_cache_marked_spoiled") + + // 2. Send a request the actor never answers. + type result struct { + status int + err error + } + done := make(chan result, 1) + go func() { + resp, err := router.Get(ctx, actorRef, "/hang") + if err != nil { + done <- result{err: err} + return + } + resp.Body.Close() + done <- result{status: resp.StatusCode} + }() + + // 3. Wait until it reached the actor, asking on another connection. + err = wait.PollUntilContextTimeout(ctx, 200*time.Millisecond, 30*time.Second, true, func(ctx context.Context) (bool, error) { + resp, err := router.Get(ctx, actorRef, "/hanging") + if err != nil { + return false, err + } + defer resp.Body.Close() + body, err := io.ReadAll(resp.Body) + if err != nil { + return false, err + } + return resp.StatusCode == http.StatusOK && strings.TrimSpace(string(body)) != "0", nil + }) + if err != nil { + t.Fatalf("waiting for /hang to reach the actor: %v", err) + } + + // 4. Suspend the actor with the request in flight. + if _, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: networkingAtespace, Name: actorName}, + }); err != nil { + t.Fatalf("SuspendActor: %v", err) + } + + // 5. A replay would resume the actor and hang again, so a 503 means no replay. + // Don't check the replay counter: other tests running in parallel can replay. + res := <-done + if res.err != nil { + t.Fatalf("GET /hang failed: %v", res.err) + } + if res.status != http.StatusServiceUnavailable { + t.Fatalf("GET /hang returned status %d, want 503 without a replay", res.status) + } + + scrapeAfter, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics after request: %v", err) + } + if spoiledAfter := e2e.RouterCacheCounterValue(scrapeAfter, "ate_ingress_cache_marked_spoiled"); spoiledAfter <= spoiledBefore { + t.Fatalf("expected ate_ingress_cache_marked_spoiled to increment, before=%.0f, after=%.0f", spoiledBefore, spoiledAfter) + } +} + +// TestIngressCache_BodyBypassesCache verifies that a request with a body is +// never served from the cache: even with a stale entry for a suspended actor, it +// goes through ext_proc, which resumes the actor, and counts as a bypass. +func TestIngressCache_BodyBypassesCache(t *testing.T) { + e2e.RequireIngressCache(t) + ctx := context.Background() + clients := e2e.GetClients() + _, actorName, _ := createAndResumeSubstrateActor(t, ctx, "cache-body", e2e.SubstrateCounterFixture()) + router := mustRouterClient(t, ctx) + defer router.Close() + + actorRef := resources.ActorRef{Atespace: networkingAtespace, Name: actorName} + + // 1. Warm route and cache with a bodiless request. + waitForRouteReady(t, "Warm up actor route", func() (*http.Response, error) { + return router.Get(ctx, actorRef, "/readyz") + }) + + // 2. Suspend the actor. The cache entry still points at its old worker. + if _, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: networkingAtespace, Name: actorName}, + }); err != nil { + t.Fatalf("SuspendActor: %v", err) + } + waitForActorState(t, ctx, clients, networkingAtespace, actorName, ateapi.ActorState_ACTOR_STATE_SUSPENDED) + + scrapeBefore, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics before POST: %v", err) + } + bypassBefore := e2e.RouterCacheCounterValue(scrapeBefore, "ate_ingress_cache_bypass") + + // 3. A POST with a body skips the stale entry and succeeds through ext_proc. + resp, err := router.PostJSON(ctx, actorRef, "/count", []byte(`{"count": 1}`)) + if err != nil { + t.Fatalf("POST with body failed: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("POST with body returned status %d, want 200; body: %s", resp.StatusCode, body) + } + + // 4. It counted as a bypass. Don't check the hit counter: other tests + // running in parallel can hit the cache. + scrapeAfter, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics after POST: %v", err) + } + if bypassAfter := e2e.RouterCacheCounterValue(scrapeAfter, "ate_ingress_cache_bypass"); bypassAfter <= bypassBefore { + t.Fatalf("expected ate_ingress_cache_bypass to increment, before=%.0f, after=%.0f", bypassBefore, bypassAfter) + } +} + +// TestIngressCache_DisabledByDefault verifies that without the IngressCache +// preview gate the ingress-cache filter never sees a request: it's served +// through ext_proc and no cache counter moves. +func TestIngressCache_DisabledByDefault(t *testing.T) { + if e2e.PreviewEnabled(preview.GateIngressCache) { + t.Skipf("preview gate %q is enabled; this test covers the default install", preview.GateIngressCache) + } + ctx := context.Background() + _, actorName, _ := createAndResumeSubstrateActor(t, ctx, "cache-off", e2e.SubstrateCounterFixture()) + router := mustRouterClient(t, ctx) + defer router.Close() + + actorRef := resources.ActorRef{Atespace: networkingAtespace, Name: actorName} + waitForRouteReady(t, "Warm up actor route", func() (*http.Response, error) { + return router.Get(ctx, actorRef, "/readyz") + }) + + countCacheMetrics := e2e.CurrentAtenetDataplane().SupportsIngressCache() + var lookupsBefore float64 + if countCacheMetrics { + scrape, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics before request: %v", err) + } + lookupsBefore = e2e.RouterCacheCounterValue(scrape, "ate_ingress_cache_hit") + + e2e.RouterCacheCounterValue(scrape, "ate_ingress_cache_miss") + + e2e.RouterCacheCounterValue(scrape, "ate_ingress_cache_bypass") + } + + resp, err := router.Get(ctx, actorRef, "/readyz") + if err != nil { + t.Fatalf("GET /readyz failed: %v", err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET /readyz returned status %d, want 200; body: %s", resp.StatusCode, body) + } + + if countCacheMetrics { + scrape, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics after request: %v", err) + } + lookupsAfter := e2e.RouterCacheCounterValue(scrape, "ate_ingress_cache_hit") + + e2e.RouterCacheCounterValue(scrape, "ate_ingress_cache_miss") + + e2e.RouterCacheCounterValue(scrape, "ate_ingress_cache_bypass") + if lookupsAfter != lookupsBefore { + t.Fatalf("ingress cache lookups changed with the gate off, before=%.0f, after=%.0f", lookupsBefore, lookupsAfter) + } + } +} + +// TestIngressCache_GRPCBypassesCache verifies that gRPC calls, which always +// carry a body, never use the cache: after the actor is suspended, the next call +// goes through ext_proc, which resumes the actor, instead of hitting the stale +// entry. +func TestIngressCache_GRPCBypassesCache(t *testing.T) { + e2e.RequireIngressCache(t) + if _, err := e2e.CheckEnv("KO_DOCKER_REPO"); err != nil { + t.Fatalf("CheckEnv failed: %v", err) + } + ctx := context.Background() + clients := e2e.GetClients() + + fixture := deployGRPCEchoTemplate(t, ctx) + _, actorName, _ := createAndResumeSubstrateActor(t, ctx, "cache-grpc", fixture) + actorRef := resources.ActorRef{Atespace: networkingAtespace, Name: actorName} + ctx = metadata.AppendToOutgoingContext(ctx, + atenet.TargetActorHeader, actorRef.String(), + ) + + rc := mustRouterClient(t, ctx) + t.Cleanup(rc.Close) + conn, err := grpc.NewClient(rc.Address(), grpc.WithTransportCredentials(credentials.NewTLS(rc.TLSConfig()))) + if err != nil { + t.Fatalf("creating gRPC client: %v", err) + } + defer conn.Close() + client := grpcechopb.NewEchoClient(conn) + + // 1. A successful call resolves the route; its response is learned into the cache. + const message = "grpc bypasses the cache" + waitForGRPCRouteReady(t, ctx, client, message) + + // 2. Suspend the actor. The cache entry still points at its old worker. + if _, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: networkingAtespace, Name: actorName}, + }); err != nil { + t.Fatalf("SuspendActor: %v", err) + } + waitForActorState(t, ctx, clients, networkingAtespace, actorName, ateapi.ActorState_ACTOR_STATE_SUSPENDED) + + scrapeBefore, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics before call: %v", err) + } + bypassBefore := e2e.RouterCacheCounterValue(scrapeBefore, "ate_ingress_cache_bypass") + + // 3. The next call skips the stale entry and succeeds through ext_proc. + callCtx, cancel := context.WithTimeout(ctx, 30*time.Second) + defer cancel() + resp, err := client.Echo(callCtx, &grpcechopb.EchoRequest{Message: message}) + if err != nil { + t.Fatalf("Echo after suspend failed: %v", err) + } + if resp.GetMessage() != message { + t.Fatalf("Echo after suspend got %q, want %q", resp.GetMessage(), message) + } + + // 4. It counted as a bypass. Don't check the hit counter: other tests + // running in parallel can hit the cache. + scrapeAfter, err := e2e.ScrapeRouterEnvoyMetrics(ctx) + if err != nil { + t.Fatalf("ScrapeRouterEnvoyMetrics after call: %v", err) + } + if bypassAfter := e2e.RouterCacheCounterValue(scrapeAfter, "ate_ingress_cache_bypass"); bypassAfter <= bypassBefore { + t.Fatalf("expected ate_ingress_cache_bypass to increment, before=%.0f, after=%.0f", bypassBefore, bypassAfter) + } +} + +func waitForActorState(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string, want ateapi.ActorState) { + t.Helper() + deadline := time.Now().Add(15 * time.Second) + for time.Now().Before(deadline) { + resp, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: atespace, Name: name}, + }) + if err == nil && resp.GetStatus().GetState() == want { + return + } + time.Sleep(100 * time.Millisecond) + } + t.Fatalf("timed out waiting for actor %s/%s to reach %v", atespace, name, want) +} diff --git a/internal/e2e/suites/networking/websocketegress_test.go b/internal/e2e/suites/networking/websocketegress_test.go index baad55c509..a8fb2b28ce 100644 --- a/internal/e2e/suites/networking/websocketegress_test.go +++ b/internal/e2e/suites/networking/websocketegress_test.go @@ -15,11 +15,18 @@ package networking import ( + "context" "encoding/json" + "net" "net/http" + "slices" "testing" + "time" + "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/internal/e2e" + "go.ate.dev/substrate/internal/resources" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) // egressWebSocketResponse mirrors observations returned by the actor. The @@ -38,58 +45,114 @@ type egressWebSocketMessage struct { Message string `json:"message"` } +// websocketTextMessage is the RFC 6455 text frame opcode the actor reports. +const websocketTextMessage = 1 + +// An http rule naming the origin allows ws:// to it. The same server is +// refused by its address, which the rule does not name. func TestActorEgressWebSocket(t *testing.T) { ctx := t.Context() - _, address, _ := prepareProtocolOrigin(t, ctx, e2e.ServerPod{ + target, address, _ := prepareProtocolOrigin(t, ctx, e2e.ServerPod{ Name: "ws-origin", ImportPath: "go.ate.dev/substrate/internal/e2e/fixtures/testserver", Args: []string{"websocket", "--echo"}, Port: 80, TargetPort: 8080, HealthPath: "/readyz", }, false) - _, router, actorRef := prepareProtocolActor(t, ctx, "ws") - raw := postEgressWithStatus(t, ctx, router, actorRef, "/websocket", map[string]any{ - "url": "ws://" + address + "/ws", "messages": []string{"ws-message"}, - }, http.StatusBadGateway) - var got egressWebSocketResponse - if err := json.Unmarshal(raw, &got); err != nil { - t.Fatalf("decoding WebSocket observation: %v", err) - } - if got.StatusCode != http.StatusForbidden { - t.Errorf("WebSocket handshake status = %d, want %d", got.StatusCode, http.StatusForbidden) + host, _, err := net.SplitHostPort(address) + if err != nil { + t.Fatalf("splitting origin address %q: %v", address, err) } - if got.HandshakeBody != "WebSocket egress is not supported" { - t.Errorf("WebSocket handshake body = %q, want %q", got.HandshakeBody, "WebSocket egress is not supported") + actorName, router, actorRef := prepareEgressWebSocketActor(t, ctx, "ws", e2e.EgressAllowHTTP(host)) + if e2e.IsAgentGateway() { + assertEgressWebSocketRefused(t, ctx, router, actorRef, "ws://"+address+"/ws") + return } - if got.Error == "" { - t.Error("WebSocket handshake error is empty") - } - if len(got.Messages) != 0 { - t.Errorf("WebSocket messages = %+v, want no echoes", got.Messages) + since := metav1.NewTime(time.Now().Add(-time.Minute)) + assertEgressWebSocket(t, ctx, router, actorRef, "ws://"+address+"/ws", false) + assertProtocolGateway(t, ctx, since, actorName, target.Address()) + + byAddress := "ws://" + target.Address() + "/ws" + got := openEgressWebSocket(t, ctx, router, actorRef, byAddress, http.StatusBadGateway) + if !e2e.CurrentAtenetDataplane().IsEgressPolicyDenied(got.StatusCode, got.HandshakeBody) || len(got.Messages) != 0 { + t.Errorf("WebSocket to %s = %+v; want an egress-policy denial and no echoes", byAddress, got) } } +// An https rule naming the origin allows wss:// to it. The origin prefers +// HTTP/2, so the handshake succeeds only if the gateway sends it upstream over +// HTTP/1.1. func TestActorEgressSecureWebSocket(t *testing.T) { ctx := t.Context() - _, address, _ := prepareProtocolOrigin(t, ctx, e2e.ServerPod{ + target, address, _ := prepareProtocolOrigin(t, ctx, e2e.ServerPod{ Name: "wss-origin", ImportPath: "go.ate.dev/substrate/internal/e2e/fixtures/testserver", Args: []string{"websocket", "--echo"}, Port: 80, TargetPort: 8080, TLSPort: 443, HealthPath: "/readyz", }, true) - _, router, actorRef := prepareProtocolActor(t, ctx, "wss") - raw := postEgressWithStatus(t, ctx, router, actorRef, "/websocket", map[string]any{ - "url": "wss://" + address + "/ws", "messages": []string{"wss-message"}, - }, http.StatusBadGateway) + host, _, err := net.SplitHostPort(address) + if err != nil { + t.Fatalf("splitting origin address %q: %v", address, err) + } + actorName, router, actorRef := prepareEgressWebSocketActor(t, ctx, "wss", e2e.EgressAllowHTTPS(host)) + if e2e.IsAgentGateway() { + assertEgressWebSocketRefused(t, ctx, router, actorRef, "wss://"+address+"/ws") + return + } + since := metav1.NewTime(time.Now().Add(-time.Minute)) + assertEgressWebSocket(t, ctx, router, actorRef, "wss://"+address+"/ws", true) + assertProtocolGateway(t, ctx, since, actorName, target.TLSAddress()) +} + +// prepareEgressWebSocketActor resumes an egress actor whose policy is rule +// alone, and waits until the router reaches it. +func prepareEgressWebSocketActor(t *testing.T, ctx context.Context, prefix string, rule *ateapi.EgressRule) (string, *e2e.RouterClient, resources.ActorRef) { + t.Helper() + _, actorName, _ := createAndResumeActorWithEgress(t, ctx, prefix, egressFixture(), rule) + router := mustRouterClient(t, ctx) + t.Cleanup(func() { router.Close() }) + actorRef := resources.ActorRef{Atespace: networkingAtespace, Name: actorName} + waitForRouteReady(t, "egress actor ingress readiness", func() (*http.Response, error) { return router.Get(ctx, actorRef, "/readyz") }) + return actorName, router, actorRef +} + +// egressWebSocketMessages are what the actor sends on each WebSocket it opens. +var egressWebSocketMessages = []string{"first", "second", "third", "fourth", "fifth"} + +// openEgressWebSocket has the actor open a WebSocket to url and send +// egressWebSocketMessages, and returns what the actor observed. wantStatus is +// the status of the actor's own answer: 200 when every message was echoed, +// 502 otherwise. +func openEgressWebSocket(t *testing.T, ctx context.Context, router *e2e.RouterClient, actorRef resources.ActorRef, url string, wantStatus int) egressWebSocketResponse { + t.Helper() + raw := postEgressWithStatus(t, ctx, router, actorRef, "/websocket", map[string]any{"url": url, "messages": egressWebSocketMessages}, wantStatus) var got egressWebSocketResponse if err := json.Unmarshal(raw, &got); err != nil { - t.Fatalf("decoding secure WebSocket observation: %v", err) + t.Fatalf("decoding WebSocket observation: %v", err) } - if got.StatusCode != http.StatusForbidden { - t.Errorf("secure WebSocket handshake status = %d, want %d", got.StatusCode, http.StatusForbidden) + return got +} + +// assertEgressWebSocket opens a WebSocket from the actor to url, which the +// actor's policy allows, and checks the echoes. +func assertEgressWebSocket(t *testing.T, ctx context.Context, router *e2e.RouterClient, actorRef resources.ActorRef, url string, wantTLS bool) { + t.Helper() + got := openEgressWebSocket(t, ctx, router, actorRef, url, http.StatusOK) + if got.Error != "" || got.StatusCode != http.StatusSwitchingProtocols || got.TLS != wantTLS { + t.Errorf("WebSocket to %s = %+v; want a 101 handshake with verified TLS = %v", url, got, wantTLS) } - if got.HandshakeBody != "WebSocket egress is not supported" { - t.Errorf("secure WebSocket handshake body = %q, want %q", got.HandshakeBody, "WebSocket egress is not supported") + want := make([]egressWebSocketMessage, len(egressWebSocketMessages)) + for i, message := range egressWebSocketMessages { + want[i] = egressWebSocketMessage{Type: websocketTextMessage, Message: message} } - if got.Error == "" { - t.Error("secure WebSocket handshake error is empty") + if !slices.Equal(got.Messages, want) { + t.Errorf("WebSocket echoes from %s = %+v, want %+v", url, got.Messages, want) } - if len(got.Messages) != 0 { - t.Errorf("secure WebSocket messages = %+v, want no echoes", got.Messages) +} + +// assertEgressWebSocketRefused opens a WebSocket from the actor to url on +// agentgateway, which does not carry WebSocket: the handshake must get 403 +// before the origin sees a message. +// TODO: Run the rest of each test on agentgateway once it carries WebSocket. +func assertEgressWebSocketRefused(t *testing.T, ctx context.Context, router *e2e.RouterClient, actorRef resources.ActorRef, url string) { + t.Helper() + got := openEgressWebSocket(t, ctx, router, actorRef, url, http.StatusBadGateway) + if got.StatusCode != http.StatusForbidden || got.HandshakeBody != "WebSocket egress is not supported" || got.Error == "" || len(got.Messages) != 0 { + t.Errorf("WebSocket to %s = %+v; want a handshake refused with 403 and no echoes", url, got) } } diff --git a/internal/e2e/suites/security/README.md b/internal/e2e/suites/security/README.md index d92fa3b7f0..0f5e11582c 100644 --- a/internal/e2e/suites/security/README.md +++ b/internal/e2e/suites/security/README.md @@ -1,50 +1,164 @@ -# Security e2e suite +# Running the security e2e suite by hand -End-to-end tests for Substrate's isolation boundaries. This is the runbook -for running them on a local kind cluster and for watching what they do while -they run. +This is the manual runbook for the security isolation tests: how to run them +on a local kind cluster, how to run a subset, and what to watch while they +run. CI runs them with every other e2e suite; nothing here is needed for that. -Prereqs: Go, kubectl, a running Docker. kind is auto-managed. +Prereqs: Go, kubectl, a running Docker. kind is created for you. -## Steps to run the security tests +## Run the tests -1. Create the cluster (in the repo root): +1. Create the cluster, from the repo root: -``` -hack/create-kind-cluster.sh -``` + ``` + hack/create-kind-cluster.sh + ``` -2. Install the control plane (slow step — pulls ~570 MB): +2. Install the control plane. This is the slow step; it pulls about 570 MB: -``` -go run ./cmd/ate-setup --kind deploy ate-system --credential-provider='{"name":"k8s.io"}' -``` + ``` + go run ./cmd/ate-setup --kind deploy ate-system --credential-provider='{"name":"k8s.io"}' \ + --ingress-allowed-spiffe-ids=spiffe://cluster.local/ns/ate-e2e-router-client/sa/router-client + ``` + + Stop there. The NFS/CSI and demo steps CI runs are for other suites. + +3. Run one of the three top-level tests. They are split by the boundary under + test: between two actors in one atespace, between two atespaces, or across + two worker pods running concurrently in space. + + **`TestActorIsolation`** ([actor_isolation_test.go](actor_isolation_test.go)), + one atespace, fixtures `actor-isolation.yaml.tmpl` and + `actor-isolation-template.yaml.tmpl`: + + ``` + hack/run-e2e-kind.sh ./internal/e2e/suites/security -v -run TestActorIsolation + ``` + + - `VictimDurableMarkerNotVisibleThroughAttackerMount` — **ST-1 [time]** (durable-dir volume mount isolation across worker reuse) + - `VictimHostStateNotReachableFromAttackerSandbox` — **EX-4 [time]** (per-actor host state and worker-pod credential isolation: T-18, T-19, T-22) + - `VictimEphemeralStateNotPresentInAttackerSandbox` — **EX-5 [time]** (no residual `/tmp`, writable rootfs layer, `/dev` tmpfs, or open fd state across worker reuse: T-27) + - `ActorNetworkIsolatedToPrivateVeth` — **NW-1** (actor network namespace isolated from worker pod CNI network, connected only via private veth) + - `MintedActorCertificateBoundToAssignedActor` — **CP-2a** (worker's minted actor certificate bound to currently assigned actor and resistant to actor-side spoofing: T-28) + - `OnlyRouterCanOpenWorkerTunnel` — **NW-3** (only `atenet-router` pod identity may open an ingress tunnel to a worker's `atunnel`) + - `WorkerTunnelForwardsOnlyToAssignedActor` — **NW-4 [time]** (reused worker's `atunnel` forwards only to its currently assigned actor and rejects the previous actor with `421 Misdirected Request`) + - `ProjectedIdentityNotCapturedInSnapshot` — **ST-3 [time]** (projected `/run/ate` `system-info` identity excluded from snapshots: T-23) + - `DeletedActorSnapshotsRemoved` — **ST-5 [time]** (actor deletion removes external snapshots from object storage and prevents recovery) + + **`TestCrossAtespaceIsolation`** ([crossatespace_test.go](crossatespace_test.go)), + two atespaces, fixtures `atespace-a-pool.yaml.tmpl`, + `atespace-b-namespace.yaml.tmpl` and `atespace-template.yaml.tmpl`: + + ``` + hack/run-e2e-kind.sh ./internal/e2e/suites/security -v -run TestCrossAtespaceIsolation + ``` + + - `TagScopedToAtespaceCannotSeedAnotherAtespace` — **ST-4 [space]** (unpublished `ATESPACE`-scoped snapshot tag isolation across atespaces) + + **`TestConcurrentActorIsolation`** ([concurrent_isolation_test.go](concurrent_isolation_test.go)), + two replicas, fixtures `concurrent-a-pool.yaml.tmpl`, + `concurrent-b-namespace.yaml.tmpl` and `concurrent-template.yaml.tmpl`: + + ``` + hack/run-e2e-kind.sh ./internal/e2e/suites/security -v -run TestConcurrentActorIsolation + ``` + + - `RouterDeliversOnlyToNamedActorInSpace` — **NW-6 [space]** (ingress router atespace/actor isolation with concurrent actors on distinct workers: T-14) + - `DirectActorToActorTrafficBlocked` — **NW-2 [space]** (no direct actor-to-actor traffic across the pod network; blocked by NetworkPolicy: T-17) + - `ConcurrentDurableMountIsolation` — **ST-1 [space]** (durable-dir volume mount isolation across concurrent actors: T-18, T-27) + + To run a subset of subtests: + + ``` + hack/run-e2e-kind.sh ./internal/e2e/suites/security -v \ + -run 'TestActorIsolation/(VictimDurableMarkerNotVisibleThroughAttackerMount|VictimHostStateNotReachableFromAttackerSandbox)' + ``` + + The setup still runs in full (victim runs, writes, suspends; attacker takes + the worker). The filter only picks which assertions execute. + +4. The fixture namespaces do not outlive the test, even a failed one: + `e2e.DeploySubstrateFixture` deletes them in `t.Cleanup`. To read the + worker logs of a failing run, follow them while the test runs (see + [Watch a run](#watch-a-run)): + + ``` + kubectl get ns | grep ate-e2e + kubectl -n logs -l ate.dev/worker-pool -c worker -f + ``` + + Only an interrupted run (Ctrl-C, a killed process) leaves namespaces + behind. Reclaim them with: + + ``` + KIND_CLUSTER_NAME=kind hack/cleanup-e2e.sh + ``` + + `cleanup-e2e.sh` removes namespaces labeled `ate.dev/e2e`. Of this suite's + fixtures `actor-isolation.yaml.tmpl`, `concurrent-a-pool.yaml.tmpl` and + `concurrent-b-namespace.yaml.tmpl` carry that label. The cross-atespace + fixtures do not, so delete `ate-e2e-sec-a` and `ate-e2e-sec-b` by hand if + an interrupted cross-atespace test left them behind. -Stop here — the NFS/CSI and demo steps CI runs are for other suites; this suite needs none of them. +## Watch a run -3. Run the cross-atespace isolation test: +Namespaces are `ate-e2e-sec-actor` for `TestActorIsolation`, +`ate-e2e-sec-a` plus `ate-e2e-sec-b` for `TestCrossAtespaceIsolation`, and +`ate-e2e-sec-conc-a` plus `ate-e2e-sec-conc-b` for +`TestConcurrentActorIsolation`. The micro-VM lane inserts `-microvm` after +`ate-e2e`. Worker pods are labeled `ate.dev/worker-pool=`; the pools +are `actor`, `shared` and `concurrent`. The `concurrent` pool runs both of +its worker pods in `ate-e2e-sec-conc-a`. + +Start these before launching the test. + +Lifecycle: ``` -hack/run-e2e-kind.sh ./internal/e2e/suites/security -v -run TestCrossAtespaceIsolation +# Fixture namespaces appear and vanish; this is the run's heartbeat. +kubectl get ns -w | grep ate-e2e + +# The single worker pod. It should be reused, never replaced. +kubectl get pods -n ate-e2e-sec-actor -w ``` -The wrapper sets KO_DOCKER_REPO, BUCKET_NAME, the kube context, and builds the probe image via ko. To run only the durable-mount and host-state subtests and skip the tag-scope one: +The reuse, which is the point of `TestActorIsolation`. Actors are not +Kubernetes objects, so use the plugin: ``` -hack/run-e2e-kind.sh ./internal/e2e/suites/security -v \ - -run 'TestCrossAtespaceIsolation/(VictimDurableMarkerNotVisibleThroughAttackerMount|VictimHostStateNotReachableFromAttackerSandbox)' -``` +# Actor state and worker assignment: victim runs, suspends, attacker binds +# to the same worker, then the clone, then the recreated victim. +watch -n1 'kubectl ate get actors -a ate-e2e-sec-actor' -Note the setup (victim run/write/suspend, attacker reuse) runs regardless — the subtest filter only selects which assertions execute. +kubectl ate get workers +kubectl ate top workers # Actors used/total goes 1/1, 0/1, 1/1, ... +``` -4. On failure, a failed suite keeps its namespaces so you can read the worker logs: +The worker name every actor shows is the string `requireReusedWorker` +asserts on. +The worker host: -kubectl get ns -l ate.dev/e2e -kubectl -n logs -c ateworker -KIND_CLUSTER_NAME=kind hack/cleanup-e2e.sh # reclaim when done +``` +# Sandbox lifecycle, checkpoints and restores. +kubectl logs -n ate-e2e-sec-actor -l ate.dev/worker-pool=actor -c worker -f + +# The per-actor layout under /var/lib/ate/actors that the +# host-state probes target. Only the running actor has durable-dir and +# system-info; atelet removes both at suspend, and a suspended actor's UID +# directory keeps just sandbox-assets.json. +POD=$(kubectl get pods -n ate-e2e-sec-actor -l ate.dev/worker-pool=actor -o name | head -1) +kubectl exec -n ate-e2e-sec-actor "$POD" -c worker -- ls -la /var/lib/ate/actors +``` +Control plane and snapshots: +``` +kubectl ate get tags -a ate-e2e-sec-actor # actor-snapshot-tag, during ProjectedIdentityNotCapturedInSnapshot +kubectl ate get tags -a ate-e2e-sec-a # atespace-a-tag, during the cross-atespace test +kubectl ate get atespaces +kubectl logs -n ate-system -l app=ateapi -f +``` ## Run the GitHub checks locally @@ -53,7 +167,7 @@ The PR workflow (`.github/workflows/pr-workflow.yaml`) runs three checks: E2E matrix. Every one of them compiles this suite, so a build error here fails all three. -Fast, no cluster needed. This is what CI's `run-tests` job does, minus the +Fast, no cluster needed. This is what CI's `run-tests` and `verify` jobs do, minus the JUnit wrapping, and it also type-checks every E2E suite: ``` @@ -61,17 +175,17 @@ go vet ./... && go test -race ./... && hack/verify-all.sh && (cd tools/apitool & ``` `hack/verify-all.sh` runs gofmt, boilerplate, licenses, go.mod, metrics -registry, and generated-code checks. -Commit or stash first: the generated-code check refuses a dirty tree. The -metrics check needs Docker or a local `weaver` at the version pinned in -`hack/verify/metrics.sh`. The root-gated tests CI runs under sudo need Linux: +registry, and generated-code checks. Commit or stash first: the +generated-code check refuses a dirty tree. The metrics check needs Docker or +a local `weaver` at the version pinned in `hack/verify/metrics.sh`. The +root-gated tests CI runs under sudo need Linux: ``` hack/run-root-tests.sh -race -v ``` -Full E2E, same as CI's gVisor lane. Do steps 1 and 2 above, then run every -suite with CI's flags instead of the `-run` filter from step 3: +Full e2e, same as CI's gVisor lane. Do steps 1 and 2 above, then run every +suite with CI's flags: ``` hack/run-e2e-kind.sh -v -args --no-color @@ -79,41 +193,3 @@ hack/run-e2e-kind.sh -v -args --no-color CI also deploys the NFS CSI driver and the demos before this, and repeats the run with `E2E_SANDBOX_CLASS=microvm`. Neither matters for this suite. - -## Commands to run while the test is running to observe -Watch the lifecycle (start these first, before/at test launch) - -# The two atespace namespaces appear and vanish — this is the run's heartbeat -kubectl get ns -l ate.dev/e2e -w - -# The one shared worker pod: watch the victim's pod get reused, not replaced -kubectl get pods -n ate-e2e-sec-a -w -The reuse itself (the point of the test) -Actors aren't in k8s, so use the plugin. This is where you see victim B run, suspend, then attacker A bind to the same worker: - - -# Actor state + worker assignment, atespace B (victim) then A (attacker) -watch -n1 'kubectl ate get actors -a ate-e2e-sec-b; echo ---; kubectl ate get actors -a ate-e2e-sec-a' - -# Which worker each actor is on — the name should match across the two atespaces -kubectl ate get workers -kubectl ate top workers # capacity: Actors used/total (you'll see 1/1 then 0/1 then 1/1) -The worker name that B's victim shows, then A's attacker shows after the suspend, is the same string requireReusedWorker asserts on. Seeing them match live is the manual version of that check. - -The shared worker pod on the host - -# The pod hosting both actors in turn -kubectl get pods -n ate-e2e-sec-a -o wide - -# worker logs — the sandbox lifecycle, checkpoints, resumes -kubectl logs -n ate-e2e-sec-a -l app=ateworker -c ateworker -f - -# The on-host per-actor layout the host-state probes assert against. -# Two UID-keyed durable dirs (victim's + attacker's) live side by side here: -POD=$(kubectl get pods -n ate-e2e-sec-a -l app=ateworker -o name | head -1) -kubectl exec -n ate-e2e-sec-a "$POD" -c ateworker -- ls -la /var/lib/ateworker-gvisor/actors -Control plane / snapshots (for the tag-scope subtest) - -kubectl ate get tags -a ate-e2e-sec-a # atespace-a-tag appears during the last subtest -kubectl ate get atespaces # ate-e2e-sec-a / -b listed while live -kubectl logs -n ate-system -l app=ateapi -f # Create \ No newline at end of file diff --git a/internal/e2e/suites/security/actor_isolation_test.go b/internal/e2e/suites/security/actor_isolation_test.go new file mode 100644 index 0000000000..2f3e7e4e20 --- /dev/null +++ b/internal/e2e/suites/security/actor_isolation_test.go @@ -0,0 +1,1523 @@ +// Copyright 2026 The Agent Substrate 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. + +// This file covers the actor-level isolation boundary within a single +// atespace. Both the victim and attacker actors are created from the same +// ActorTemplate in the same atespace and take turns on a single-worker pool +// (fixtures/security/actor-isolation.yaml.tmpl) +package security + +import ( + "context" + "crypto/ecdsa" + "crypto/elliptic" + "crypto/rand" + "crypto/tls" + "crypto/x509" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "net" + "net/http" + "net/url" + "os" + "path/filepath" + "slices" + "strings" + "testing" + "time" + + "cloud.google.com/go/storage" + "github.com/aws/aws-sdk-go-v2/aws" + "github.com/aws/aws-sdk-go-v2/credentials" + "github.com/aws/aws-sdk-go-v2/service/s3" + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/actoridjwt" + "go.ate.dev/substrate/internal/ateclient" + "go.ate.dev/substrate/internal/atenet" + "go.ate.dev/substrate/internal/e2e" + "go.ate.dev/substrate/internal/installdefaults" + "go.ate.dev/substrate/internal/localca" + "go.ate.dev/substrate/internal/nodepath" + "go.ate.dev/substrate/internal/objectstore" + "go.ate.dev/substrate/internal/portforward" + "go.ate.dev/substrate/internal/resources" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" + corev1 "k8s.io/api/core/v1" + apierrors "k8s.io/apimachinery/pkg/api/errors" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +// echoServer is the plain-HTTP origin the egress identity checks fetch from. +// Its /echoheaders returns the request headers the gateway delivered, +// including the injected actor JWT. +var echoServer = e2e.ServerPod{ + Name: "echo", + ImportPath: "go.ate.dev/substrate/internal/e2e/fixtures/testserver", + Args: []string{"http"}, + Port: 80, + TargetPort: 8080, +} + +const ( + // templateName is the ActorTemplate name deployed by the security fixtures. + templateName = "probe" + + // Actor names used by TestActorIsolation. + victim = "victim" + attacker = "attacker" + cloneName = "cloned-actor" + + // dataMount is where the security template mounts the durable-dir volume, + // and durableVolume is that volume's name. Keep both in sync with the manifest. + dataMount = "/data" + durableVolume = "data" + + neverWritten = dataMount + "/never-written" + + // Durable markers written inside /data by the victim and attacker actors + // in the same atespace. + victimDurableMarker = dataMount + "/victim-marker" + attackerDurableMarker = dataMount + "/attacker-marker" + + // Ephemeral markers written outside durable volumes by the victim and + // attacker actors. + // - /tmp (ephemeral directory inside the container) + // - / (the container's writable rootfs upper layer) + // - /dev (the sandbox's tmpfs mount) + victimTmpMarker = "/tmp/victim-tmp-marker" + attackerTmpMarker = "/tmp/attacker-tmp-marker" + victimRootfsMarker = "/victim-rootfs-marker" + attackerRootfsMarker = "/attacker-rootfs-marker" + victimTmpfsMarker = "/dev/victim-tmpfs-marker" + attackerTmpfsMarker = "/dev/attacker-tmpfs-marker" + + // Private point-to-point veth geometry between the worker pod and the + // actor sandbox (mirrors internal/ateworker/actornet, which is linux-only). + actorVethName = "eth0" + actorVethIP = "169.254.17.2/30" + hostVethIP = "169.254.17.1" + + // staleAssignmentHeader is the response header atunnel's ingress sets on a + // 421 for an actor no longer assigned to the worker. It is unexported in + // internal/atunnel/ingress, so mirror the value here. + staleAssignmentHeader = "X-Ate-Assignment-Stale" + + // Pod-identity CA pool secret used to sign workload mTLS certificates for + // atunnel and atenet-router. + podIdentityCANamespace = "podcertificate-controller-system" + podIdentityCASecret = "pod-identity-ca-pool" + podIdentityCASecretKey = "pool" + + // Header and audience used when verifying CP-2a egress actor identity. + actorTokenHeader = "X-Actor-Token" + cp2aAudience = "cp2a-echo" +) + +// fileResponse mirrors the probe's /readfile and /writefile responses. +type fileResponse struct { + Path string `json:"path"` + Content string `json:"content"` + OK string `json:"ok"` + Error string `json:"error"` +} + +// whoamiResponse mirrors the probe's /whoami response. +type whoamiResponse struct { + File string `json:"file"` + Atespace string `json:"atespace"` + UID string `json:"uid"` + Held string `json:"held"` + Error string `json:"error"` +} + +// netInterfaceInfo and netInfoResponse mirror the probe's /netinfo response. +type netInterfaceInfo struct { + Name string `json:"name"` + Addrs []string `json:"addrs"` +} + +type netInfoResponse struct { + Interfaces []netInterfaceInfo `json:"interfaces"` + Error string `json:"error"` +} + +// echoFetchResult mirrors the probe's /fetch response when it fetches the echo +// origin's /echoheaders. +type echoFetchResult struct { + Status string `json:"status"` + Body string `json:"body"` + Error string `json:"error"` +} + +// echoedHeaders mirrors the /echoheaders response of the echo origin +// (testserver), carried in the body of the probe's /fetch response. +type echoedHeaders struct { + Headers map[string]string `json:"headers"` +} + +// TestActorIsolation checks that actor-level isolation invariants hold across +// worker reuse and snapshot lifecycle. +func TestActorIsolation(t *testing.T) { + if _, err := e2e.CheckEnv("KO_DOCKER_REPO"); err != nil { + t.Fatalf("CheckEnv failed: %v", err) + } + ctx := context.Background() + clients := e2e.GetClients() + + atespace, _ := e2e.DeploySubstrateFixture(t, ctx, clients, e2e.SubstrateFixtureManifests{ + Pool: "internal/e2e/fixtures/security/actor-isolation.yaml.tmpl", + Template: "internal/e2e/fixtures/security/actor-isolation-template.yaml.tmpl", + }, "sec-actor", nil) + + rc, err := e2e.NewRouterClient(t, ctx) + if err != nil { + t.Fatalf("NewRouterClient: %v", err) + } + defer rc.Close() + + // The echo origin MintedActorCertificateBoundToAssignedActor fetches from + // through the egress gateway. It is deployed before the victim so the + // victim can use egress too: a policy has to be in place before an actor + // resumes. + var echoHost string + var victimRules, attackerRules []*ateapi.EgressRule + if supportsEgressActorJWTInjection() { + echoHost = e2e.DeployServerPod(t, ctx, echoServer).SvcName() + victimRules = append(victimRules, e2e.EgressAllowHTTP(echoHost, echoHost+".cluster.local")) + attackerRules = append(attackerRules, actorJWTEchoRule(echoHost)) + } + + // Victim: runs first on the single shared worker. Record its UID and + // worker. + createAndResumeActor(t, ctx, clients, atespace, victim, victimRules...) + victimActor := resources.ActorRef{Atespace: atespace, Name: victim} + victimUID := actorUID(t, ctx, clients, atespace, victim) + victimWorker := assignedWorker(t, ctx, clients, atespace, victim) + + // Populate durable and ephemeral state in the victim, and + // verify each write with a positive read control before suspending. + for _, path := range []string{ + victimDurableMarker, + victimTmpMarker, + victimRootfsMarker, + victimTmpfsMarker, + } { + writeFile(t, ctx, rc, victimActor, path) + if got := readFile(t, ctx, rc, victimActor, path); got.Content != markerContent(victimActor) { + t.Fatalf("control: victim %s reading its OWN %s = %q (error %q), want %q — the probe cannot see its own written state, so nothing below is meaningful", + victimActor, path, got.Content, got.Error, markerContent(victimActor)) + } + } + victimWhoami := whoami(t, ctx, rc, victimActor) + if victimWhoami.File != victim || victimWhoami.Held != victim || victimWhoami.Atespace != atespace || victimWhoami.UID != victimUID { + t.Fatalf("control: victim %s /whoami = %+v, want file=%q held=%q atespace=%q uid=%q", + victimActor, victimWhoami, victim, victim, atespace, victimUID) + } + + // Have the victim use egress once, so the worker's atunnel holds an egress + // client certificate and gateway connection for the victim when the + // attacker takes the worker over. MintedActorCertificateBoundToAssignedActor + // then fails if that state outlives the victim. + if echoHost != "" { + echoURL := "http://" + echoHost + "/echoheaders" + if got := fetchEchoHeadersWithRetry(t, ctx, rc, victimActor, echoURL, nil); got.Error != "" || got.Status != "200" { + diagnoseEgressDNS(t, ctx, clients, rc, victimActor, echoHost) + t.Fatalf("control: victim %s /fetch %s returned status=%q error=%q body=%q, want 200 — the victim never used egress, so the worker holds no victim egress state to leak", + victimActor, echoURL, got.Status, got.Error, got.Body) + } + } + + // Suspend the victim to free the worker. The durable marker stays on the + // worker; the snapshot goes to object storage. Record the snapshot URI for + // post-delete bucket check. + victimSnapshotURI := suspendDurably(t, ctx, clients, atespace, victim) + + // Attacker: a second actor in the SAME atespace takes the freed worker. + createAndResumeActor(t, ctx, clients, atespace, attacker, attackerRules...) + attackerActor := resources.ActorRef{Atespace: atespace, Name: attacker} + attackerUID := actorUID(t, ctx, clients, atespace, attacker) + requireReusedWorker(t, ctx, clients, atespace, attacker, victimWorker) + + // Sanity checks before the negative assertions. First confirm that + // /readfile reports a missing file as an error at all, and that the + // attacker can write and read its own files. + if got := readFile(t, ctx, rc, attackerActor, neverWritten); got.Error == "" { + t.Fatalf("control: attacker %s read %s, which nothing ever created, and reported no error (content %q) — /readfile does not report misses as errors, so every negative assertion here would pass vacuously", + attackerActor, neverWritten, got.Content) + } + for _, path := range []string{ + attackerDurableMarker, + attackerTmpMarker, + attackerRootfsMarker, + attackerTmpfsMarker, + } { + writeFile(t, ctx, rc, attackerActor, path) + if got := readFile(t, ctx, rc, attackerActor, path); got.Content != markerContent(attackerActor) { + t.Fatalf("control: attacker %s reading its OWN %s = %q (error %q), want %q", + attackerActor, path, got.Content, got.Error, markerContent(attackerActor)) + } + } + + // Baseline identity read on the attacker while RUNNING. This also indexes + // the /run/ate inodes and exercises heldIdentity in the guest before + // snapshotting the attacker. + attackerWhoami := whoami(t, ctx, rc, attackerActor) + if attackerWhoami.File != attacker || attackerWhoami.Held != attacker || attackerWhoami.Atespace != atespace || attackerWhoami.UID != attackerUID { + t.Fatalf("control: attacker %s /whoami = %+v, want file=%q held=%q atespace=%q uid=%q", + attackerActor, attackerWhoami, attacker, attacker, atespace, attackerUID) + } + + // ST-1 [time], durable mount: the attacker's /data must be its own. + // The victim's durable data left the worker in its snapshot, so seeing the marker here would mean durable dirs are + // keyed by something shared, breaking the security invariant. + t.Run("VictimDurableMarkerNotVisibleThroughAttackerMount", func(t *testing.T) { + t.Log("Invariant ST-1 [time]: An actor must not read or write another actor's durable-dir volume through its own mount") + if got := readFile(t, ctx, rc, attackerActor, victimDurableMarker); got.Error == "" { + t.Errorf("attacker %s read %s, the victim's durable marker in the same atespace %s, through its own mount: content %q — durable-dir volumes shouldn't have been shared across worker-reuse", + attackerActor, victimDurableMarker, atespace, got.Content) + } + }) + + // EX-4 [time], an actor must not read/write the per-actor host state of another actor on the same worker. + t.Run("VictimHostStateNotReachableFromAttackerSandbox", func(t *testing.T) { + t.Log("Invariant EX-4 [time]: An actor must not read/write the per-actor host state of another actor on the same worker or worker-pod credentials (T-18/T-19/T-22/T-27)") + for _, probe := range []struct { + what string + path string + }{ + {"the victim's durable marker on the host", actorHostPath(victimUID, "durable-dir", durableVolume, filepath.Base(victimDurableMarker))}, + {"the victim's projected actor identity", actorHostPath(victimUID, "system-info", "system-info", "actor-id")}, + {"the victim's sandbox asset record", actorHostPath(victimUID, "sandbox-assets.json")}, + {"the worker pod's pod-identity credential bundle (T-19)", "/run/podidentity.podcert.ate.dev/credential-bundle.pem"}, + {"the worker pod's Kubernetes ServiceAccount token (T-22)", "/var/run/secrets/kubernetes.io/serviceaccount/token"}, + } { + if got := readFile(t, ctx, rc, attackerActor, probe.path); got.Error == "" { + t.Errorf("attacker %s read %s (%s): content %q — the sandbox exposes the worker's per-actor host state or worker credentials across the reuse boundary", + attackerActor, probe.path, probe.what, got.Content) + } + } + + // A write is the more serious direction of the same boundary: reaching the + // victim's durable directory means an actor can corrupt another actor's data. + injected := actorHostPath(victimUID, "durable-dir", durableVolume, "injected") + if got := writeFileAllowingFailure(t, ctx, rc, attackerActor, injected); got.Error == "" { + t.Errorf("attacker %s wrote %s, inside the victim's durable directory on the worker — an actor can corrupt another actor's stored data", + attackerActor, injected) + } + }) + + // Ephemeral sandbox state: when the worker hosts the attacker + // after the victim, the attacker must find none of the victim's ephemeral + // state in /tmp, the writable rootfs layer (/), the sandbox tmpfs (/dev), + // or open file descriptors. + t.Run("VictimEphemeralStateNotPresentInAttackerSandbox", func(t *testing.T) { + t.Log("Invariant EX-5 [time]: When a worker hosts a new actor, the new actor must find no state from the previous actor (/tmp, writable layer, tmpfs, file descriptors) (T-27)") + for _, probe := range []struct { + what string + path string + }{ + {"the victim's /tmp file", victimTmpMarker}, + {"the victim's writable rootfs upper-layer file", victimRootfsMarker}, + {"the victim's /dev tmpfs file", victimTmpfsMarker}, + } { + if got := readFile(t, ctx, rc, attackerActor, probe.path); got.Error == "" { + t.Errorf("attacker %s read %s (%s): content %q — ephemeral state from the previous actor survived worker reuse", + attackerActor, probe.path, probe.what, got.Content) + } + } + + // The file descriptor part of the claim. The probe holds + // /run/ate/actor-id open from startup, and the attacker restored that + // open descriptor from the golden snapshot onto the worker the victim + // just left. The baseline /whoami above already requires it to read + // the attacker's identity; this repeats the read so the subtest fails + // on its own if the descriptor, or the projected files, still resolve + // to the victim's. + gotWhoami := whoami(t, ctx, rc, attackerActor) + if gotWhoami.Held == victim || gotWhoami.File == victim || gotWhoami.UID == victimUID { + t.Errorf("attacker %s /whoami = %+v, carries previous actor %s (uid %s) state across worker reuse", + attackerActor, gotWhoami, victim, victimUID) + } + }) + + // NW-1: an actor runs in an isolated network namespace with only a private + // point-to-point veth to the worker pod, never the worker pod's CNI network. + t.Run("ActorNetworkIsolatedToPrivateVeth", func(t *testing.T) { + t.Log("Invariant NW-1: An actor's network namespace must be isolated from the worker pod's network namespace, connected only via a private veth pair") + testActorNetworkIsolatedToPrivateVeth(t, ctx, clients, rc, attackerActor) + }) + + // CP-2a: the actor mTLS certificate minted for the worker is bound to its + // currently assigned actor, and an actor cannot spoof another actor's identity. + t.Run("MintedActorCertificateBoundToAssignedActor", func(t *testing.T) { + t.Log("Invariant CP-2a: The worker's minted actor certificate must carry only the assigned actor's identity and resist actor-side spoofing (T-28)") + testMintedActorCertificateBoundToAssignedActor(t, ctx, clients, rc, atespace, attackerActor, attackerUID, victimUID, echoHost) + }) + + wt := openWorkerTunnel(t, ctx, clients, attackerActor) + + // NW-3: only atenet-router's pod identity may open an mTLS tunnel to a + // worker's atunnel listener; other cluster workloads are rejected. + t.Run("OnlyRouterCanOpenWorkerTunnel", func(t *testing.T) { + t.Log("Invariant NW-3: Only atenet-router may establish an ingress tunnel to a worker pod") + testOnlyRouterCanOpenWorkerTunnel(t, ctx, wt, attackerActor) + }) + + // NW-4 [time]: a reused worker's atunnel forwards only to its currently + // assigned actor and rejects traffic targeting the previously hosted actor. + t.Run("WorkerTunnelForwardsOnlyToAssignedActor", func(t *testing.T) { + t.Log("Invariant NW-4 [time]: A worker's atunnel must forward traffic only when the target actor matches its currently assigned actor") + testWorkerTunnelForwardsOnlyToAssignedActor(t, ctx, wt, attackerActor, victimActor) + }) + + // ST-3 [time]: projected identity must never be captured in + // snapshots and leaked to a cloned actor in the same atespace. + t.Run("ProjectedIdentityNotCapturedInSnapshot", func(t *testing.T) { + t.Log("Invariant ST-3 [time]: Projected identity (system-info volume) must never be captured in snapshots (T-23)") + testProjectedIdentityNotInSnapshot(t, ctx, clients, rc, atespace, attacker, attackerUID) + }) + + // ST-5 [time]: deleting the victim actor must remove its external snapshots + // from object storage and prevent a newly created actor of the same name + // from recovering the deleted actor's state. + t.Run("DeletedActorSnapshotsRemoved", func(t *testing.T) { + t.Log("Invariant ST-5 [time]: Deletion of an actor must remove its snapshots, so a later actor cannot recover them") + testDeletedActorSnapshotsRemoved(t, ctx, clients, rc, atespace, victim, victimUID, victimSnapshotURI, victimWorker) + }) +} + +// actorHostPath is nodepath.ActorsDir// on the worker host. The +// leaves (durable-dir, system-info, sandbox-assets.json) mirror +// cmd/atelet/internal/ateletpath, which this suite cannot import. +func actorHostPath(actorUID string, elem ...string) string { + return filepath.Join(append([]string{nodepath.ActorsDir, actorUID}, elem...)...) +} + +// testProjectedIdentityNotInSnapshot checks that an actor cloned from a +// snapshot tag in the same atespace observes its own projected system-info +// identity, never the snapshot source actor's identity. +func testProjectedIdentityNotInSnapshot(t *testing.T, ctx context.Context, clients *e2e.Clients, rc *e2e.RouterClient, atespace, sourceName, sourceUID string) { + t.Helper() + + // The tag needs a durable snapshot to capture. + suspendDurably(t, ctx, clients, atespace, sourceName) + + // Clear a clone leaked by an interrupted run before its tag: the clone was + // created from the tag, so it goes first. + cloneRef := &ateapi.ObjectRef{Atespace: atespace, Name: cloneName} + _, _ = clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: cloneRef}) + _, _ = clients.SubstrateAPI.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: cloneRef}) + + tagRef := &ateapi.ObjectRef{Atespace: atespace, Name: "actor-snapshot-tag"} + t.Cleanup(func() { + _, _ = clients.SubstrateAPI.DeleteTag(context.Background(), &ateapi.DeleteTagRequest{Tag: tagRef}) + }) + _, _ = clients.SubstrateAPI.DeleteTag(ctx, &ateapi.DeleteTagRequest{Tag: tagRef}) + tag, err := clients.SubstrateAPI.CreateTag(ctx, &ateapi.CreateTagRequest{ + Tag: &ateapi.Tag{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: tagRef.GetName()}, + Scope: ateapi.TagScope_TAG_SCOPE_ATESPACE, + SourceActor: &ateapi.ObjectRef{Atespace: atespace, Name: sourceName}, + }, + }) + if err != nil { + t.Fatalf("CreateTag %s/%s: %v", atespace, tagRef.GetName(), err) + } + if snapshotURI(tag.GetStatus().GetSnapshot()) == "" { + t.Fatalf("tag %s/%s has no snapshot uri", atespace, tagRef.GetName()) + } + + t.Cleanup(func() { + cleanupCtx := context.Background() + _, _ = clients.SubstrateAPI.SuspendActor(cleanupCtx, &ateapi.SuspendActorRequest{Actor: cloneRef}) + _, _ = clients.SubstrateAPI.DeleteActor(cleanupCtx, &ateapi.DeleteActorRequest{Actor: cloneRef}) + }) + if _, err := clients.SubstrateAPI.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: cloneName}, + ActorTemplate: &ateapi.ObjectRef{Atespace: atespace, Name: templateName}, + SourceTag: tagRef, + }}); err != nil { + t.Fatalf("CreateActor %s/%s from tag %s: %v", atespace, cloneName, tagRef.GetName(), err) + } + if _, err := e2e.ResumeActorAwaitCapacity(t, ctx, clients, &ateapi.ResumeActorRequest{Actor: cloneRef}); err != nil { + t.Fatalf("ResumeActor %s/%s: %v", atespace, cloneName, err) + } + waitForActorState(t, ctx, clients, atespace, cloneName, ateapi.ActorState_ACTOR_STATE_RUNNING) + + // Positive control: the clone carries the snapshot source's durable data, + // proving it actually restored from the source actor's checkpoint. + cloneActor := resources.ActorRef{Atespace: atespace, Name: cloneName} + sourceContent := markerContent(resources.ActorRef{Atespace: atespace, Name: sourceName}) + if got := readFile(t, ctx, rc, cloneActor, attackerDurableMarker); got.Content != sourceContent { + t.Fatalf("control: clone %s restored from tag %s reads %s = %q (error %q), want %q — the clone did not restore the source snapshot", + cloneActor, tagRef.GetName(), attackerDurableMarker, got.Content, got.Error, sourceContent) + } + + cloneUID := actorUID(t, ctx, clients, atespace, cloneName) + if cloneUID == sourceUID { + t.Fatalf("clone %s/%s was assigned the same UID %q as source %s/%s", atespace, cloneName, cloneUID, atespace, sourceName) + } + + got := whoami(t, ctx, rc, cloneActor) + if got.File == sourceName { + t.Errorf("clone %s/%s /run/ate/actor-id = %q (the snapshot source's name) — projected identity was captured in the snapshot", + atespace, cloneName, got.File) + } else if got.File != cloneName { + t.Errorf("clone %s/%s /run/ate/actor-id = %q, want %q (probe error: %q)", + atespace, cloneName, got.File, cloneName, got.Error) + } + + if got.Held == sourceName { + t.Errorf("clone %s/%s startup-held fd for /run/ate/actor-id read %q (the snapshot source's name) — open system-info fd did not re-bind on restore", + atespace, cloneName, got.Held) + } else if got.Held != cloneName { + t.Errorf("clone %s/%s startup-held fd for /run/ate/actor-id = %q, want %q (probe error: %q)", + atespace, cloneName, got.Held, cloneName, got.Error) + } + + if got.UID == sourceUID { + t.Errorf("clone %s/%s /run/ate/actor-uid = %q (the snapshot source's UID) — projected UID was captured in the snapshot", + atespace, cloneName, got.UID) + } else if got.UID != cloneUID { + t.Errorf("clone %s/%s /run/ate/actor-uid = %q, want %q (probe error: %q)", + atespace, cloneName, got.UID, cloneUID, got.Error) + } + + if got.Atespace != atespace { + t.Errorf("clone %s/%s /run/ate/atespace = %q, want %q (probe error: %q)", + atespace, cloneName, got.Atespace, atespace, got.Error) + } +} + +// testDeletedActorSnapshotsRemoved checks that deleting an actor removes all +// objects under its owner prefix in object storage, and a newly created actor +// with the same name starts fresh without recovering the deleted actor's +// snapshot or durable/ephemeral data. +func testDeletedActorSnapshotsRemoved(t *testing.T, ctx context.Context, clients *e2e.Clients, rc *e2e.RouterClient, atespace, victim, victimUID, victimSnapshotURI, victimWorker string) { + t.Helper() + + uri, err := resources.ParseSnapshotURI(victimSnapshotURI) + if err != nil { + t.Fatalf("ParseSnapshotURI(%q): %v", victimSnapshotURI, err) + } + bucket, prefix, err := objectstore.BucketPrefix(uri.OwnerPrefix()) + if err != nil { + t.Fatalf("BucketPrefix(%s): %v", uri.OwnerPrefix(), err) + } + + store := openSnapshotObjectStore(t, ctx, clients) + + // Positive control: before DeleteActor, the suspended victim's snapshot + // objects must be visible at bucket/prefix so the post-delete empty check + // below cannot pass vacuously on a miscalculated prefix. + before, err := store.List(ctx, bucket, prefix) + if err != nil { + t.Fatalf("listing victim snapshot prefix %s/%s before DeleteActor: %v", bucket, prefix, err) + } + if len(before) == 0 { + t.Fatalf("control: victim %s/%s (uid %s) has 0 objects under %s/%s before DeleteActor (snapshotUri %q) — post-delete empty check would be vacuous", + atespace, victim, victimUID, bucket, prefix, victimSnapshotURI) + } + + victimRef := &ateapi.ObjectRef{Atespace: atespace, Name: victim} + if _, err := clients.SubstrateAPI.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: victimRef}); err != nil { + t.Fatalf("DeleteActor %s/%s: %v", atespace, victim, err) + } + + // Negative assertion 1: the deleted actor's object-storage prefix is empty. + after, err := store.List(ctx, bucket, prefix) + if err != nil { + t.Fatalf("listing victim snapshot prefix %s/%s after DeleteActor: %v", bucket, prefix, err) + } + if len(after) != 0 { + t.Errorf("deleted actor %s/%s (uid %s) still has %d snapshot objects under %s/%s: %v", + atespace, victim, victimUID, len(after), bucket, prefix, after) + } + + // Negative assertion 2: a new actor created in the same atespace with the + // exact same name starts with a new UID and cannot recover the deleted + // actor's durable or ephemeral markers. Free the single shared worker first. + for _, active := range []string{attacker, cloneName} { + suspendIfActive(t, ctx, clients, atespace, active) + } + createAndResumeActor(t, ctx, clients, atespace, victim) + requireReusedWorker(t, ctx, clients, atespace, victim, victimWorker) + + reincarnatedUID := actorUID(t, ctx, clients, atespace, victim) + if reincarnatedUID == victimUID { + t.Errorf("recreated actor %s/%s reused deleted actor's UID %q", atespace, victim, victimUID) + } + victimActor := resources.ActorRef{Atespace: atespace, Name: victim} + for _, marker := range []string{ + victimDurableMarker, + victimTmpMarker, + victimRootfsMarker, + victimTmpfsMarker, + } { + if got := readFile(t, ctx, rc, victimActor, marker); got.Error == "" { + t.Errorf("recreated actor %s/%s (uid %s) read deleted actor's marker %s = %q — state survived actor deletion", + atespace, victim, reincarnatedUID, marker, got.Content) + } + } +} + +// openSnapshotObjectStore connects to the cluster's snapshot object store: +// port-forwarding to the in-cluster rustfs S3 service on kind, or using the +// default GCS client on GKE. +func openSnapshotObjectStore(t *testing.T, ctx context.Context, clients *e2e.Clients) objectstore.Store { + t.Helper() + sysNS := e2e.SystemNamespace() + rustfsSvc := e2e.ResourceName("rustfs") + if _, err := clients.K8s.CoreV1().Services(sysNS).Get(ctx, rustfsSvc, metav1.GetOptions{}); err == nil { + config, err := ateclient.LoadKubeConfig(e2e.KubeConfig, e2e.KubeContext) + if err != nil { + t.Fatalf("loading kubeconfig for rustfs port-forward: %v", err) + } + localPort, stop, err := portforward.ServicePortForward(ctx, config, clients.K8s, sysNS, rustfsSvc, 9000) + if err != nil { + t.Fatalf("port-forwarding to %s/%s:9000: %v", sysNS, rustfsSvc, err) + } + t.Cleanup(stop) + return objectstore.NewS3(s3.New(s3.Options{ + Region: "us-east-1", + Credentials: credentials.NewStaticCredentialsProvider("rustfsadmin", "rustfsadmin", ""), + BaseEndpoint: aws.String(fmt.Sprintf("http://127.0.0.1:%d", localPort)), + UsePathStyle: true, + })) + } else if !apierrors.IsNotFound(err) { + t.Fatalf("checking for %s/%s service: %v", sysNS, rustfsSvc, err) + } + + gcsClient, err := storage.NewClient(ctx) + if err != nil { + t.Fatalf("creating GCS client: %v", err) + } + t.Cleanup(func() { _ = gcsClient.Close() }) + return objectstore.NewGCS(gcsClient) +} + +// requireReusedWorker fails unless the actor landed on priorWorker. The fixture +// runs one worker, so any other worker means the attacker never touched the +// host the victim left its state on and the test proves nothing. +func requireReusedWorker(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name, priorWorker string) { + t.Helper() + got := assignedWorker(t, ctx, clients, atespace, name) + if got != priorWorker { + t.Fatalf("actor %s/%s landed on worker %q, not the worker %q the victim vacated; the fixture deploys one worker, so the reuse boundary under test is not being exercised", + atespace, name, got, priorWorker) + } + t.Logf("actor %s/%s reused worker %s", atespace, name, priorWorker) +} + +func assignedWorker(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string) string { + t.Helper() + actor, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: atespace, Name: name}, + }) + if err != nil { + t.Fatalf("GetActor %s/%s: %v", atespace, name, err) + } + worker := actor.GetStatus().GetWorkerAssignment().GetWorker().GetName() + if worker == "" { + t.Fatalf("actor %s/%s has no worker assignment while RUNNING", atespace, name) + } + return worker +} + +func actorUID(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string) string { + t.Helper() + actor, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: atespace, Name: name}, + }) + if err != nil { + t.Fatalf("GetActor %s/%s: %v", atespace, name, err) + } + uid := actor.GetMetadata().GetUid() + if uid == "" { + t.Fatalf("actor %s/%s has no uid", atespace, name) + } + return uid +} + +// createAndResumeActor creates an actor from its atespace's template and resumes +// it from the golden snapshot, removing it when the test ends. +// createAndResumeActor creates and resumes the actor. Any rules become its +// egress policy before it resumes, the way the egress suites set theirs, so +// the policy is in force from the sandbox's first DNS query. +func createAndResumeActor(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string, rules ...*ateapi.EgressRule) { + t.Helper() + ref := &ateapi.ObjectRef{Atespace: atespace, Name: name} + // Actor records outlive the fixture namespace, so an interrupted run can + // leave one behind and wedge reruns on AlreadyExists. DeleteActor needs + // SUSPENDED or CRASHED, hence the suspend; both are best-effort. + _, _ = clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: ref}) + _, _ = clients.SubstrateAPI.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref}) + if _, err := clients.SubstrateAPI.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ + Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: name}, + ActorTemplate: &ateapi.ObjectRef{Atespace: atespace, Name: templateName}, + }}); err != nil { + t.Fatalf("CreateActor %s/%s: %v", atespace, name, err) + } + t.Cleanup(func() { + cleanupCtx := context.Background() + _, _ = clients.SubstrateAPI.SuspendActor(cleanupCtx, &ateapi.SuspendActorRequest{Actor: ref}) + // NotFound is normal: a subtest may already have deleted the actor. + if _, err := clients.SubstrateAPI.DeleteActor(cleanupCtx, &ateapi.DeleteActorRequest{Actor: ref}); err != nil && status.Code(err) != codes.NotFound { + t.Logf("cleanup: DeleteActor %s/%s failed, actor leaked (remove with: kubectl ate delete actor %s -a %s): %v", atespace, name, name, atespace, err) + } + }) + + if len(rules) > 0 { + e2e.EnsureEgressPolicy(t, ctx, clients, ref, rules...) + } + + if _, err := e2e.ResumeActorAwaitCapacity(t, ctx, clients, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { + t.Fatalf("ResumeActor %s/%s: %v", atespace, name, err) + } + waitForActorState(t, ctx, clients, atespace, name, ateapi.ActorState_ACTOR_STATE_RUNNING) +} + +func waitForActorState(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string, want ateapi.ActorState) { + t.Helper() + deadline := time.Now().Add(60 * time.Second) + for time.Now().Before(deadline) { + resp, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: atespace, Name: name}, + }) + if err == nil && resp.GetStatus().GetState() == want { + return + } + time.Sleep(time.Second) + } + t.Fatalf("timed out waiting for actor %s/%s to reach state %v", atespace, name, want) +} + +// suspendIfActive frees the worker actor name holds, if it holds one. An actor +// that does not exist (a subtest filtered out by -run never created it) or is +// already SUSPENDED is left alone. Any other actor is suspended and awaited, +// so a failed suspend fails here instead of surfacing later as a misleading +// capacity timeout on the next resume. +func suspendIfActive(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string) { + t.Helper() + ref := &ateapi.ObjectRef{Atespace: atespace, Name: name} + actor, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) + if status.Code(err) == codes.NotFound { + return + } + if err != nil { + t.Fatalf("GetActor %s/%s: %v", atespace, name, err) + } + if actor.GetStatus().GetState() == ateapi.ActorState_ACTOR_STATE_SUSPENDED { + return + } + if _, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: ref}); err != nil { + t.Fatalf("SuspendActor %s/%s (state %v): %v", atespace, name, actor.GetStatus().GetState(), err) + } + waitForActorState(t, ctx, clients, atespace, name, ateapi.ActorState_ACTOR_STATE_SUSPENDED) +} + +// markerContent is the body writeFile gives every file actor writes. It names +// the writer, so a read that returns another actor's file under the reader's +// own path does not pass for the reader's own. +func markerContent(actor resources.ActorRef) string { + return "written by " + actor.String() +} + +// writeFile writes markerContent(actor) at path and fails the test if the +// write did not land, so a later negative assertion cannot pass on missing +// state. +func writeFile(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, path string) { + t.Helper() + if got := writeFileAllowingFailure(t, ctx, rc, actor, path); got.OK != "true" { + t.Fatalf("actor %s writing %s: %q", actor, path, got.Error) + } +} + +// writeFileAllowingFailure is writeFile for assertions that expect the write +// to be refused; it returns the probe's report instead of failing. +func writeFileAllowingFailure(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, path string) fileResponse { + t.Helper() + return probeFileOp(t, ctx, rc, actor, "/writefile", url.Values{"path": {path}, "content": {markerContent(actor)}}) +} + +func readFile(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, path string) fileResponse { + t.Helper() + return probeFileOp(t, ctx, rc, actor, "/readfile", url.Values{"path": {path}}) +} + +// probeFileOp calls one of the probe's file endpoints. A transport or HTTP +// failure is fatal rather than returned: the probe never ran the operation, +// which is not the same as the actor being denied. +func probeFileOp(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, endpoint string, query url.Values) fileResponse { + t.Helper() + resp, err := rc.Get(ctx, actor, endpoint+"?"+query.Encode()) + if err != nil { + t.Fatalf("GET %s for %s: %v", endpoint, actor, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET %s for %s: status %d, body %q", endpoint, actor, resp.StatusCode, body) + } + var out fileResponse + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("decoding %s for %s: %v", endpoint, actor, err) + } + return out +} + +// whoami calls the probe's /whoami endpoint, which reads /run/ate/actor-id, +// /run/ate/atespace, /run/ate/actor-uid, and the startup-held open file +// descriptor to /run/ate/actor-id. +func whoami(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef) whoamiResponse { + t.Helper() + resp, err := rc.Get(ctx, actor, "/whoami") + if err != nil { + t.Fatalf("GET /whoami for %s: %v", actor, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET /whoami for %s: status %d, body %q", actor, resp.StatusCode, body) + } + var out whoamiResponse + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("decoding /whoami for %s: %v", actor, err) + } + return out +} + +// suspendDurably suspends the actor, waits for it to be SUSPENDED, and returns +// the object-storage URI of its own durable snapshot. The default suspend +// mode returns once the snapshot is captured on the node and uploads in the +// background, so this asks for a synchronous suspend and still polls: an +// actor that was already suspended is returned with whatever snapshot it +// holds, which may not have been uploaded yet. +func suspendDurably(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string) string { + t.Helper() + ref := &ateapi.ObjectRef{Atespace: atespace, Name: name} + if _, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{ + Actor: ref, + Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, + }); err != nil { + t.Fatalf("SuspendActor %s/%s: %v", atespace, name, err) + } + waitForActorState(t, ctx, clients, atespace, name, ateapi.ActorState_ACTOR_STATE_SUSPENDED) + + deadline := time.Now().Add(2 * time.Minute) + for { + actor, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{Actor: ref}) + if err != nil { + t.Fatalf("GetActor %s/%s: %v", atespace, name, err) + } + if uri := durableSnapshotURI(actor.GetStatus()); uri != "" { + return uri + } + if time.Now().After(deadline) { + t.Fatalf("suspended actor %s/%s has no completed durable snapshot of its own after two minutes: %v", + atespace, name, actor.GetStatus().GetSnapshots()) + } + time.Sleep(time.Second) + } +} + +// durableSnapshotURI returns the object-storage URI of the newest snapshot +// in status that the actor itself owns and that has finished uploading, or "" +// if none has. A suspended actor always has one. status.snapshots also lists +// tag-owned snapshots (the golden snapshot the actor was restored from), which +// live under the tag's prefix, not the actor's, so they are skipped. +func durableSnapshotURI(status *ateapi.ActorStatus) string { + var newest *ateapi.Snapshot + for _, snap := range status.GetSnapshots() { + if snap.GetOwner() != ateapi.SnapshotOwner_SNAPSHOT_OWNER_ACTOR { + continue + } + if uri := snapshotURI(snap); uri != "" { + if newest == nil || snap.GetGeneration() > newest.GetGeneration() { + newest = snap + } + } + } + return snapshotURI(newest) +} + +func snapshotURI(snap *ateapi.Snapshot) string { + st := snap.GetDurableSnapshot() + if st.GetState() == ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED { + return st.GetObject().GetSnapshotUri() + } + return "" +} + +// testActorNetworkIsolatedToPrivateVeth checks that the actor's network +// namespace holds only loopback and the private point-to-point veth (eth0 at +// 169.254.17.2/30), not the worker pod's CNI IP or host-side veth, and that +// the actor's HTTP listener is unreachable on the worker pod's CNI network. +func testActorNetworkIsolatedToPrivateVeth(t *testing.T, ctx context.Context, clients *e2e.Clients, rc *e2e.RouterClient, actor resources.ActorRef) { + t.Helper() + + workerNS, workerPod := assignedWorkerPod(t, ctx, clients, actor) + pod, err := clients.K8s.CoreV1().Pods(workerNS).Get(ctx, workerPod, metav1.GetOptions{}) + if err != nil { + t.Fatalf("getting worker pod %s/%s: %v", workerNS, workerPod, err) + } + workerPodIP := pod.Status.PodIP + if workerPodIP == "" { + t.Fatalf("worker pod %s/%s has no PodIP", workerNS, workerPod) + } + + info := netInfo(t, ctx, rc, actor) + if info.Error != "" { + t.Fatalf("GET /netinfo for %s reported error: %s", actor, info.Error) + } + var sawLo, sawActorVeth bool + for _, iface := range info.Interfaces { + switch iface.Name { + case "lo": + sawLo = true + case actorVethName: + if slices.Equal(iface.Addrs, []string{actorVethIP}) { + sawActorVeth = true + } else { + t.Errorf("actor %s interface %q has addrs %v, want [%s]", actor, iface.Name, iface.Addrs, actorVethIP) + } + default: + t.Errorf("actor %s sees unexpected network interface %q (%v) inside its network namespace", actor, iface.Name, iface.Addrs) + } + for _, cidr := range iface.Addrs { + ip, _, _ := strings.Cut(cidr, "/") + if ip == workerPodIP { + t.Errorf("actor %s interface %q carries the worker pod's CNI IP %s (%v) — actor shares the worker pod's network namespace", + actor, iface.Name, workerPodIP, iface.Addrs) + } + if ip == hostVethIP { + t.Errorf("actor %s interface %q carries the worker host veth IP %s (%v)", + actor, iface.Name, hostVethIP, iface.Addrs) + } + } + } + if !sawLo { + t.Errorf("actor %s /netinfo = %+v, missing loopback interface lo", actor, info.Interfaces) + } + if !sawActorVeth { + t.Errorf("actor %s /netinfo = %+v, missing private veth %s with %s", actor, info.Interfaces, actorVethName, actorVethIP) + } + + // Direct pod-IP access to port 80 on the worker pod must fail because the + // actor's listener lives inside the isolated actor netns, not the worker + // pod's CNI netns. + // + // Control first: the same apiserver proxy path has to reach a port the + // worker pod does listen on (8080, the worker's /readyz). Without it a + // proxy that cannot reach the pod at all, for RBAC or NetworkPolicy + // reasons, would pass the check below for the wrong reason. + proxyGet := func(port, path string) ([]byte, error) { + return clients.K8s.CoreV1().RESTClient().Get(). + Namespace(workerNS). + Resource("pods"). + Name(workerPod + ":" + port). + SubResource("proxy"). + Suffix(path). + Do(ctx). + Raw() + } + if body, err := proxyGet("8080", "readyz"); err != nil { + t.Fatalf("control: apiserver proxy to %s/%s:8080/readyz failed (body %q): %v — the proxy cannot reach the worker pod, so a failure on port 80 would prove nothing", + workerNS, workerPod, body, err) + } + if body, err := proxyGet("80", "healthz"); err == nil { + t.Errorf("direct HTTP access to %s/%s:80/healthz on the worker pod succeeded (body %q) — actor listener is exposed on the worker pod network", + workerNS, workerPod, body) + } else { + t.Logf("direct HTTP access to %s/%s:80/healthz refused as expected: %v", workerNS, workerPod, err) + } +} + +// supportsEgressActorJWTInjection reports whether the active atenet dataplane +// supports EgressPolicy replace_headers with ActorJwt (currently Envoy-only). +func supportsEgressActorJWTInjection() bool { + return os.Getenv(e2e.AtenetDataplaneEnv) != "agentgateway" +} + +// actorJWTEchoRule allows plain HTTP to the echo origin at echoHost and has +// the gateway replace actorTokenHeader with an actor JWT on the way. The +// probe's resolver search path tries the fully qualified +// echo..svc.cluster.local first, and the actor's DNS only answers for +// hostnames the policy allows, so both forms are listed. +// +// TODO(https://github.com/agent-substrate/substrate/issues/3286): atenet-egress +// caches minted JWTs by (atespace, actorName, audiences, expiration) without +// the actor UID, so use a per-run audience to keep local reruns from hitting +// a cached token from the previous run's attacker UID. Once that is fixed, +// use a fixed audience again and add a case for an actor recreated under the +// same name. +func actorJWTEchoRule(echoHost string) *ateapi.EgressRule { + rule := e2e.EgressAllowHTTP(echoHost, echoHost+".cluster.local") + rule.Http.Effects = &ateapi.HttpRuleEffects{ + ReplaceHeaders: []*ateapi.CredentialHeader{{ + Header: actorTokenHeader, + ActorJwt: &ateapi.ActorJwtSource{ + Audiences: []string{fmt.Sprintf("%s-%d", cp2aAudience, time.Now().UnixNano())}, + ExpirationSeconds: 900, + }, + }}, + } + return rule +} + +// testMintedActorCertificateBoundToAssignedActor verifies that outbound traffic +// from the reused worker authenticates to atenet-egress with the certificate +// minted for the currently assigned actor (attacker, never the previous +// victim), and that the actor cannot spoof victim's identity by attempting to +// overwrite /run/ate/actor-id or setting a forged header. echoHost is the echo +// origin the attacker's egress policy allows, deployed before the attacker +// resumed; the actor JWT the gateway injects comes back in its /echoheaders body. +func testMintedActorCertificateBoundToAssignedActor(t *testing.T, ctx context.Context, clients *e2e.Clients, rc *e2e.RouterClient, atespace string, attackerActor resources.ActorRef, attackerUID, victimUID, echoHost string) { + t.Helper() + + // The gateway half of this test reads the injected actor JWT and the + // gateway's access log, which only the Envoy dataplane provides. The + // projected identity files are read-only on every dataplane. + gateway := supportsEgressActorJWTInjection() + if !gateway { + t.Log("Egress ActorJwt header injection is only supported on the Envoy dataplane; checking only that the projected identity files cannot be overwritten") + } + + echoURL := "http://" + echoHost + "/echoheaders" + // Bound the access-log scan to this test, with slack for clock skew + // against the gateway's node. Each step then waits for a line that was + // not there before its own request, so one step cannot pass on another + // step's line. + logSince := metav1.NewTime(time.Now().Add(-1 * time.Minute)) + assertCertifiedAttackerIdentity := func(step string, forgedToken string) { + t.Helper() + logged := countEgressGatewayAuthLines(t, ctx, clients, logSince, attackerActor) + // Both headers claim the victim: the routing header names it and the + // token is forged. The gateway must act on neither. + headers := []string{ + atenet.TargetActorHeader + ":" + resources.ActorRef{Atespace: atespace, Name: victim}.String(), + actorTokenHeader + ":" + forgedToken, + } + got := fetchEchoHeadersWithRetry(t, ctx, rc, attackerActor, echoURL, headers) + if got.Error != "" || got.Status != "200" { + diagnoseEgressDNS(t, ctx, clients, rc, attackerActor, echoHost) + t.Fatalf("%s: probe /fetch %s returned status=%q error=%q body=%q, want 200", + step, echoURL, got.Status, got.Error, got.Body) + } + waitForNewEgressGatewayAuthLine(t, ctx, clients, logSince, attackerActor, logged) + + var echoed echoedHeaders + if err := json.Unmarshal([]byte(got.Body), &echoed); err != nil { + t.Fatalf("%s: decoding /echoheaders body %q: %v", step, got.Body, err) + } + token := echoed.Headers[actorTokenHeader] + if token == "" || strings.Contains(token, ",") || strings.Contains(token, forgedToken) { + t.Fatalf("%s: upstream received %s=%q, want a single gateway-injected actor JWT replacing %q", + step, actorTokenHeader, token, forgedToken) + } + claims := parseActorJWTClaims(t, step, token) + kind, sub, ok := claims.Substrate() + if !ok || kind != actoridjwt.KindActor || sub == nil { + t.Fatalf("%s: unexpected actor JWT substrate claims: %+v", step, claims) + } + wantSub := "actor/" + atespace + "/" + attackerActor.Name + if claims.Subject != wantSub { + t.Errorf("%s: certified JWT sub = %q, want %q", step, claims.Subject, wantSub) + } + if sub.Atespace != atespace || sub.ActorName != attackerActor.Name || sub.ActorUID != attackerUID { + t.Errorf("%s: certified JWT identity = (%s/%s uid %s), want (%s/%s uid %s)", + step, sub.Atespace, sub.ActorName, sub.ActorUID, atespace, attackerActor.Name, attackerUID) + } + if sub.ActorName == victim || sub.ActorUID == victimUID { + t.Errorf("%s: certified JWT carried previous actor %s (uid %s)", step, victim, victimUID) + } + } + + // Step 1: verify the certificate minted for the worker on reuse carries the + // assigned attacker's identity, not the victim's. + if gateway { + assertCertifiedAttackerIdentity("initial egress on reused worker", "forged-"+victim) + } + + // Step 2: attempt to overwrite projected identity files inside the sandbox to + // claim the victim's identity, and verify both that the writes are refused + // and that subsequent outbound requests still carry the attacker's identity. + for _, path := range []string{"/run/ate/actor-id", "/run/ate/actor-uid"} { + if got := writeFileAllowingFailure(t, ctx, rc, attackerActor, path); got.Error == "" { + t.Errorf("attacker %s overwrote read-only projected identity file %s", attackerActor, path) + } + } + if got := whoami(t, ctx, rc, attackerActor); got.File != attackerActor.Name || got.UID != attackerUID { + t.Errorf("attacker %s /whoami after attempted identity overwrite = %+v, want file=%q uid=%q", + attackerActor, got, attackerActor.Name, attackerUID) + } + if gateway { + assertCertifiedAttackerIdentity("egress after attempted /run/ate/actor-id overwrite", "spoofed-"+victim+"-"+victimUID) + } +} + +// workerTunnel names the reused worker pod whose atunnel listener (:443) is +// under test, and holds the cluster's pod-identity CA material and a pre-built +// client presenting atenet-router's pod-identity certificate. Each request +// gets its own port-forward: a port-forward tears down its whole tunnel once +// one forwarded connection fails, so a refused TLS handshake on a shared one +// would turn every request after it into a dial error. +type workerTunnel struct { + clients *e2e.Clients + workerNS string + workerPod string + ca *localca.CA + roots *x509.CertPool + routerClient *http.Client +} + +func openWorkerTunnel(t *testing.T, ctx context.Context, clients *e2e.Clients, actor resources.ActorRef) *workerTunnel { + t.Helper() + workerNS, workerPod := assignedWorkerPod(t, ctx, clients, actor) + + ca, roots := podIdentityCA(t, ctx, clients) + routerCert := mintPodIdentityCertificate(t, ca, installdefaults.RouterSPIFFEID(e2e.SystemNamespace())) + return &workerTunnel{ + clients: clients, + workerNS: workerNS, + workerPod: workerPod, + ca: ca, + roots: roots, + routerClient: newWorkerTunnelClient(roots, routerCert), + } +} + +// newRequest builds GET /whoami for target over a fresh port-forward to the +// worker's atunnel listener, torn down when t ends. +func (wt *workerTunnel) newRequest(t *testing.T, ctx context.Context, target resources.ActorRef) *http.Request { + t.Helper() + localPort, stop := portForwardWorkerTunnel(t, ctx, wt.clients, wt.workerNS, wt.workerPod) + t.Cleanup(stop) + req, err := http.NewRequestWithContext(ctx, http.MethodGet, fmt.Sprintf("https://127.0.0.1:%d/whoami", localPort), nil) + if err != nil { + t.Fatalf("building request to worker tunnel for %s: %v", target, err) + } + req.Host = fmt.Sprintf("%s.%s.actor.internal", target.Name, target.Atespace) + req.Header.Set(atenet.TargetActorHeader, target.String()) + return req +} + +func (wt *workerTunnel) doRouterGet(t *testing.T, ctx context.Context, target resources.ActorRef) (*http.Response, []byte) { + t.Helper() + resp, err := wt.routerClient.Do(wt.newRequest(t, ctx, target)) + if err != nil { + t.Fatalf("GET /whoami on worker tunnel %s/%s for %s: %v", wt.workerNS, wt.workerPod, target, err) + } + body, err := io.ReadAll(resp.Body) + resp.Body.Close() + if err != nil { + t.Fatalf("reading response from worker tunnel for %s: %v", target, err) + } + return resp, body +} + +// workerTunnelRefusalAttempts bounds the tries the refused client in +// testOnlyRouterCanOpenWorkerTunnel gets, each on a fresh port-forward. +const workerTunnelRefusalAttempts = 3 + +// testOnlyRouterCanOpenWorkerTunnel verifies on the reused worker's atunnel +// listener that a request presenting atenet-router's pod-identity +// certificate succeeds (200 OK), while a request presenting a valid +// pod-identity certificate for a non-router workload is rejected during the TLS +// handshake with a TLS alert. +func testOnlyRouterCanOpenWorkerTunnel(t *testing.T, ctx context.Context, wt *workerTunnel, attackerActor resources.ActorRef) { + t.Helper() + + // Positive control: presenting atenet-router's certificate succeeds, + // proving the worker's atunnel listener is live and reachable. + okResp, okBody := wt.doRouterGet(t, ctx, attackerActor) + if okResp.StatusCode != http.StatusOK { + t.Fatalf("control: router-authenticated request to worker tunnel %s/%s for %s returned %d (%q), want 200", + wt.workerNS, wt.workerPod, attackerActor, okResp.StatusCode, okBody) + } + + // Negative assertion: a valid pod-identity certificate for a non-router + // workload must be rejected by atunnel's VerifyConnection with a TLS alert. + nonRouterSPIFFE := installdefaults.SPIFFEID(attackerActor.Atespace, "default") + nonRouterCert := mintPodIdentityCertificate(t, wt.ca, nonRouterSPIFFE) + nonRouterClient := newWorkerTunnelClient(wt.roots, nonRouterCert) + + // atunnel closes right after its alert, and over a port-forward that close + // sometimes reaches the client before the alert does. Such an attempt + // proves neither acceptance nor refusal, so it is retried on a fresh + // port-forward (newRequest opens one per request), as the ingressauth + // suite does for the router's listeners. + for attempt := 1; ; attempt++ { + resp, err := nonRouterClient.Do(wt.newRequest(t, ctx, attackerActor)) + if err == nil { + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Fatalf("worker tunnel %s/%s accepted connection from non-router identity %s: status %d, body %q", + wt.workerNS, wt.workerPod, nonRouterSPIFFE, resp.StatusCode, body) + } + var opErr *net.OpError + if errors.As(err, &opErr) && opErr.Op == "remote error" && strings.Contains(opErr.Err.Error(), "bad certificate") { + t.Logf("worker tunnel refused non-router identity %s: %v", nonRouterSPIFFE, err) + return + } + if attempt == workerTunnelRefusalAttempts { + t.Fatalf("worker tunnel %s/%s rejected non-router identity %s with %v on attempt %d, want the bad-certificate TLS alert from VerifyConnection", + wt.workerNS, wt.workerPod, nonRouterSPIFFE, err, attempt) + } + t.Logf("attempt %d failed without the bad-certificate TLS alert; retrying on a fresh port-forward: %v", attempt, err) + } +} + +// testWorkerTunnelForwardsOnlyToAssignedActor verifies that when a connection +// authenticated with atenet-router's identity reaches the reused worker's +// atunnel, requests targeting the currently assigned actor (attacker) succeed +// while requests targeting the previously assigned actor (victim) are rejected +// with 421 Misdirected Request and X-Ate-Assignment-Stale: true. +func testWorkerTunnelForwardsOnlyToAssignedActor(t *testing.T, ctx context.Context, wt *workerTunnel, attackerActor, victimActor resources.ActorRef) { + t.Helper() + + // Positive control: the currently assigned actor (attacker) is served. + okResp, okBody := wt.doRouterGet(t, ctx, attackerActor) + if okResp.StatusCode != http.StatusOK { + t.Fatalf("control: worker tunnel request for assigned actor %s returned %d (%q), want 200", + attackerActor, okResp.StatusCode, okBody) + } + var gotWhoami whoamiResponse + if err := json.Unmarshal(okBody, &gotWhoami); err != nil || gotWhoami.File != attackerActor.Name { + t.Fatalf("control: worker tunnel /whoami for %s = %+v (err %v), want file=%q", + attackerActor, gotWhoami, err, attackerActor.Name) + } + + // Negative assertion: targeting the previously assigned actor (victim) on + // the same reused worker must be rejected with 421 Misdirected Request. + staleResp, staleBody := wt.doRouterGet(t, ctx, victimActor) + if staleResp.StatusCode != http.StatusMisdirectedRequest { + t.Errorf("worker tunnel request for previous actor %s on reused worker %s/%s returned status %d (body %q), want %d Misdirected Request", + victimActor, wt.workerNS, wt.workerPod, staleResp.StatusCode, staleBody, http.StatusMisdirectedRequest) + } + if got := staleResp.Header.Get(staleAssignmentHeader); got != "true" { + t.Errorf("worker tunnel rejection for %s has %s=%q, want \"true\"", + victimActor, staleAssignmentHeader, got) + } +} + +// diagnoseEgressDNS logs what the sandbox resolves, the egress policy the +// API server holds for the actor, and the worker's atunnel records about the +// policy and DNS, for a fetch that failed to resolve its origin. +func diagnoseEgressDNS(t *testing.T, ctx context.Context, clients *e2e.Clients, rc *e2e.RouterClient, actor resources.ActorRef, echoHost string) { + t.Helper() + for _, host := range []string{ + echoHost, + echoHost + ".cluster.local", + "kubernetes.default.svc.cluster.local", + e2e.ResourceName(installdefaults.RouterServiceName) + "." + e2e.SystemNamespace() + ".svc.cluster.local", + } { + resp, err := rc.Get(ctx, actor, "/lookup?host="+url.QueryEscape(host)) + if err != nil { + t.Logf("diagnose: /lookup %s: %v", host, err) + continue + } + body, _ := io.ReadAll(resp.Body) + resp.Body.Close() + t.Logf("diagnose: /lookup %s -> %d %s", host, resp.StatusCode, strings.TrimSpace(string(body))) + } + policy, err := clients.SubstrateAPI.GetActorEgressPolicy(ctx, &ateapi.GetActorEgressPolicyRequest{Actor: actor.ToObjectRef(), Name: resources.SingletonName}) + if err != nil { + t.Logf("diagnose: GetActorEgressPolicy %s: %v", actor, err) + } else { + t.Logf("diagnose: egress policy of %s: %v", actor, policy) + } + workerNS, workerPod := assignedWorkerPod(t, ctx, clients, actor) + pod, err := clients.K8s.CoreV1().Pods(workerNS).Get(ctx, workerPod, metav1.GetOptions{}) + if err != nil { + t.Logf("diagnose: reading worker pod %s/%s: %v", workerNS, workerPod, err) + return + } + for _, c := range pod.Spec.Containers { + logs, err := clients.K8s.CoreV1().Pods(workerNS).GetLogs(workerPod, &corev1.PodLogOptions{Container: c.Name}).DoRaw(ctx) + if err != nil { + t.Logf("diagnose: logs of %s/%s[%s]: %v", workerNS, workerPod, c.Name, err) + continue + } + for line := range strings.SplitSeq(string(logs), "\n") { + l := strings.ToLower(line) + if strings.Contains(l, "egress policy") || strings.Contains(l, "dns") || strings.Contains(l, "resolv") { + t.Logf("diagnose: worker %s[%s]: %s", workerPod, c.Name, line) + } + } + } +} + +func assignedWorkerPod(t *testing.T, ctx context.Context, clients *e2e.Clients, actor resources.ActorRef) (string, string) { + t.Helper() + resp, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{Actor: actor.ToObjectRef()}) + if err != nil { + t.Fatalf("GetActor %s: %v", actor, err) + } + wa := resp.GetStatus().GetWorkerAssignment() + if wa.GetWorkerNamespace() == "" || wa.GetWorkerPod() == "" { + t.Fatalf("actor %s has no worker pod assignment: %+v", actor, wa) + } + return wa.GetWorkerNamespace(), wa.GetWorkerPod() +} + +func netInfo(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef) netInfoResponse { + t.Helper() + resp, err := rc.Get(ctx, actor, "/netinfo") + if err != nil { + t.Fatalf("GET /netinfo for %s: %v", actor, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET /netinfo for %s: status %d, body %q", actor, resp.StatusCode, body) + } + var out netInfoResponse + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("decoding /netinfo for %s: %v", actor, err) + } + return out +} + +func fetchEchoHeadersWithRetry(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, targetURL string, headers []string) echoFetchResult { + t.Helper() + path := "/fetch?roots=system&url=" + url.QueryEscape(targetURL) + for _, h := range headers { + path += "&header=" + url.QueryEscape(h) + } + deadline := time.Now().Add(30 * time.Second) + var last echoFetchResult + var lastErr error + for { + // A transport error is retried like a 503: right after a resume the + // router's port-forward can reset before the actor answers. + resp, err := rc.Get(ctx, actor, path) + if err != nil { + lastErr = fmt.Errorf("GET %s for %s: %w", path, actor, err) + } else { + body, readErr := io.ReadAll(resp.Body) + resp.Body.Close() + switch { + case readErr != nil: + lastErr = fmt.Errorf("reading %s for %s: %w", path, actor, readErr) + case resp.StatusCode != http.StatusOK: + lastErr = fmt.Errorf("GET %s for %s: status %d, body %q", path, actor, resp.StatusCode, body) + default: + lastErr = nil + if err := json.Unmarshal(body, &last); err != nil { + t.Fatalf("decoding /fetch for %s: %v (body %q)", actor, err, body) + } + if last.Error == "" && last.Status == "200" { + return last + } + } + } + if time.Now().After(deadline) { + if lastErr != nil { + t.Fatalf("%v (still failing after 30s)", lastErr) + } + return last + } + time.Sleep(time.Second) + } +} + +func parseActorJWTClaims(t *testing.T, step, token string) actoridjwt.WireClaims { + t.Helper() + parts := strings.Split(token, ".") + if len(parts) != 3 { + t.Fatalf("%s: malformed JWT %q (want 3 segments)", step, token) + } + headerBytes, err := base64.RawURLEncoding.DecodeString(parts[0]) + if err != nil { + t.Fatalf("%s: decoding JWT header: %v", step, err) + } + var header map[string]any + if err := json.Unmarshal(headerBytes, &header); err != nil { + t.Fatalf("%s: unmarshaling JWT header %q: %v", step, headerBytes, err) + } + payload, err := base64.RawURLEncoding.DecodeString(parts[1]) + if err != nil { + t.Fatalf("%s: decoding JWT payload: %v", step, err) + } + sig, err := base64.RawURLEncoding.DecodeString(parts[2]) + if err != nil || len(sig) == 0 { + t.Fatalf("%s: decoding JWT signature: %v (len %d)", step, err, len(sig)) + } + var claims actoridjwt.WireClaims + if err := json.Unmarshal(payload, &claims); err != nil { + t.Fatalf("%s: unmarshaling JWT claims %q: %v", step, payload, err) + } + return claims +} + +// countEgressGatewayAuthLines counts the Envoy atenet-egress access-log lines +// since `since` that show the gateway authenticated a worker's outbound CONNECT +// tunnel as actor (by its +// spiffe://substrate-actor.local/worker-for-actor// client +// certificate). +func countEgressGatewayAuthLines(t *testing.T, ctx context.Context, clients *e2e.Clients, since metav1.Time, actor resources.ActorRef) int { + t.Helper() + sysNS := e2e.SystemNamespace() + pods, err := clients.K8s.CoreV1().Pods(sysNS).List(ctx, metav1.ListOptions{LabelSelector: "app=atenet-egress"}) + if err != nil { + t.Fatalf("listing atenet-egress pods: %v", err) + } + if len(pods.Items) == 0 { + t.Fatalf("no atenet-egress pods in %s", sysNS) + } + + wantSPIFFE := resources.WorkerForActorSPIFFEID(actor).String() + count := 0 + for _, pod := range pods.Items { + logs, err := clients.K8s.CoreV1().Pods(sysNS).GetLogs(pod.Name, &corev1.PodLogOptions{ + Container: "envoy", + SinceTime: &since, + }).DoRaw(ctx) + if err != nil { + t.Fatalf("reading logs of %s/%s: %v", sysNS, pod.Name, err) + } + for line := range strings.SplitSeq(string(logs), "\n") { + if strings.Contains(line, "[egress] ") && strings.Contains(line, wantSPIFFE) { + count++ + } + } + } + return count +} + +// waitForNewEgressGatewayAuthLine waits until the gateway has logged more +// lines authenticating actor than the before lines counted ahead of the +// request under test. The access log carries nothing that identifies a single +// request, so a line the gateway logs late for an earlier request of the same +// actor still counts; taking the count right before each request keeps that +// window as small as the log allows. +func waitForNewEgressGatewayAuthLine(t *testing.T, ctx context.Context, clients *e2e.Clients, since metav1.Time, actor resources.ActorRef, before int) { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + if countEgressGatewayAuthLines(t, ctx, clients, since, actor) > before { + return + } + if time.Now().After(deadline) { + t.Fatalf("timed out waiting for a new atenet-egress access log line authenticating %s (%s); %d such lines before the request and none since", + actor, resources.WorkerForActorSPIFFEID(actor), before) + } + time.Sleep(time.Second) + } +} + +func portForwardWorkerTunnel(t *testing.T, ctx context.Context, clients *e2e.Clients, workerNS, workerPod string) (int, func()) { + t.Helper() + config, err := ateclient.LoadKubeConfig(e2e.KubeConfig, e2e.KubeContext) + if err != nil { + t.Fatalf("loading kubeconfig for worker port-forward: %v", err) + } + localPort, stop, err := portforward.PodPortForward(ctx, config, clients.K8s, workerNS, workerPod, 443) + if err != nil { + t.Fatalf("port-forwarding to %s/%s:443: %v", workerNS, workerPod, err) + } + return localPort, stop +} + +func podIdentityCA(t *testing.T, ctx context.Context, clients *e2e.Clients) (*localca.CA, *x509.CertPool) { + t.Helper() + secret, err := clients.K8s.CoreV1().Secrets(podIdentityCANamespace).Get(ctx, podIdentityCASecret, metav1.GetOptions{}) + if err != nil { + t.Fatalf("reading pod-identity CA secret %s/%s: %v", podIdentityCANamespace, podIdentityCASecret, err) + } + pool, err := localca.Unmarshal(secret.Data[podIdentityCASecretKey]) + if err != nil { + t.Fatalf("parsing pod-identity CA pool: %v", err) + } + if len(pool.CAs) == 0 { + t.Fatalf("pod-identity CA pool %s/%s is empty", podIdentityCANamespace, podIdentityCASecret) + } + roots := x509.NewCertPool() + for _, ca := range pool.CAs { + roots.AddCert(ca.RootCertificate) + } + return pool.CAs[0], roots +} + +func mintPodIdentityCertificate(t *testing.T, ca *localca.CA, spiffeID string) tls.Certificate { + t.Helper() + uri, err := url.Parse(spiffeID) + if err != nil { + t.Fatalf("parsing SPIFFE ID %q: %v", spiffeID, err) + } + key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) + if err != nil { + t.Fatalf("generating ECDSA key: %v", err) + } + tmpl := &x509.Certificate{ + URIs: []*url.URL{uri}, + NotBefore: time.Now().Add(-5 * time.Minute), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageDigitalSignature, + ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageClientAuth, x509.ExtKeyUsageServerAuth}, + BasicConstraintsValid: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, ca.RootCertificate, key.Public(), ca.SigningKey) + if err != nil { + t.Fatalf("signing pod-identity certificate for %s: %v", spiffeID, err) + } + return tls.Certificate{ + Certificate: [][]byte{der}, + PrivateKey: key, + } +} + +// newWorkerTunnelClient builds an HTTPS client that connects to a port-forwarded +// worker atunnel listener, presenting clientCert and verifying that the server +// certificate chains to the cluster's pod-identity CA pool. +func newWorkerTunnelClient(roots *x509.CertPool, clientCert tls.Certificate) *http.Client { + return &http.Client{ + Timeout: 10 * time.Second, + Transport: &http.Transport{ + TLSClientConfig: &tls.Config{ + MinVersion: tls.VersionTLS13, + Certificates: []tls.Certificate{clientCert}, + // Port-forwarding connects via 127.0.0.1 while the worker's + // pod-identity certificate carries its SPIFFE URI SAN; verify + // the chain against the pod-identity CA pool explicitly. + InsecureSkipVerify: true, + VerifyPeerCertificate: func(rawCerts [][]byte, _ [][]*x509.Certificate) error { + certs := make([]*x509.Certificate, len(rawCerts)) + for i, asn1Data := range rawCerts { + cert, err := x509.ParseCertificate(asn1Data) + if err != nil { + return err + } + certs[i] = cert + } + intermediates := x509.NewCertPool() + for _, cert := range certs[1:] { + intermediates.AddCert(cert) + } + _, err := certs[0].Verify(x509.VerifyOptions{ + Roots: roots, + Intermediates: intermediates, + KeyUsages: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, + }) + return err + }, + }, + }, + } +} diff --git a/internal/e2e/suites/security/concurrent_isolation_test.go b/internal/e2e/suites/security/concurrent_isolation_test.go new file mode 100644 index 0000000000..3f68d8801a --- /dev/null +++ b/internal/e2e/suites/security/concurrent_isolation_test.go @@ -0,0 +1,428 @@ +// Copyright 2026 The Agent Substrate 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. +// +// This file covers security invariants that require TWO actors running at the +// same time on distinct worker pods (replicas: 2 in the WorkerPool) to verify +// space invariance. +package security + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net" + "net/http" + "net/url" + "strconv" + "strings" + "sync" + "testing" + "time" + + "go.ate.dev/substrate/api/ateapi/v1" + "go.ate.dev/substrate/internal/e2e" + "go.ate.dev/substrate/internal/resources" + metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" +) + +const ( + markerConcurrentA = dataMount + "/concurrent-marker-a" + markerConcurrentB = dataMount + "/concurrent-marker-b" + + // concurrentPool is the WorkerPool concurrent-a-pool.yaml.tmpl deploys, and + // concurrentPoolReplicas its replicas. Keep both in sync with the manifest. + concurrentPool = "concurrent" + concurrentPoolReplicas = 2 +) + +type fetchResponse struct { + Status string `json:"status"` + Body string `json:"body"` + Error string `json:"error"` +} + +// TestConcurrentActorIsolation tests space invariants between two actors +// running concurrently on two distinct worker pods. +func TestConcurrentActorIsolation(t *testing.T) { + if _, err := e2e.CheckEnv("KO_DOCKER_REPO"); err != nil { + t.Fatalf("CheckEnv failed: %v", err) + } + ctx := context.Background() + clients := e2e.GetClients() + + ns := deployConcurrentAtespaces(t, ctx, clients) + + rc, err := e2e.NewRouterClient(t, ctx) + if err != nil { + t.Fatalf("NewRouterClient: %v", err) + } + defer rc.Close() + + // Both actors share the same name ("actor-a") in their respective + // atespaces so the router must disambiguate live concurrent actors by + // (atespace, actor) rather than actor name alone. + const actorName = "actor-a" + + // The fixture is ready as soon as one worker has built the golden + // snapshot. A worker hosts many actors, so if the second worker has not + // registered yet, both actors land on the first. Wait for both workers: + // the scheduler then places the second actor on the idle one. + waitForActiveWorkers(t, ctx, clients, ns.a, concurrentPool, concurrentPoolReplicas) + + createAndResumeActor(t, ctx, clients, ns.a, actorName) + createAndResumeActor(t, ctx, clients, ns.b, actorName) + + refA := resources.ActorRef{Atespace: ns.a, Name: actorName} + refB := resources.ActorRef{Atespace: ns.b, Name: actorName} + + uidA := actorUID(t, ctx, clients, ns.a, actorName) + uidB := actorUID(t, ctx, clients, ns.b, actorName) + if uidA == uidB { + t.Fatalf("actors %s and %s were assigned the same UID %q", refA, refB, uidA) + } + + workerA := assignedWorker(t, ctx, clients, ns.a, actorName) + workerB := assignedWorker(t, ctx, clients, ns.b, actorName) + + if workerA == workerB { + t.Fatalf("actors landed on the same worker (%s); pool has replicas: 2, want distinct workers to test space isolation", workerA) + } + t.Logf("actor %s (uid %s) running on worker %s; actor %s (uid %s) running on worker %s", + refA, uidA, workerA, refB, uidB, workerB) + + // NW-6 [space]: while two identically named actors are concurrently live in + // different atespaces on distinct workers, the ingress router must deliver + // each request to the actor in the atespace named in the request. + t.Run("RouterDeliversOnlyToNamedActorInSpace", func(t *testing.T) { + t.Log("The router must deliver a request only to the actor and atespace named in the request (T-14)") + + gotA := whoami(t, ctx, rc, refA) + if gotA.Atespace != ns.a || gotA.File != actorName || gotA.UID != uidA { + t.Fatalf("router delivered %s /whoami = %+v, want atespace=%q file=%q uid=%q", + refA, gotA, ns.a, actorName, uidA) + } + + gotB := whoami(t, ctx, rc, refB) + if gotB.Atespace != ns.b || gotB.File != actorName || gotB.UID != uidB { + t.Fatalf("router delivered %s /whoami = %+v, want atespace=%q file=%q uid=%q", + refB, gotB, ns.b, actorName, uidB) + } + + // Parallel concurrent routing: fire simultaneous requests to both + // same-named actors to verify no crosstalk under concurrent traffic. + const iterations = 10 + errs := make(chan string, iterations*2) + var wg sync.WaitGroup + for i := range iterations { + wg.Add(2) + go func(iter int) { + defer wg.Done() + got, err := tryWhoami(ctx, rc, refA) + if err != nil { + errs <- fmt.Sprintf("iter %d: parallel whoami for %s failed: %v", iter, refA, err) + return + } + if got.Atespace != ns.a || got.File != actorName || got.UID != uidA { + errs <- fmt.Sprintf("iter %d: parallel whoami for %s delivered wrong actor %+v, want atespace=%q file=%q uid=%q", + iter, refA, got, ns.a, actorName, uidA) + } + }(i) + go func(iter int) { + defer wg.Done() + got, err := tryWhoami(ctx, rc, refB) + if err != nil { + errs <- fmt.Sprintf("iter %d: parallel whoami for %s failed: %v", iter, refB, err) + return + } + if got.Atespace != ns.b || got.File != actorName || got.UID != uidB { + errs <- fmt.Sprintf("iter %d: parallel whoami for %s delivered wrong actor %+v, want atespace=%q file=%q uid=%q", + iter, refB, got, ns.b, actorName, uidB) + } + }(i) + } + wg.Wait() + close(errs) + for msg := range errs { + t.Errorf("%s", msg) + } + }) + + // NW-2 [space]: an actor must not open a connection directly to another + // actor across the pod network. The worker pool's NetworkPolicy admits + // ingress only from atenet-router. + t.Run("DirectActorToActorTrafficBlocked", func(t *testing.T) { + t.Log("An actor must not open a connection directly to another actor (T-17)") + + // Actors have egress denied by default. Grant actor A an allow-all + // EgressPolicy and verify with a positive control that actor A can + // reach an in-cluster HTTP server through egress, so that failure to + // reach worker B is attributable to the worker NetworkPolicy rather + // than egress being off. + // + // The control is a pod in the worker pods' own namespace, dialed by + // pod IP exactly as worker B is below. The worker NetworkPolicy + // selects pods by their ate.dev/worker-pool label, which this pod + // does not carry, so that policy is the one difference between the + // dial that must succeed and the dials that must not. + e2e.EnsureEgressPolicy(t, ctx, clients, &ateapi.ObjectRef{Atespace: ns.a, Name: actorName}, e2e.EgressAllowAll()...) + + const controlName, controlPort = "egress-control", 8080 + e2e.DeployServerPod(t, ctx, e2e.ServerPod{ + Name: controlName, + Namespace: ns.a, + ImportPath: "go.ate.dev/substrate/internal/e2e/fixtures/testserver", + Args: []string{"http"}, + Port: 80, + TargetPort: controlPort, + }) + controlPod, err := clients.K8s.CoreV1().Pods(ns.a).Get(ctx, controlName, metav1.GetOptions{}) + if err != nil { + t.Fatalf("getting control pod %s/%s: %v", ns.a, controlName, err) + } + if controlPod.Status.PodIP == "" { + t.Fatalf("control pod %s/%s has no PodIP", ns.a, controlName) + } + controlURL := fmt.Sprintf("http://%s/healthz", net.JoinHostPort(controlPod.Status.PodIP, strconv.Itoa(controlPort))) + controlResp := probeFetchUntilReached(t, ctx, rc, refA, controlURL) + if controlResp.Error != "" || controlResp.Status != "200" { + t.Fatalf("control: actor %s egress fetch to %s = %+v, want status 200 and no error — actor egress is not working, so the worker-pod dial check below would be vacuous", + refA, controlURL, controlResp) + } + + // Positive control on actor B: confirm worker B is live and serving + // actor B through the authorized ingress path (atenet-router). + if gotB := whoami(t, ctx, rc, refB); gotB.UID != uidB { + t.Fatalf("control: actor %s /whoami through router = %+v, want uid=%q", refB, gotB, uidB) + } + + workerPodIP_B := getWorkerPodIP(t, ctx, clients, ns.b, actorName) + t.Logf("discovered worker B pod IP: %s", workerPodIP_B) + + // Worker pods listen on 443 (atunnel HTTPS), 8443 (atunnel CONNECT), + // and 8080 (ateworker /readyz); see buildDeploymentApplyConfig in + // cmd/atecontroller/internal/controllers/workerpool_apply.go. + // Dial all three over cleartext HTTP so atenet-egress matches + // EgressAllowAll()'s all-ports HttpRule on the IP literal and attempts + // a TCP connection to workerPodIP_B: on the pod network (an + // https:// request to an IP literal carries no SNI per RFC 6066 and + // would be rejected at atenet-egress before any packet is sent toward + // worker B). + for _, port := range []int{443, 8443, 8080} { + targetURL := fmt.Sprintf("http://%s/readyz", net.JoinHostPort(workerPodIP_B, strconv.Itoa(port))) + got := probeFetch(t, ctx, rc, refA, targetURL) + if !isBlockedWorkerDial(got) { + t.Errorf("actor %s reached worker B at %s (status %q, body %q, error %q) — NetworkPolicy did not block traffic to worker B across the pod network", + refA, targetURL, got.Status, got.Body, got.Error) + } else { + t.Logf("actor %s dial to %s blocked as expected (status=%q error=%q body=%q)", + refA, targetURL, got.Status, got.Error, got.Body) + } + } + }) + + // ST-1 [space]: while two actors run concurrently in space, their + // durable-dir mounts must be strictly isolated. + t.Run("ConcurrentDurableMountIsolation", func(t *testing.T) { + t.Log("Two concurrent actors must not read or write each other's durable-dir volume") + + // Controls. /readfile has to report a missing file as an error, or + // the cross-reads below pass on anything; and each actor has to see + // the file it wrote itself. + for _, ref := range []resources.ActorRef{refA, refB} { + if got := readFile(t, ctx, rc, ref, neverWritten); got.Error == "" { + t.Fatalf("control: actor %s read %s, which nothing ever created, and reported no error (content %q) — /readfile does not report misses as errors, so the negative assertions here would pass vacuously", + ref, neverWritten, got.Content) + } + } + + writeFile(t, ctx, rc, refA, markerConcurrentA) + writeFile(t, ctx, rc, refB, markerConcurrentB) + + if got := readFile(t, ctx, rc, refA, markerConcurrentA); got.Content != markerContent(refA) { + t.Fatalf("control: actor %s reading its OWN %s = %q (error %q), want %q", + refA, markerConcurrentA, got.Content, got.Error, markerContent(refA)) + } + if got := readFile(t, ctx, rc, refB, markerConcurrentB); got.Content != markerContent(refB) { + t.Fatalf("control: actor %s reading its OWN %s = %q (error %q), want %q", + refB, markerConcurrentB, got.Content, got.Error, markerContent(refB)) + } + + if got := readFile(t, ctx, rc, refA, markerConcurrentB); got.Error == "" { + t.Errorf("actor %s read %s, belonging to concurrent actor %s: content %q — durable-dir volume isolation failed in space", + refA, markerConcurrentB, refB, got.Content) + } + if got := readFile(t, ctx, rc, refB, markerConcurrentA); got.Error == "" { + t.Errorf("actor %s read %s, belonging to concurrent actor %s: content %q — durable-dir volume isolation failed in space", + refB, markerConcurrentA, refA, got.Content) + } + }) +} + +func deployConcurrentAtespaces(t *testing.T, ctx context.Context, clients *e2e.Clients) atespaces { + t.Helper() + a, _ := e2e.DeploySubstrateFixture(t, ctx, clients, e2e.SubstrateFixtureManifests{ + Pool: "internal/e2e/fixtures/security/concurrent-a-pool.yaml.tmpl", + Template: "internal/e2e/fixtures/security/concurrent-template.yaml.tmpl", + }, "sec-conc-a", nil) + b, _ := e2e.DeploySubstrateFixture(t, ctx, clients, e2e.SubstrateFixtureManifests{ + Pool: "internal/e2e/fixtures/security/concurrent-b-namespace.yaml.tmpl", + Template: "internal/e2e/fixtures/security/concurrent-template.yaml.tmpl", + }, "sec-conc-b", nil) + if a == b { + t.Fatalf("both fixtures rendered to atespace %q", a) + } + return atespaces{a: a, b: b} +} + +// waitForActiveWorkers blocks until pool in namespace has at least want +// workers registered and ACTIVE, the state the scheduler places actors on. +func waitForActiveWorkers(t *testing.T, ctx context.Context, clients *e2e.Clients, namespace, pool string, want int) { + t.Helper() + const timeout = 2 * time.Minute + ctx, cancel := context.WithTimeout(ctx, timeout) + defer cancel() + + for { + var states []string + active := 0 + resp, err := clients.SubstrateAPI.ListWorkers(ctx, &ateapi.ListWorkersRequest{}) + if err == nil { + for _, w := range resp.GetWorkers() { + if w.GetWorkerNamespace() != namespace || w.GetWorkerPool() != pool { + continue + } + state := w.GetStatus().GetState() + states = append(states, fmt.Sprintf("%s=%v", w.GetWorkerPod(), state)) + if state == ateapi.WorkerState_WORKER_STATE_ACTIVE { + active++ + } + } + if active >= want { + t.Logf("pool %s/%s has %d ACTIVE workers: %v", namespace, pool, active, states) + return + } + } + select { + case <-ctx.Done(): + t.Fatalf("timed out after %v waiting for pool %s/%s to have %d ACTIVE workers (workers %v, err %v)", + timeout, namespace, pool, want, states, err) + case <-time.After(500 * time.Millisecond): + } + } +} + +func getWorkerPodIP(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, actorName string) string { + t.Helper() + actor, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{ + Actor: &ateapi.ObjectRef{Atespace: atespace, Name: actorName}, + }) + if err != nil { + t.Fatalf("GetActor %s/%s: %v", atespace, actorName, err) + } + wa := actor.GetStatus().GetWorkerAssignment() + if wa == nil || wa.GetWorkerPod() == "" || wa.GetWorkerNamespace() == "" { + t.Fatalf("actor %s/%s has no worker assignment: %+v", atespace, actorName, actor.GetStatus()) + } + pod, err := clients.K8s.CoreV1().Pods(wa.GetWorkerNamespace()).Get(ctx, wa.GetWorkerPod(), metav1.GetOptions{}) + if err != nil { + t.Fatalf("getting worker pod %s/%s: %v", wa.GetWorkerNamespace(), wa.GetWorkerPod(), err) + } + if pod.Status.PodIP == "" { + t.Fatalf("worker pod %s/%s has no PodIP", wa.GetWorkerNamespace(), wa.GetWorkerPod()) + } + return pod.Status.PodIP +} + +// tryWhoami calls the probe's /whoami endpoint and returns an error instead of +// calling t.Fatalf, making it safe to call from child goroutines. +func tryWhoami(ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef) (whoamiResponse, error) { + resp, err := rc.Get(ctx, actor, "/whoami") + if err != nil { + return whoamiResponse{}, fmt.Errorf("GET /whoami for %s: %w", actor, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + return whoamiResponse{}, fmt.Errorf("GET /whoami for %s: status %d, body %q", actor, resp.StatusCode, body) + } + var out whoamiResponse + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + return whoamiResponse{}, fmt.Errorf("decoding /whoami for %s: %w", actor, err) + } + return out, nil +} + +// probeFetch asks actor's probe to fetch targetURL using system roots (the +// security fixture template does not mount the MITM egress trust bundle). +func probeFetch(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, targetURL string) fetchResponse { + t.Helper() + endpoint := "/fetch?roots=system&url=" + url.QueryEscape(targetURL) + resp, err := rc.Get(ctx, actor, endpoint) + if err != nil { + t.Fatalf("GET %s for %s: %v", endpoint, actor, err) + } + defer resp.Body.Close() + if resp.StatusCode != http.StatusOK { + body, _ := io.ReadAll(resp.Body) + t.Fatalf("GET %s for %s: status %d, body %q", endpoint, actor, resp.StatusCode, body) + } + var out fetchResponse + if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { + t.Fatalf("decoding %s for %s: %v", endpoint, actor, err) + } + return out +} + +// probeFetchUntilReached retries probeFetch until it returns 200 OK or the +// 30s deadline expires, riding out initial service endpoint or policy +// propagation. +func probeFetchUntilReached(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, targetURL string) fetchResponse { + t.Helper() + deadline := time.Now().Add(30 * time.Second) + for { + got := probeFetch(t, ctx, rc, actor, targetURL) + if (got.Error == "" && got.Status == "200") || time.Now().After(deadline) { + return got + } + time.Sleep(time.Second) + } +} + +// isBlockedWorkerDial reports whether a probeFetch result shows that the +// outbound connection to the worker pod was blocked before reaching any +// listener on the worker. +// +// Actor TCP egress traverses atunnel -> atenet-egress, where Envoy terminates +// the downstream HTTP connection and dials the target IP:port upstream. When +// the worker's NetworkPolicy drops the SYN packets from atenet-egress, Envoy's +// upstream dial times out and returns HTTP 503 ("connection timeout" / +// "upstream connect error"). If the gateway takes longer than the probe's own +// client timeout to give up, the probe reports that timeout as an error +// instead. Any other probe error is not evidence of the block: a refused or +// reset connection, or a failure on the way to the gateway, is an unrelated +// fault and must not pass for the NetworkPolicy. By contrast, if the packet +// reaches the worker pod, port 8080 (/readyz) returns 200 and ports 443/8443 +// (atunnel TLS listeners) return 400 ("Client sent an HTTP request to an +// HTTPS server"). +func isBlockedWorkerDial(got fetchResponse) bool { + if got.Error != "" { + return strings.Contains(got.Error, "context deadline exceeded") || strings.Contains(got.Error, "Client.Timeout") + } + if (got.Status == "502" || got.Status == "503" || got.Status == "504") && + (strings.Contains(got.Body, "connection timeout") || strings.Contains(got.Body, "upstream connect error")) { + return true + } + return false +} diff --git a/internal/e2e/suites/security/crossatespace_test.go b/internal/e2e/suites/security/crossatespace_test.go index 9e71d141a6..faffefe665 100644 --- a/internal/e2e/suites/security/crossatespace_test.go +++ b/internal/e2e/suites/security/crossatespace_test.go @@ -12,88 +12,35 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package security holds the end-to-end tests for Substrate's security -// boundaries. Every assertion here is negative: something must not be -// possible. Each is paired with a positive control showing the probe could -// have seen the violation, because a negative test that stops exercising its -// boundary keeps passing. -// -// This file covers the boundary between two atespaces whose actors are -// identical except for the atespace they run in. The victim actor runs, writes -// state, and vacates its worker; the attacker actor, in the other atespace, -// then reuses that worker and must find none of it. A single-worker pool -// (fixtures/security/atespace-a-pool.yaml.tmpl) forces the reuse, and the test -// checks that it happened. +// This file covers security invariants that specifically depend on the +// boundary between two distinct atespaces (for actor-level isolation within a +// single atespace, see actor_isolation_test.go). package security import ( "context" - "encoding/json" - "io" - "net/http" - "net/url" - "path/filepath" "strings" "testing" - "time" "go.ate.dev/substrate/api/ateapi/v1" "go.ate.dev/substrate/internal/e2e" - "go.ate.dev/substrate/internal/nodepath" "go.ate.dev/substrate/internal/resources" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" ) const ( - // templateName is the ActorTemplate name both atespaces deploy. - templateName = "probe" - - // dataMount is where atespace-template.yaml.tmpl mounts the durable-dir - // volume, and durableVolume is that volume's name, which is also the last - // segment of its mount point on the worker. Keep both in sync with the - // manifest. - dataMount = "/data" - durableVolume = "data" - - // writtenByProbe is the fixed body the probe's /writefile endpoint writes. - // Actors are told apart by the path they write, not by the content. - writtenByProbe = "written by probe" - - // markerA and markerB are named for the atespace that owns them, so a file - // seen across the boundary is attributable. + // markerA is written by the actor in atespace A to verify that a same-atespace + // clone restored from atespace-a-tag carries the source actor's durable data. markerA = dataMount + "/atespace-a-marker" - markerB = dataMount + "/atespace-b-marker" - - // neverWritten is a path no actor creates. Reading it proves /readfile - // reports a missing file as an error, which every negative assertion in - // this file relies on. - neverWritten = dataMount + "/never-written" ) -// fileResponse mirrors the probe's /readfile and /writefile responses. -type fileResponse struct { - Path string `json:"path"` - Content string `json:"content"` - OK string `json:"ok"` - Error string `json:"error"` -} - // atespaces is the pair of atespaces under test. type atespaces struct { a, b string } -// TestCrossAtespaceIsolation checks that the atespace boundary holds across -// worker reuse for an actor's stored data and its snapshots. -// -// The victim, in atespace B, runs, writes its durable marker, and is -// suspended. The attacker, in atespace A, then starts on the worker the victim -// left and must find none of its state. -// -// The fixture is deployed once for the whole test. Deploying waits for each -// atespace's golden snapshot, which on the micro-VM lane is a cold boot plus a -// checkpoint, so per-subtest fixtures would dominate the runtime. +// TestCrossAtespaceIsolation validates isolation between two atespaces. func TestCrossAtespaceIsolation(t *testing.T) { if _, err := e2e.CheckEnv("KO_DOCKER_REPO"); err != nil { t.Fatalf("CheckEnv failed: %v", err) @@ -109,125 +56,34 @@ func TestCrossAtespaceIsolation(t *testing.T) { } defer rc.Close() - // Victim: the actor in atespace B runs first. Its UID and worker are recorded while it is - // RUNNING: the attacker probes host paths keyed by that UID and must land - // on that worker. - const victim = "victim" - createAndResumeActor(t, ctx, clients, ns.b, victim) - victimActor := resources.ActorRef{Atespace: ns.b, Name: victim} - victimUID := actorUID(t, ctx, clients, ns.b, victim) - victimWorker := assignedWorker(t, ctx, clients, ns.b, victim) - - writeFile(t, ctx, rc, victimActor, markerB) - // Control: the victim reads back its own marker, so the attacker's failure - // to read it below means the boundary held, not that the marker was never - // written. - if got := readFile(t, ctx, rc, victimActor, markerB); got.Content != writtenByProbe { - t.Fatalf("control: victim %s reading its OWN %s = %q (error %q), want %q — the probe cannot see its own durable data, so nothing below is meaningful", - victimActor, markerB, got.Content, got.Error, writtenByProbe) - } + const source = "actor-a" + createAndResumeActor(t, ctx, clients, ns.a, source) + sourceActor := resources.ActorRef{Atespace: ns.a, Name: source} - // Suspend the victim to free the worker. The durable marker stays on the - // worker; the snapshot goes to object storage. - if _, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: ns.b, Name: victim}, - }); err != nil { - t.Fatalf("SuspendActor %s/%s: %v", ns.b, victim, err) + writeFile(t, ctx, rc, sourceActor, markerA) + if got := readFile(t, ctx, rc, sourceActor, markerA); got.Content != markerContent(sourceActor) { + t.Fatalf("control: actor %s reading its OWN %s = %q (error %q), want %q", + sourceActor, markerA, got.Content, got.Error, markerContent(sourceActor)) } - waitForActorState(t, ctx, clients, ns.b, victim, ateapi.ActorState_ACTOR_STATE_SUSPENDED) - // Attacker: the actor in atespace A takes the freed worker. - const attacker = "attacker" - createAndResumeActor(t, ctx, clients, ns.a, attacker) - attackerActor := resources.ActorRef{Atespace: ns.a, Name: attacker} - requireReusedWorker(t, ctx, clients, ns.a, attacker, victimWorker) - - // Controls for every negative assertion below. A failure is fatal: the - // probe cannot tell a denial from a missing file, so the subtests would - // pass for the wrong reason. - if got := readFile(t, ctx, rc, attackerActor, neverWritten); got.Error == "" { - t.Fatalf("control: attacker %s read %s, which nothing ever created, and reported no error (content %q) — /readfile does not report misses as errors, so every negative assertion here would pass vacuously", - attackerActor, neverWritten, got.Content) - } - writeFile(t, ctx, rc, attackerActor, markerA) - if got := readFile(t, ctx, rc, attackerActor, markerA); got.Content != writtenByProbe { - t.Fatalf("control: attacker %s reading its OWN %s = %q (error %q), want %q — the probe cannot see its own durable data", - attackerActor, markerA, got.Content, got.Error, writtenByProbe) - } - - // Durable mount: the attacker's /data must be its own. The victim's - // marker is known to exist, so reading it through the attacker's mount - // means durable directories are shared or mis-keyed across reuse. - t.Run("VictimDurableMarkerNotVisibleThroughAttackerMount", func(t *testing.T) { - if got := readFile(t, ctx, rc, attackerActor, markerB); got.Error == "" { - t.Errorf("attacker %s read %s, the victim's durable marker in atespace %s, through its own mount: content %q — durable-dir volumes are shared across the worker-reuse boundary", - attackerActor, markerB, ns.b, got.Content) - } - }) - - // Host state: the mount is confined (above); this checks the sandbox - // does not expose the host directories that mount is built from. The paths - // come from internal/nodepath so they move with the worker layout; see - // actorHostPath. - t.Run("VictimHostStateNotReachableFromAttackerSandbox", func(t *testing.T) { - for _, probe := range []struct { - what string - path string - }{ - {"the victim's durable marker on the host", actorHostPath(victimUID, "durable-dir", durableVolume, filepath.Base(markerB))}, - {"the victim's projected actor identity", actorHostPath(victimUID, "system-info", "system-info", "actor-id")}, - {"the victim's sandbox asset record", actorHostPath(victimUID, "sandbox-assets.json")}, - } { - if got := readFile(t, ctx, rc, attackerActor, probe.path); got.Error == "" { - t.Errorf("attacker %s read %s (%s): content %q — the sandbox exposes the worker's per-actor host state across the reuse boundary", - attackerActor, probe.path, probe.what, got.Content) - } - } - - // A write is the more serious direction of the same boundary: reaching the - // victim's durable directory means an actor can corrupt another atespace's data. - injected := actorHostPath(victimUID, "durable-dir", durableVolume, "injected") - if got := writeFileAllowingFailure(t, ctx, rc, attackerActor, injected); got.Error == "" { - t.Errorf("attacker %s wrote %s, inside the victim's durable directory (atespace %s) on the worker — an actor can corrupt another atespace's stored data", - attackerActor, injected, ns.b) - } - }) - - // Tag scope. Runs last: it suspends the attacker to snapshot it. + // ST-4 [space]: an ATESPACE-scoped tag in atespace A must not seed an + // actor in atespace B. Suspends `source` to snapshot it. t.Run("TagScopedToAtespaceCannotSeedAnotherAtespace", func(t *testing.T) { - testTagScopeBoundary(t, ctx, clients, rc, ns, attacker) + t.Log("Invariant ST-4 [space]: A snapshot must not seed an actor in another atespace unless the tag is published") + testTagScopeBoundary(t, ctx, clients, rc, ns, source) }) } -// actorHostPath is nodepath.ActorsDir// on the worker host. The -// leaves (durable-dir, system-info, sandbox-assets.json) mirror -// cmd/atelet/internal/ateletpath, which this suite cannot import. -func actorHostPath(actorUID string, elem ...string) string { - return filepath.Join(append([]string{nodepath.ActorsDir, actorUID}, elem...)...) -} - // testTagScopeBoundary checks that an Actor cannot be seeded from a snapshot -// taken in another atespace. A snapshot carries the source's memory, root filesystem -// and durable data, so loading one across the boundary hands over everything. -// -// Substrate enforces this through the Tag's scope in ateapi's CreateActor. The -// negative case matches the error message, not just the code. +// taken in another atespace. // // source is a running actor in atespace A holding markerA; it is suspended here // to produce the snapshot the tag captures. func testTagScopeBoundary(t *testing.T, ctx context.Context, clients *e2e.Clients, rc *e2e.RouterClient, ns atespaces, source string) { t.Helper() - suspended, err := clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: ns.a, Name: source}, - Options: &ateapi.SuspendOptions{Mode: ateapi.DurabilityMode_DURABILITY_MODE_SYNCHRONOUS}, - }) - if err != nil { - t.Fatalf("SuspendActor %s/%s: %v", ns.a, source, err) - } - if durableSnapshotURI(suspended.GetActor().GetStatus()) == "" { - t.Fatalf("suspended actor %s/%s has no external snapshot, so there is nothing for a tag to capture", ns.a, source) - } + // The tag needs a durable snapshot to capture. + suspendDurably(t, ctx, clients, ns.a, source) tagRef := &ateapi.ObjectRef{Atespace: ns.a, Name: "atespace-a-tag"} t.Cleanup(func() { @@ -296,9 +152,10 @@ func testTagScopeBoundary(t *testing.T, ctx context.Context, clients *e2e.Client t.Fatalf("control: ResumeActor %s/%s: %v", ns.a, clone, err) } waitForActorState(t, ctx, clients, ns.a, clone, ateapi.ActorState_ACTOR_STATE_RUNNING) - if got := readFile(t, ctx, rc, resources.ActorRef{Atespace: ns.a, Name: clone}, markerA); got.Content != writtenByProbe { + sourceContent := markerContent(resources.ActorRef{Atespace: ns.a, Name: source}) + if got := readFile(t, ctx, rc, resources.ActorRef{Atespace: ns.a, Name: clone}, markerA); got.Content != sourceContent { t.Fatalf("control: actor %s/%s restored from tag %s reads %s = %q (error %q), want %q — the tag carries no durable data, so the cross-atespace rejection above proves nothing", - ns.a, clone, tagRef.GetName(), markerA, got.Content, got.Error, writtenByProbe) + ns.a, clone, tagRef.GetName(), markerA, got.Content, got.Error, sourceContent) } } @@ -320,154 +177,3 @@ func deployAtespaces(t *testing.T, ctx context.Context, clients *e2e.Clients) at } return atespaces{a: a, b: b} } - -// requireReusedWorker fails unless the actor landed on priorWorker. The fixture -// runs one worker for both atespaces, so any other worker means the attacker never -// touched the host the victim left its state on and the test proves nothing. -func requireReusedWorker(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name, priorWorker string) { - t.Helper() - got := assignedWorker(t, ctx, clients, atespace, name) - if got != priorWorker { - t.Fatalf("actor %s/%s landed on worker %q, not the worker %q the victim vacated; the fixture deploys one worker for both atespaces, so the reuse boundary under test is not being exercised", - atespace, name, got, priorWorker) - } - t.Logf("actor %s/%s reused worker %s", atespace, name, priorWorker) -} - -func assignedWorker(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string) string { - t.Helper() - actor, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: atespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor %s/%s: %v", atespace, name, err) - } - worker := actor.GetStatus().GetWorkerAssignment().GetWorker().GetName() - if worker == "" { - t.Fatalf("actor %s/%s has no worker assignment while RUNNING", atespace, name) - } - return worker -} - -func actorUID(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string) string { - t.Helper() - actor, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: atespace, Name: name}, - }) - if err != nil { - t.Fatalf("GetActor %s/%s: %v", atespace, name, err) - } - uid := actor.GetMetadata().GetUid() - if uid == "" { - t.Fatalf("actor %s/%s has no uid", atespace, name) - } - return uid -} - -// createAndResumeActor creates an actor from its atespace's template and resumes -// it from the golden snapshot, removing it when the test ends. -func createAndResumeActor(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string) { - t.Helper() - ref := &ateapi.ObjectRef{Atespace: atespace, Name: name} - // Actor records outlive the fixture namespace, so an interrupted run can - // leave one behind and wedge reruns on AlreadyExists. DeleteActor needs - // SUSPENDED or CRASHED, hence the suspend; both are best-effort. - _, _ = clients.SubstrateAPI.SuspendActor(ctx, &ateapi.SuspendActorRequest{Actor: ref}) - _, _ = clients.SubstrateAPI.DeleteActor(ctx, &ateapi.DeleteActorRequest{Actor: ref}) - if _, err := clients.SubstrateAPI.CreateActor(ctx, &ateapi.CreateActorRequest{Actor: &ateapi.Actor{ - Metadata: &ateapi.ResourceMetadata{Atespace: atespace, Name: name}, - ActorTemplate: &ateapi.ObjectRef{Atespace: atespace, Name: templateName}, - }}); err != nil { - t.Fatalf("CreateActor %s/%s: %v", atespace, name, err) - } - t.Cleanup(func() { - cleanupCtx := context.Background() - _, _ = clients.SubstrateAPI.SuspendActor(cleanupCtx, &ateapi.SuspendActorRequest{Actor: ref}) - if _, err := clients.SubstrateAPI.DeleteActor(cleanupCtx, &ateapi.DeleteActorRequest{Actor: ref}); err != nil { - t.Logf("cleanup: DeleteActor %s/%s failed, actor leaked (remove with: kubectl ate delete actor %s -a %s): %v", atespace, name, name, atespace, err) - } - }) - - if _, err := e2e.ResumeActorAwaitCapacity(t, ctx, clients, &ateapi.ResumeActorRequest{Actor: ref}); err != nil { - t.Fatalf("ResumeActor %s/%s: %v", atespace, name, err) - } - waitForActorState(t, ctx, clients, atespace, name, ateapi.ActorState_ACTOR_STATE_RUNNING) -} - -func waitForActorState(t *testing.T, ctx context.Context, clients *e2e.Clients, atespace, name string, want ateapi.ActorState) { - t.Helper() - deadline := time.Now().Add(60 * time.Second) - for time.Now().Before(deadline) { - resp, err := clients.SubstrateAPI.GetActor(ctx, &ateapi.GetActorRequest{ - Actor: &ateapi.ObjectRef{Atespace: atespace, Name: name}, - }) - if err == nil && resp.GetStatus().GetState() == want { - return - } - time.Sleep(time.Second) - } - t.Fatalf("timed out waiting for actor %s/%s to reach state %v", atespace, name, want) -} - -// writeFile writes the probe's fixed body at path and fails the test if the -// write did not land, so a later negative assertion cannot pass on missing -// state. -func writeFile(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, path string) { - t.Helper() - if got := writeFileAllowingFailure(t, ctx, rc, actor, path); got.OK != "true" { - t.Fatalf("actor %s writing %s: %q", actor, path, got.Error) - } -} - -// writeFileAllowingFailure is writeFile for assertions that expect the write -// to be refused; it returns the probe's report instead of failing. -func writeFileAllowingFailure(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, path string) fileResponse { - t.Helper() - return probeFileOp(t, ctx, rc, actor, "/writefile", path) -} - -func readFile(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, path string) fileResponse { - t.Helper() - return probeFileOp(t, ctx, rc, actor, "/readfile", path) -} - -// probeFileOp calls one of the probe's file endpoints. A transport or HTTP -// failure is fatal rather than returned: the probe never ran the operation, -// which is not the same as the actor being denied. -func probeFileOp(t *testing.T, ctx context.Context, rc *e2e.RouterClient, actor resources.ActorRef, endpoint, path string) fileResponse { - t.Helper() - resp, err := rc.Get(ctx, actor, endpoint+"?path="+url.QueryEscape(path)) - if err != nil { - t.Fatalf("GET %s for %s: %v", endpoint, actor, err) - } - defer resp.Body.Close() - if resp.StatusCode != http.StatusOK { - body, _ := io.ReadAll(resp.Body) - t.Fatalf("GET %s for %s: status %d, body %q", endpoint, actor, resp.StatusCode, body) - } - var out fileResponse - if err := json.NewDecoder(resp.Body).Decode(&out); err != nil { - t.Fatalf("decoding %s for %s: %v", endpoint, actor, err) - } - return out -} - -func durableSnapshotURI(status *ateapi.ActorStatus) string { - var best *ateapi.Snapshot - for _, snap := range status.GetSnapshots() { - if uri := snapshotURI(snap); uri != "" { - if best == nil || snap.GetGeneration() > best.GetGeneration() { - best = snap - } - } - } - return snapshotURI(best) -} - -func snapshotURI(snap *ateapi.Snapshot) string { - st := snap.GetDurableSnapshot() - if st.GetState() == ateapi.SnapshotStorageState_SNAPSHOT_STORAGE_STATE_COMPLETED { - return st.GetObject().GetSnapshotUri() - } - return "" -} diff --git a/internal/egresspolicy/egresspolicy.go b/internal/egresspolicy/egresspolicy.go index 23de4a0e9e..1653681f9e 100644 --- a/internal/egresspolicy/egresspolicy.go +++ b/internal/egresspolicy/egresspolicy.go @@ -27,6 +27,7 @@ import ( "fmt" "net" "net/netip" + "net/url" "slices" "strconv" "strings" @@ -407,6 +408,31 @@ func NormalizeHostname(raw string) (string, bool) { return name, true } +// TokenURLDestination is the hostname and port a token exchange's token_url +// names, the port defaulting to 443. The URL must be https with a DNS +// hostname and no userinfo, query, or fragment. +func TokenURLDestination(raw string) (Destination, bool) { + u, err := url.Parse(raw) + // ForceQuery and the '#' check catch an empty query or fragment, which + // url.Parse otherwise drops. + if err != nil || u.Scheme != "https" || u.User != nil || u.RawQuery != "" || u.ForceQuery || strings.ContainsRune(raw, '#') { + return Destination{}, false + } + name, ok := NormalizeHostname(u.Hostname()) + if !ok { + return Destination{}, false + } + port := defaultHTTPSPort + if p := u.Port(); p != "" { + n, err := strconv.ParseUint(p, 10, 16) + if err != nil || n == 0 { + return Destination{}, false + } + port = uint16(n) + } + return Destination{Hostname: name, Port: port}, true +} + // isHostname reports whether name is a lowercase DNS-1123 subdomain whose last // label is not all digits. RFC 1123 section 2.1 requires that, and it is what // keeps a dotted-decimal address from passing as a name, including spellings diff --git a/internal/egresspolicy/egresspolicy_test.go b/internal/egresspolicy/egresspolicy_test.go index cd27c02b56..33810d30fc 100644 --- a/internal/egresspolicy/egresspolicy_test.go +++ b/internal/egresspolicy/egresspolicy_test.go @@ -214,6 +214,39 @@ func TestNormalizeHostname(t *testing.T) { } } +func TestTokenURLDestination(t *testing.T) { + tests := []struct { + raw string + want Destination + wantOK bool + }{ + {raw: "https://sts.googleapis.com/v1/token", want: Destination{Hostname: "sts.googleapis.com", Port: 443}, wantOK: true}, + {raw: "https://STS.Example.com./token", want: Destination{Hostname: "sts.example.com", Port: 443}, wantOK: true}, + {raw: "https://sts.example.com:8443/token", want: Destination{Hostname: "sts.example.com", Port: 8443}, wantOK: true}, + {raw: "https://sts.example.com", want: Destination{Hostname: "sts.example.com", Port: 443}, wantOK: true}, + {raw: "http://sts.example.com/token"}, + {raw: "https://user:pass@sts.example.com/token"}, + {raw: "https://sts.example.com/token?audience=x"}, + {raw: "https://sts.example.com/token#frag"}, + {raw: "https://sts.example.com?"}, + {raw: "https://sts.example.com#"}, + {raw: "https://sts.example.com/token?#"}, + {raw: "https://192.0.2.1/token"}, + {raw: "https://[2001:db8::1]/token"}, + {raw: "https://sts.example.com:0/token"}, + {raw: "https://sts.example.com:99999/token"}, + {raw: "https:///token"}, + {raw: "sts.example.com/token"}, + {raw: ""}, + } + for _, tc := range tests { + got, ok := TokenURLDestination(tc.raw) + if ok != tc.wantOK || got != tc.want { + t.Errorf("TokenURLDestination(%q) = (%+v, %v), want (%+v, %v)", tc.raw, got, ok, tc.want, tc.wantOK) + } + } +} + func TestCompileReportsAndDropsInvalidEntries(t *testing.T) { compiled, errs := Compile(policy( httpRule("good.example.com", "BAD.example.com"), diff --git a/internal/grpclb/grpclb.go b/internal/grpclb/grpclb.go new file mode 100644 index 0000000000..dd2bb87d9e --- /dev/null +++ b/internal/grpclb/grpclb.go @@ -0,0 +1,22 @@ +// Copyright 2026 The Agent Substrate 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 grpclb holds gRPC load balancing settings shared by Substrate's +// clients. +package grpclb + +// RoundRobinServiceConfig is a gRPC service config that spreads RPCs over +// every address the resolver returns. gRPC's default, pick_first, sends all of +// a client's RPCs to the first address it connects to. +const RoundRobinServiceConfig = `{"loadBalancingConfig": [{"round_robin":{}}]}` diff --git a/internal/hardware/cpufeatures_table.go b/internal/hardware/cpufeatures_table.go index d698832600..c08cd6a2cb 100644 --- a/internal/hardware/cpufeatures_table.go +++ b/internal/hardware/cpufeatures_table.go @@ -25,8 +25,8 @@ package hardware // moves between gVisor versions, and a bit with no entry is one the hardware // reserves. // -// The tables were produced once from gVisor's pkg/cpuid sources at -// gvisor.dev/gvisor@v0.0.0-20261014212059-ddc37c698141: for every constant of +// The tables were produced from gVisor's pkg/cpuid sources (updated through +// google/gvisor@ce0884fa5472, nightly 2026-12-02): for every constant of // type Feature in features_amd64.go and features_arm64.go with an entry in // that file's allFeatures map, the constant's value (evaluated with go/types) // keyed to the entry's display name. To take features from a newer gVisor, @@ -240,5 +240,9 @@ var ( 21: "sha512", // ARM64FeatureSHA512 22: "sve", // ARM64FeatureSVE 23: "asimdfhm", // ARM64FeatureASIMDFHM + 24: "dit", // ARM64FeatureDIT + 25: "uscat", // ARM64FeatureUSCAT + 26: "ilrcpc", // ARM64FeatureILRCPC + 27: "flagm", // ARM64FeatureFLAGM } ) diff --git a/internal/hardware/cpufeatures_test.go b/internal/hardware/cpufeatures_test.go index 5db4b05d91..e3df93de4f 100644 --- a/internal/hardware/cpufeatures_test.go +++ b/internal/hardware/cpufeatures_test.go @@ -152,6 +152,8 @@ func TestCPUFeatureTables(t *testing.T) { {"amd64", "avx512_bf16", 8*32 + 5}, {"arm64", "fp", 0}, {"arm64", "asimdfhm", 23}, + {"arm64", "dit", 24}, + {"arm64", "flagm", 27}, } { if got, ok := cpuFeatureTables[tc.arch].index[tc.name]; !ok || got != tc.bit { t.Errorf("%s %q at bit %d (present=%v), want %d", tc.arch, tc.name, got, ok, tc.bit) diff --git a/internal/hardware/hardware.go b/internal/hardware/hardware.go index 2c35548901..574c115c1c 100644 --- a/internal/hardware/hardware.go +++ b/internal/hardware/hardware.go @@ -27,6 +27,10 @@ const ( // SchemaVersionV1 is the initial compatibility schema version. SchemaVersionV1 = "v1" + // AttrActorIPFamilies identifies the address families configured in a + // microVM guest network. + AttrActorIPFamilies = "actor_ip_families" + // AttrArchitecture is the CPU architecture ("amd64", "arm64", etc.). AttrArchitecture = "architecture" @@ -189,25 +193,49 @@ func runtimeOf(class string, compat *ateapi.VersionedSandboxCompat) *ateapi.Acto return &ateapi.ActorSandboxRuntime{SandboxClass: class, Version: compat} } -// matchingRuntime returns the runtime from status that can restore the -// snapshot: in the worker's entry for the snapshot's class, DefaultRuntime -// first, then RestorableRuntimes in order. nil if the worker does not run -// that class or nothing in its entry matches. Only for a requirement of -// something. -func (r Requirement) matchingRuntime(status *ateapi.WorkerStatus) *ateapi.WorkerSandboxRuntime { +// BestRuntime returns the runtime from status that restores the most of the +// snapshot, and that fidelity: in the worker's entry for the snapshot's class, +// DefaultRuntime first, then RestorableRuntimes in order for +// SNAPSHOT_FIDELITY_MEMORY. When no runtime matches at MEMORY, a worker of the +// snapshot's class can cold-boot the snapshot without memory on DefaultRuntime +// at SNAPSHOT_FIDELITY_ROOTFS. Returns nil and SNAPSHOT_FIDELITY_UNSPECIFIED +// if the worker does not run that class. A zero Requirement imposes no runtime +// constraint: it returns DefaultRuntime at SNAPSHOT_FIDELITY_MEMORY, or nil +// and SNAPSHOT_FIDELITY_UNSPECIFIED before the worker has registered. +func (r Requirement) BestRuntime(status *ateapi.WorkerStatus) (*ateapi.WorkerSandboxRuntime, ateapi.SnapshotFidelity) { + if r.snap == nil { + classes := status.GetSandboxClasses() + if len(classes) == 0 { + return nil, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_UNSPECIFIED + } + return classes[0].GetDefaultRuntime(), ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY + } c := classOf(status, r.snap.GetSandboxClass()) if c == nil { - return nil + return nil, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_UNSPECIFIED } - if def := c.GetDefaultRuntime(); r.matchesCompat(def.GetVersion()) { - return def + def := c.GetDefaultRuntime() + if r.matchesCompat(def.GetVersion()) { + return def, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY } for _, rt := range c.GetRestorableRuntimes() { if r.matchesCompat(rt.GetVersion()) { - return rt + return rt, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY } } - return nil + return def, ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS +} + +// matchingRuntime returns the runtime from status that can restore the +// snapshot with memory state: DefaultRuntime first, then RestorableRuntimes in +// order. nil if the worker does not run that class or nothing in its entry +// matches. Only for a requirement of something. +func (r Requirement) matchingRuntime(status *ateapi.WorkerStatus) *ateapi.WorkerSandboxRuntime { + rt, fidelity := r.BestRuntime(status) + if fidelity != ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY { + return nil + } + return rt } // MatchingRuntime returns the runtime from status that can restore the @@ -231,18 +259,11 @@ func (r Requirement) WorkerMatches(status *ateapi.WorkerStatus) bool { } // WorkerRuntimeFor returns the worker's runtime that RuntimeFor stamps, as the -// worker reported it, or nil before the worker has registered. +// worker reported it, or nil when the worker has not registered or does not +// run the snapshot's class. func (r Requirement) WorkerRuntimeFor(status *ateapi.WorkerStatus) *ateapi.WorkerSandboxRuntime { - if r.snap != nil { - if rt := r.matchingRuntime(status); rt != nil { - return rt - } - } - classes := status.GetSandboxClasses() - if len(classes) == 0 { - return nil - } - return classes[0].GetDefaultRuntime() + rt, _ := r.BestRuntime(status) + return rt } // RuntimeFor returns the runtime a worker with status runs an actor under diff --git a/internal/hardware/hardware_test.go b/internal/hardware/hardware_test.go index aa834501ee..5473a8afdb 100644 --- a/internal/hardware/hardware_test.go +++ b/internal/hardware/hardware_test.go @@ -363,3 +363,81 @@ func TestWorkerRuntimeFor(t *testing.T) { t.Errorf("WorkerRuntimeFor() before registration = %v, want nil", got) } } + +func TestBestRuntime(t *testing.T) { + compat := func(hash string) *ateapi.VersionedSandboxCompat { + return &ateapi.VersionedSandboxCompat{SchemaVersion: SchemaVersionV1, Attributes: []*ateapi.AttributeEntry{ + {Key: AttrArchitecture, Value: "amd64"}, + {Key: AttrSandboxBundleHash, Value: hash}, + }} + } + def := &ateapi.WorkerSandboxRuntime{Version: compat("v2"), ActorOverhead: &ateapi.RuntimeOverhead{MemoryBytes: 4 << 20}} + restorable1 := &ateapi.WorkerSandboxRuntime{Version: compat("v1"), ActorOverhead: &ateapi.RuntimeOverhead{MemoryBytes: 8 << 20}} + restorable0 := &ateapi.WorkerSandboxRuntime{Version: compat("v0"), ActorOverhead: &ateapi.RuntimeOverhead{MemoryBytes: 16 << 20}} + status := &ateapi.WorkerStatus{SandboxClasses: []*ateapi.WorkerSandboxClass{{ + SandboxClass: "microvm", + DefaultRuntime: def, + RestorableRuntimes: []*ateapi.WorkerSandboxRuntime{restorable1, restorable0}, + }}} + stamp := func(class string, c *ateapi.VersionedSandboxCompat) *ateapi.ActorSandboxRuntime { + return &ateapi.ActorSandboxRuntime{SandboxClass: class, Version: c} + } + + for _, tc := range []struct { + name string + status *ateapi.WorkerStatus + snap *ateapi.ActorSandboxRuntime + wantRuntime *ateapi.WorkerSandboxRuntime + wantFidelity ateapi.SnapshotFidelity + }{ + { + name: "zero requirement returns DefaultRuntime at MEMORY", + status: status, + snap: nil, + wantRuntime: def, + wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + }, + { + name: "zero requirement before registration returns nil and UNSPECIFIED", + status: &ateapi.WorkerStatus{}, + snap: nil, + wantRuntime: nil, + wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_UNSPECIFIED, + }, + { + name: "matches DefaultRuntime at MEMORY", + status: status, + snap: stamp("microvm", compat("v2")), + wantRuntime: def, + wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + }, + { + name: "matches RestorableRuntime at MEMORY over DefaultRuntime fallback", + status: status, + snap: stamp("microvm", compat("v0")), + wantRuntime: restorable0, + wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_MEMORY, + }, + { + name: "mismatched runtime of same class falls back to DefaultRuntime at ROOTFS", + status: status, + snap: stamp("microvm", compat("gone")), + wantRuntime: def, + wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_ROOTFS, + }, + { + name: "different sandbox class returns nil and UNSPECIFIED", + status: status, + snap: stamp("gvisor", compat("v2")), + wantRuntime: nil, + wantFidelity: ateapi.SnapshotFidelity_SNAPSHOT_FIDELITY_UNSPECIFIED, + }, + } { + t.Run(tc.name, func(t *testing.T) { + gotRT, gotFidelity := NewRequirement(tc.snap).BestRuntime(tc.status) + if gotRT != tc.wantRuntime || gotFidelity != tc.wantFidelity { + t.Errorf("BestRuntime() = (%v, %v), want (%v, %v)", gotRT, gotFidelity, tc.wantRuntime, tc.wantFidelity) + } + }) + } +} diff --git a/internal/imagecache/README.md b/internal/imagecache/README.md index d7e54d7c70..558289c90a 100644 --- a/internal/imagecache/README.md +++ b/internal/imagecache/README.md @@ -187,10 +187,10 @@ extraction. The microVM path is nearly untouched: it bind-mounts the (now overlay-composed) bundle rootfs into virtiofsd's shared dir and the guest keeps building its own tmpfs upper, as before. -**Teardown**: `UnmountAllUnder(bundleDir)` lazily detaches every mount below -an actor's bundle directory (via `/proc/self/mountinfo`) before atelet wipes -it — called from the checkpoint cleanup path in ateworker-gvisor and -`teardownActor` in ateworker-microvm. +**Teardown**: `UnmountBundlesUnder(bundleDir)` lazily detaches the rootfs and +image volume mounts in each of an actor's bundles (checked with `statx` +`STATX_ATTR_MOUNT_ROOT`) before atelet wipes them. Both worker runtimes call it +on teardown and setup failure paths. ## Garbage collection @@ -299,9 +299,8 @@ restructuring. - Portable unit tests (run everywhere, including macOS): the unpack security suite (traversal, symlink/hardlink escape, whiteout capture, later-entry- wins, read-only dirs, missing parents), spec round-trips, overlay option - assembly (including duplicate-layer dedup), mountinfo parsing, ref - rewriting, options. End-to-end pull tests run against an in-memory - registry (`pkg/registry`). + assembly (including duplicate-layer dedup), ref rewriting, options. + End-to-end pull tests run against an in-memory registry (`pkg/registry`). - Linux-tagged tests (`bundle_linux_test.go`): unprivileged ones cover escape rejection and specless/zero-layer compose; root-gated ones execute the real `mknod`/xattr materialization and a full mount → write-isolation diff --git a/internal/imagecache/bundle_linux.go b/internal/imagecache/bundle_linux.go index 78dbafba8e..e39c8b8982 100644 --- a/internal/imagecache/bundle_linux.go +++ b/internal/imagecache/bundle_linux.go @@ -24,6 +24,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "sort" "strings" @@ -114,6 +115,9 @@ func SetupBundleRootfs(bundlePath string) error { // bundle-local mount point, for the OCI spec to bind into the container. func setupImageVolumes(bundlePath string, volumes []ImageVolumeOverlay) error { for _, vol := range volumes { + if err := validateImageVolumeName(vol.Name); err != nil { + return err + } for _, layerDir := range vol.Layers { if err := FinalizeLayer(layerDir); err != nil { return fmt.Errorf("while finalizing layer %q of image volume %q: %w", layerDir, vol.Name, err) @@ -334,34 +338,272 @@ func setOpaque(root *os.Root, rel string) error { return nil } +// maxUnmountPasses bounds how many rounds of detaches UnmountAllUnder and +// UnmountBundlesUnder make. Each round after the first finds mounts that an +// earlier detach uncovered, such as a lower mount stacked under the one statx +// reported. SetupBundleRootfs detaches a stale mount before it mounts, so a +// path rarely holds more than two. +const maxUnmountPasses = 8 + // UnmountAllUnder lazily detaches every mount at or below dir in the calling -// process's mount namespace. It is the teardown counterpart of -// SetupBundleRootfs, keyed by directory rather than by container name so a -// single call cleans up all of an actor's bundle mounts. Missing mounts are -// not an error. +// process's mount namespace. Missing mounts are not an error. +// +// dir must be an absolute path. UnmountAllUnder walks dir again after each +// round of detaches. It returns an error if mounts remain after +// maxUnmountPasses rounds or if any entry could not be checked, so callers +// must not remove dir when it returns an error. func UnmountAllUnder(dir string) error { - points, err := mountPointsUnder(dir) - if err != nil { - return err + return unmountAllUnder(dir, hostMountSys(), mountPointsUnder) +} + +// UnmountBundlesUnder lazily detaches the mounts SetupBundleRootfs makes in +// each bundle under dir, an OCI bundle dir that holds one bundle per container +// (actorDirs.GetOciBundleDir()). It is the teardown counterpart of +// SetupBundleRootfs, keyed by directory rather than by container name so a +// single call cleans up all of an actor's bundle mounts. It checks only +//
//rootfs and //volumes/, so use +// UnmountAllUnder for dirs that may hold other mounts. It returns errors as +// UnmountAllUnder does. +func UnmountBundlesUnder(dir string) error { + return unmountAllUnder(dir, hostMountSys(), bundleMountPoints) +} + +// mountSys holds the syscalls unmountAllUnder makes, so tests can fake them. +type mountSys struct { + // statx stats path relative to dirfd, as statxAt does. + statx func(dirfd int, path string) (unix.Statx_t, error) + // unmount detaches target, as unix.Unmount does. + unmount func(target string, flags int) error +} + +// hostMountSys returns the mountSys that makes the real syscalls. +func hostMountSys() mountSys { + return mountSys{statx: statxAt, unmount: unix.Unmount} +} + +// mountPoint is a path found by mountPointsUnder or bundleMountPoints. +type mountPoint struct { + path string + // statErr is set when statx failed on path. path may be a mount whose + // root cannot be stat'ed, such as a FUSE mount whose server is gone. + statErr error +} + +// unmountAllUnder detaches the mounts under dir that find lists, deepest +// first, until find lists none. +func unmountAllUnder(dir string, sys mountSys, find func(dir string, sys mountSys) ([]mountPoint, error)) error { + if !filepath.IsAbs(dir) { + return fmt.Errorf("refusing to unmount under %q: not an absolute path", dir) + } + dir = filepath.Clean(dir) + for pass := 0; ; pass++ { + points, err := find(dir, sys) + if len(points) == 0 { + return err + } + errs := []error{err} + if pass == maxUnmountPasses { + for _, p := range points { + if p.statErr != nil { + errs = append(errs, fmt.Errorf("while checking %q: %w", p.path, p.statErr)) + } + } + errs = append(errs, fmt.Errorf("mounts remain under %q after %d passes: %q", dir, maxUnmountPasses, mountPaths(points))) + return errors.Join(errs...) + } + progress := false + // Deepest first, so nested mounts unmount before their parents. + sort.Slice(points, func(i, j int) bool { return len(points[i].path) > len(points[j].path) }) + for _, p := range points { + uerr := sys.unmount(p.path, unix.MNT_DETACH|unix.UMOUNT_NOFOLLOW) + notMounted := errors.Is(uerr, unix.EINVAL) || errors.Is(uerr, os.ErrNotExist) + // A mount that was detached since the walk, or cannot be + // detached, also returns EINVAL. The next walk tells which. + if uerr == nil || (notMounted && p.statErr == nil) { + progress = true + continue + } + if p.statErr != nil { + errs = append(errs, fmt.Errorf("while checking %q: %w", p.path, p.statErr)) + } + if !notMounted { + errs = append(errs, fmt.Errorf("while unmounting %q: %w", p.path, uerr)) + } + } + if !progress { + return errors.Join(errs...) + } + } +} + +// mountPaths returns the sorted paths of points. +func mountPaths(points []mountPoint) []string { + paths := make([]string, len(points)) + for i, p := range points { + paths[i] = p.path + } + slices.Sort(paths) + return paths +} + +// statxAt queries file type and mount-root attribute metadata for path relative +// to dirfd without following symlinks, triggering automounts or forcing a +// remote filesystem sync. +// +// STATX_ATTR_MOUNT_ROOT needs Linux 5.8. mountOverlay already needs 6.7 or +// 6.6.23. +func statxAt(dirfd int, path string) (unix.Statx_t, error) { + var sx unix.Statx_t + err := unix.Statx(dirfd, path, unix.AT_SYMLINK_NOFOLLOW|unix.AT_NO_AUTOMOUNT|unix.AT_STATX_DONT_SYNC, unix.STATX_TYPE, &sx) + return sx, err +} + +// bundleMountPoints lists which of //rootfs and +// //volumes/ are mount points. SetupBundleRootfs mounts +// nothing else. It skips container and volumes dirs that are symlinks. An +// entry that fails statx is listed with statErr set. Other errors do not stop +// the listing: bundleMountPoints returns the points it found together with +// the joined errors. +func bundleMountPoints(dir string, sys mountSys) ([]mountPoint, error) { + containers, err := readDirNames(dir) + if errors.Is(err, os.ErrNotExist) { + return nil, nil } - // Deepest first, so nested mounts unmount before their parents. - sort.Slice(points, func(i, j int) bool { return len(points[i]) > len(points[j]) }) var errs []error - for _, p := range points { - if err := unix.Unmount(p, unix.MNT_DETACH); err != nil && !errors.Is(err, unix.EINVAL) && !errors.Is(err, os.ErrNotExist) { - errs = append(errs, fmt.Errorf("while unmounting %q: %w", p, err)) + if err != nil { + errs = append(errs, err) + } + var points []mountPoint + for _, c := range containers { + bundle := filepath.Join(dir, c) + if !isDir(sys, bundle, &errs) { + continue + } + points = appendIfMount(points, sys, filepath.Join(bundle, "rootfs")) + volumes := filepath.Join(bundle, "volumes") + names, err := readDirNames(volumes) + if err != nil && !errors.Is(err, os.ErrNotExist) && !errors.Is(err, unix.ENOTDIR) && !errors.Is(err, unix.ELOOP) { + errs = append(errs, err) + } + for _, name := range names { + points = appendIfMount(points, sys, filepath.Join(volumes, name)) } } - return errors.Join(errs...) + return points, errors.Join(errs...) } -// mountPointsUnder lists mount points at or below dir per -// /proc/self/mountinfo. -func mountPointsUnder(dir string) ([]string, error) { - f, err := os.Open("/proc/self/mountinfo") +// readDirNames returns the names in dir without following a symlink at dir. +func readDirNames(dir string) ([]string, error) { + f, err := os.OpenFile(dir, os.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW, 0) if err != nil { - return nil, fmt.Errorf("while opening mountinfo: %w", err) + return nil, err } defer f.Close() - return mountPointsIn(f, dir) + names, err := f.Readdirnames(-1) + if err != nil { + return names, fmt.Errorf("while reading %q: %w", dir, err) + } + return names, nil +} + +// isDir reports whether path is a dir and not a symlink. It appends any statx +// error other than ENOENT to errs. +func isDir(sys mountSys, path string, errs *[]error) bool { + sx, err := sys.statx(unix.AT_FDCWD, path) + if err != nil { + if !errors.Is(err, os.ErrNotExist) { + *errs = append(*errs, fmt.Errorf("while checking %q: %w", path, err)) + } + return false + } + return sx.Mode&unix.S_IFMT == unix.S_IFDIR +} + +// appendIfMount appends path to points if it is a mount root, or with statErr +// set if statx fails on it with anything but ENOENT. +func appendIfMount(points []mountPoint, sys mountSys, path string) []mountPoint { + sx, err := sys.statx(unix.AT_FDCWD, path) + switch { + case errors.Is(err, os.ErrNotExist): + return points + case err != nil: + return append(points, mountPoint{path: path, statErr: err}) + case sx.Attributes&unix.STATX_ATTR_MOUNT_ROOT != 0: + return append(points, mountPoint{path: path}) + } + return points +} + +// mountPointsUnder lists the mount points at or below dir using +// STATX_ATTR_MOUNT_ROOT. +// +// An entry that fails statx is listed with statErr set. Errors reading a dir +// do not stop the walk: mountPointsUnder returns the points it found together +// with the joined errors. +func mountPointsUnder(dir string, sys mountSys) ([]mountPoint, error) { + sx, err := sys.statx(unix.AT_FDCWD, dir) + if errors.Is(err, os.ErrNotExist) { + return nil, nil + } + if err != nil { + return []mountPoint{{path: dir, statErr: err}}, nil + } + var points []mountPoint + if sx.Attributes&unix.STATX_ATTR_MOUNT_ROOT != 0 { + points = append(points, mountPoint{path: dir}) + } + var errs []error + if sx.Mode&unix.S_IFMT == unix.S_IFDIR { + walkMounts(dir, "", sys, &points, &errs) + } + return points, errors.Join(errs...) +} + +// walkMounts appends the mount points below root/rel to points and the errors +// for dirs it could not read to errs. It does not follow symlinks or descend +// into mount points. It closes each dir before recursing, so it holds one open +// file at a time. +func walkMounts(root, rel string, sys mountSys, points *[]mountPoint, errs *[]error) { + curDir := filepath.Join(root, rel) + f, err := os.OpenFile(curDir, os.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW, 0) + if errors.Is(err, os.ErrNotExist) { + return + } + if err != nil { + *errs = append(*errs, err) + return + } + names, err := f.Readdirnames(-1) + if err != nil && !errors.Is(err, os.ErrNotExist) { + *errs = append(*errs, fmt.Errorf("while reading %q: %w", curDir, err)) + } + + dirfd := int(f.Fd()) + var subdirs []string + for _, name := range names { + path := filepath.Join(curDir, name) + sx, err := sys.statx(dirfd, name) + if errors.Is(err, os.ErrNotExist) { + continue + } + if err != nil { + *points = append(*points, mountPoint{path: path, statErr: err}) + continue + } + if sx.Mode&unix.S_IFMT == unix.S_IFLNK { + continue + } + if sx.Attributes&unix.STATX_ATTR_MOUNT_ROOT != 0 { + *points = append(*points, mountPoint{path: path}) + continue + } + if sx.Mode&unix.S_IFMT == unix.S_IFDIR { + subdirs = append(subdirs, filepath.Join(rel, name)) + } + } + _ = f.Close() + + for _, sub := range subdirs { + walkMounts(root, sub, sys, points, errs) + } } diff --git a/internal/imagecache/bundle_linux_test.go b/internal/imagecache/bundle_linux_test.go index 41a4345a67..a0de5493ea 100644 --- a/internal/imagecache/bundle_linux_test.go +++ b/internal/imagecache/bundle_linux_test.go @@ -23,6 +23,7 @@ import ( "fmt" "os" "path/filepath" + "slices" "strings" "testing" @@ -510,3 +511,300 @@ func testSetupBundleRootfsRepairsWhiteoutParentUnderSetgidDir(t *testing.T) { t.Errorf("whited-out srv/shared/docs/old: Lstat error %v, want ErrNotExist", err) } } + +// fakeMounts fakes mounts on a real directory tree, keyed by absolute path. +type fakeMounts struct { + // mounted counts the mounts stacked at each path. + mounted map[string]int + // statErr is returned by statx for each path until its last mount is + // detached. + statErr map[string]error +} + +// sys returns a mountSys that runs the real statx and then applies f. +func (f *fakeMounts) sys(t *testing.T) mountSys { + return mountSys{ + statx: func(dirfd int, path string) (unix.Statx_t, error) { + if dirfd != unix.AT_FDCWD { + dir, err := os.Readlink(fmt.Sprintf("/proc/self/fd/%d", dirfd)) + if err != nil { + t.Fatal(err) + } + path = filepath.Join(dir, path) + } + if err := f.statErr[path]; err != nil { + return unix.Statx_t{}, err + } + sx, err := statxAt(unix.AT_FDCWD, path) + if f.mounted[path] > 0 { + sx.Attributes |= unix.STATX_ATTR_MOUNT_ROOT + } + return sx, err + }, + unmount: func(target string, flags int) error { + if flags != unix.MNT_DETACH|unix.UMOUNT_NOFOLLOW { + t.Errorf("unmount(%q) flags = %#x, want MNT_DETACH|UMOUNT_NOFOLLOW", target, flags) + } + if f.mounted[target] == 0 { + return unix.EINVAL + } + if f.mounted[target]--; f.mounted[target] == 0 { + delete(f.statErr, target) + } + return nil + }, + } +} + +func TestUnmount_DirArgument(t *testing.T) { + for _, unmount := range []func(string) error{UnmountAllUnder, UnmountBundlesUnder} { + for _, dir := range []string{"", ".", "bundles"} { + if err := unmount(dir); err == nil { + t.Errorf("unmount(%q) = nil, want error for a relative dir", dir) + } + } + if err := unmount(filepath.Join(t.TempDir(), "missing")); err != nil { + t.Errorf("unmount(missing dir) = %v, want nil", err) + } + } +} + +func TestUnmount_FakeMounts(t *testing.T) { + for _, tc := range []struct { + name string + find func(string, mountSys) ([]mountPoint, error) + mounted map[string]int // relative path -> stacked mounts + statErr map[string]error // relative path -> statx error + // left are the mounts that must remain; all others must be detached. + left map[string]int + wantErr []error + wantMsg string + }{{ + name: "bad entry, walk", + find: mountPointsUnder, + mounted: map[string]int{"a/rootfs": 1, "b/rootfs": 1}, + statErr: map[string]error{"a/volumes/bad": unix.EACCES}, + wantErr: []error{unix.EACCES}, + }, { + name: "bad entry, bundles", + find: bundleMountPoints, + mounted: map[string]int{"a/rootfs": 1, "b/rootfs": 1}, + statErr: map[string]error{"a/volumes/bad": unix.EACCES}, + wantErr: []error{unix.EACCES}, + }, { + // The dead mount is detached. other/rootfs is not a mount, so its + // statx error is returned. + name: "dead mount, walk", + find: mountPointsUnder, + mounted: map[string]int{"main/volumes/fuse": 1}, + statErr: map[string]error{"main/volumes/fuse": unix.ENOTCONN, "other/rootfs": unix.EIO}, + wantErr: []error{unix.EIO}, + }, { + name: "dead mount, bundles", + find: bundleMountPoints, + mounted: map[string]int{"main/volumes/fuse": 1}, + statErr: map[string]error{"main/volumes/fuse": unix.ENOTCONN, "other/rootfs": unix.EIO}, + wantErr: []error{unix.EIO}, + }, { + name: "gives up after max passes", + find: bundleMountPoints, + mounted: map[string]int{"main/rootfs": maxUnmountPasses + 1}, + left: map[string]int{"main/rootfs": 1}, + wantMsg: "mounts remain", + }, { + // Only rootfs and volumes/* of each container are checked, also for + // containers named like bundle subdirs. link is a symlink to main. + name: "bundles checks only bundle mounts", + find: bundleMountPoints, + mounted: map[string]int{ + "main/rootfs": 1, "main/volumes/agent": 1, "upper/rootfs": 1, "volumes/volumes/data": 1, + "main/upper": 1, "main/other": 1, "plain/rootfs/inner": 1, "link/rootfs": 1, + }, + left: map[string]int{"main/upper": 1, "main/other": 1, "plain/rootfs/inner": 1, "link/rootfs": 1}, + }} { + t.Run(tc.name, func(t *testing.T) { + root, err := filepath.EvalSymlinks(t.TempDir()) + if err != nil { + t.Fatal(err) + } + if err := os.Mkdir(filepath.Join(root, "main"), 0o755); err != nil { + t.Fatal(err) + } + if err := os.Symlink("main", filepath.Join(root, "link")); err != nil { + t.Fatal(err) + } + f := &fakeMounts{mounted: map[string]int{}, statErr: map[string]error{}} + for rel, n := range tc.mounted { + f.mounted[filepath.Join(root, rel)] = n + } + for rel, e := range tc.statErr { + f.statErr[filepath.Join(root, rel)] = e + } + for _, m := range []map[string]int{tc.mounted, tc.left} { + for rel := range m { + if err := os.MkdirAll(filepath.Join(root, rel), 0o755); err != nil { + t.Fatal(err) + } + } + } + for rel := range tc.statErr { + if err := os.MkdirAll(filepath.Join(root, rel), 0o755); err != nil { + t.Fatal(err) + } + } + + err = unmountAllUnder(root, f.sys(t), tc.find) + for _, want := range tc.wantErr { + if !errors.Is(err, want) { + t.Errorf("unmountAllUnder = %v, want %v", err, want) + } + } + if tc.wantMsg != "" && (err == nil || !strings.Contains(err.Error(), tc.wantMsg)) { + t.Errorf("unmountAllUnder = %v, want %q", err, tc.wantMsg) + } + if tc.wantErr == nil && tc.wantMsg == "" && err != nil { + t.Errorf("unmountAllUnder = %v, want nil", err) + } + for rel, e := range tc.statErr { + if tc.mounted[rel] > 0 && tc.left[rel] == 0 && errors.Is(err, e) { + t.Errorf("unmountAllUnder = %v, want no error for detached %s", err, rel) + } + } + for rel := range tc.mounted { + if got := f.mounted[filepath.Join(root, rel)]; got != tc.left[rel] { + t.Errorf("%s: %d mounts left, want %d", rel, got, tc.left[rel]) + } + } + }) + } +} + +func TestSetupBundleRootfs_MultiBundleUnmount(t *testing.T) { + roottest.Require(t, "mount/unmount") + + rootLayer := t.TempDir() + writeLayer(t, rootLayer, map[string]string{"root.txt": "root"}, nil) + volLayer1 := t.TempDir() + writeLayer(t, volLayer1, map[string]string{"vol1.txt": "vol1"}, nil) + volLayer2 := t.TempDir() + writeLayer(t, volLayer2, map[string]string{"vol.txt": "vol"}, nil) + + // Containers and volumes named after bundle subdirs must still be found. + bundlesDir := filepath.Join(t.TempDir(), "bundles") + t.Cleanup(func() { _ = UnmountBundlesUnder(bundlesDir) }) + var want []string + for _, c := range []string{"main", "upper", "rootfs", "volumes"} { + b := filepath.Join(bundlesDir, c) + if err := os.MkdirAll(b, 0o755); err != nil { + t.Fatal(err) + } + spec := &OverlaySpec{Layers: []string{rootLayer}} + want = append(want, filepath.Join(b, "rootfs")) + if c == "main" { + for _, v := range []string{"agent", "upper"} { + spec.ImageVolumes = append(spec.ImageVolumes, ImageVolumeOverlay{Name: v, Layers: []string{volLayer1, volLayer2}}) + want = append(want, ImageVolumeMountPath(b, v)) + } + } + if err := WriteSpec(b, spec); err != nil { + t.Fatalf("WriteSpec(%q): %v", b, err) + } + if err := SetupBundleRootfs(b); err != nil { + t.Fatalf("SetupBundleRootfs(%q): %v", b, err) + } + } + slices.Sort(want) + + points, err := bundleMountPoints(bundlesDir, hostMountSys()) + if err != nil { + t.Fatalf("bundleMountPoints(bundlesDir): %v", err) + } + if got := mountPaths(points); !slices.Equal(got, want) { + t.Fatalf("bundleMountPoints(bundlesDir) = %q, want %q", got, want) + } + if err := UnmountBundlesUnder(bundlesDir); err != nil { + t.Fatalf("UnmountBundlesUnder(bundlesDir): %v", err) + } + if points, err := mountPointsUnder(bundlesDir, hostMountSys()); err != nil || len(points) != 0 { + t.Errorf("after UnmountBundlesUnder: mounts %q, err %v; want none", mountPaths(points), err) + } +} + +func TestUnmount_RealMounts(t *testing.T) { + roottest.Require(t, "mount/unmount") + // mount attaches a tmpfs at dir/rel, or binds dir/src there if src is set. + mount := func(t *testing.T, dir, rel, src string) { + target := filepath.Join(dir, rel) + var err error + if src == "" { + if err := os.MkdirAll(target, 0o755); err != nil { + t.Fatal(err) + } + err = unix.Mount("tmpfs", target, "tmpfs", 0, "") + } else { + for _, f := range []string{filepath.Join(dir, src), target} { + if err := os.WriteFile(f, nil, 0o600); err != nil { + t.Fatal(err) + } + } + err = unix.Mount(filepath.Join(dir, src), target, "", unix.MS_BIND, "") + } + if err != nil { + t.Fatalf("mount at %q: %v", target, err) + } + t.Cleanup(func() { _ = unix.Unmount(target, unix.MNT_DETACH) }) + } + for _, tc := range []struct { + name string + setup func(t *testing.T, dir string) + // found are the mounts the first walk lists, relative to dir. + found []string + // unmount runs after the walk, if set. No mount may remain after it. + unmount func(string) error + }{{ + name: "stacked", + setup: func(t *testing.T, dir string) { + for range 3 { + mount(t, dir, "main/rootfs", "") + } + }, + found: []string{"main/rootfs"}, + unmount: UnmountBundlesUnder, + }, { + // The mount over a hides the mount at a/b from the first walk. + name: "shadowed", + setup: func(t *testing.T, dir string) { + mount(t, dir, "a/b", "") + mount(t, dir, "a", "") + }, + found: []string{"a"}, + unmount: UnmountAllUnder, + }, { + // runsc leaves a bind-mounted file in its state dir. + name: "file bind mount", + setup: func(t *testing.T, dir string) { mount(t, dir, "null-netns", "netns") }, + found: []string{"null-netns"}, + }} { + t.Run(tc.name, func(t *testing.T) { + dir := t.TempDir() + tc.setup(t, dir) + points, err := mountPointsUnder(dir, hostMountSys()) + var want []string + for _, rel := range tc.found { + want = append(want, filepath.Join(dir, rel)) + } + if got := mountPaths(points); err != nil || !slices.Equal(got, want) { + t.Fatalf("mountPointsUnder = %q, %v; want %q", got, err, want) + } + if tc.unmount == nil { + return + } + if err := tc.unmount(dir); err != nil { + t.Fatalf("unmount: %v", err) + } + if points, err := mountPointsUnder(dir, hostMountSys()); err != nil || len(points) != 0 { + t.Errorf("after unmount: mounts %q, err %v; want none", mountPaths(points), err) + } + }) + } +} diff --git a/internal/imagecache/imagecache.go b/internal/imagecache/imagecache.go index d49112c6c9..d79bff77d2 100644 --- a/internal/imagecache/imagecache.go +++ b/internal/imagecache/imagecache.go @@ -48,6 +48,7 @@ package imagecache import ( + "cmp" "context" "encoding/json" "errors" @@ -634,7 +635,8 @@ func (s *Store) pullWith(ctx context.Context, parsedRef name.Reference, digest v layerDirs := make([]string, len(layers)) g, gctx := errgroup.WithContext(ctx) g.SetLimit(layerPullConcurrency) - for i, layer := range layers { + for _, i := range layerPullOrder(ctx, layers) { + layer := layers[i] g.Go(func() error { // This is the config's claim. Unpack hashes the content to check // it, since a remote layer's DiffID() would just repeat the config. @@ -694,6 +696,31 @@ func (s *Store) pullWith(ctx context.Context, parsedRef name.Reference, digest v return &Image{Digest: digest, Config: cfgFile.Config, LayerDirs: layerDirs}, nil } +// layerPullOrder returns layer indices by descending compressed size, so the +// largest layers start first. Ties keep manifest order. The order only +// schedules unpacks, so if a size can't be read it logs and returns manifest +// order. +func layerPullOrder(ctx context.Context, layers []v1.Layer) []int { + order := make([]int, len(layers)) + for i := range order { + order[i] = i + } + sizes := make([]int64, len(layers)) + for i, l := range layers { + size, err := l.Size() + if err != nil { + slog.WarnContext(ctx, "Failed to read image layer size, unpacking layers in manifest order", + slog.Int("layer", i), slog.Any("err", err)) + return order + } + sizes[i] = size + } + slices.SortStableFunc(order, func(a, b int) int { + return cmp.Compare(sizes[b], sizes[a]) + }) + return order +} + // pinLayers marks the layers as in use by an in-flight pull and returns the // matching unpin. Taken by each pull for all of its layers before any // ensureLayer call, outside the layer flight, so a pull that joins another diff --git a/internal/imagecache/imagecache_test.go b/internal/imagecache/imagecache_test.go index 07666b0725..279d0fcbeb 100644 --- a/internal/imagecache/imagecache_test.go +++ b/internal/imagecache/imagecache_test.go @@ -17,7 +17,9 @@ package imagecache import ( "archive/tar" "bytes" + "compress/gzip" "context" + "errors" "io" "log" "net/http" @@ -26,6 +28,7 @@ import ( "os" "path/filepath" "slices" + "strings" "sync/atomic" "testing" "time" @@ -59,12 +62,12 @@ func newWrappedRegistry(t *testing.T, wrap func(http.Handler) http.Handler) (*ht return srv, u.Host } -func layerFromEntries(t *testing.T, entries []tarEntry) v1.Layer { +func layerFromEntries(t *testing.T, entries []tarEntry, opts ...tarball.LayerOption) v1.Layer { t.Helper() b := buildTar(t, entries) l, err := tarball.LayerFromOpener(func() (io.ReadCloser, error) { return io.NopCloser(bytes.NewReader(b)), nil - }) + }, opts...) if err != nil { t.Fatalf("tarball.LayerFromOpener: %v", err) } @@ -241,6 +244,25 @@ func TestEnsureImage_TagPullAndDigestHit(t *testing.T) { } } +// sizeErrLayer is a layer whose Size fails. +type sizeErrLayer struct{ v1.Layer } + +func (sizeErrLayer) Size() (int64, error) { return 0, errors.New("no size") } + +// A layer size that can't be read falls back to manifest order rather than +// failing the pull or sorting the unknown layer as empty. +func TestLayerPullOrderFallsBackToManifestOrder(t *testing.T) { + layer := func(name string, size int) v1.Layer { + return layerFromEntries(t, []tarEntry{ + {name: name, typeflag: tar.TypeReg, mode: 0o644, body: strings.Repeat(name, size)}, + }, tarball.WithCompressionLevel(gzip.NoCompression)) + } + layers := []v1.Layer{layer("a", 1<<11), sizeErrLayer{layer("b", 1<<11)}, layer("c", 1<<16)} + if got, want := layerPullOrder(context.Background(), layers), []int{0, 1, 2}; !slices.Equal(got, want) { + t.Errorf("layerPullOrder = %v, want manifest order %v", got, want) + } +} + // Two images sharing a base layer must share its unpacked tree: the pool // holds three layer dirs, not four. func TestEnsureImage_SharedLayersDeduplicated(t *testing.T) { diff --git a/internal/imagecache/mountinfo.go b/internal/imagecache/mountinfo.go deleted file mode 100644 index e4aa06cfb7..0000000000 --- a/internal/imagecache/mountinfo.go +++ /dev/null @@ -1,93 +0,0 @@ -// Copyright 2026 The Agent Substrate 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. - -// mountinfo parsing lives in a portable file (the reader comes in as an -// io.Reader) so the logic is unit-testable off-Linux; only the caller that -// opens /proc/self/mountinfo is linux-tagged. - -package imagecache - -import ( - "bufio" - "bytes" - "fmt" - "io" - "math" - "path/filepath" - "strings" -) - -// mountinfo octal-escapes space, tab, newline and backslash in paths (\040, -// \011, \012, \134); these decode and encode that form. -var ( - mountPathUnescaper = strings.NewReplacer(`\040`, " ", `\011`, "\t", `\012`, "\n", `\134`, `\`) - mountPathEscaper = strings.NewReplacer(" ", `\040`, "\t", `\011`, "\n", `\012`, `\`, `\134`) -) - -// mountPointsIn returns the mount points at or below dir found in r, which -// must be in /proc/[pid]/mountinfo format: -// -// ID parentID major:minor root MOUNTPOINT options... -// -// mountinfo can run to several MB on a dense worker and is read on every -// teardown, so the loop allocates only for matching lines. -func mountPointsIn(r io.Reader, dir string) ([]string, error) { - // Compare in mountinfo's escaped form, so only matches are decoded. The - // escaping is per character and leaves '/' alone, so a prefix match on - // the escaped path is a prefix match on the decoded one. - esc := []byte(mountPathEscaper.Replace(filepath.Clean(dir))) - var points []string - scanner := bufio.NewScanner(r) - // No line-length cap: an overlay's record lists every lowerdir path, and - // a long chain outgrows the 64 KiB default token size. - scanner.Buffer(nil, math.MaxInt) - for scanner.Scan() { - mp, ok := mountinfoField(scanner.Bytes(), 4) - if !ok || !bytes.HasPrefix(mp, esc) { - continue - } - if rest := mp[len(esc):]; len(rest) == 0 || rest[0] == '/' { - points = append(points, unescapeMountPath(string(mp))) - } - } - if err := scanner.Err(); err != nil { - return nil, fmt.Errorf("while reading mountinfo: %w", err) - } - return points, nil -} - -// mountinfoField returns the nth (0-based) field of line. The kernel -// separates fields with a single space. -func mountinfoField(line []byte, n int) ([]byte, bool) { - for ; n > 0; n-- { - i := bytes.IndexByte(line, ' ') - if i < 0 { - return nil, false - } - line = line[i+1:] - } - if i := bytes.IndexByte(line, ' '); i >= 0 { - line = line[:i] - } - return line, len(line) > 0 -} - -// unescapeMountPath decodes the octal escapes mountinfo uses for space, tab, -// newline, and backslash. -func unescapeMountPath(s string) string { - if !strings.Contains(s, `\`) { - return s - } - return mountPathUnescaper.Replace(s) -} diff --git a/internal/imagecache/mountinfo_test.go b/internal/imagecache/mountinfo_test.go deleted file mode 100644 index 27f4b58d95..0000000000 --- a/internal/imagecache/mountinfo_test.go +++ /dev/null @@ -1,118 +0,0 @@ -// Copyright 2026 The Agent Substrate 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 imagecache - -import ( - "bufio" - "slices" - "strings" - "testing" -) - -func TestMountPointsIn(t *testing.T) { - mountinfo := strings.Join([]string{ - `22 26 0:20 / /sys rw,nosuid,nodev shared:7 - sysfs sysfs rw`, - `40 21 8:1 / /var/lib/ateworker-gvisor/actors/a1/bundles/task/rootfs rw shared:1 - overlay overlay rw,lowerdir=/x`, - `41 21 8:1 / /var/lib/ateworker-gvisor/actors/a1/bundles/pause/rootfs rw - overlay overlay rw`, - `42 21 8:1 / /var/lib/ateworker-gvisor/actors/a2/bundles/task/rootfs rw - overlay overlay rw`, - // Path with an escaped space; mountinfo octal-escapes it. - `43 21 8:1 / /var/lib/ateworker-gvisor/actors/a1/bundles/odd\040name/rootfs rw - overlay overlay rw`, - // Prefix-sibling directory that must NOT match a1's subtree. - `44 21 8:1 / /var/lib/ateworker-gvisor/actors/a1-sibling/bundles/x/rootfs rw - overlay overlay rw`, - `malformed line`, - ``, - }, "\n") - - got, err := mountPointsIn(strings.NewReader(mountinfo), "/var/lib/ateworker-gvisor/actors/a1/bundles") - if err != nil { - t.Fatalf("mountPointsIn: %v", err) - } - want := []string{ - "/var/lib/ateworker-gvisor/actors/a1/bundles/task/rootfs", - "/var/lib/ateworker-gvisor/actors/a1/bundles/pause/rootfs", - "/var/lib/ateworker-gvisor/actors/a1/bundles/odd name/rootfs", - } - if !slices.Equal(got, want) { - t.Errorf("mount points = %v, want %v", got, want) - } -} - -func TestMountPointsIn_ExactDirMatch(t *testing.T) { - got, err := mountPointsIn(strings.NewReader(`40 21 8:1 / /mnt/target rw - ext4 /dev/sda1 rw`), "/mnt/target") - if err != nil { - t.Fatalf("mountPointsIn: %v", err) - } - if !slices.Equal(got, []string{"/mnt/target"}) { - t.Errorf("mount points = %v, want the exact dir itself", got) - } -} - -// dir is compared in mountinfo's escaped form; a dir with a space must match -// its own mounts and not a longer sibling. -func TestMountPointsIn_EscapedDir(t *testing.T) { - mountinfo := strings.Join([]string{ - `40 21 8:1 / /mnt/odd\040name rw - ext4 /dev/sda1 rw`, - `41 21 8:1 / /mnt/odd\040name/rootfs rw - overlay overlay rw`, - `42 21 8:1 / /mnt/odd\040name2/rootfs rw - overlay overlay rw`, - ``, - }, "\n") - - got, err := mountPointsIn(strings.NewReader(mountinfo), "/mnt/odd name") - if err != nil { - t.Fatalf("mountPointsIn: %v", err) - } - want := []string{"/mnt/odd name", "/mnt/odd name/rootfs"} - if !slices.Equal(got, want) { - t.Errorf("mount points = %v, want %v", got, want) - } -} - -// An overlay's record lists every lowerdir path, so one line can be longer -// than bufio.Scanner's default token size; the lines after it must still be -// read. -func TestMountPointsIn_LongLine(t *testing.T) { - long := `40 21 8:1 / /mnt/target/rootfs rw - overlay overlay rw,lowerdir=` + strings.Repeat("/l", 40_000) - if len(long) <= bufio.MaxScanTokenSize { - t.Fatalf("test line is %d bytes, not exceeding bufio's %d-byte default", len(long), bufio.MaxScanTokenSize) - } - mountinfo := strings.Join([]string{ - long, - `41 21 8:1 / /mnt/target/volumes/agent rw - overlay overlay rw`, - ``, - }, "\n") - - got, err := mountPointsIn(strings.NewReader(mountinfo), "/mnt/target") - if err != nil { - t.Fatalf("mountPointsIn: %v", err) - } - want := []string{"/mnt/target/rootfs", "/mnt/target/volumes/agent"} - if !slices.Equal(got, want) { - t.Errorf("mount points = %v, want %v", got, want) - } -} - -func TestUnescapeMountPath(t *testing.T) { - tests := []struct{ in, want string }{ - {`/plain/path`, `/plain/path`}, - {`/with\040space`, `/with space`}, - {`/tab\011and\012newline`, "/tab\tand\nnewline"}, - {`/back\134slash`, `/back\slash`}, - } - for _, tc := range tests { - if got := unescapeMountPath(tc.in); got != tc.want { - t.Errorf("unescapeMountPath(%q) = %q, want %q", tc.in, got, tc.want) - } - } -} diff --git a/internal/imagecache/pull_gated_test.go b/internal/imagecache/pull_gated_test.go index 445c577b3d..5f7263eacf 100644 --- a/internal/imagecache/pull_gated_test.go +++ b/internal/imagecache/pull_gated_test.go @@ -20,18 +20,21 @@ package imagecache import ( "archive/tar" + "compress/gzip" "context" "encoding/json" "errors" "net/http" "os" "path/filepath" + "slices" "strings" "sync" "testing" "time" v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/google/go-containerregistry/pkg/v1/tarball" ) // gatedRegistry is an in-memory registry whose blob GETs block while their @@ -39,8 +42,9 @@ import ( type gatedRegistry struct { host string - mu sync.Mutex - gates map[string]chan struct{} + mu sync.Mutex + gates map[string]chan struct{} + arrived chan string // nil until arrivals is called } func newGatedRegistry(t *testing.T) *gatedRegistry { @@ -50,15 +54,23 @@ func newGatedRegistry(t *testing.T) *gatedRegistry { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Method == http.MethodGet && strings.Contains(r.URL.Path, "/blobs/") { g.mu.Lock() - var ch chan struct{} + var ( + matched string + ch chan struct{} + ) for hex, c := range g.gates { if strings.Contains(r.URL.Path, hex) { + matched = hex ch = c break } } + arrived := g.arrived g.mu.Unlock() if ch != nil { + if arrived != nil { + arrived <- matched + } <-ch } } @@ -68,6 +80,15 @@ func newGatedRegistry(t *testing.T) *gatedRegistry { return g } +// arrivals returns a channel that receives the digest hex of each gated blob +// GET as it reaches its gate. +func (g *gatedRegistry) arrivals() <-chan string { + g.mu.Lock() + defer g.mu.Unlock() + g.arrived = make(chan string, 16) + return g.arrived +} + // gate blocks future GETs of the layer's compressed blob until release. func (g *gatedRegistry) gate(t *testing.T, layer v1.Layer) (release func()) { t.Helper() @@ -389,3 +410,88 @@ func TestDetachedPullBoundedByPullTimeout(t *testing.T) { t.Fatalf("EnsureImage on a wedged pull = %v, want context.DeadlineExceeded", err) } } + +// Larger layers at the end of the manifest must start in the first +// layerPullConcurrency wave ahead of smaller layers, breaking ties in manifest +// order while LayerDirs still returns layers in manifest order. +func TestPullStartsLargestLayersFirst(t *testing.T) { + if layerPullConcurrency != 4 { + t.Fatalf("layerPullConcurrency = %d, want 4; update specs so the first wave still excludes one layer", layerPullConcurrency) + } + reg := newGatedRegistry(t) + specs := []struct { + name string + size int + }{ + {"a", 1 << 11}, + {"b", 1 << 11}, // ties with "a"; manifest order picks "a" before "b" + {"c", 1 << 16}, + {"d", 1 << 18}, + {"e", 1 << 20}, + } + layers := make([]v1.Layer, len(specs)) + digests := make([]string, len(specs)) + releases := make([]func(), len(specs)) + for i, s := range specs { + // Without compression the blob size, which layerPullOrder sorts by, + // follows the body size, so the tie and order above hold exactly. + layers[i] = layerFromEntries(t, []tarEntry{ + {name: s.name, typeflag: tar.TypeReg, mode: 0o644, body: strings.Repeat(s.name, s.size)}, + }, tarball.WithCompressionLevel(gzip.NoCompression)) + d, err := layers[i].Digest() + if err != nil { + t.Fatalf("layer %s digest: %v", s.name, err) + } + digests[i] = d.Hex + releases[i] = reg.gate(t, layers[i]) + } + + if got, want := layerPullOrder(context.Background(), layers), []int{4, 3, 2, 0, 1}; !slices.Equal(got, want) { + t.Fatalf("layerPullOrder = %v, want %v", got, want) + } + + ref := reg.host + "/test/lpt:latest" + pushImage(t, ref, v1.Config{}, layers...) + + arrived := reg.arrivals() + store := newTestStore(t) + done := make(chan error, 1) + var img *Image + go func() { + var err error + img, err = store.EnsureImage(context.Background(), ref) + done <- err + }() + + // All 5 layers are gated, so at most layerPullConcurrency (4) blob GETs can + // arrive before a gate opens: "c", "d", "e" by size, plus "a" ahead of + // equal-sized "b" by manifest order. + firstWave := make([]string, layerPullConcurrency) + for i := range firstWave { + select { + case firstWave[i] = <-arrived: + case err := <-done: + t.Fatalf("EnsureImage returned before %d layer pulls arrived: %v", layerPullConcurrency, err) + case <-time.After(10 * time.Second): + t.Fatalf("%d of %d layer pulls arrived within 10s: %v", i, layerPullConcurrency, firstWave[:i]) + } + } + if slices.Contains(firstWave, digests[1]) { + t.Errorf("first %d layer pulls = %v, want layer b (%s) queued behind larger layers c..e and earlier tie a", layerPullConcurrency, firstWave, digests[1]) + } + + for _, release := range releases { + release() + } + if err := <-done; err != nil { + t.Fatalf("EnsureImage: %v", err) + } + if len(img.LayerDirs) != len(layers) { + t.Fatalf("len(LayerDirs) = %d, want %d", len(img.LayerDirs), len(layers)) + } + for i, dir := range img.LayerDirs { + if _, err := os.Stat(filepath.Join(dir, layerFSDirName, specs[i].name)); err != nil { + t.Errorf("LayerDirs[%d] missing entry %q: %v", i, specs[i].name, err) + } + } +} diff --git a/internal/imagecache/spec.go b/internal/imagecache/spec.go index a4ed15180c..7fe3ef2540 100644 --- a/internal/imagecache/spec.go +++ b/internal/imagecache/spec.go @@ -31,6 +31,25 @@ func ImageVolumeMountPath(bundlePath, volumeName string) string { return filepath.Join(bundlePath, "volumes", volumeName) } +// validateImageVolumeName rejects any volume name that would not land under +// the bundle's volumes/ directory as a directory of its own. +// +// The worker composes a mount point by joining the name onto that directory +// and then creates, unmounts and mounts over the result, as root. A name +// carrying a separator or a ".." element would place those operations +// somewhere else on the host, and "." or an empty name would place them on +// volumes/ itself, over the mount points of every other volume in the bundle. +// +// API validation already constrains the name to a DNS label, so this is the +// second line: the worker reads the name back from the bundle's +// rootfs-overlay.json rather than from the request it was validated in. +func validateImageVolumeName(name string) error { + if name == "." || !filepath.IsLocal(name) || filepath.Base(name) != name { + return fmt.Errorf("image volume name %q is not a single path element", name) + } + return nil +} + // OverlaySpecFileName is the file atelet writes into each container bundle // describing how to compose the bundle's rootfs from cached layers. Its // absence means the bundle's rootfs is a plain directory (e.g. one prepared by diff --git a/internal/imagecache/spec_test.go b/internal/imagecache/spec_test.go index 5e86d3f5c3..fbc0cb770a 100644 --- a/internal/imagecache/spec_test.go +++ b/internal/imagecache/spec_test.go @@ -23,6 +23,67 @@ import ( "testing" ) +// TestValidateImageVolumeName pins which names setupImageVolumes will build a +// mount point from. The table is the decision; the assertion under it is why +// the decision matters, that an accepted name is always a direct child of the +// bundle's volumes/ directory. +func TestValidateImageVolumeName(t *testing.T) { + const bundle = "/var/lib/ate/bundles/b1" + volumes := filepath.Join(bundle, "volumes") + + for _, tc := range []struct { + name string + valid bool + }{ + {name: "agent", valid: true}, + {name: "my-volume-1", valid: true}, + // Dots are ordinary characters inside a path element. + {name: "..foo", valid: true}, + {name: "foo..", valid: true}, + + {name: "", valid: false}, + // "." resolves to volumes/ itself, which holds every other volume's + // mount point in the bundle. + {name: ".", valid: false}, + {name: "..", valid: false}, + {name: "../../../etc", valid: false}, + // A separator nests the mount somewhere below volumes/ instead; an + // absolute or dot-prefixed form is cleaned by filepath.Join into a + // different volume than the one named. Neither escapes the bundle, + // but neither is the directory the caller asked for either. + {name: "a/b", valid: false}, + {name: "./agent", valid: false}, + {name: "agent/", valid: false}, + {name: "/etc", valid: false}, + } { + t.Run(tc.name, func(t *testing.T) { + err := validateImageVolumeName(tc.name) + if got := err == nil; got != tc.valid { + t.Fatalf("validateImageVolumeName(%q) error = %v, want valid: %t", tc.name, err, tc.valid) + } + if !tc.valid { + return + } + if got := ImageVolumeMountPath(bundle, tc.name); filepath.Dir(got) != volumes { + t.Errorf("ImageVolumeMountPath(%q) = %q, want a direct child of %q", tc.name, got, volumes) + } + }) + } +} + +// TestImageVolumeMountPathEscapesOnTraversal records the behavior the check +// above exists to prevent: without it, the mount point leaves the bundle +// entirely, and setupImageVolumes would MkdirAll, unmount and mount over it. +func TestImageVolumeMountPathEscapesOnTraversal(t *testing.T) { + const bundle = "/var/lib/ate/bundles/b1" + if got, want := ImageVolumeMountPath(bundle, "../../../etc"), "/var/lib/ate/etc"; got != want { + t.Fatalf("ImageVolumeMountPath(%q, %q) = %q, want %q", bundle, "../../../etc", got, want) + } + if got, want := ImageVolumeMountPath(bundle, "."), filepath.Join(bundle, "volumes"); got != want { + t.Fatalf("ImageVolumeMountPath(%q, %q) = %q, want %q", bundle, ".", got, want) + } +} + func TestOverlaySpecRoundTrip(t *testing.T) { bundle := t.TempDir() in := &OverlaySpec{ diff --git a/internal/imagecache/unpack.go b/internal/imagecache/unpack.go index f404f62308..a8c845620e 100644 --- a/internal/imagecache/unpack.go +++ b/internal/imagecache/unpack.go @@ -128,6 +128,10 @@ func unpackLayer(ctx context.Context, tarData io.Reader, root *os.Root) (*whiteo // fabricated attrs. declared := map[string]bool{} implicit := map[string]bool{} + // Paths known to resolve to a directory, so MkdirAll can be skipped. + // replaceExisting clears it, because removing or retargeting any entry + // can change what a cached path resolves to. + existingDirs := map[string]bool{} markAncestors := func(name string) { for p := filepath.Dir(name); p != "."; p = filepath.Dir(p) { if !declared[p] { @@ -151,6 +155,7 @@ func unpackLayer(ctx context.Context, tarData io.Reader, root *os.Root) (*whiteo if err := root.RemoveAll(name); err != nil { return fmt.Errorf("while replacing existing path at %q before %s: %w", name, before, err) } + clear(existingDirs) for inode := range removed { delete(dirHdrs, inode) } @@ -161,6 +166,7 @@ func unpackLayer(ctx context.Context, tarData io.Reader, root *os.Root) (*whiteo } tarReader := tar.NewReader(tarData) + copyBuf := make([]byte, 32*1024) for { hdr, err := tarReader.Next() if errors.Is(err, io.EOF) { @@ -211,45 +217,50 @@ func unpackLayer(ctx context.Context, tarData io.Reader, root *os.Root) (*whiteo // parents must be created here; overlayfs merges them with the // lower layers' directories at compose time. markAncestors(name) - if parent := filepath.Dir(name); parent != "." { + if parent := filepath.Dir(name); parent != "." && !existingDirs[parent] { if err := root.MkdirAll(parent, 0o755); err != nil { return nil, fmt.Errorf("while creating parent directories for %q: %w", name, err) } + for p := parent; p != "." && !existingDirs[p]; p = filepath.Dir(p) { + existingDirs[p] = true + } } switch hdr.Typeflag { case tar.TypeReg: // Regular file - // "Later entry wins" within the layer: if any entry exists at the target - // path, remove it first. This ensures that: - // 1. If it's a symlink, we don't write through it (security vulnerability / incorrectness). - // 2. If it's a hardlink, we unlink it instead of truncating the shared inode. - // 3. If it's a directory, we recursively remove it so we can write the file. - if err := replaceExisting(name, "regular file"); err != nil { - return nil, err - } - // Stream directly from tarReader to target file to avoid buffering in memory. - outFile, err := root.OpenFile(name, os.O_CREATE|os.O_RDWR|os.O_TRUNC, mode) + // O_EXCL fast-paths the common case where name does not exist yet; on + // collision ("later entry wins"), remove the existing entry first so we + // do not follow a symlink, truncate a shared hardlink inode, or fail on a + // directory. + outFile, err := root.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_EXCL, mode) + if errors.Is(err, os.ErrExist) { + if err := replaceExisting(name, "regular file"); err != nil { + return nil, err + } + outFile, err = root.OpenFile(name, os.O_CREATE|os.O_WRONLY|os.O_EXCL, mode) + } if err != nil { return nil, fmt.Errorf("while creating file %q: %w", name, err) } - _, err = io.Copy(outFile, tarReader) - closeErr := outFile.Close() - if err != nil { + if _, err := io.CopyBuffer(writerOnly{outFile}, tarReader, copyBuf); err != nil { + outFile.Close() return nil, fmt.Errorf("while writing contents of %q from tar stream: %w", name, err) } - if closeErr != nil { - return nil, fmt.Errorf("while closing file %q: %w", name, closeErr) - } // OpenFile's mode passed through atelet's umask and carries no // setuid, setgid or sticky bit, and chown clears setuid and // setgid, so the header's mode goes after the owner. - if err := tarutil.Lchown(root, name, hdr); err != nil { + if err := tarutil.Fchown(outFile, hdr); err != nil { + outFile.Close() return nil, err } - if err := setFileMode(root, name, tarutil.Mode(hdr)); err != nil { + if err := setOpenFileMode(outFile, name, tarutil.Mode(hdr)); err != nil { + outFile.Close() return nil, err } + if err := outFile.Close(); err != nil { + return nil, fmt.Errorf("while closing file %q: %w", name, err) + } if err := restoreModTime(root, name, hdr.ModTime); err != nil { return nil, err } @@ -273,6 +284,7 @@ func unpackLayer(ctx context.Context, tarData io.Reader, root *os.Root) (*whiteo return nil, fmt.Errorf("while checking directory %q: %w", name, err) } if fi.IsDir() { + existingDirs[name] = true inode, err := dirInodeOf(name, fi) if err != nil { return nil, err @@ -502,17 +514,37 @@ func dirPaths(root *os.Root, dir string) (map[dirInode]string, error) { return paths, nil } -// setFileMode sets name, a regular file whose owner was just applied, to -// mode. Without CAP_FSETID, chmod drops setgid for a group the caller is not -// in instead of failing, so a setgid mode is read back. +// writerOnly hides *os.File's io.ReaderFrom so io.CopyBuffer uses the caller's +// buffer instead of falling back to genericReadFrom's per-file allocation. +type writerOnly struct{ io.Writer } + +// setOpenFileMode sets an already-open regular file's mode, avoiding a path +// walk through root when the caller still holds the descriptor. +func setOpenFileMode(f *os.File, name string, mode os.FileMode) error { + return applyFileMode(name, mode, f.Chmod, f.Stat) +} + +// setFileMode sets name, a regular file whose owner was just applied, to mode. func setFileMode(root *os.Root, name string, mode os.FileMode) error { - if err := root.Chmod(name, mode); err != nil { + return applyFileMode( + name, + mode, + func(m os.FileMode) error { return root.Chmod(name, m) }, + func() (os.FileInfo, error) { return root.Lstat(name) }, + ) +} + +// applyFileMode sets a regular file's mode and checks that setgid was kept. +// Without CAP_FSETID, chmod drops setgid for a group the caller is not in +// instead of failing, so a setgid mode is read back. +func applyFileMode(name string, mode os.FileMode, chmod func(os.FileMode) error, stat func() (os.FileInfo, error)) error { + if err := chmod(mode); err != nil { return fmt.Errorf("while setting mode %v on %q: %w", mode, name, err) } if mode&os.ModeSetgid == 0 { return nil } - fi, err := root.Lstat(name) + fi, err := stat() if err != nil { return fmt.Errorf("while checking mode of %q: %w", name, err) } diff --git a/internal/imagecache/unpack_test.go b/internal/imagecache/unpack_test.go index d52c2ee80c..b00961ac44 100644 --- a/internal/imagecache/unpack_test.go +++ b/internal/imagecache/unpack_test.go @@ -544,6 +544,27 @@ func TestUnpackLayer_LaterEntryWins(t *testing.T) { t.Errorf("bin/sh content was overwritten to %q (hardlink was not unlinked)", gotSh) } }) + + t.Run("implicit parent recreated after ancestor replaced by symlink", func(t *testing.T) { + // "a/b/first" populates existingDirs["a/b"]. Replacing "a" with a + // symlink to "cc" (which has no "b/" yet) must invalidate existingDirs + // so "a/b/second" creates "cc/b". + entries := []tarEntry{ + {name: "a/b/first", typeflag: tar.TypeReg, body: "first"}, + {name: "cc/", typeflag: tar.TypeDir}, + {name: "a", typeflag: tar.TypeSymlink, linkname: "cc"}, + {name: "a/b/second", typeflag: tar.TypeReg, body: "second"}, + } + dir, _, err := runUnpack(t, entries) + if err != nil { + t.Fatalf("unpackLayer: %v", err) + } + if got, err := os.ReadFile(filepath.Join(dir, "cc/b/second")); err != nil { + t.Fatalf("read cc/b/second: %v", err) + } else if string(got) != "second" { + t.Errorf("cc/b/second = %q, want %q", got, "second") + } + }) } // A read-only directory in the image (e.g. ko ships /ko-app as 0555) must still diff --git a/internal/imagecache/verify.go b/internal/imagecache/verify.go index f2b5151eb8..563df84fc5 100644 --- a/internal/imagecache/verify.go +++ b/internal/imagecache/verify.go @@ -15,18 +15,28 @@ package imagecache import ( + "bufio" + "bytes" "encoding/hex" "errors" "fmt" "io" v1 "github.com/google/go-containerregistry/pkg/v1" + "github.com/klauspost/compress/gzip" + "github.com/klauspost/compress/zstd" ) // errDiffIDMismatch marks layer content that does not hash to its claimed // diffID. It is a property of the image, so retrying cannot fix it. var errDiffIDMismatch = errors.New("layer content does not match its claimed diffID") +// Magic numbers at the start of gzip (RFC 1952) and zstd (RFC 8878) streams. +var ( + gzipMagic = []byte{0x1f, 0x8b} + zstdMagic = []byte{0x28, 0xb5, 0x2f, 0xfd} +) + // readVerifiedLayer passes the layer's uncompressed stream to consume, then // reads whatever consume left unread and checks that the whole stream // hashes to diffID. It returns only the number of bytes consume read. The @@ -39,17 +49,44 @@ var errDiffIDMismatch = errors.New("layer content does not match its claimed dif // go-containerregistry check the compressed blob against the manifest // digest, which it does only at EOF. func readVerifiedLayer(layer v1.Layer, diffID v1.Hash, consume func(io.Reader) error) (int64, error) { - rc, err := layer.Uncompressed() + // Decompress here because layer.Uncompressed() uses the slower stdlib gzip. + rc, err := layer.Compressed() if err != nil { return 0, fmt.Errorf("while opening layer stream: %w", err) } defer rc.Close() + buf := bufio.NewReader(rc) + // A stream shorter than zstdMagic returns io.EOF with the bytes it has. + magic, err := buf.Peek(len(zstdMagic)) + if err != nil && !errors.Is(err, io.EOF) { + return 0, fmt.Errorf("while peeking layer stream: %w", err) + } + var r io.Reader = buf + switch { + case bytes.HasPrefix(magic, gzipMagic): + gzr, err := gzip.NewReader(buf) + if err != nil { + return 0, fmt.Errorf("while opening gzip layer stream: %w", err) + } + defer gzr.Close() + r = gzr + case bytes.HasPrefix(magic, zstdMagic): + zr, err := zstd.NewReader(buf) + if err != nil { + return 0, fmt.Errorf("while opening zstd layer stream: %w", err) + } + defer zr.Close() + r = zr + default: + // Not compressed. go-containerregistry's Uncompressed() passes these through as is. + } + hasher, err := v1.Hasher(diffID.Algorithm) if err != nil { return 0, fmt.Errorf("while creating hasher for %s: %w", diffID, err) } - tee := io.TeeReader(rc, hasher) + tee := io.TeeReader(r, hasher) counter := &countingReader{r: tee} if err := consume(counter); err != nil { return 0, err diff --git a/internal/imagecache/verify_test.go b/internal/imagecache/verify_test.go index 5fd9687523..00b222a0bc 100644 --- a/internal/imagecache/verify_test.go +++ b/internal/imagecache/verify_test.go @@ -28,9 +28,11 @@ import ( "strings" "sync/atomic" "testing" + "testing/iotest" "testing/synctest" "github.com/google/go-containerregistry/pkg/authn" + "github.com/google/go-containerregistry/pkg/compression" "github.com/google/go-containerregistry/pkg/name" v1 "github.com/google/go-containerregistry/pkg/v1" "github.com/google/go-containerregistry/pkg/v1/empty" @@ -235,7 +237,7 @@ func TestDiffIDMismatchNotRetriedPerCredential(t *testing.T) { } } -// gatedLayer holds a layer flight open: its uncompressed stream closes +// gatedLayer holds a layer flight open: its compressed stream closes // started, blocks until release is closed, then fails with err if set. type gatedLayer struct { v1.Layer @@ -247,24 +249,24 @@ func newGatedLayer(layer v1.Layer, err error) gatedLayer { return gatedLayer{Layer: layer, started: make(chan struct{}), release: make(chan struct{}), err: err} } -func (g gatedLayer) Uncompressed() (io.ReadCloser, error) { +func (g gatedLayer) Compressed() (io.ReadCloser, error) { close(g.started) <-g.release if g.err != nil { return nil, g.err } - return g.Layer.Uncompressed() + return g.Layer.Compressed() } -// openCountingLayer counts opens of its uncompressed stream. +// openCountingLayer counts opens of its compressed stream. type openCountingLayer struct { v1.Layer opens *atomic.Int32 } -func (c openCountingLayer) Uncompressed() (io.ReadCloser, error) { +func (c openCountingLayer) Compressed() (io.ReadCloser, error) { c.opens.Add(1) - return c.Layer.Uncompressed() + return c.Layer.Compressed() } // joinFlight runs ensureLayer for leader, then for joiner once the leader's @@ -351,6 +353,27 @@ func TestSameBlobPullsShareOneFlight(t *testing.T) { }) } +type uncompressedLayer struct{ v1.Layer } + +func (u uncompressedLayer) Compressed() (io.ReadCloser, error) { return u.Uncompressed() } + +var errBlobEOF = errors.New("compressed blob read to EOF") + +// blobEOFLayer returns errBlobEOF where its compressed stream would return +// io.EOF. go-containerregistry checks the manifest digest only at that EOF. +type blobEOFLayer struct{ v1.Layer } + +func (l blobEOFLayer) Compressed() (io.ReadCloser, error) { + rc, err := l.Layer.Compressed() + if err != nil { + return nil, err + } + return struct { + io.Reader + io.Closer + }{io.MultiReader(rc, iotest.ErrReader(errBlobEOF)), rc}, nil +} + // The hash covers the whole uncompressed stream, while the returned length // covers only what the consumer read. func TestReadVerifiedLayerDrainsStream(t *testing.T) { @@ -359,19 +382,36 @@ func TestReadVerifiedLayerDrainsStream(t *testing.T) { if err != nil { t.Fatal(err) } + zstdLayer := func(body string) v1.Layer { + return layerFromEntries(t, []tarEntry{{name: "lib", typeflag: tar.TypeReg, mode: 0o644, body: body}}, tarball.WithCompression(compression.ZStd)) + } readTen := func(r io.Reader) error { _, err := io.CopyN(io.Discard, r, 10) return err } - n, err := readVerifiedLayer(good, diffID, readTen) - if err != nil { - t.Fatalf("readVerifiedLayer(good): %v", err) - } - if n != 10 { - t.Errorf("length = %d, want 10", n) - } - if _, err := readVerifiedLayer(evil, diffID, readTen); !errors.Is(err, errDiffIDMismatch) { - t.Errorf("readVerifiedLayer(evil) error = %v, want errDiffIDMismatch", err) + for _, tc := range []struct { + name string + good, evil v1.Layer + }{ + {name: "gzip", good: good, evil: evil}, + {name: "zstd", good: zstdLayer("good"), evil: zstdLayer("EVIL")}, + {name: "uncompressed", good: uncompressedLayer{good}, evil: uncompressedLayer{evil}}, + } { + t.Run(tc.name, func(t *testing.T) { + n, err := readVerifiedLayer(tc.good, diffID, readTen) + if err != nil { + t.Fatalf("readVerifiedLayer(good): %v", err) + } + if n != 10 { + t.Errorf("length = %d, want 10", n) + } + if _, err := readVerifiedLayer(tc.evil, diffID, readTen); !errors.Is(err, errDiffIDMismatch) { + t.Errorf("readVerifiedLayer(evil) error = %v, want errDiffIDMismatch", err) + } + if _, err := readVerifiedLayer(blobEOFLayer{tc.good}, diffID, readTen); !errors.Is(err, errBlobEOF) { + t.Errorf("readVerifiedLayer error = %v, want %v: the compressed blob must be read to EOF", err, errBlobEOF) + } + }) } } diff --git a/internal/linuxsys/sockopt_linux.go b/internal/linuxsys/sockopt_linux.go new file mode 100644 index 0000000000..3bbeeb7003 --- /dev/null +++ b/internal/linuxsys/sockopt_linux.go @@ -0,0 +1,80 @@ +// Copyright 2026 The Agent Substrate 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. + +//go:build linux + +package linuxsys + +import ( + "fmt" + "net" + "syscall" + + "golang.org/x/sys/unix" +) + +// TCPNotSentLowatControl returns a net.Dialer or net.ListenConfig Control +// function that sets TCP_NOTSENT_LOWAT to bytes: the socket accepts writes +// only while fewer than bytes wait to be sent, so a slow reader blocks the +// writer instead of filling the kernel send queue. With bytes 0 it sets +// nothing. +func TCPNotSentLowatControl(bytes int) func(network, address string, c syscall.RawConn) error { + return func(_, _ string, c syscall.RawConn) error { + return setTCPNotSentLowat(c, bytes) + } +} + +// SetTCPNotSentLowat sets TCP_NOTSENT_LOWAT on an open TCP connection, such as +// one returned by Accept. With bytes 0 it does nothing. +func SetTCPNotSentLowat(conn net.Conn, bytes int) error { + if bytes == 0 { + return nil + } + rawConn, err := tcpRawConn(conn) + if err != nil { + return err + } + return setTCPNotSentLowat(rawConn, bytes) +} + +func setTCPNotSentLowat(c syscall.RawConn, bytes int) error { + if bytes < 0 { + return fmt.Errorf("linuxsys: TCP_NOTSENT_LOWAT must not be negative, got %d", bytes) + } + if bytes == 0 { + return nil + } + var sockoptErr error + if err := c.Control(func(fd uintptr) { + sockoptErr = unix.SetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_NOTSENT_LOWAT, bytes) + }); err != nil { + return fmt.Errorf("linuxsys: accessing socket: %w", err) + } + if sockoptErr != nil { + return fmt.Errorf("linuxsys: setting TCP_NOTSENT_LOWAT to %d: %w", bytes, sockoptErr) + } + return nil +} + +func tcpRawConn(conn net.Conn) (syscall.RawConn, error) { + tcpConn, ok := conn.(*net.TCPConn) + if !ok { + return nil, fmt.Errorf("linuxsys: TCP_NOTSENT_LOWAT requires a TCP connection, got %T", conn) + } + rawConn, err := tcpConn.SyscallConn() + if err != nil { + return nil, fmt.Errorf("linuxsys: acquiring TCP syscall connection: %w", err) + } + return rawConn, nil +} diff --git a/internal/linuxsys/sockopt_linux_test.go b/internal/linuxsys/sockopt_linux_test.go new file mode 100644 index 0000000000..b46f607118 --- /dev/null +++ b/internal/linuxsys/sockopt_linux_test.go @@ -0,0 +1,100 @@ +// Copyright 2026 The Agent Substrate 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. + +//go:build linux + +package linuxsys + +import ( + "net" + "testing" + + "golang.org/x/sys/unix" +) + +// connPair returns a connection dialed with dialer and the one accepted for it. +func connPair(t *testing.T, dialer *net.Dialer) (client, server net.Conn) { + t.Helper() + listener, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { listener.Close() }) + client, err = dialer.Dial("tcp", listener.Addr().String()) + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { client.Close() }) + server, err = listener.Accept() + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { server.Close() }) + return client, server +} + +// readLowat returns the TCP_NOTSENT_LOWAT in effect on conn: 0 while the +// socket uses the net.ipv4.tcp_notsent_lowat sysctl. +func readLowat(t *testing.T, conn net.Conn) int { + t.Helper() + rawConn, err := tcpRawConn(conn) + if err != nil { + t.Fatal(err) + } + var got int + var sockoptErr error + if err := rawConn.Control(func(fd uintptr) { + got, sockoptErr = unix.GetsockoptInt(int(fd), unix.IPPROTO_TCP, unix.TCP_NOTSENT_LOWAT) + }); err != nil { + t.Fatal(err) + } + if sockoptErr != nil { + t.Fatal(sockoptErr) + } + return got +} + +func TestTCPNotSentLowatDialAndSet(t *testing.T) { + client, server := connPair(t, &net.Dialer{Control: TCPNotSentLowatControl(16384)}) + if got := readLowat(t, client); got != 16384 { + t.Errorf("dialed connection TCP_NOTSENT_LOWAT = %d, want 16384", got) + } + // The accepted connection starts at 0, or at -1 under an MPTCP listener. + if got := readLowat(t, server); got == 16384 { + t.Fatal("accepted connection has TCP_NOTSENT_LOWAT 16384 before SetTCPNotSentLowat") + } + if err := SetTCPNotSentLowat(server, 16384); err != nil { + t.Fatal(err) + } + if got := readLowat(t, server); got != 16384 { + t.Errorf("accepted connection TCP_NOTSENT_LOWAT = %d, want 16384", got) + } +} + +func TestTCPNotSentLowatZeroSetsNothing(t *testing.T) { + client, _ := connPair(t, &net.Dialer{Control: TCPNotSentLowatControl(0)}) + if err := SetTCPNotSentLowat(client, 0); err != nil { + t.Fatal(err) + } + if got := readLowat(t, client); got != 0 { + t.Errorf("TCP_NOTSENT_LOWAT = %d, want 0", got) + } +} + +func TestTCPNotSentLowatRejectsNegative(t *testing.T) { + client, _ := connPair(t, &net.Dialer{}) + if err := SetTCPNotSentLowat(client, -1); err == nil { + t.Error("SetTCPNotSentLowat accepted -1") + } +} diff --git a/internal/netns/netns.go b/internal/netns/netns.go index eb20f56f83..008d4d5a42 100644 --- a/internal/netns/netns.go +++ b/internal/netns/netns.go @@ -152,7 +152,7 @@ func Listen(ctx context.Context, ns Handle, ports []uint16) (_ []net.Listener, r }() if err := Do(ctx, ns, func(context.Context) error { for _, port := range ports { - l, err := net.Listen("tcp", fmt.Sprintf("0.0.0.0:%d", port)) + l, err := net.Listen("tcp", net.JoinHostPort("", fmt.Sprint(port))) if err != nil { return fmt.Errorf("while listening on port %d: %w", port, err) } diff --git a/internal/nodepath/nodepath.go b/internal/nodepath/nodepath.go index f8ae3c6b72..c73f5ed9cc 100644 --- a/internal/nodepath/nodepath.go +++ b/internal/nodepath/nodepath.go @@ -86,7 +86,8 @@ func AteletOTLPSocketPath() string { // WorkersDir is the parent of every per-worker directory, so listing it is how // a scraper with no prior knowledge discovers the node's workers. atelet -// creates WorkerPath(podUID) once it writes the pod's sandbox runtimes file and +// creates WorkerPath(podUID) when it first stages the pod's default sandbox +// runtime under it, before it writes the pod's sandbox runtimes file, and // removes it when the pod is deleted; the worker also MkdirAlls it at boot. A // directory may exist before its worker listens on its socket. func WorkersDir() string { diff --git a/internal/objectstoreplugin/exchange/exchange.go b/internal/objectstoreplugin/exchange/exchange.go index 0a121be353..87c00f038d 100644 --- a/internal/objectstoreplugin/exchange/exchange.go +++ b/internal/objectstoreplugin/exchange/exchange.go @@ -41,11 +41,12 @@ import ( const DefaultPort = 8445 // Issuer mints a credential limited to grants for the actor. force skips any -// cache the issuer keeps. An error carrying a gRPC status code other than -// Unavailable is passed to the caller unchanged, for failures the same request -// would hit again, and one wrapping the context's error keeps the caller's -// code. Any other error is reported as Unavailable. The GCS issuer is -// gcsissuer. +// cache of minted credentials the issuer keeps. What the issuer keeps to mint +// them, such as gcsissuer's intermediary token, may still be reused. An error +// carrying a gRPC status code other than Unavailable is passed to the caller +// unchanged, for failures the same request would hit again, and one wrapping +// the context's error keeps the caller's code. Any other error is reported as +// Unavailable. The GCS issuer is gcsissuer. type Issuer interface { Issue(ctx context.Context, actorUID string, grants []actorscope.Grant, force bool) (credential.Token, error) } diff --git a/internal/objectstoreplugin/exchangeclient/exchangeclient.go b/internal/objectstoreplugin/exchangeclient/exchangeclient.go index abf7999c9d..1a2721ba9a 100644 --- a/internal/objectstoreplugin/exchangeclient/exchangeclient.go +++ b/internal/objectstoreplugin/exchangeclient/exchangeclient.go @@ -23,14 +23,20 @@ package exchangeclient import ( "context" "crypto/tls" + "crypto/x509" "errors" "fmt" "io" + "net" + "net/http" + "strings" + "sync/atomic" "time" "go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc" "golang.org/x/oauth2" "google.golang.org/api/option" + htransport "google.golang.org/api/transport/http" "google.golang.org/grpc" "google.golang.org/grpc/codes" "google.golang.org/grpc/credentials" @@ -49,6 +55,11 @@ import ( // only costs the next transfer an exchange and a new client. const defaultCacheSize = 1_000 +// transportPoolSize is how many HTTP/2 transports Source shares across actor +// clients on a node, sized so concurrent ranged restores across several actors +// do not bottleneck on a single transfer's 8-stream width. +const transportPoolSize = 32 + // Config is how the exchange is reached. type Config struct { // Address is the exchange's host and port, the ate-api-server Service. @@ -69,7 +80,7 @@ type Source struct { // cache maps an actor JWT to its entry: the token the exchange returned // for that JWT and the storage client built with the token. Nothing // closes a client that leaves the cache. A transfer still using it - // finishes on it, and its connections close on their own once idle. + // finishes on the shared transport pool. cache *lru.Cache } @@ -85,30 +96,127 @@ func New(cfg Config) (*Source, error) { if cfg.Address == "" { return nil, errors.New("exchangeclient: Address is required") } - pool, err := credbundle.ParsePool(cfg.CAFile) - if err != nil { + serverName := cfg.ServerName + if serverName == "" { + // Name the exchange is verified against when ServerName is unset, + // as gRPC did from the dial address before verification moved into + // VerifyConnection. x509 skips the hostname check for an empty name. + target := cfg.Address[strings.LastIndex(cfg.Address, "/")+1:] + host, _, err := net.SplitHostPort(target) + if err != nil || host == "" { + return nil, fmt.Errorf("exchangeclient: ServerName is required when Address %q has no host", cfg.Address) + } + serverName = host + } + loadRootCAs := credbundle.PoolLoader(cfg.CAFile) + if _, err := loadRootCAs(); err != nil { return nil, fmt.Errorf("exchangeclient: while loading the exchange CA bundle: %w", err) } - creds := credentials.NewTLS(&tls.Config{MinVersion: tls.VersionTLS13, RootCAs: pool, ServerName: cfg.ServerName}) + creds := credentials.NewTLS(&tls.Config{ + MinVersion: tls.VersionTLS13, + ServerName: serverName, + // RootCAs is frozen once the config is in use, so the exchange's + // certificate is verified in VerifyConnection against the reloadable + // pool: a CA rotation applies on the next handshake, without + // restarting the plugin. + InsecureSkipVerify: true, //nolint:gosec + VerifyConnection: func(cs tls.ConnectionState) error { + pool, err := loadRootCAs() + if err != nil { + return err + } + if len(cs.PeerCertificates) == 0 { + return errors.New("exchangeclient: the exchange presented no certificate") + } + inter := x509.NewCertPool() + for _, c := range cs.PeerCertificates[1:] { + inter.AddCert(c) + } + _, err = cs.PeerCertificates[0].Verify(x509.VerifyOptions{ + Roots: pool, + Intermediates: inter, + DNSName: serverName, + }) + return err + }, + }) conn, err := grpc.NewClient(cfg.Address, grpc.WithTransportCredentials(creds), grpc.WithStatsHandler(otelgrpc.NewClientHandler())) if err != nil { return nil, fmt.Errorf("exchangeclient: while creating the exchange client: %w", err) } - s := newSource(exchangepb.NewCredentialExchangeClient(conn), newGCSClient) + s := newPoolSource(exchangepb.NewCredentialExchangeClient(conn), defaultBaseTransport()) s.conn = conn return s, nil } +func defaultBaseTransport() *http.Transport { + if t, ok := http.DefaultTransport.(*http.Transport); ok && t != nil { + return t + } + return &http.Transport{ + Proxy: http.ProxyFromEnvironment, + DialContext: (&net.Dialer{ + Timeout: 30 * time.Second, + KeepAlive: 30 * time.Second, + }).DialContext, + ForceAttemptHTTP2: true, + MaxIdleConns: 100, + IdleConnTimeout: 90 * time.Second, + TLSHandshakeTimeout: 10 * time.Second, + ExpectContinueTimeout: 1 * time.Second, + } +} + func newSource(exchange exchangepb.CredentialExchangeClient, newClient func(context.Context, credential.Token) (objectstorage.ObjectStorage, error)) *Source { return &Source{exchange: exchange, newClient: newClient, now: time.Now, cache: lru.New(defaultCacheSize)} } -// newGCSClient builds a client that authenticates with tok alone. It outlives -// the request that built it, so it must not carry that request's +func newPoolSource(exchange exchangepb.CredentialExchangeClient, base *http.Transport) *Source { + return newSource(exchange, newTransportPool(base).newClient) +} + +// transportPool spreads GCS requests round-robin across a fixed set of +// HTTP/2 transports shared by every actor client built from a Source. +type transportPool struct { + transports []*http.Transport + next atomic.Uint64 +} + +func newTransportPool(base *http.Transport) *transportPool { + transports := make([]*http.Transport, transportPoolSize) + for i := range transports { + t := base.Clone() + // WithHTTPClient skips google.golang.org/api/transport/http's + // defaultBaseTransport, so apply its idle pool and HTTP/2 ping defaults + // here. + t.MaxIdleConnsPerHost = 100 + if t.HTTP2 == nil { + t.HTTP2 = &http.HTTP2Config{} + } + t.HTTP2.SendPingTimeout = 31 * time.Second + transports[i] = t + } + return &transportPool{transports: transports} +} + +func (p *transportPool) RoundTrip(req *http.Request) (*http.Response, error) { + i := (p.next.Add(1) - 1) % uint64(len(p.transports)) + return p.transports[i].RoundTrip(req) +} + +// newClient builds a client that authenticates with tok alone over p. It +// outlives the request that built it, so it must not carry that request's // cancellation. -func newGCSClient(ctx context.Context, tok credential.Token) (objectstorage.ObjectStorage, error) { +func (p *transportPool) newClient(ctx context.Context, tok credential.Token) (objectstorage.ObjectStorage, error) { + bg := context.WithoutCancel(ctx) source := oauth2.StaticTokenSource(&oauth2.Token{AccessToken: tok.AccessToken, Expiry: tok.Expiry}) - return objectstorage.NewGCSClient(context.WithoutCancel(ctx), option.WithTokenSource(source)) + rt, err := htransport.NewTransport(bg, p, option.WithTokenSource(source)) + if err != nil { + return nil, err + } + // rt already attaches tok. WithoutAuthentication keeps storage.NewClient + // from probing ambient credentials that WithHTTPClient ignores. + return objectstorage.NewGCSClient(bg, option.WithoutAuthentication(), option.WithHTTPClient(&http.Client{Transport: rt})) } // Close closes the connection to the exchange. diff --git a/internal/objectstoreplugin/exchangeclient/exchangeclient_test.go b/internal/objectstoreplugin/exchangeclient/exchangeclient_test.go index 56e54c7311..fd76feeac1 100644 --- a/internal/objectstoreplugin/exchangeclient/exchangeclient_test.go +++ b/internal/objectstoreplugin/exchangeclient/exchangeclient_test.go @@ -15,21 +15,36 @@ package exchangeclient import ( + "bytes" "context" + "crypto/tls" + "encoding/pem" "errors" + "fmt" "io" + "net" + "net/http" + "net/http/httptest" + "os" "path/filepath" + "strings" + "sync" + "sync/atomic" "testing" "time" + "golang.org/x/sync/errgroup" "google.golang.org/grpc" "google.golang.org/grpc/codes" + "google.golang.org/grpc/credentials" "google.golang.org/grpc/status" "google.golang.org/protobuf/types/known/timestamppb" "k8s.io/utils/lru" + "go.ate.dev/substrate/internal/localca" "go.ate.dev/substrate/internal/objectstoreplugin/credential" exchangepb "go.ate.dev/substrate/internal/proto/objectstoreexchangepb" + "go.ate.dev/substrate/internal/testcert" "go.ate.dev/substrate/pkg/objectstorage" ) @@ -110,6 +125,9 @@ func TestClient_CachesTheTokenAndClientPerJWTUntilNearExpiry(t *testing.T) { if client, err := s.Client(t.Context(), "jwt-a", false); err != nil || tokenOf(client) != "tok-2" || len(exchange.calls) != 3 { t.Fatalf("after the refresh: client %v, err %v, calls %d, want tok-2 from the cache", client, err, len(exchange.calls)) } + if err := s.Close(); err != nil { + t.Fatalf("Close() = %v", err) + } } func TestClient_ForceSkipsBothCaches(t *testing.T) { @@ -251,4 +269,471 @@ func TestNew_ChecksItsConfig(t *testing.T) { } } +type actorTokenExchange struct { + exchangepb.CredentialExchangeClient + expiry time.Time +} + +func (e *actorTokenExchange) ExchangeActorJwt(_ context.Context, in *exchangepb.ExchangeActorJwtRequest, _ ...grpc.CallOption) (*exchangepb.ExchangeActorJwtResponse, error) { + tok := "tok-" + in.GetActorJwt() + if in.GetForce() { + tok += "-forced" + } + return &exchangepb.ExchangeActorJwtResponse{ + AccessToken: tok, + ExpireTime: timestamppb.New(e.expiry), + }, nil +} + +func TestSource_SharesTransportsAcrossActors(t *testing.T) { + t.Setenv("STORAGE_EMULATOR_HOST", "") + t.Setenv("GOOGLE_APPLICATION_CREDENTIALS", "") + t.Setenv("GCE_METADATA_HOST", "127.0.0.1:1") + + var ( + totalConns atomic.Int64 + liveConns atomic.Int64 + connsMu sync.Mutex + connHits = make(map[string]int) + holdEntered = make(chan struct{}) + holdRelease = make(chan struct{}) + holdOnce sync.Once + badReq atomic.Pointer[string] + ) + releaseHold := sync.OnceFunc(func() { close(holdRelease) }) + recordFailure := func(msg string) { + badReq.CompareAndSwap(nil, &msg) + } + + gcs := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.ProtoMajor != 2 { + recordFailure(fmt.Sprintf("proto = %s, want HTTP/2", r.Proto)) + http.Error(w, "want HTTP/2", http.StatusHTTPVersionNotSupported) + return + } + connsMu.Lock() + connHits[r.RemoteAddr]++ + connsMu.Unlock() + var object string + switch r.Method { + case http.MethodPost: + object = r.URL.Query().Get("name") + case http.MethodGet: + object = strings.TrimPrefix(r.URL.Path, "/bucket/") + default: + recordFailure(fmt.Sprintf("unexpected %s %s", r.Method, r.URL)) + http.Error(w, "unexpected method", http.StatusMethodNotAllowed) + return + } + actor, rest, ok := strings.Cut(object, "/") + if !ok { + recordFailure(fmt.Sprintf("unexpected object %q", object)) + http.Error(w, "bad object", http.StatusBadRequest) + return + } + wantAuth := "Bearer tok-" + actor + if strings.HasPrefix(rest, "forced") { + wantAuth += "-forced" + } + if got := r.Header.Get("Authorization"); got != wantAuth { + recordFailure(fmt.Sprintf("object %q got Authorization %q, want %q", object, got, wantAuth)) + http.Error(w, "wrong token", http.StatusForbidden) + return + } + if r.Method == http.MethodGet { + body := "payload-" + actor + w.Header().Set("Content-Type", "application/octet-stream") + w.Header().Set("Content-Range", fmt.Sprintf("bytes 0-%d/%d", len(body)-1, len(body))) + w.Header().Set("Content-Length", fmt.Sprintf("%d", len(body))) + w.WriteHeader(http.StatusPartialContent) + _, _ = io.WriteString(w, body) + return + } + _, _ = io.Copy(io.Discard, r.Body) + if rest == "inflight" { + holdOnce.Do(func() { close(holdEntered) }) + select { + case <-holdRelease: + case <-r.Context().Done(): + return + } + } + w.Header().Set("Content-Type", "application/json") + _, _ = fmt.Fprintf(w, `{"name":%q,"bucket":"bucket"}`, object) + })) + gcs.EnableHTTP2 = true + gcs.Config.ConnState = func(_ net.Conn, state http.ConnState) { + switch state { + case http.StateNew: + totalConns.Add(1) + liveConns.Add(1) + case http.StateClosed, http.StateHijacked: + liveConns.Add(-1) + } + } + gcs.StartTLS() + t.Cleanup(gcs.Close) + t.Cleanup(gcs.CloseClientConnections) + t.Cleanup(releaseHold) + + now := time.Date(2026, 10, 20, 10, 0, 0, 0, time.UTC) + base := gcs.Client().Transport.(*http.Transport).Clone() + base.DialContext = func(ctx context.Context, network, _ string) (net.Conn, error) { + var d net.Dialer + return d.DialContext(ctx, network, gcs.Listener.Addr().String()) + } + base.TLSClientConfig.ServerName = "example.com" + base.HTTP2 = &http.HTTP2Config{MaxReadFrameSize: 32 << 10} + for i, tr := range newTransportPool(base).transports { + if tr.MaxIdleConnsPerHost != 100 || tr.HTTP2 == nil || tr.HTTP2.MaxReadFrameSize != 32<<10 || tr.HTTP2.SendPingTimeout != 31*time.Second { + t.Fatalf("transport %d settings = (MaxIdleConnsPerHost=%d, HTTP2=%+v)", i, tr.MaxIdleConnsPerHost, tr.HTTP2) + } + } + s := newPoolSource(&actorTokenExchange{expiry: now.Add(time.Hour)}, base) + if base.HTTP2.SendPingTimeout != 0 { + t.Fatalf("newPoolSource mutated base.HTTP2.SendPingTimeout = %v", base.HTTP2.SendPingTimeout) + } + s.now = func() time.Time { return now } + s.cache = lru.New(2) + + getObject := func(ctx context.Context, c objectstorage.ObjectStorage, actor, object string) error { + rc, err := c.GetObject(ctx, "bucket", object) + if err != nil { + return err + } + got, readErr := io.ReadAll(rc) + if err := errors.Join(readErr, rc.Close()); err != nil { + return err + } + if want := "payload-" + actor; string(got) != want { + return fmt.Errorf("GetObject(%s) = %q, want %q", object, got, want) + } + return nil + } + + // Open all transportPoolSize HTTP/2 connections before concurrent transfers + // so cold ALPN handshakes do not race. Warm with GetObject because + // PutObject allocates a 64 MiB lookahead buffer per unbounded reader. + warmClient, err := s.Client(t.Context(), "actor-1", false) + if err != nil { + t.Fatal(err) + } + for i := range transportPoolSize { + if err := getObject(t.Context(), warmClient, "actor-1", fmt.Sprintf("actor-1/warm-%d", i)); err != nil { + t.Fatalf("warm GetObject %d: %v", i, err) + } + } + if got := totalConns.Load(); got != transportPoolSize { + t.Fatalf("warmed %d TLS connections, want %d", got, transportPoolSize) + } + + // Hold an upload open on actor-0 while later actors evict it from s.cache. + evictedClient, err := s.Client(t.Context(), "actor-0", false) + if err != nil { + t.Fatal(err) + } + heldErr := make(chan error, 1) + go func() { + heldErr <- evictedClient.PutObject(t.Context(), "bucket", "actor-0/inflight", bytes.NewReader([]byte("snap"))) + }() + select { + case <-holdEntered: + case err := <-heldErr: + t.Fatalf("actor-0 upload exited before hold: %v", err) + case <-t.Context().Done(): + t.Fatal("timed out waiting for actor-0 upload to reach server") + } + + const actors = 40 + grp, gctx := errgroup.WithContext(t.Context()) + for i := 2; i < 2+actors; i++ { + actor := fmt.Sprintf("actor-%d", i) + put := i < 4 + grp.Go(func() error { + c, err := s.Client(gctx, actor, false) + if err != nil { + return err + } + if put { + if err := c.PutObject(gctx, "bucket", actor+"/put", bytes.NewReader([]byte("snap"))); err != nil { + return err + } + } + return getObject(gctx, c, actor, actor+"/get") + }) + } + if err := grp.Wait(); err != nil { + t.Fatalf("actor transfers failed: %v", err) + } + + forced, err := s.Client(t.Context(), "actor-2", true) + if err != nil { + t.Fatal(err) + } + if err := forced.PutObject(t.Context(), "bucket", "actor-2/forced", bytes.NewReader([]byte("snap"))); err != nil { + t.Fatalf("forced PutObject: %v", err) + } + + releaseHold() + if err := <-heldErr; err != nil { + t.Fatalf("evicted actor-0 upload failed: %v", err) + } + if msg := badReq.Load(); msg != nil { + t.Fatalf("server saw invalid request: %s", *msg) + } + if got := totalConns.Load(); got != transportPoolSize { + t.Fatalf("opened %d TLS connections across %d actors, want %d", got, actors+2, transportPoolSize) + } + if got := liveConns.Load(); got != transportPoolSize { + t.Fatalf("live TLS connections = %d, want %d", got, transportPoolSize) + } + connsMu.Lock() + distinctConns := len(connHits) + for addr, hits := range connHits { + if hits < 2 { + t.Errorf("connection %s served %d requests, want >= 2 across actor churn", addr, hits) + } + } + connsMu.Unlock() + if distinctConns != transportPoolSize { + t.Fatalf("requests used %d distinct TLS connections, want %d", distinctConns, transportPoolSize) + } +} + +type exchangeServer struct { + exchangepb.UnimplementedCredentialExchangeServer + expiry time.Time +} + +func (s *exchangeServer) ExchangeActorJwt(_ context.Context, in *exchangepb.ExchangeActorJwtRequest) (*exchangepb.ExchangeActorJwtResponse, error) { + return &exchangepb.ExchangeActorJwtResponse{ + AccessToken: "tok-" + in.GetActorJwt(), + ExpireTime: timestamppb.New(s.expiry), + }, nil +} + +func TestNew_ExchangesAndCloses(t *testing.T) { + var gotAuth atomic.Pointer[string] + emulator := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + auth := r.Header.Get("Authorization") + gotAuth.Store(&auth) + _, _ = io.Copy(io.Discard, r.Body) + w.Header().Set("Content-Type", "application/json") + _, _ = w.Write([]byte(`{"name":"obj","bucket":"bucket"}`)) + })) + t.Cleanup(emulator.Close) + t.Setenv("STORAGE_EMULATOR_HOST", strings.TrimPrefix(emulator.URL, "http://")) + + serverTLS := testcert.NewServerTLS(t, net.ParseIP("127.0.0.1")) + caFile := filepath.Join(t.TempDir(), "ca.pem") + if err := os.WriteFile(caFile, serverTLS.RootCA, 0o600); err != nil { + t.Fatal(err) + } + cert, err := tls.X509KeyPair(serverTLS.Certificate, serverTLS.PrivateKey) + if err != nil { + t.Fatal(err) + } + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + grpcSrv := grpc.NewServer(grpc.Creds(credentials.NewTLS(&tls.Config{ + MinVersion: tls.VersionTLS13, + Certificates: []tls.Certificate{cert}, + }))) + exchangepb.RegisterCredentialExchangeServer(grpcSrv, &exchangeServer{expiry: time.Now().Add(time.Hour)}) + go func() { _ = grpcSrv.Serve(lis) }() + t.Cleanup(grpcSrv.Stop) + + s, err := New(Config{Address: lis.Addr().String(), CAFile: caFile}) + if err != nil { + t.Fatalf("New() = %v", err) + } + t.Cleanup(func() { _ = s.Close() }) + + client, err := s.Client(t.Context(), "actor-a", false) + if err != nil { + t.Fatalf("Client() = %v", err) + } + if err := client.PutObject(t.Context(), "bucket", "obj", bytes.NewReader([]byte("data"))); err != nil { + t.Fatalf("PutObject() = %v", err) + } + if auth := gotAuth.Load(); auth == nil || *auth != "Bearer tok-actor-a" { + t.Fatalf("Authorization = %v, want %q", auth, "Bearer tok-actor-a") + } + if err := s.Close(); err != nil { + t.Fatalf("Close() = %v", err) + } + if _, err := s.Client(t.Context(), "actor-b", false); status.Code(err) != codes.Canceled { + t.Fatalf("Client() after Close() = %v, want Canceled", err) + } +} + +type wrappedRoundTripper struct{ http.RoundTripper } + +func TestDefaultBaseTransport(t *testing.T) { + orig := http.DefaultTransport + t.Cleanup(func() { http.DefaultTransport = orig }) + + if got := defaultBaseTransport(); got != orig { + t.Fatalf("defaultBaseTransport() = %p, want http.DefaultTransport (%p)", got, orig) + } + + for _, tc := range []struct { + name string + rt http.RoundTripper + }{ + {"wrapped", wrappedRoundTripper{orig}}, + {"nil", nil}, + {"typed nil", (*http.Transport)(nil)}, + } { + t.Run(tc.name, func(t *testing.T) { + http.DefaultTransport = tc.rt + got := defaultBaseTransport() + if got == nil || !got.ForceAttemptHTTP2 || got.Proxy == nil || got.DialContext == nil { + t.Fatalf("defaultBaseTransport() = %+v, want fresh HTTP/2-capable Transport", got) + } + }) + } +} + var _ io.Closer = (*Source)(nil) + +// stubExchange answers every exchange with one token. +type stubExchange struct { + exchangepb.UnimplementedCredentialExchangeServer +} + +func (stubExchange) ExchangeActorJwt(context.Context, *exchangepb.ExchangeActorJwtRequest) (*exchangepb.ExchangeActorJwtResponse, error) { + return &exchangepb.ExchangeActorJwtResponse{AccessToken: "tok", ExpireTime: timestamppb.New(time.Now().Add(time.Hour))}, nil +} + +// waitForReady makes exchange calls wait for the connection to redial. +type waitForReady struct { + exchangepb.CredentialExchangeClient +} + +func (w waitForReady) ExchangeActorJwt(ctx context.Context, in *exchangepb.ExchangeActorJwtRequest, opts ...grpc.CallOption) (*exchangepb.ExchangeActorJwtResponse, error) { + return w.CredentialExchangeClient.ExchangeActorJwt(ctx, in, append(opts, grpc.WaitForReady(true))...) +} + +const exchangeName = "exchange.test" + +func newTestCA(t *testing.T) *localca.CA { + t.Helper() + ca, err := localca.GenerateCA("exchange-ca", localca.KeyTypeECDSAP256, time.Hour) + if err != nil { + t.Fatal(err) + } + return ca +} + +func caPEM(cas ...*localca.CA) []byte { + var out []byte + for _, ca := range cas { + out = append(out, pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: ca.RootCertificate.Raw})...) + } + return out +} + +func writeCAFile(t *testing.T, path string, cas ...*localca.CA) { + t.Helper() + if err := os.WriteFile(path, caPEM(cas...), 0o600); err != nil { + t.Fatal(err) + } +} + +// serveExchange serves a stub exchange over TLS with a certificate from ca for +// exchangeName and returns its address. +func serveExchange(t *testing.T, ca *localca.CA) string { + t.Helper() + material := testcert.ServerTLSWithCA(t, ca, net.ParseIP("10.0.0.7"), exchangeName) + cert, err := tls.X509KeyPair(material.Certificate, material.PrivateKey) + if err != nil { + t.Fatal(err) + } + srv := grpc.NewServer(grpc.Creds(credentials.NewTLS(&tls.Config{Certificates: []tls.Certificate{cert}, MinVersion: tls.VersionTLS13}))) + exchangepb.RegisterCredentialExchangeServer(srv, stubExchange{}) + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatal(err) + } + go srv.Serve(lis) + t.Cleanup(srv.Stop) + return lis.Addr().String() +} + +func newTLSSource(t *testing.T, addr, caFile, serverName string) *Source { + t.Helper() + s, err := New(Config{Address: addr, CAFile: caFile, ServerName: serverName}) + if err != nil { + t.Fatalf("New() error = %v", err) + } + t.Cleanup(func() { s.Close() }) + s.newClient = func(context.Context, credential.Token) (objectstorage.ObjectStorage, error) { + return &fakeClient{}, nil + } + return s +} + +func TestNew_VerifiesTheExchangeCertificate(t *testing.T) { + ca, otherCA := newTestCA(t), newTestCA(t) + addr := serveExchange(t, ca) + for _, tc := range []struct { + name string + trust *localca.CA + serverName string + wantOK bool + }{ + {"trusted CA and matching name", ca, exchangeName, true}, + {"untrusted CA", otherCA, exchangeName, false}, + {"wrong server name", ca, "other.test", false}, + // The dial host, 127.0.0.1, is not on the certificate. + {"empty server name falls back to the dial host", ca, "", false}, + } { + t.Run(tc.name, func(t *testing.T) { + caFile := filepath.Join(t.TempDir(), "ca.pem") + writeCAFile(t, caFile, tc.trust) + s := newTLSSource(t, addr, caFile, tc.serverName) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + _, err := s.Client(ctx, "jwt", false) + if tc.wantOK && err != nil { + t.Fatalf("Client() error = %v, want success", err) + } + if !tc.wantOK && status.Code(err) != codes.Unavailable { + t.Fatalf("Client() error = %v, want a handshake failure", err) + } + }) + } +} + +func TestNew_RequiresAServerNameWithoutAnAddressHost(t *testing.T) { + caFile := filepath.Join(t.TempDir(), "ca.pem") + writeCAFile(t, caFile, newTestCA(t)) + if _, err := New(Config{Address: ":443", CAFile: caFile}); err == nil { + t.Fatal("New() accepted an empty ServerName and an Address without a host") + } +} + +// TestNew_ReloadsTheCAFile verifies that a rotation of the exchange CA bundle +// on disk is picked up by the next handshake, without rebuilding the Source. +func TestNew_ReloadsTheCAFile(t *testing.T) { + ca, rotatedCA := newTestCA(t), newTestCA(t) + caFile := filepath.Join(t.TempDir(), "ca.pem") + writeCAFile(t, caFile, ca) + s := newTLSSource(t, serveExchange(t, rotatedCA), caFile, exchangeName) + ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second) + defer cancel() + + if _, err := s.Client(ctx, "jwt", false); status.Code(err) != codes.Unavailable { + t.Fatalf("Client() before trusting the rotated CA: error = %v, want a handshake failure", err) + } + + // Step 1 of the rotation: the bundle carries the old and the new root. + writeCAFile(t, caFile, ca, rotatedCA) + s.exchange = waitForReady{s.exchange} + if _, err := s.Client(ctx, "jwt", false); err != nil { + t.Fatalf("Client() after the CA rotation: error = %v", err) + } +} diff --git a/internal/objectstoreplugin/gcsboundary/boundary.go b/internal/objectstoreplugin/gcsboundary/boundary.go index 8a17ed333b..3cf8f06e04 100644 --- a/internal/objectstoreplugin/gcsboundary/boundary.go +++ b/internal/objectstoreplugin/gcsboundary/boundary.go @@ -21,8 +21,6 @@ import ( "fmt" "strings" - "golang.org/x/oauth2/google/downscope" - "go.ate.dev/substrate/internal/objectstore" "go.ate.dev/substrate/internal/objectstoreplugin/actorscope" "go.ate.dev/substrate/internal/resources" @@ -33,16 +31,30 @@ const ( // objectAdmin, not objectCreator: an upload overwrites on retry and deletes // parts after a compose. roleObjectAdmin = "inRole:roles/storage.objectAdmin" + // maxRules is the most rules GCS accepts in one boundary. + maxRules = 10 ) +// Rule is one Credential Access Boundary rule: permissions on a bucket, limited +// to the objects a CEL condition matches. ObjectPrefix is the name prefix in +// the condition, unescaped. +type Rule struct { + Resource string + Permissions []string + Condition string + ObjectPrefix string +} + // FromGrants builds the rules. Each grant's prefix must be a gs:// prefix. The // condition's path ends in "/", so a match cannot spill into a sibling whose // name merely starts the same way. No objectListPrefix term is added: the node -// plugin never lists objects. downscope.NewTokenSource enforces the rule -// count, between one and ten, see +// plugin never lists objects. A boundary takes one to ten rules, see // https://docs.cloud.google.com/iam/docs/downscoping-short-lived-credentials. -func FromGrants(grants []actorscope.Grant) ([]downscope.AccessBoundaryRule, error) { - var rules []downscope.AccessBoundaryRule +func FromGrants(grants []actorscope.Grant) ([]Rule, error) { + if len(grants) == 0 || len(grants) > maxRules { + return nil, fmt.Errorf("an access boundary takes 1 to %d rules, got %d", maxRules, len(grants)) + } + var rules []Rule for _, g := range grants { bucket, path, err := splitGCS(g.Prefix) if err != nil { @@ -57,12 +69,12 @@ func FromGrants(grants []actorscope.Grant) ([]downscope.AccessBoundaryRule, erro default: return nil, fmt.Errorf("grant on %s has unknown access %v", g.Prefix, g.Access) } - rules = append(rules, downscope.AccessBoundaryRule{ - AvailableResource: "//storage.googleapis.com/projects/_/buckets/" + bucket, - AvailablePermissions: []string{role}, - Condition: &downscope.AvailabilityCondition{ - Expression: fmt.Sprintf("resource.name.startsWith('projects/_/buckets/%s/objects/%s')", celEscape(bucket), celEscape(path)), - }, + literal := resources.GCSResourceName(bucket, path) + rules = append(rules, Rule{ + Resource: "//storage.googleapis.com/projects/_/buckets/" + bucket, + Permissions: []string{role}, + Condition: fmt.Sprintf("resource.name.startsWith('%s')", celEscape(literal)), + ObjectPrefix: literal, }) } return rules, nil @@ -78,8 +90,8 @@ func splitGCS(prefix resources.StoragePrefix) (bucket, path string, err error) { } // celEscaper quotes the two characters that would end or alter a CEL -// single-quoted string literal. A storage location may contain a quote, since -// Substrate accepts one, so it is escaped rather than refused. +// single-quoted string literal. A location stored before the segment rules +// may contain a quote, so it is escaped rather than refused. var celEscaper = strings.NewReplacer(`\`, `\\`, `'`, `\'`) func celEscape(s string) string { return celEscaper.Replace(s) } diff --git a/internal/objectstoreplugin/gcsboundary/boundary_test.go b/internal/objectstoreplugin/gcsboundary/boundary_test.go index 0ae7ec532c..dafec3ae18 100644 --- a/internal/objectstoreplugin/gcsboundary/boundary_test.go +++ b/internal/objectstoreplugin/gcsboundary/boundary_test.go @@ -15,10 +15,10 @@ package gcsboundary import ( + "fmt" "testing" "github.com/google/go-cmp/cmp" - "golang.org/x/oauth2/google/downscope" "go.ate.dev/substrate/internal/objectstoreplugin/actorscope" "go.ate.dev/substrate/internal/resources" @@ -42,16 +42,18 @@ func TestFromGrants(t *testing.T) { if err != nil { t.Fatalf("FromGrants: %v", err) } - want := []downscope.AccessBoundaryRule{ + want := []Rule{ { - AvailableResource: "//storage.googleapis.com/projects/_/buckets/snaps", - AvailablePermissions: []string{"inRole:roles/storage.objectAdmin"}, - Condition: &downscope.AvailabilityCondition{Expression: "resource.name.startsWith('projects/_/buckets/snaps/objects/ate-demo/atespaces/team-a/actors/9f1e/')"}, + Resource: "//storage.googleapis.com/projects/_/buckets/snaps", + Permissions: []string{"inRole:roles/storage.objectAdmin"}, + Condition: "resource.name.startsWith('projects/_/buckets/snaps/objects/ate-demo/atespaces/team-a/actors/9f1e/')", + ObjectPrefix: "projects/_/buckets/snaps/objects/ate-demo/atespaces/team-a/actors/9f1e/", }, { - AvailableResource: "//storage.googleapis.com/projects/_/buckets/snaps", - AvailablePermissions: []string{"inRole:roles/storage.objectViewer"}, - Condition: &downscope.AvailabilityCondition{Expression: "resource.name.startsWith('projects/_/buckets/snaps/objects/ate-demo/atespaces/ate-golden/tags/7a3c/')"}, + Resource: "//storage.googleapis.com/projects/_/buckets/snaps", + Permissions: []string{"inRole:roles/storage.objectViewer"}, + Condition: "resource.name.startsWith('projects/_/buckets/snaps/objects/ate-demo/atespaces/ate-golden/tags/7a3c/')", + ObjectPrefix: "projects/_/buckets/snaps/objects/ate-demo/atespaces/ate-golden/tags/7a3c/", }, } if diff := cmp.Diff(want, b); diff != "" { @@ -67,6 +69,8 @@ func TestFromGrants_Refuses(t *testing.T) { {"not gs", []actorscope.Grant{{Prefix: prefix(t, "s3://b/p"), Access: actorscope.ReadOnly}}}, {"zero prefix", []actorscope.Grant{{Prefix: resources.StoragePrefix{}, Access: actorscope.ReadOnly}}}, {"unknown access", []actorscope.Grant{{Prefix: prefix(t, "gs://b/p"), Access: 0}}}, + {"no grants", nil}, + {"more than ten grants", manyGrants(t, 11)}, } { t.Run(tc.name, func(t *testing.T) { if _, err := FromGrants(tc.grants); err == nil { @@ -77,17 +81,25 @@ func TestFromGrants_Refuses(t *testing.T) { } func TestFromGrants_EscapesTheCELLiteral(t *testing.T) { - // Substrate accepts a quote in a storage location, so the condition must - // escape it rather than let it end the string literal. + // A location stored before the segment rules may contain a quote, so the + // condition must escape it rather than let it end the string literal. rules, err := FromGrants([]actorscope.Grant{{Prefix: prefix(t, `gs://snaps/tenant's/atespaces/team-a/actors/9f1e`), Access: actorscope.ReadWrite}}) if err != nil { t.Fatalf("FromGrants: %v", err) } want := `resource.name.startsWith('projects/_/buckets/snaps/objects/tenant\'s/atespaces/team-a/actors/9f1e/')` - if got := rules[0].Condition.Expression; got != want { + if got := rules[0].Condition; got != want { t.Errorf("expression = %s, want %s", got, want) } if got := celEscape(`a\b'c`); got != `a\\b\'c` { t.Errorf("celEscape = %s", got) } } + +func manyGrants(t *testing.T, n int) []actorscope.Grant { + var gs []actorscope.Grant + for i := range n { + gs = append(gs, actorscope.Grant{Prefix: prefix(t, fmt.Sprintf("gs://b/p%d", i)), Access: actorscope.ReadOnly}) + } + return gs +} diff --git a/internal/objectstoreplugin/gcsissuer/clientside.go b/internal/objectstoreplugin/gcsissuer/clientside.go new file mode 100644 index 0000000000..2e97a1620d --- /dev/null +++ b/internal/objectstoreplugin/gcsissuer/clientside.go @@ -0,0 +1,354 @@ +// Copyright 2026 The Agent Substrate 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 gcsissuer + +import ( + "bytes" + "context" + "encoding/base64" + "encoding/json" + "errors" + "fmt" + "io" + "log/slog" + "net/http" + "net/url" + "strings" + "time" + + "github.com/google/cel-go/cel" + "github.com/tink-crypto/tink-go/v2/aead" + "github.com/tink-crypto/tink-go/v2/insecurecleartextkeyset" + "github.com/tink-crypto/tink-go/v2/keyset" + "github.com/tink-crypto/tink-go/v2/tink" + "golang.org/x/oauth2" + "golang.org/x/sync/singleflight" + "google.golang.org/protobuf/proto" + + "go.ate.dev/substrate/internal/objectstoreplugin/credential" + "go.ate.dev/substrate/internal/objectstoreplugin/gcsboundary" + pb "go.ate.dev/substrate/internal/proto/clientsideboundarypb" +) + +// Client-side Credential Access Boundaries, as google-auth-library-java's +// ClientSideCredentialAccessBoundaryFactory implements them, see +// https://docs.cloud.google.com/iam/docs/create-downscoped-short-lived-credentials#client-side-token-exchange +// and +// https://github.com/googleapis/google-auth-library-java/blob/9ac2d4340ebc6a8582b898e97f65aeed3c1776d6/cab-token-generator/java/com/google/auth/credentialaccessboundary/ClientSideCredentialAccessBoundaryFactory.java. +// One STS exchange per source token returns an intermediary token and a +// session key. Each downscoped token is then the intermediary token, a dot, +// and the boundary encrypted with the session key. GCS accepts the +// intermediary token only with a boundary appended. +const ( + stsTokenURL = "https://sts.googleapis.com/v1/token" + tokenExchangeGrant = "urn:ietf:params:oauth:grant-type:token-exchange" + accessTokenType = "urn:ietf:params:oauth:token-type:access_token" + intermediaryTokenType = "urn:ietf:params:oauth:token-type:access_boundary_intermediary_token" + // maxSTSResponse bounds what is read of an STS response, which is under + // a few KiB when valid. An error quotes at most the first KiB. + maxSTSResponse = 64 << 10 + // maxBoundary is the largest serialized boundary GCS accepts in a locally + // minted token, in bytes. GCS refuses a token with a larger one with a 401 + // that does not say why. We measured the limit. It is not documented. + maxBoundary = 4096 + // minRetryDelay is how long exchanges pause after one failure. Each further + // failure doubles the pause, up to stsTimeout. + minRetryDelay = time.Second +) + +// intermediary is what one STS exchange returns for a source token. +type intermediary struct { + token string + expiry time.Time + aead tink.AEAD +} + +// currentIntermediary returns the intermediary to mint with. Intermediaries +// are stored by source token until they expire, so a caller still holding a +// token that was just replaced finds its intermediary too. +// +// When the source token has none yet, the latest intermediary is used while +// it has at least minServeLifetime left, and the exchange runs in the +// background, as Google's Java library refreshes ahead of expiry. So a slow +// or failing STS does not hold up mints. Only without such an intermediary +// does a mint wait for the exchange, and if that fails it still uses the +// latest intermediary while it has more than stsTimeout left, as the source +// token's own fallback does. +func (i *Issuer) currentIntermediary(ctx context.Context) (*intermediary, error) { + src, err := i.source.Token() + if err != nil { + // Formatted with %v so an IAM error code or timeout does not reach the + // caller as a code of its own. + return nil, fmt.Errorf("while getting the source token: %v", err) + } + if in := i.stored(src); in != nil { + return in, nil + } + last := i.latest.Load() + if last != nil && last.expiry.Sub(i.now()) >= minServeLifetime { + i.exchange(ctx, src) + return last, nil + } + select { + case <-ctx.Done(): + return nil, ctx.Err() + case res := <-i.exchange(ctx, src): + if res.Err != nil { + if last != nil && last.expiry.Sub(i.now()) > stsTimeout { + return last, nil + } + return nil, res.Err + } + return res.Val.(*intermediary), nil + } +} + +// exchange starts the exchange for src, or joins one in flight. Concurrent +// mints share it, and it outlives a caller that gives up, so that caller does +// not fail the mints waiting on it. After a failed exchange it returns the +// failure instead of calling STS again until the pause ends, so an STS outage +// or refusal does not turn every mint into an STS call. The pause starts at +// minRetryDelay, so one transient failure with nothing to fall back on fails +// mints only briefly, and doubles with each further failure up to stsTimeout. +func (i *Issuer) exchange(ctx context.Context, src *oauth2.Token) <-chan singleflight.Result { + if f := i.failure.Load(); f != nil && i.now().Before(f.until) { + ch := make(chan singleflight.Result, 1) + ch <- singleflight.Result{Err: fmt.Errorf("STS exchanges paused until %s after a failed exchange: %w", f.until.Format(time.RFC3339), f.err)} + return ch + } + return i.flight.DoChan(src.AccessToken, func() (any, error) { + if in := i.stored(src); in != nil { + return in, nil + } + // The caller's deadline is dropped with its cancellation. The default + // client times out after stsTimeout, and one set with WithHTTPClient + // may not, so the exchange gets its own deadline. + xctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), stsTimeout) + defer cancel() + in, err := i.exchangeIntermediary(xctx, src) + if err != nil { + delay := minRetryDelay + if f := i.failure.Load(); f != nil { + delay = min(2*f.delay, stsTimeout) + } + i.failure.Store(&failure{err: err, delay: delay, until: i.now().Add(delay)}) + slog.WarnContext(ctx, "Exchanging the source token for an intermediary token failed", "error", err) + return nil, err + } + i.failure.Store(nil) + i.intermediaries.Set(src.AccessToken, in, in.expiry.Sub(i.now())) + i.keepLatest(in) + slog.InfoContext(ctx, "Exchanged the source token for an intermediary token", "expiry", in.expiry) + return in, nil + }) +} + +// failure is the last exchange's error, returned without calling STS until +// until, delay after the failure. +type failure struct { + err error + delay time.Duration + until time.Time +} + +// keepLatest stores in as the fallback intermediary, unless one that expires +// later is stored already. +func (i *Issuer) keepLatest(in *intermediary) { + for { + last := i.latest.Load() + if last != nil && !in.expiry.After(last.expiry) { + return + } + if i.latest.CompareAndSwap(last, in) { + return + } + } +} + +// stored returns the intermediary exchanged for src, if it has not expired. +// The cache expires entries on the wall clock, so expiry is checked again on +// the issuer's clock, which tests set with WithClock. +func (i *Issuer) stored(src *oauth2.Token) *intermediary { + if v, ok := i.intermediaries.Get(src.AccessToken); ok { + if in := v.(*intermediary); i.now().Before(in.expiry) { + return in + } + } + return nil +} + +func (i *Issuer) exchangeIntermediary(ctx context.Context, src *oauth2.Token) (*intermediary, error) { + r, expiry, err := i.postSTS(ctx, src, intermediaryTokenType, "") + if err != nil { + return nil, err + } + if r.SessionKey == "" { + return nil, errors.New("STS returned no session key") + } + // Java's decoder accepts the key with or without padding. + rawKey, err := base64.RawStdEncoding.DecodeString(strings.TrimRight(r.SessionKey, "=")) + if err != nil { + return nil, fmt.Errorf("while decoding the session key: %w", err) + } + handle, err := insecurecleartextkeyset.Read(keyset.NewBinaryReader(bytes.NewReader(rawKey))) + if err != nil { + return nil, fmt.Errorf("while reading the session key: %w", err) + } + a, err := aead.New(handle) + if err != nil { + return nil, fmt.Errorf("while loading the session key: %w", err) + } + return &intermediary{token: r.AccessToken, expiry: expiry, aead: a}, nil +} + +// exchangeServerSide exchanges the source token at STS for a token STS +// downscopes to rules itself. It costs an STS call per mint, so mint uses it +// only for a boundary a locally minted token cannot carry. +func (i *Issuer) exchangeServerSide(ctx context.Context, rules []gcsboundary.Rule) (credential.Token, error) { + src, err := i.source.Token() + if err != nil { + // Formatted with %v so an IAM error code or timeout does not reach the + // caller as a code of its own. + return credential.Token{}, fmt.Errorf("while getting the source token: %v", err) + } + type condition struct { + Expression string `json:"expression"` + } + type rule struct { + AvailableResource string `json:"availableResource"` + AvailablePermissions []string `json:"availablePermissions"` + AvailabilityCondition condition `json:"availabilityCondition"` + } + var opts struct { + AccessBoundary struct { + AccessBoundaryRules []rule `json:"accessBoundaryRules"` + } `json:"accessBoundary"` + } + for _, r := range rules { + opts.AccessBoundary.AccessBoundaryRules = append(opts.AccessBoundary.AccessBoundaryRules, rule{r.Resource, r.Permissions, condition{r.Condition}}) + } + b, err := json.Marshal(opts) + if err != nil { + return credential.Token{}, err + } + xctx, cancel := context.WithTimeout(ctx, stsTimeout) + defer cancel() + r, expiry, err := i.postSTS(xctx, src, accessTokenType, string(b)) + if err != nil { + if cerr := ctx.Err(); cerr != nil { + return credential.Token{}, cerr + } + return credential.Token{}, err + } + return credential.Token{AccessToken: r.AccessToken, Expiry: expiry}, nil +} + +// stsResponse is what the issuer reads of an STS token exchange response. +type stsResponse struct { + AccessToken string `json:"access_token"` + ExpiresIn int64 `json:"expires_in"` + SessionKey string `json:"access_boundary_session_key"` +} + +// postSTS exchanges src at STS for a token of type requested, with options +// when set, and returns the response and the token's expiry. +func (i *Issuer) postSTS(ctx context.Context, src *oauth2.Token, requested, options string) (stsResponse, time.Time, error) { + form := url.Values{ + "grant_type": {tokenExchangeGrant}, + "subject_token_type": {accessTokenType}, + "subject_token": {src.AccessToken}, + "requested_token_type": {requested}, + } + if options != "" { + form.Set("options", options) + } + req, err := http.NewRequestWithContext(ctx, http.MethodPost, stsTokenURL, strings.NewReader(form.Encode())) + if err != nil { + return stsResponse{}, time.Time{}, err + } + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") + resp, err := i.client.Do(req) + if err != nil { + // Formatted with %v so a timeout of the exchange's own deadline does not + // reach the caller as context.DeadlineExceeded. + return stsResponse{}, time.Time{}, fmt.Errorf("while exchanging at STS: %v", err) + } + defer resp.Body.Close() + body, err := io.ReadAll(io.LimitReader(resp.Body, maxSTSResponse)) + if err != nil { + return stsResponse{}, time.Time{}, fmt.Errorf("while reading the STS response: %v", err) + } + if resp.StatusCode != http.StatusOK { + return stsResponse{}, time.Time{}, fmt.Errorf("while exchanging at STS: status %d: %.1024s", resp.StatusCode, body) + } + var r stsResponse + if err := json.Unmarshal(body, &r); err != nil { + return stsResponse{}, time.Time{}, fmt.Errorf("while decoding the STS response: %w", err) + } + if r.AccessToken == "" { + return stsResponse{}, time.Time{}, errors.New("STS returned no access token") + } + // For a service account's source token, STS reports the token's remaining + // life, less a second. Google's Java library says it reports nothing for + // other tokens. The token is not trusted past the source token either way. + expiry := src.Expiry + if r.ExpiresIn > 0 { + if sts := i.now().Add(time.Duration(r.ExpiresIn) * time.Second); expiry.IsZero() || sts.Before(expiry) { + expiry = sts + } + } + if expiry.IsZero() { + // Without an expiry the node plugin could not know when to stop using + // the token. + return stsResponse{}, time.Time{}, errors.New("the exchanged token has no expiry") + } + return r, expiry, nil +} + +// encode serializes rules as the ClientSideAccessBoundary STS decrypts. A +// condition is parsed without type checking, as the Java factory does. +func encode(env *cel.Env, rules []gcsboundary.Rule) ([]byte, error) { + var b pb.ClientSideAccessBoundary + for _, r := range rules { + ast, iss := env.Parse(r.Condition) + if iss.Err() != nil { + return nil, fmt.Errorf("while parsing condition %q: %w", r.Condition, iss.Err()) + } + parsed, err := cel.AstToParsedExpr(ast) + if err != nil { + return nil, fmt.Errorf("while converting condition %q: %w", r.Condition, err) + } + cond, err := proto.Marshal(parsed.GetExpr()) + if err != nil { + return nil, fmt.Errorf("while encoding condition %q: %w", r.Condition, err) + } + b.AccessBoundaryRules = append(b.AccessBoundaryRules, &pb.ClientSideAccessBoundaryRule{ + AvailableResource: r.Resource, + AvailablePermissions: r.Permissions, + CompiledAvailabilityCondition: cond, + }) + } + return proto.Marshal(&b) +} + +// seal encrypts the boundary with the session key and appends it to the +// intermediary token, unpadded as the Java library writes it. +func (in *intermediary) seal(plain []byte) (string, error) { + sealed, err := in.aead.Encrypt(plain, []byte{}) + if err != nil { + return "", fmt.Errorf("while encrypting the access boundary: %w", err) + } + return in.token + "." + base64.RawURLEncoding.EncodeToString(sealed), nil +} diff --git a/internal/objectstoreplugin/gcsissuer/issuer.go b/internal/objectstoreplugin/gcsissuer/issuer.go index 35595b7c47..19c1b981bf 100644 --- a/internal/objectstoreplugin/gcsissuer/issuer.go +++ b/internal/objectstoreplugin/gcsissuer/issuer.go @@ -18,31 +18,38 @@ // // The source credential is a token for the snapshot transfer service account, // which the pod's own identity impersonates through the IAM Credentials API. -// GCS audit logs then name that account rather than ate-api-server. The -// downscope package exchanges the token at STS with a Credential Access -// Boundary and returns an access token GCS limits to the boundary. STS reports -// no lifetime for that token, so the package falls back to the source token's -// expiry, and the two expire together. +// GCS audit logs then name that account rather than ate-api-server. Each +// source token is exchanged at STS once, for an intermediary token and a +// session key. Downscoped tokens are then minted locally, with the actor's +// Credential Access Boundary encrypted into it, so STS sees one call per source +// token instead of one per actor. A downscoped token expires with the +// intermediary token. STS gives that the source token's remaining life, and +// the issuer never lets it outlive the source token. A boundary too large for +// a locally minted token, from a long storage location, goes to STS instead, +// which downscopes that actor's token itself. package gcsissuer import ( "context" - "errors" "fmt" "net/http" "slices" + "sync/atomic" "time" + "github.com/google/cel-go/cel" "golang.org/x/oauth2" - "golang.org/x/oauth2/google/downscope" + "golang.org/x/sync/singleflight" "google.golang.org/api/option" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "k8s.io/apimachinery/pkg/util/cache" "k8s.io/utils/lru" "go.ate.dev/substrate/internal/objectstoreplugin/actorscope" "go.ate.dev/substrate/internal/objectstoreplugin/credential" "go.ate.dev/substrate/internal/objectstoreplugin/gcsboundary" + "go.ate.dev/substrate/internal/resources" ) const ( @@ -53,22 +60,32 @@ const ( // minServeLifetime is the least remaining lifetime a token is cached and // served with, the same on the node plugin's side. minServeLifetime = credential.MinServeLifetime - // defaultCacheSize bounds the per-actor cache. A miss costs an exchange, + // defaultCacheSize bounds the per-actor cache. A miss costs a local mint, // never correctness. defaultCacheSize = 100_000 - // stsTimeout bounds one exchange. The downscope package does not take a - // per-call context, so the client's timeout is the only bound. + // stsTimeout bounds one exchange. stsTimeout = 30 * time.Second ) -// Issuer exchanges the transfer account's token for per-actor downscoped -// tokens and caches them by actor UID. +// Issuer mints per-actor downscoped tokens from the transfer account's token +// and caches them by actor UID. type Issuer struct { source oauth2.TokenSource iamOptions []option.ClientOption client *http.Client now func() time.Time cache *lru.Cache + cel *cel.Env + + flight singleflight.Group + // intermediaries maps a source token to its *intermediary until the + // intermediary expires. + intermediaries *cache.Expiring + // latest is the intermediary that expires last, minted with while a + // refreshed source token's exchange runs or after it fails. + latest atomic.Pointer[intermediary] + // failure holds the last failed exchange while new ones are paused. + failure atomic.Pointer[failure] } // entry is a cached token with the grants it was minted for, so a request can @@ -107,13 +124,19 @@ func WithCacheSize(n int) Option { // the Issuer's whole life, so ctx is detached from cancellation. func New(ctx context.Context, account string, opts ...Option) (*Issuer, error) { i := &Issuer{ - client: &http.Client{Timeout: stsTimeout}, - now: time.Now, - cache: lru.New(defaultCacheSize), + client: &http.Client{Timeout: stsTimeout}, + now: time.Now, + cache: lru.New(defaultCacheSize), + intermediaries: cache.NewExpiring(), } for _, o := range opts { o(i) } + env, err := cel.NewEnv() + if err != nil { + return nil, fmt.Errorf("while creating the CEL environment: %w", err) + } + i.cel = env if i.source == nil { src, err := newTransferAccountSource(context.WithoutCancel(ctx), account, i.iamOptions...) if err != nil { @@ -127,12 +150,21 @@ func New(ctx context.Context, account string, opts ...Option) (*Issuer, error) { // Issue returns a token downscoped to grants for the actor. A cached token is // returned while it covers the grants and has at least minServeLifetime left, // unless force is set, which mints regardless and is what the node plugin -// sends after GCS refused a token. A minted token expires with the source -// token, which is fetched again once less than sourceRefreshMargin is left, so -// it starts with at least that long. If that fetch fails, the previous source -// token is used until it expires. A minted token with less than -// minServeLifetime left, which only that leaves behind, is handed out anyway, -// since a short token beats a failed transfer, but it is not cached. +// sends after GCS refused a token. A forced locally minted token still uses +// the stored intermediary token: a new one for the same source token carries +// the same permissions, and an STS call on every refusal would bring back the +// per-actor calls this package avoids. +// +// A minted token expires with the intermediary token it was minted from, which +// expires no later than its source token. A token STS downscopes itself also +// expires no later than its source token. Normally a minted token starts with +// at least minServeLifetime: the source token is fetched again once less than +// sourceRefreshMargin is left, and mints keep using the previous intermediary +// until the new one is exchanged. When fetching or exchanging the source token +// keeps failing, mints use what is left, so a token can start with as little +// as stsTimeout. A minted token with less than minServeLifetime left is handed +// out anyway, since a short token beats a failed transfer, but it is not +// cached. // // The cache is keyed by actor UID and each entry remembers its grants. Grants // narrow when the tag an actor was created from drops out after its first @@ -142,7 +174,8 @@ func New(ctx context.Context, account string, opts ...Option) (*Issuer, error) { // nothing and a repoint never hands out a token GCS would refuse. // // A grant set the access boundary cannot express fails with codes.Internal. -// Every other failure is an STS or network error and carries no code. +// The caller's own context error is returned as it is. Every other failure is +// a source token, STS, network or encryption failure and carries no code. func (i *Issuer) Issue(ctx context.Context, actorUID string, grants []actorscope.Grant, force bool) (credential.Token, error) { if len(grants) == 0 { // Checked before the cache: an empty set is covered by any cached @@ -186,43 +219,21 @@ func (i *Issuer) mint(ctx context.Context, grants []actorscope.Grant) (credentia if err != nil { return credential.Token{}, status.Errorf(codes.Internal, "while building the access boundary: %v", err) } - // The downscope package reads its HTTP client from the context but sends - // the STS request without one, so the caller's deadline is attached by the - // transport instead. - ctx = context.WithValue(ctx, oauth2.HTTPClient, &http.Client{ - Transport: contextTransport{ctx: ctx, base: i.client.Transport}, - Timeout: i.client.Timeout, - }) - ts, err := downscope.NewTokenSource(ctx, downscope.DownscopingConfig{RootSource: i.source, Rules: rules}) + plain, err := encode(i.cel, rules) if err != nil { - return credential.Token{}, status.Errorf(codes.Internal, "while building the access boundary: %v", err) + return credential.Token{}, status.Errorf(codes.Internal, "while encoding the access boundary: %v", err) } - tok, err := ts.Token() - if err != nil { - return credential.Token{}, fmt.Errorf("while exchanging at STS: %w", err) - } - if tok.AccessToken == "" { - return credential.Token{}, errors.New("STS returned no access token") + tooLong := func(r gcsboundary.Rule) bool { return len(r.ObjectPrefix) > resources.MaxGCSResourceName } + if len(plain) > maxBoundary || slices.ContainsFunc(rules, tooLong) { + return i.exchangeServerSide(ctx, rules) } - if tok.Expiry.IsZero() { - // Without an expiry the node plugin could not know when to stop using - // the token. - return credential.Token{}, errors.New("downscoped token has no expiry") + in, err := i.currentIntermediary(ctx) + if err != nil { + return credential.Token{}, err } - return credential.Token{AccessToken: tok.AccessToken, Expiry: tok.Expiry}, nil -} - -// contextTransport sends every request with ctx, so a cancelled or expired -// caller stops an STS exchange in flight instead of waiting out the timeout. -type contextTransport struct { - ctx context.Context - base http.RoundTripper -} - -func (t contextTransport) RoundTrip(req *http.Request) (*http.Response, error) { - base := t.base - if base == nil { - base = http.DefaultTransport + tok, err := in.seal(plain) + if err != nil { + return credential.Token{}, err } - return base.RoundTrip(req.WithContext(t.ctx)) + return credential.Token{AccessToken: tok, Expiry: in.expiry}, nil } diff --git a/internal/objectstoreplugin/gcsissuer/issuer_test.go b/internal/objectstoreplugin/gcsissuer/issuer_test.go index 7554fb480f..108448fb36 100644 --- a/internal/objectstoreplugin/gcsissuer/issuer_test.go +++ b/internal/objectstoreplugin/gcsissuer/issuer_test.go @@ -15,24 +15,34 @@ package gcsissuer import ( + "bytes" "context" + "encoding/base64" "encoding/json" + "errors" "fmt" "net/http" "net/http/httptest" "net/url" + "slices" "strings" + "sync" "testing" "time" "github.com/google/go-cmp/cmp" + "github.com/tink-crypto/tink-go/v2/aead" + "github.com/tink-crypto/tink-go/v2/insecurecleartextkeyset" + "github.com/tink-crypto/tink-go/v2/keyset" "golang.org/x/oauth2" - "golang.org/x/oauth2/google/downscope" + exprpb "google.golang.org/genproto/googleapis/api/expr/v1alpha1" "google.golang.org/grpc/codes" "google.golang.org/grpc/status" + "google.golang.org/protobuf/proto" "go.ate.dev/substrate/internal/objectstoreplugin/actorscope" "go.ate.dev/substrate/internal/objectstoreplugin/gcsboundary" + pb "go.ate.dev/substrate/internal/proto/clientsideboundarypb" "go.ate.dev/substrate/internal/resources" ) @@ -50,21 +60,44 @@ var ( testGrants = []actorscope.Grant{rwGrant, roGrant} ) -// fakeSTS records the last exchange request and answers with a token. +// fakeSTS records the last exchange request and answers with an intermediary +// token and a session key it keeps, so a test can open the boundaries minted +// with it. A request for an access token gets a server-side downscoped token. type fakeSTS struct { - t *testing.T + t *testing.T + status int + body string + // expiresIn is the lifetime reported: an hour when zero, as STS reports + // for a service account's fresh token, and none when negative. + expiresIn int + // unpaddedKey sends the session key without base64 padding. + unpaddedKey bool + // holdSubject pauses a request for that subject token: the handler + // closes held and waits for release before answering. + holdSubject string + held, release chan struct{} + heldOnce sync.Once + + mu sync.Mutex calls int - status int - body string lastURL string last map[string]string + key *keyset.Handle } func (f *fakeSTS) handler(w http.ResponseWriter, r *http.Request) { - f.calls++ if err := r.ParseForm(); err != nil { f.t.Errorf("parse form: %v", err) } + if f.holdSubject != "" && r.PostForm.Get("subject_token") == f.holdSubject { + // Once, so a second held request leaves the call counts to report it + // rather than panicking on a closed channel. + f.heldOnce.Do(func() { close(f.held) }) + <-f.release + } + f.mu.Lock() + defer f.mu.Unlock() + f.calls++ f.last = map[string]string{} for k := range r.PostForm { f.last[k] = r.PostForm.Get(k) @@ -72,11 +105,81 @@ func (f *fakeSTS) handler(w http.ResponseWriter, r *http.Request) { if f.status != 0 { w.WriteHeader(f.status) } - body := f.body - if body == "" { - body = `{"access_token":"downscoped-` + strings.Repeat("x", 8) + `","issued_token_type":"urn:ietf:params:oauth:token-type:access_token","token_type":"Bearer"}` + if f.body != "" { + _, _ = w.Write([]byte(f.body)) + return + } + resp := map[string]any{"token_type": "Bearer"} + if r.PostForm.Get("requested_token_type") == accessTokenType { + resp["access_token"] = fmt.Sprintf("downscoped-%d", f.calls) + } else { + resp["access_token"] = fmt.Sprintf("intermediary-%d", f.calls) + resp["issued_token_type"] = intermediaryTokenType + resp["access_boundary_session_key"] = f.sessionKey() + } + switch { + case f.expiresIn > 0: + resp["expires_in"] = f.expiresIn + case f.expiresIn == 0: + resp["expires_in"] = 3600 + } + _ = json.NewEncoder(w).Encode(resp) +} + +// sessionKey is the session key STS hands out, a serialized Tink keyset. +func (f *fakeSTS) sessionKey() string { + for { + if f.key == nil { + h, err := keyset.NewHandle(aead.AES256GCMKeyTemplate()) + if err != nil { + f.t.Fatal(err) + } + f.key = h + } + var buf bytes.Buffer + if err := insecurecleartextkeyset.Write(f.key, keyset.NewBinaryWriter(&buf)); err != nil { + f.t.Fatal(err) + } + key := base64.StdEncoding.EncodeToString(buf.Bytes()) + if !f.unpaddedKey { + return key + } + // A key whose encoding needs no padding would not test anything, so + // draw another. + if strings.HasSuffix(key, "=") { + return strings.TrimRight(key, "=") + } + f.key = nil + } +} + +// open splits a minted token into its intermediary token and the boundary, +// decrypted with the session key, as STS does. +func (f *fakeSTS) open(t *testing.T, token string) (string, *pb.ClientSideAccessBoundary) { + t.Helper() + inter, sealed, ok := strings.Cut(token, ".") + if !ok { + t.Fatalf("token %q has no boundary", token) + } + ct, err := base64.RawURLEncoding.DecodeString(sealed) + if err != nil { + t.Fatalf("boundary is not unpadded base64url: %v", err) + } + f.mu.Lock() + a, err := aead.New(f.key) + f.mu.Unlock() + if err != nil { + t.Fatal(err) } - _, _ = w.Write([]byte(body)) + plain, err := a.Decrypt(ct, []byte{}) + if err != nil { + t.Fatalf("decrypting the boundary: %v", err) + } + var b pb.ClientSideAccessBoundary + if err := proto.Unmarshal(plain, &b); err != nil { + t.Fatalf("decoding the boundary: %v", err) + } + return inter, &b } // redirect sends every request to the fake STS, recording where it was bound. @@ -86,7 +189,9 @@ type redirect struct { } func (r redirect) RoundTrip(req *http.Request) (*http.Response, error) { + r.sts.mu.Lock() r.sts.lastURL = req.URL.String() + r.sts.mu.Unlock() req = req.Clone(req.Context()) req.URL.Scheme, req.URL.Host = r.target.Scheme, r.target.Host return http.DefaultTransport.RoundTrip(req) @@ -105,11 +210,25 @@ func newTestIssuer(t *testing.T, sts *fakeSTS, src oauth2.TokenSource, now func( return i } +// hold pauses STS requests for subject until the test releases them. The +// release on cleanup runs before the server's close, so a request still +// paused does not block it. +func (f *fakeSTS) hold(t *testing.T, subject string) { + f.holdSubject, f.held, f.release = subject, make(chan struct{}), make(chan struct{}) + t.Cleanup(func() { + select { + case <-f.release: + default: + close(f.release) + } + }) +} + func staticSource(expiry time.Time) oauth2.TokenSource { return oauth2.StaticTokenSource(&oauth2.Token{AccessToken: "source-token", Expiry: expiry}) } -func TestIssue_ExchangesWithTheBoundary(t *testing.T) { +func TestIssue_MintsTheBoundaryIntoTheToken(t *testing.T) { now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) expiry := now.Add(time.Hour) sts := &fakeSTS{t: t} @@ -119,9 +238,6 @@ func TestIssue_ExchangesWithTheBoundary(t *testing.T) { if err != nil { t.Fatalf("Issue: %v", err) } - if !strings.HasPrefix(tok.AccessToken, "downscoped-") { - t.Errorf("AccessToken = %q", tok.AccessToken) - } if !tok.Expiry.Equal(expiry) { t.Errorf("Expiry = %v, want the source token's %v", tok.Expiry, expiry) } @@ -131,24 +247,519 @@ func TestIssue_ExchangesWithTheBoundary(t *testing.T) { for k, want := range map[string]string{ "grant_type": "urn:ietf:params:oauth:grant-type:token-exchange", "subject_token_type": "urn:ietf:params:oauth:token-type:access_token", - "requested_token_type": "urn:ietf:params:oauth:token-type:access_token", + "requested_token_type": "urn:ietf:params:oauth:token-type:access_boundary_intermediary_token", "subject_token": "source-token", } { if got := sts.last[k]; got != want { t.Errorf("form %s = %q, want %q", k, got, want) } } - var options struct { - AccessBoundary struct { - AccessBoundaryRules []downscope.AccessBoundaryRule `json:"accessBoundaryRules"` - } `json:"accessBoundary"` + inter, got := sts.open(t, tok.AccessToken) + if inter != "intermediary-1" { + t.Errorf("token starts with %q, want the intermediary token", inter) + } + rules, err := gcsboundary.FromGrants(testGrants) + if err != nil { + t.Fatal(err) + } + if len(got.GetAccessBoundaryRules()) != len(rules) { + t.Fatalf("boundary has %d rules, want %d", len(got.GetAccessBoundaryRules()), len(rules)) + } + wantPaths := []string{ + "projects/_/buckets/snaps/objects/root/atespaces/team-a/actors/9f1e/", + "projects/_/buckets/snaps/objects/root/atespaces/ate-golden/tags/7a3c/", + } + for n, want := range rules { + rule := got.GetAccessBoundaryRules()[n] + if rule.GetAvailableResource() != want.Resource { + t.Errorf("rule %d resource = %q, want %q", n, rule.GetAvailableResource(), want.Resource) + } + if diff := cmp.Diff(want.Permissions, rule.GetAvailablePermissions()); diff != "" { + t.Errorf("rule %d permissions (-want +got):\n%s", n, diff) + } + if got := conditionPrefix(t, rule.GetCompiledAvailabilityCondition()); got != wantPaths[n] { + t.Errorf("rule %d condition limits objects to %q, want %q", n, got, wantPaths[n]) + } + } +} + +// conditionPrefix checks that raw is the parsed CEL expression +// resource.name.startsWith(path) and returns path. +func conditionPrefix(t *testing.T, raw []byte) string { + t.Helper() + var e exprpb.Expr + if err := proto.Unmarshal(raw, &e); err != nil { + t.Fatalf("condition is not an Expr: %v", err) + } + call := e.GetCallExpr() + sel := call.GetTarget().GetSelectExpr() + if call.GetFunction() != "startsWith" || sel.GetField() != "name" || sel.GetOperand().GetIdentExpr().GetName() != "resource" || len(call.GetArgs()) != 1 { + t.Fatalf("condition is %v, want resource.name.startsWith(path)", &e) + } + return call.GetArgs()[0].GetConstExpr().GetStringValue() +} + +func TestIssue_ConditionKeepsAQuoteInThePath(t *testing.T) { + // A location stored before the segment rules may contain a quote. + // gcsboundary escapes it in the CEL literal, and the parsed constant must + // hold the raw path. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + grant := actorscope.Grant{Prefix: prefix("gs://snaps/tenant's/atespaces/team-a/actors/9f1e"), Access: actorscope.ReadWrite} + tok, err := i.Issue(t.Context(), "9f1e", []actorscope.Grant{grant}, false) + if err != nil { + t.Fatal(err) + } + _, b := sts.open(t, tok.AccessToken) + want := "projects/_/buckets/snaps/objects/tenant's/atespaces/team-a/actors/9f1e/" + if got := conditionPrefix(t, b.GetAccessBoundaryRules()[0].GetCompiledAvailabilityCondition()); got != want { + t.Errorf("condition limits objects to %q, want %q", got, want) + } +} + +func TestIssue_FallsBackToTheLatestIntermediaryWhenAnExchangeFails(t *testing.T) { + // The source token is refreshed and STS refuses the exchange. Mints use + // the previous intermediary while it has more than stsTimeout left. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + later time.Duration + wantErr bool + }{ + {"the latest has 40 minutes left", 20 * time.Minute, false}, + {"the latest has just over stsTimeout left", time.Hour - stsTimeout - time.Second, false}, + {"the latest has stsTimeout left", time.Hour - stsTimeout, true}, + {"the latest has expired", time.Hour + time.Second, true}, + } { + t.Run(tc.name, func(t *testing.T) { + clock := now + src := &changingSource{tok: oauth2.Token{AccessToken: "source-1", Expiry: now.Add(time.Hour)}} + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, src, func() time.Time { return clock }) + if _, err := i.Issue(t.Context(), "a", testGrants, true); err != nil { + t.Fatal(err) + } + clock = now.Add(tc.later) + src.mu.Lock() + src.tok = oauth2.Token{AccessToken: "source-2", Expiry: clock.Add(time.Hour)} + src.mu.Unlock() + sts.mu.Lock() + sts.status, sts.body = http.StatusServiceUnavailable, `{"error":"unavailable"}` + sts.mu.Unlock() + tok, err := i.Issue(t.Context(), "b", testGrants, true) + if tc.wantErr { + if err == nil { + t.Fatal("Issue fell back to an intermediary with stsTimeout or less left") + } + return + } + if err != nil { + t.Fatalf("Issue: %v", err) + } + if inter, _ := sts.open(t, tok.AccessToken); inter != "intermediary-1" { + t.Errorf("token starts with %q, want the previous intermediary token", inter) + } + }) + } +} + +// changingSource returns whatever token it holds, so a test can rotate it. +type changingSource struct { + mu sync.Mutex + tok oauth2.Token +} + +func (s *changingSource) Token() (*oauth2.Token, error) { + s.mu.Lock() + defer s.mu.Unlock() + tok := s.tok + return &tok, nil +} + +// failingSource fails every fetch with err. +type failingSource struct{ err error } + +func (s failingSource) Token() (*oauth2.Token, error) { return nil, s.err } + +func TestIssue_ExchangesOncePerSourceToken(t *testing.T) { + // The first intermediary has less than minServeLifetime left, so the mint + // after the refresh waits for the new exchange. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + src := &changingSource{tok: oauth2.Token{AccessToken: "source-1", Expiry: now.Add(minServeLifetime - time.Minute)}} + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, src, func() time.Time { return now }) + for _, uid := range []string{"a", "b", "c"} { + if _, err := i.Issue(t.Context(), uid, testGrants, true); err != nil { + t.Fatal(err) + } + } + if sts.calls != 1 { + t.Fatalf("three mints on one source token made %d STS calls, want 1", sts.calls) + } + src.mu.Lock() + src.tok = oauth2.Token{AccessToken: "source-2", Expiry: now.Add(time.Hour)} + src.mu.Unlock() + tok, err := i.Issue(t.Context(), "a", testGrants, true) + if err != nil { + t.Fatal(err) + } + if sts.calls != 2 || sts.last["subject_token"] != "source-2" { + t.Fatalf("a new source token made %d STS calls in total with subject %q, want 2 with source-2", sts.calls, sts.last["subject_token"]) + } + if inter, _ := sts.open(t, tok.AccessToken); inter != "intermediary-2" { + t.Errorf("token starts with %q, want the new intermediary token", inter) + } +} + +func TestIssue_ExpiresWithTheIntermediaryToken(t *testing.T) { + // STS reports the source token's remaining life, a second or so short of + // it. A longer lifetime is not trusted past the source token. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + source := now.Add(time.Hour) + for _, tc := range []struct { + name string + expiresIn int + want time.Time + }{ + {"what STS reports", 3599, now.Add(3599 * time.Second)}, + {"longer than the source token", 7200, source}, + {"no lifetime reported", -1, source}, + } { + t.Run(tc.name, func(t *testing.T) { + sts := &fakeSTS{t: t, expiresIn: tc.expiresIn} + i := newTestIssuer(t, sts, staticSource(source), func() time.Time { return now }) + tok, err := i.Issue(t.Context(), "9f1e", testGrants, false) + if err != nil { + t.Fatal(err) + } + if !tok.Expiry.Equal(tc.want) { + t.Errorf("Expiry = %v, want %v", tok.Expiry, tc.want) + } + }) + } +} + +func TestIssue_ExchangeOutlivesACallerThatGivesUp(t *testing.T) { + // The first mint on a new source token starts the exchange and gives up. + // The exchange still finishes, and the next mint uses it. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + sts.hold(t, "source-token") + ctx, cancel := context.WithCancel(t.Context()) + done := make(chan error) + go func() { + _, err := i.Issue(ctx, "a", testGrants, true) + done <- err + }() + <-sts.held + cancel() + if err := <-done; err == nil { + t.Fatal("Issue succeeded for a caller that gave up") + } + close(sts.release) + if _, err := i.Issue(t.Context(), "b", testGrants, true); err != nil { + t.Fatalf("Issue after the first caller gave up: %v", err) + } + if sts.calls != 1 { + t.Fatalf("STS calls = %d, want 1: the exchange should have survived the first caller", sts.calls) + } +} + +func TestIssue_ReplacedSourceTokenReusesItsIntermediary(t *testing.T) { + // A mint can hold the source token from just before a refresh, after + // another mint has exchanged the refreshed one. It reuses the old token's + // intermediary rather than exchanging the old token again. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + src := &changingSource{tok: oauth2.Token{AccessToken: "source-1", Expiry: now.Add(40 * time.Minute)}} + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, src, func() time.Time { return now }) + setSource := func(tok oauth2.Token) { + src.mu.Lock() + src.tok = tok + src.mu.Unlock() + } + old, err := i.Issue(t.Context(), "a", testGrants, true) + if err != nil { + t.Fatal(err) + } + refreshed := oauth2.Token{AccessToken: "source-2", Expiry: now.Add(time.Hour)} + setSource(refreshed) + if _, err := i.Issue(t.Context(), "b", testGrants, true); err != nil { + t.Fatal(err) + } + // The refreshed token is exchanged in the background. Joining it waits + // for it. + <-i.exchange(t.Context(), &refreshed) + setSource(oauth2.Token{AccessToken: "source-1", Expiry: now.Add(40 * time.Minute)}) + stale, err := i.Issue(t.Context(), "c", testGrants, true) + if err != nil { + t.Fatal(err) + } + oldInter, _ := sts.open(t, old.AccessToken) + if staleInter, _ := sts.open(t, stale.AccessToken); staleInter != oldInter || sts.calls != 2 { + t.Fatalf("a mint on the replaced token used %q with %d STS calls, want %q with 2", staleInter, sts.calls, oldInter) + } +} + +func TestIssue_AnOlderExchangeFinishingLateKeepsTheNewerIntermediary(t *testing.T) { + // A mint starts an exchange for the source token from just before a + // refresh. A second mint exchanges the refreshed token and finishes first. + // The first exchange finishing later must not change what mints on the + // refreshed token use. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + src := &changingSource{tok: oauth2.Token{AccessToken: "source-1", Expiry: now.Add(40 * time.Minute)}} + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, src, func() time.Time { return now }) + sts.hold(t, "source-1") + done := make(chan error) + go func() { + _, err := i.Issue(t.Context(), "a", testGrants, true) + done <- err + }() + <-sts.held + src.mu.Lock() + src.tok = oauth2.Token{AccessToken: "source-2", Expiry: now.Add(time.Hour)} + src.mu.Unlock() + newer, err := i.Issue(t.Context(), "b", testGrants, true) + if err != nil { + t.Fatal(err) + } + close(sts.release) + if err := <-done; err != nil { + t.Fatal(err) + } + later, err := i.Issue(t.Context(), "c", testGrants, true) + if err != nil { + t.Fatal(err) + } + newerInter, _ := sts.open(t, newer.AccessToken) + if laterInter, _ := sts.open(t, later.AccessToken); laterInter != newerInter || sts.calls != 2 { + t.Fatalf("after the older exchange finished, a mint used %q with %d STS calls, want %q with 2", laterInter, sts.calls, newerInter) + } + // The next refresh fails. Mints fall back to the newer intermediary, not + // the one whose exchange finished last. + src.mu.Lock() + src.tok = oauth2.Token{AccessToken: "source-3", Expiry: now.Add(2 * time.Hour)} + src.mu.Unlock() + sts.mu.Lock() + sts.status, sts.body = http.StatusServiceUnavailable, `{"error":"unavailable"}` + sts.mu.Unlock() + fallback, err := i.Issue(t.Context(), "d", testGrants, true) + if err != nil { + t.Fatal(err) + } + if inter, _ := sts.open(t, fallback.AccessToken); inter != newerInter { + t.Errorf("after a failed refresh, a mint used %q, want the newer %q", inter, newerInter) + } +} + +func TestIssue_ExchangesAgainOnceTheIntermediaryExpires(t *testing.T) { + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + clock := now + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return clock }) + if _, err := i.Issue(t.Context(), "a", testGrants, true); err != nil { + t.Fatal(err) + } + clock = now.Add(time.Hour + time.Second) + if _, err := i.Issue(t.Context(), "a", testGrants, true); err != nil { + t.Fatal(err) + } + if sts.calls != 2 { + t.Fatalf("STS calls = %d, want 2: the expired intermediary should not be reused", sts.calls) + } +} + +func TestIssue_RefreshesInTheBackground(t *testing.T) { + // The previous intermediary has 40 minutes left when the source token is + // refreshed. A mint uses it at once, even with STS hanging, and later mints + // use the new intermediary once its exchange is done. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + src := &changingSource{tok: oauth2.Token{AccessToken: "source-1", Expiry: now.Add(40 * time.Minute)}} + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, src, func() time.Time { return now }) + if _, err := i.Issue(t.Context(), "a", testGrants, true); err != nil { + t.Fatal(err) + } + refreshed := oauth2.Token{AccessToken: "source-2", Expiry: now.Add(time.Hour)} + src.mu.Lock() + src.tok = refreshed + src.mu.Unlock() + sts.hold(t, "source-2") + ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) + defer cancel() + tok, err := i.Issue(ctx, "b", testGrants, true) + if err != nil { + t.Fatalf("Issue waited for a hanging exchange: %v", err) + } + if inter, _ := sts.open(t, tok.AccessToken); inter != "intermediary-1" { + t.Errorf("token starts with %q, want the previous intermediary token", inter) + } + close(sts.release) + <-i.exchange(t.Context(), &refreshed) + tok, err = i.Issue(t.Context(), "c", testGrants, true) + if err != nil { + t.Fatal(err) + } + if inter, _ := sts.open(t, tok.AccessToken); inter != "intermediary-2" || sts.calls != 2 { + t.Errorf("after the exchange, a mint used %q with %d STS calls, want intermediary-2 with 2", inter, sts.calls) + } +} + +func TestIssue_PausesExchangesAfterAFailure(t *testing.T) { + // STS refuses after a refresh. Mints keep using the previous intermediary + // without calling STS again until stsTimeout has passed. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + clock := now + src := &changingSource{tok: oauth2.Token{AccessToken: "source-1", Expiry: now.Add(time.Hour)}} + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, src, func() time.Time { return clock }) + if _, err := i.Issue(t.Context(), "a", testGrants, true); err != nil { + t.Fatal(err) + } + refreshed := oauth2.Token{AccessToken: "source-2", Expiry: now.Add(2 * time.Hour)} + src.mu.Lock() + src.tok = refreshed + src.mu.Unlock() + sts.mu.Lock() + sts.status, sts.body = http.StatusTooManyRequests, `{"error":"quota_exceeded"}` + sts.mu.Unlock() + for n := range 5 { + if _, err := i.Issue(t.Context(), fmt.Sprintf("actor-%d", n), testGrants, true); err != nil { + t.Fatal(err) + } + // Joining the exchange the mint started lets it finish, so the next + // mint sees the failure. + <-i.exchange(t.Context(), &refreshed) + } + if sts.calls != 2 { + t.Fatalf("5 mints after a refused exchange made %d STS calls in total, want 2", sts.calls) + } + clock = now.Add(stsTimeout + time.Second) + if _, err := i.Issue(t.Context(), "later", testGrants, true); err != nil { + t.Fatal(err) + } + <-i.exchange(t.Context(), &refreshed) + if sts.calls != 3 { + t.Fatalf("a mint after the pause made %d STS calls in total, want 3", sts.calls) + } +} + +func TestIssue_RetriesSoonWithoutAFallback(t *testing.T) { + // With no intermediary to fall back on, one failed exchange fails mints + // only until minRetryDelay has passed. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + clock := now + sts := &fakeSTS{t: t, status: http.StatusServiceUnavailable, body: `{"error":"unavailable"}`} + i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return clock }) + if _, err := i.Issue(t.Context(), "a", testGrants, false); err == nil { + t.Fatal("Issue succeeded against a failing STS") } - if err := json.Unmarshal([]byte(sts.last["options"]), &options); err != nil { - t.Fatalf("options is not a boundary: %v", err) + clock = now.Add(minRetryDelay / 2) + if _, err := i.Issue(t.Context(), "a", testGrants, false); err == nil || !strings.Contains(err.Error(), "paused") || sts.calls != 1 { + t.Fatalf("a mint during the pause got %v with %d STS calls, want a paused error with 1", err, sts.calls) } - want, _ := gcsboundary.FromGrants(testGrants) - if diff := cmp.Diff(want, options.AccessBoundary.AccessBoundaryRules); diff != "" { - t.Errorf("rules on the wire (-want +got):\n%s", diff) + sts.mu.Lock() + sts.status, sts.body = 0, "" + sts.mu.Unlock() + clock = now.Add(minRetryDelay + time.Millisecond) + if _, err := i.Issue(t.Context(), "a", testGrants, false); err != nil || sts.calls != 2 { + t.Fatalf("a mint after the pause got %v with %d STS calls, want success with 2", err, sts.calls) + } +} + +func TestIssue_RetryPauseDoublesAndResets(t *testing.T) { + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + clock := now + src := &changingSource{tok: oauth2.Token{AccessToken: "source-1", Expiry: now.Add(time.Hour)}} + sts := &fakeSTS{t: t, status: http.StatusServiceUnavailable, body: `{"error":"unavailable"}`} + i := newTestIssuer(t, sts, src, func() time.Time { return clock }) + for _, want := range []time.Duration{1, 2, 4, 8, 16, 30, 30} { + if _, err := i.Issue(t.Context(), "a", testGrants, true); err == nil { + t.Fatal("Issue succeeded against a failing STS") + } + f := i.failure.Load() + if f == nil || f.delay != want*time.Second { + t.Fatalf("pause after failure = %v, want %v", f, want*time.Second) + } + clock = f.until + } + // A success clears the pause, so the next failure starts at + // minRetryDelay again. + sts.mu.Lock() + sts.status, sts.body = 0, "" + sts.mu.Unlock() + if _, err := i.Issue(t.Context(), "a", testGrants, true); err != nil { + t.Fatal(err) + } + src.mu.Lock() + src.tok = oauth2.Token{AccessToken: "source-2", Expiry: clock.Add(minServeLifetime - time.Minute)} + src.mu.Unlock() + sts.mu.Lock() + sts.status, sts.body = http.StatusServiceUnavailable, `{"error":"unavailable"}` + sts.mu.Unlock() + // The previous intermediary now has under minServeLifetime left, so the + // mint waits for the exchange, which fails. It may still fall back. + clock = clock.Add(time.Hour - minServeLifetime + time.Minute) + if _, err := i.Issue(t.Context(), "b", testGrants, true); err != nil && !strings.Contains(err.Error(), "503") { + t.Fatal(err) + } + if f := i.failure.Load(); f == nil || f.delay != minRetryDelay { + t.Fatalf("pause after a success and a new failure = %v, want %v", f, minRetryDelay) + } +} + +func TestIssue_AnExchangeTimeoutIsNotTheCallersDeadline(t *testing.T) { + // The exchange times out on its own deadline while the caller's has time + // left. Neither that mint nor the paused ones after it may report + // DeadlineExceeded, which the exchange would pass on as the caller's code. + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + sts := &fakeSTS{t: t} + srv := httptest.NewServer(http.HandlerFunc(sts.handler)) + t.Cleanup(srv.Close) + target, _ := url.Parse(srv.URL) + i, err := New(t.Context(), "", WithTokenSource(staticSource(now.Add(time.Hour))), WithClock(func() time.Time { return now }), + WithHTTPClient(&http.Client{Transport: redirect{sts: sts, target: target}, Timeout: 50 * time.Millisecond})) + if err != nil { + t.Fatal(err) + } + sts.hold(t, "source-token") + for _, what := range []string{"the mint that ran the exchange", "a paused mint"} { + _, err := i.Issue(t.Context(), "a", testGrants, false) + if err == nil || errors.Is(err, context.DeadlineExceeded) || status.Code(err) != codes.Unknown { + t.Fatalf("%s got %v (code %v), want an error without a code or context.DeadlineExceeded", what, err, status.Code(err)) + } + } +} + +func TestIssue_AcceptsASessionKeyWithoutPadding(t *testing.T) { + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + sts := &fakeSTS{t: t, unpaddedKey: true} + i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + tok, err := i.Issue(t.Context(), "9f1e", testGrants, false) + if err != nil { + t.Fatalf("Issue: %v", err) + } + sts.open(t, tok.AccessToken) +} + +func TestIssue_ConcurrentMintsShareOneExchange(t *testing.T) { + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + var wg sync.WaitGroup + for n := range 20 { + wg.Go(func() { + if _, err := i.Issue(t.Context(), fmt.Sprintf("actor-%d", n), testGrants, true); err != nil { + t.Error(err) + } + }) + } + wg.Wait() + if sts.calls != 1 { + t.Fatalf("20 concurrent mints on one source token made %d STS calls, want 1", sts.calls) } } @@ -166,22 +777,24 @@ func TestIssue_CachesPerActorUntilNearExpiry(t *testing.T) { if err != nil { t.Fatal(err) } - if sts.calls != 1 || second != first { - t.Fatalf("second Issue made %d STS calls in total and returned a different token", sts.calls) + if second != first { + t.Fatal("second Issue minted again instead of serving the cached token") } - if _, err := i.Issue(t.Context(), "other", testGrants, false); err != nil { + other, err := i.Issue(t.Context(), "other", testGrants, false) + if err != nil { t.Fatal(err) } - if sts.calls != 2 { - t.Fatalf("a different actor should exchange, STS calls = %d", sts.calls) + if other == first { + t.Fatal("a different actor was served the first actor's token") } // With less than minServeLifetime left the cached token is not served. clock = now.Add(time.Hour - minServeLifetime + time.Second) - if _, err := i.Issue(t.Context(), "9f1e", testGrants, false); err != nil { + third, err := i.Issue(t.Context(), "9f1e", testGrants, false) + if err != nil { t.Fatal(err) } - if sts.calls != 3 { - t.Fatalf("a token with under %v left should be re-minted, STS calls = %d", minServeLifetime, sts.calls) + if third == first { + t.Fatalf("a token with under %v left was served from the cache", minServeLifetime) } } @@ -189,13 +802,16 @@ func TestIssue_ForceBypassesTheCache(t *testing.T) { now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) sts := &fakeSTS{t: t} i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + var toks []string for _, force := range []bool{false, true} { - if _, err := i.Issue(t.Context(), "9f1e", testGrants, force); err != nil { + tok, err := i.Issue(t.Context(), "9f1e", testGrants, force) + if err != nil { t.Fatal(err) } + toks = append(toks, tok.AccessToken) } - if sts.calls != 2 { - t.Fatalf("force should exchange again, STS calls = %d", sts.calls) + if toks[0] == toks[1] { + t.Fatal("force served the cached token instead of minting") } } @@ -203,14 +819,17 @@ func TestIssue_CacheIsBounded(t *testing.T) { now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) sts := &fakeSTS{t: t} i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + var toks []string for _, uid := range []string{"a", "b", "c", "a"} { - if _, err := i.Issue(t.Context(), uid, testGrants, false); err != nil { + tok, err := i.Issue(t.Context(), uid, testGrants, false) + if err != nil { t.Fatal(err) } + toks = append(toks, tok.AccessToken) } - // Size 2: c evicted a, so the last call for a exchanged again. - if sts.calls != 4 || i.cache.Len() != 2 { - t.Fatalf("STS calls = %d, cache len = %d, want 4 and 2", sts.calls, i.cache.Len()) + // Size 2: c evicted a, so the last call for a minted again. + if toks[3] == toks[0] || i.cache.Len() != 2 { + t.Fatalf("a served from the cache after eviction: %v, cache len = %d, want 2", toks[3] == toks[0], i.cache.Len()) } } @@ -219,27 +838,30 @@ func TestIssue_ServesTheCachedTokenWhenItCoversTheGrants(t *testing.T) { rwOther := actorscope.Grant{Prefix: prefix("gs://other/root/atespaces/team-a/actors/9f1e"), Access: actorscope.ReadWrite} roOnOwn := actorscope.Grant{Prefix: rwGrant.Prefix, Access: actorscope.ReadOnly} for _, tc := range []struct { - name string - first []actorscope.Grant - second []actorscope.Grant - wantMints int + name string + first []actorscope.Grant + second []actorscope.Grant + wantHit bool }{ - {"same grants", testGrants, testGrants, 1}, - {"tag dropped after the first suspend", testGrants, []actorscope.Grant{rwGrant}, 1}, - {"read-only covered by read-write", testGrants, []actorscope.Grant{roOnOwn}, 1}, - {"repoint adds a location", testGrants, []actorscope.Grant{rwGrant, rwOther, roGrant}, 2}, - {"read-write not covered by read-only", []actorscope.Grant{roOnOwn}, []actorscope.Grant{rwGrant}, 2}, + {"same grants", testGrants, testGrants, true}, + {"tag dropped after the first suspend", testGrants, []actorscope.Grant{rwGrant}, true}, + {"read-only covered by read-write", testGrants, []actorscope.Grant{roOnOwn}, true}, + {"repoint adds a location", testGrants, []actorscope.Grant{rwGrant, rwOther, roGrant}, false}, + {"read-write not covered by read-only", []actorscope.Grant{roOnOwn}, []actorscope.Grant{rwGrant}, false}, } { t.Run(tc.name, func(t *testing.T) { sts := &fakeSTS{t: t} i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + var toks []string for _, grants := range [][]actorscope.Grant{tc.first, tc.second} { - if _, err := i.Issue(t.Context(), "9f1e", grants, false); err != nil { + tok, err := i.Issue(t.Context(), "9f1e", grants, false) + if err != nil { t.Fatal(err) } + toks = append(toks, tok.AccessToken) } - if sts.calls != tc.wantMints { - t.Fatalf("STS calls = %d, want %d", sts.calls, tc.wantMints) + if hit := toks[0] == toks[1]; hit != tc.wantHit { + t.Fatalf("second Issue served the cached token: %v, want %v", hit, tc.wantHit) } }) } @@ -266,19 +888,9 @@ func TestIssue_StopsWhenTheCallerGivesUp(t *testing.T) { // STS hangs. A cancelled caller must get an error at once, not after the // client timeout. now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) - srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - select { - case <-r.Context().Done(): - case <-time.After(3 * time.Second): - } - })) - t.Cleanup(srv.Close) - target, _ := url.Parse(srv.URL) - client := &http.Client{Transport: redirect{sts: &fakeSTS{t: t}, target: target}, Timeout: time.Minute} - i, err := New(t.Context(), "", WithTokenSource(staticSource(now.Add(time.Hour))), WithHTTPClient(client), WithClock(func() time.Time { return now })) - if err != nil { - t.Fatal(err) - } + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + sts.hold(t, "source-token") ctx, cancel := context.WithTimeout(t.Context(), 100*time.Millisecond) defer cancel() start := time.Now() @@ -316,6 +928,7 @@ func TestIssue_DoesNotCacheAShortLivedToken(t *testing.T) { now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) sts := &fakeSTS{t: t} i := newTestIssuer(t, sts, staticSource(now.Add(minServeLifetime-time.Minute)), func() time.Time { return now }) + var toks []string for range 2 { tok, err := i.Issue(t.Context(), "9f1e", testGrants, false) if err != nil { @@ -324,9 +937,10 @@ func TestIssue_DoesNotCacheAShortLivedToken(t *testing.T) { if tok.AccessToken == "" { t.Fatal("no token returned") } + toks = append(toks, tok.AccessToken) } - if sts.calls != 2 || i.cache.Len() != 0 { - t.Fatalf("STS calls = %d, cache len = %d, want 2 and 0", sts.calls, i.cache.Len()) + if toks[0] == toks[1] || i.cache.Len() != 0 { + t.Fatalf("short-lived token served from the cache: %v, cache len = %d, want 0", toks[0] == toks[1], i.cache.Len()) } } @@ -343,11 +957,15 @@ func TestIssue_Errors(t *testing.T) { // and Unknown for an STS or source failure, which carries no code. code codes.Code }{ - {"source without expiry", &fakeSTS{t: t}, staticSource(time.Time{}), testGrants, "no expiry", codes.Unknown}, + {"no expiry from STS or the source", &fakeSTS{t: t, expiresIn: -1}, staticSource(time.Time{}), testGrants, "no expiry", codes.Unknown}, + {"source refused", &fakeSTS{t: t}, failingSource{status.Error(codes.PermissionDenied, "IAM refused")}, testGrants, "IAM refused", codes.Unknown}, {"STS refuses", &fakeSTS{t: t, status: 400, body: `{"error":"invalid_grant"}`}, staticSource(now.Add(time.Hour)), testGrants, "400", codes.Unknown}, {"STS answers without a token", &fakeSTS{t: t, body: `{}`}, staticSource(now.Add(time.Hour)), testGrants, "no access token", codes.Unknown}, + {"STS answers without a session key", &fakeSTS{t: t, body: `{"access_token":"intermediary"}`}, staticSource(now.Add(time.Hour)), testGrants, "no session key", codes.Unknown}, + {"session key is not a keyset", &fakeSTS{t: t, body: `{"access_token":"intermediary","access_boundary_session_key":"bm90IGEga2V5c2V0"}`}, staticSource(now.Add(time.Hour)), testGrants, "session key", codes.Unknown}, {"no grants", &fakeSTS{t: t}, staticSource(now.Add(time.Hour)), nil, "no storage grants", codes.Internal}, - {"too many grants", &fakeSTS{t: t}, staticSource(now.Add(time.Hour)), manyGrants(11), "greater than 10", codes.Internal}, + {"too many grants", &fakeSTS{t: t}, staticSource(now.Add(time.Hour)), manyGrants(11), "1 to 10 rules, got 11", codes.Internal}, + {"STS refuses a server-side exchange", &fakeSTS{t: t, status: 400, body: `{"error":"invalid_request"}`}, staticSource(now.Add(time.Hour)), longGrants(1, 483), "400", codes.Unknown}, } { t.Run(tc.name, func(t *testing.T) { i := newTestIssuer(t, tc.sts, tc.source, clock) @@ -362,6 +980,74 @@ func TestIssue_Errors(t *testing.T) { } } +func TestIssue_FallsBackToServerSideForABoundaryTooLarge(t *testing.T) { + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + for _, tc := range []struct { + name string + grants []actorscope.Grant + serverSide bool + }{ + {"512-byte object prefix", longGrants(1, 482), false}, + {"513-byte object prefix", longGrants(1, 483), true}, + {"boundary over 4096 bytes", longGrants(10, 400), true}, + } { + t.Run(tc.name, func(t *testing.T) { + sts := &fakeSTS{t: t} + i := newTestIssuer(t, sts, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + tok, err := i.Issue(t.Context(), "9f1e", tc.grants, false) + if err != nil { + t.Fatal(err) + } + if got := strings.HasPrefix(tok.AccessToken, "downscoped-"); got != tc.serverSide { + t.Fatalf("server-side token = %v, want %v (token %q)", got, tc.serverSide, tok.AccessToken) + } + if !tc.serverSide { + return + } + if got := sts.last["requested_token_type"]; got != accessTokenType { + t.Errorf("requested_token_type = %q, want %q", got, accessTokenType) + } + var opts struct { + AccessBoundary struct { + AccessBoundaryRules []struct { + AvailableResource string `json:"availableResource"` + AvailablePermissions []string `json:"availablePermissions"` + AvailabilityCondition struct { + Expression string `json:"expression"` + } `json:"availabilityCondition"` + } `json:"accessBoundaryRules"` + } `json:"accessBoundary"` + } + if err := json.Unmarshal([]byte(sts.last["options"]), &opts); err != nil { + t.Fatalf("options is not a boundary: %v", err) + } + rules, err := gcsboundary.FromGrants(tc.grants) + if err != nil { + t.Fatal(err) + } + got := opts.AccessBoundary.AccessBoundaryRules + if len(got) != len(rules) { + t.Fatalf("options has %d rules, want %d", len(got), len(rules)) + } + for n, want := range rules { + if got[n].AvailableResource != want.Resource || !slices.Equal(got[n].AvailablePermissions, want.Permissions) || got[n].AvailabilityCondition.Expression != want.Condition { + t.Errorf("rule %d = %+v, want %+v", n, got[n], want) + } + } + }) + } +} + +func TestIssue_ServerSideKeepsTheCallersContextError(t *testing.T) { + now := time.Date(2026, 10, 14, 10, 0, 0, 0, time.UTC) + i := newTestIssuer(t, &fakeSTS{t: t}, staticSource(now.Add(time.Hour)), func() time.Time { return now }) + ctx, cancel := context.WithCancel(t.Context()) + cancel() + if _, err := i.Issue(ctx, "9f1e", longGrants(1, 483), false); !errors.Is(err, context.Canceled) { + t.Fatalf("Issue = %v, want context.Canceled", err) + } +} + func manyGrants(n int) []actorscope.Grant { var gs []actorscope.Grant for i := range n { @@ -369,3 +1055,15 @@ func manyGrants(n int) []actorscope.Grant { } return gs } + +// longGrants is n grants whose paths are length bytes. Each grant's object +// prefix in the condition is 30 bytes longer. +func longGrants(n, length int) []actorscope.Grant { + var gs []actorscope.Grant + for i := range n { + path := fmt.Sprintf("p%d/", i) + path += strings.Repeat("x", length-len(path)) + gs = append(gs, actorscope.Grant{Prefix: prefix("gs://b/" + path), Access: actorscope.ReadOnly}) + } + return gs +} diff --git a/internal/objectstoreplugin/gcsissuer/transferaccount.go b/internal/objectstoreplugin/gcsissuer/transferaccount.go index ece9147bc8..d3b794ad2c 100644 --- a/internal/objectstoreplugin/gcsissuer/transferaccount.go +++ b/internal/objectstoreplugin/gcsissuer/transferaccount.go @@ -81,7 +81,7 @@ func (f *fallbackSource) Token() (*oauth2.Token, error) { if err != nil { // Valid would apply the 40 minute margin the reuse source sets on its // tokens, so check the expiry itself. The token must outlast the STS - // call it is downscoped with. + // call it is exchanged in. if last := f.last.Load(); last != nil && time.Until(last.Expiry) > stsTimeout { return last, nil } diff --git a/internal/objectstoreplugin/gcsissuer/transferaccount_test.go b/internal/objectstoreplugin/gcsissuer/transferaccount_test.go index 7be3c95ff2..bb9cb0b1b9 100644 --- a/internal/objectstoreplugin/gcsissuer/transferaccount_test.go +++ b/internal/objectstoreplugin/gcsissuer/transferaccount_test.go @@ -164,8 +164,9 @@ func TestNew_NeedsATransferAccount(t *testing.T) { } // TestIssue_DownscopesTheTransferAccountsToken checks the issuer's source is -// the impersonated account: STS reports no lifetime, so the downscoped token -// expires with the token the IAM Credentials API returned. +// the impersonated account: the token the IAM Credentials API returned is +// exchanged for the intermediary token, and the downscoped token expires with +// it. func TestIssue_DownscopesTheTransferAccountsToken(t *testing.T) { iam := &fakeIAMCredentials{t: t, left: time.Hour} sts := &fakeSTS{t: t} diff --git a/internal/pluginsocket/pluginsocket.go b/internal/pluginsocket/pluginsocket.go index 57d71cfb3c..bf8ebad94f 100644 --- a/internal/pluginsocket/pluginsocket.go +++ b/internal/pluginsocket/pluginsocket.go @@ -12,9 +12,10 @@ // See the License for the specific language governing permissions and // limitations under the License. -// Package pluginsocket connects a server to its plugin sidecar over a Unix -// socket. It depends on no plugin implementation, so a server that only calls -// a plugin does not link the plugin's storage SDKs. +// Package pluginsocket connects a server to a local plugin, such as a sidecar +// or a CSI node plugin, over a Unix socket. It depends on no plugin +// implementation, so a server that only calls a plugin does not link the +// plugin's storage SDKs. package pluginsocket import ( @@ -38,9 +39,10 @@ import ( "google.golang.org/grpc/status" ) -// ReadyWait is the ready wait servers pass to Dial. It rides through a sidecar -// restart, including the first 10s step of kubelet's crash-loop back-off, and -// fails a plugin that stays down well before a caller's deadline would. +// ReadyWait is the ready wait servers pass to Dial or ReadyWaitOptions. It +// rides through a plugin restart, including the first 10s step of kubelet's +// crash-loop back-off, and fails a plugin that stays down well before a +// caller's deadline would. const ReadyWait = 30 * time.Second // reconnectParams keeps reconnect attempts to the local socket frequent, so a @@ -93,18 +95,26 @@ func Listen(path string) (net.Listener, error) { // The connection is unauthenticated: the socket is reachable only from // inside the pod, and only by its owner. func Dial(path string, readyWait time.Duration) (*grpc.ClientConn, error) { - conn, err := grpc.NewClient("unix://"+path, + opts := append([]grpc.DialOption{ grpc.WithTransportCredentials(insecure.NewCredentials()), grpc.WithStatsHandler(otelgrpc.NewClientHandler()), - grpc.WithConnectParams(reconnectParams), - grpc.WithUnaryInterceptor(boundedWaitForReady(readyWait)), - ) + }, ReadyWaitOptions(readyWait)...) + conn, err := grpc.NewClient("unix://"+path, opts...) if err != nil { return nil, fmt.Errorf("while dialing plugin at %s: %w", path, err) } return conn, nil } +// ReadyWaitOptions returns the reconnect and ready wait options that Dial +// uses, for a client that dials its own target and credentials. +func ReadyWaitOptions(readyWait time.Duration) []grpc.DialOption { + return []grpc.DialOption{ + grpc.WithConnectParams(reconnectParams), + grpc.WithUnaryInterceptor(boundedWaitForReady(readyWait)), + } +} + // boundedWaitForReady waits up to wait for cc to become ready before issuing // a call that sets no grpc.WaitForReady option, then issues it fail-fast. func boundedWaitForReady(wait time.Duration) grpc.UnaryClientInterceptor { diff --git a/internal/portforward/portforward_test.go b/internal/portforward/portforward_test.go index 272d71a032..1184c224cc 100644 --- a/internal/portforward/portforward_test.go +++ b/internal/portforward/portforward_test.go @@ -55,12 +55,12 @@ func TestResolveTargetPort(t *testing.T) { want int32 wantErr bool }{ - {"int target port", svc(corev1.ServicePort{Port: 80, TargetPort: intstr.FromInt(8080)}), pod, 8080, false}, + {"int target port", svc(corev1.ServicePort{Port: 80, TargetPort: intstr.FromInt32(8080)}), pod, 8080, false}, {"named target port", svc(corev1.ServicePort{Port: 80, TargetPort: intstr.FromString("http")}), pod, 8080, false}, {"named target not found", svc(corev1.ServicePort{Port: 80, TargetPort: intstr.FromString("nope")}), pod, 0, true}, {"named target resolves to zero", svc(corev1.ServicePort{Port: 80, TargetPort: intstr.FromString("http")}), zeroPortPod, 0, true}, {"unset target port defaults to port", svc(corev1.ServicePort{Port: 80}), pod, 80, false}, - {"no matching service port", svc(corev1.ServicePort{Port: 443, TargetPort: intstr.FromInt(8443)}), pod, 0, true}, + {"no matching service port", svc(corev1.ServicePort{Port: 443, TargetPort: intstr.FromInt32(8443)}), pod, 0, true}, } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { diff --git a/internal/preview/preview.go b/internal/preview/preview.go index 4e49e194aa..9454c37dac 100644 --- a/internal/preview/preview.go +++ b/internal/preview/preview.go @@ -14,8 +14,8 @@ // Package preview manages preview feature gates enabled via the --preview flag. // -// The gates are process-wide. A binary calls Init exactly once, before -// anything calls IsEnabled or AsMap. +// A binary calls New with its --preview values and passes the returned Gates +// to the code that checks them. package preview import ( @@ -23,7 +23,8 @@ import ( "log/slog" "slices" "strings" - "sync" + + "k8s.io/apimachinery/pkg/api/operation" ) // Gate identifies a gate-controlled preview feature. Preview gates are @@ -39,6 +40,9 @@ type Gate string // Gates should always be named in UpperCamelCase. Please keep this list // sorted alphabetically by value. const ( + // GateActorIPv6 controls whether IPv6 is added to actor networks. + GateActorIPv6 Gate = "ActorIPv6" + // GateExternalVolumes controls whether external volumes are supported. GateExternalVolumes Gate = "ExternalVolumes" @@ -50,6 +54,10 @@ const ( // field and snapshots are stored under ate-api-server's // --snapshot-location. GatePerTemplateSnapshotLocation Gate = "PerTemplateSnapshotLocation" + + // GateIngressCache controls whether the ingress router caches actor to + // worker bindings and routes cache hits around ext_proc. + GateIngressCache Gate = "IngressCache" ) // All is the pseudo-gate name that enables every known gate. @@ -58,81 +66,59 @@ const All = "ALL" // realKnownGates lists all declared preview gates. Preview gates are disabled by // default and enabled via the --preview flag. var realKnownGates = []Gate{ + GateActorIPv6, GateExternalVolumes, GateGoldenEgressPolicy, + GateIngressCache, GatePerTemplateSnapshotLocation, } -var globalKnownGates []Gate // all known gates -var globalStateMap map[string]bool // gate-name -> enabled? -var globalDisabledMap map[string]bool // gate-name -> false (all disabled) -var globalInitialized bool // true if Init has been called, false otherwise -var globalInitLock sync.Mutex - -// init sets the globalStateMap to the default state of all known gates disabled. It -// is called automatically on package initialization, but can be overridden by -// calling Init. -func init() { - globalInitLock.Lock() - defer globalInitLock.Unlock() - if globalStateMap != nil { - return - } +// Gates holds the state of each known preview gate. Build one with New. It is +// immutable, so one value may be shared freely. +type Gates struct { + known []Gate + enabled map[string]bool // all gate-names -> enabled? + disabled map[string]bool // all gate-names -> false +} - slices.Sort(realKnownGates) - if m, err := newGateMap(realKnownGates); err != nil { - panic(fmt.Sprintf("preview.init failed: %v", err)) - } else { - globalKnownGates = realKnownGates - globalStateMap = m - globalDisabledMap = newDisabledMap(realKnownGates) +// New returns the preview gates set by the --preview flag values, and logs +// their state. The special value All enables all known gates. With no values, +// all gates are disabled. +func New(values ...string) (*Gates, error) { + g, err := newGates(realKnownGates, values...) + if err != nil { + return nil, err } + slog.Info("initializing preview gates", slog.String("state", g.String())) + return g, nil } -// Init sets the process-wide preview gates from the --preview flag values. -// The special value All enables all known gates. With no values, all gates are -// disabled. It panics if called again after the first successful call. -func Init(values ...string) error { - globalInitLock.Lock() - defer globalInitLock.Unlock() - if globalInitialized { - panic("preview.Init called more than once") +// newGates is New with the known gates as a parameter, so tests can use fake +// gates. +func newGates(knownGates []Gate, values ...string) (*Gates, error) { + knownGates = slices.Sorted(slices.Values(knownGates)) + m, err := newGateMap(knownGates, values...) + if err != nil { + return nil, err } - logFunc := func(state string) { - slog.Info("initializing preview gates", slog.String("state", state)) - } - return doInit(globalKnownGates, logFunc, values...) + return &Gates{known: knownGates, enabled: m, disabled: newDisabledMap(knownGates)}, nil } -// This allows tests to use fake gates. -func doInit(knownGates []Gate, logFunc func(state string), values ...string) error { - if m, err := newGateMap(knownGates, values...); err != nil { - return err - } else { - globalKnownGates = knownGates - globalStateMap = m - globalDisabledMap = newDisabledMap(knownGates) - globalInitialized = true - - if logFunc != nil { - logStr := func() string { - en := make([]string, 0, len(knownGates)) - for _, g := range knownGates { - k := string(g) - v := "off" - if m[k] { - v = "on" - } - en = append(en, fmt.Sprintf("%s=%s", k, v)) - } - return fmt.Sprintf("[%s]", strings.Join(en, ", ")) - }() - logFunc(logStr) +// String returns the state of every known gate, like "[A=on, B=off]". +func (g *Gates) String() string { + en := make([]string, 0, len(g.known)) + for _, k := range g.known { + v := "off" + if g.enabled[string(k)] { + v = "on" } + en = append(en, fmt.Sprintf("%s=%s", k, v)) } - return nil + return fmt.Sprintf("[%s]", strings.Join(en, ", ")) } +// newGateMap creates a map of the gate states, or returns an error if any +// value is not a known gate. func newGateMap(knownGates []Gate, values ...string) (map[string]bool, error) { tmpMap := make(map[string]bool, len(knownGates)) all := false @@ -164,32 +150,53 @@ func newDisabledMap(knownGates []Gate) map[string]bool { // Verify checks that the given values are all valid preview gates. func Verify(values ...string) error { - return doVerify(globalKnownGates, values...) + return verify(realKnownGates, values...) } -func doVerify(knownGates []Gate, values ...string) error { +// verify is Verify with the known gates as a parameter, so tests can use fake +// gates. +func verify(knownGates []Gate, values ...string) error { _, err := newGateMap(knownGates, values...) return err } // IsEnabled reports whether the given preview gate is enabled. Unknown gates // are always treated as disabled. -func IsEnabled(gate Gate) bool { - return globalStateMap[string(gate)] +func (g *Gates) IsEnabled(gate Gate) bool { + return g.enabled[string(gate)] } -// AsMap returns the map of known gate names to their enabled state. -// The returned map MUST NOT be modified. -// -// TODO: Fix this to use an interface when DV supports it. -func AsMap() map[string]bool { - return globalStateMap +// Enabled returns the names of the enabled gates, sorted. +func (g *Gates) Enabled() []string { + var ret []string + for _, k := range g.known { + if g.enabled[string(k)] { + ret = append(ret, string(k)) + } + } + return ret } -// DisabledMap returns the map of known gate names, all disabled. -// The returned map MUST NOT be modified. -// -// TODO: Fix this to use an interface when DV supports it. -func DisabledMap() map[string]bool { - return globalDisabledMap +// implement operation.OptionGetter +type optionGetter struct { + gates map[string]bool +} + +func (o optionGetter) Get(gate string) (enabled, defined bool) { + enabled, defined = o.gates[gate] + return enabled, defined +} + +var _ operation.OptionGetter = optionGetter{} + +// OptionGetter returns an operation.OptionGetter that can be used to query +// the enabled state of preview gates. +func (g *Gates) OptionGetter() operation.OptionGetter { + return optionGetter{g.enabled} +} + +// DisabledOptionGetter returns an operation.OptionGetter that can be used to +// report all preview gates as disabled. +func (g *Gates) DisabledOptionGetter() operation.OptionGetter { + return optionGetter{g.disabled} } diff --git a/internal/preview/preview_test.go b/internal/preview/preview_test.go index faf782debd..e64242d071 100644 --- a/internal/preview/preview_test.go +++ b/internal/preview/preview_test.go @@ -15,36 +15,16 @@ package preview import ( + "os" "regexp" + "slices" "strings" "testing" "github.com/google/go-cmp/cmp" ) -// resetGlobalsForTest clears the global state. -func resetGlobalsForTest() { - globalKnownGates = nil - globalStateMap = nil - globalInitialized = false -} - -func wantPanic(t *testing.T, substr string, fn func()) { - t.Helper() - defer func() { - t.Helper() - r := recover() - if r == nil { - t.Fatalf("got no panic, want one containing %q", substr) - } - if msg, _ := r.(string); !strings.Contains(msg, substr) { - t.Fatalf("panic = %v, want one containing %q", r, substr) - } - }() - fn() -} - -func TestInit(t *testing.T) { +func TestNew(t *testing.T) { tests := []struct { name string values []string @@ -64,35 +44,31 @@ func TestInit(t *testing.T) { } for _, tc := range tests { t.Run(tc.name, func(t *testing.T) { - resetGlobalsForTest() - err := doInit([]Gate{"Fake", "Phony"}, nil, tc.values...) + g, err := newGates([]Gate{"Fake", "Phony"}, tc.values...) if (err != nil) != tc.wantErr { - t.Fatalf("Init(%q) error = %v, wantErr %v", tc.values, err, tc.wantErr) + t.Fatalf("newGates(%q) error = %v, wantErr %v", tc.values, err, tc.wantErr) } if tc.wantErr { - if globalStateMap != nil { - t.Errorf("Init(%q) failed but set the gates", tc.values) - } return } - if diff := cmp.Diff(tc.want, AsMap()); diff != "" { - t.Errorf("AsMap() mismatch (-want +got):\n%s", diff) + if diff := cmp.Diff(tc.want, g.enabled); diff != "" { + t.Errorf("enabled mismatch (-want +got):\n%s", diff) } }) } } -var pascalCase = regexp.MustCompile(`^[A-Z][a-z0-9]+(?:[A-Z][a-z0-9]*)*$`) +var upperCamelCase = regexp.MustCompile(`^[A-Z][A-Za-z0-9]*[a-z0-9]$`) -func TestRealGatesArePascalCase(t *testing.T) { +func TestRealGatesAreUpperCamelCase(t *testing.T) { // Sanity-check the pattern itself. - for _, s := range []string{"ExternalVolumes", "Foo", "FooV2", "FooBar2Baz"} { - if !pascalCase.MatchString(s) { + for _, s := range []string{"ExternalVolumes", "ActorIPv6", "Foo", "FooV2", "FooBar2Baz"} { + if !upperCamelCase.MatchString(s) { t.Errorf("pattern rejected valid name %q", s) } } for _, s := range []string{"", "externalVolumes", "External_Volumes", "External-Volumes", "EXTERNAL", All, "F", "Foo Bar"} { - if pascalCase.MatchString(s) { + if upperCamelCase.MatchString(s) { t.Errorf("pattern accepted invalid name %q", s) } } @@ -100,31 +76,40 @@ func TestRealGatesArePascalCase(t *testing.T) { if len(realKnownGates) == 0 { t.Fatal("no real gates defined") } - for _, g := range realKnownGates { - if !pascalCase.MatchString(string(g)) { - t.Errorf("gate %q is not PascalCase", g) + for i, g := range realKnownGates { + if !upperCamelCase.MatchString(string(g)) { + t.Errorf("gate %q is not UpperCamelCase", g) + } + if i > 0 && realKnownGates[i-1] >= g { + t.Errorf("realKnownGates not sorted: %q before %q", realKnownGates[i-1], g) } } } -func TestInitTwicePanics(t *testing.T) { - resetGlobalsForTest() - if err := Init(); err != nil { - t.Fatalf("Init(): %v", err) +func TestRealGatesAreDocumented(t *testing.T) { + doc, err := os.ReadFile("../../docs/reference/preview-gates.md") + if err != nil { + t.Fatalf("reading preview-gates.md: %v", err) + } + lines := strings.Split(string(doc), "\n") + for _, g := range realKnownGates { + heading := "### `" + string(g) + "`" + if !slices.Contains(lines, heading) { + t.Errorf("docs/reference/preview-gates.md is missing heading line %q for gate %q", heading, g) + } } - wantPanic(t, "more than once", func() { _ = Init("ALL") }) } func TestIsEnabledKnownGate(t *testing.T) { - InitForTestFake(t, []Gate{"Fake"}, "ALL") - if !IsEnabled(Gate("Fake")) { - t.Errorf("IsEnabled(unknown) = false, want true") + g := NewForTestFake(t, []Gate{"Fake"}, "ALL") + if !g.IsEnabled(Gate("Fake")) { + t.Errorf("IsEnabled(Fake) = false, want true") } } func TestIsEnabledUnknownGate(t *testing.T) { - InitForTestFake(t, []Gate{"Fake"}, "ALL") - if IsEnabled(Gate("Bogus")) { + g := NewForTestFake(t, []Gate{"Fake"}, "ALL") + if g.IsEnabled(Gate("Bogus")) { t.Errorf("IsEnabled(unknown) = true, want false") } } @@ -143,47 +128,38 @@ func TestVerify(t *testing.T) { {values: []string{"Bogus"}, wantErr: true}, {values: []string{"ALL", "Bogus"}, wantErr: true}, } { - if err := doVerify(fakeGates, tc.values...); (err != nil) != tc.wantErr { + if err := verify(fakeGates, tc.values...); (err != nil) != tc.wantErr { t.Errorf("Verify(%q) = %v, want error %v", tc.values, err, tc.wantErr) } } } -func TestSetForTest(t *testing.T) { - resetGlobalsForTest() - t.Run("enabled", func(t *testing.T) { - InitForTestFake(t, []Gate{"Fake"}, "ALL") - if !IsEnabled("Fake") { - t.Errorf("IsEnabled(%q) = false, want true", "Fake") - } - t.Run("nested disabled", func(t *testing.T) { - InitForTest(t) - if IsEnabled("Fake") { - t.Errorf("IsEnabled(%q) = true, want false", "Fake") - } - }) - if !IsEnabled("Fake") { - t.Errorf("IsEnabled(%q) after nested test = false, want true", "Fake") - } - }) - if globalStateMap != nil { - t.Errorf("InitForTest did not restore the uninitialized state") - } - // Init still works once InitForTest has been undone. - if err := Init(); err != nil { - t.Errorf("Init() after InitForTest: %v", err) +func TestEnabled(t *testing.T) { + g := NewForTestFake(t, []Gate{"C", "A", "B"}, "C", "A") + if diff := cmp.Diff([]string{"A", "C"}, g.Enabled()); diff != "" { + t.Errorf("Enabled() mismatch (-want +got):\n%s", diff) } } -func TestSetForTestFakeRestoresKnownGates(t *testing.T) { - resetGlobalsForTest() - t.Run("fake", func(t *testing.T) { - InitForTestFake(t, []Gate{"Fake"}, "Fake") - if err := Verify("Fake"); err != nil { - t.Errorf("Verify(Fake) with the fake installed = %v", err) - } - }) - if err := Verify("Fake"); err == nil { - t.Errorf("Verify(Fake) after the fake's test ended = nil, want an error: %v", globalStateMap) +func TestOptionGetter(t *testing.T) { + g := NewForTestFake(t, []Gate{"On", "Off"}, "On") + for _, tc := range []struct { + name string + getter func() (bool, bool) + wantEnabled bool + wantDefined bool + }{ + {name: "enabled known gate", getter: func() (bool, bool) { return g.OptionGetter().Get("On") }, wantEnabled: true, wantDefined: true}, + {name: "disabled known gate", getter: func() (bool, bool) { return g.OptionGetter().Get("Off") }, wantEnabled: false, wantDefined: true}, + {name: "unknown gate", getter: func() (bool, bool) { return g.OptionGetter().Get("Bogus") }, wantEnabled: false, wantDefined: false}, + {name: "disabled getter on enabled gate", getter: func() (bool, bool) { return g.DisabledOptionGetter().Get("On") }, wantEnabled: false, wantDefined: true}, + {name: "disabled getter on unknown gate", getter: func() (bool, bool) { return g.DisabledOptionGetter().Get("Bogus") }, wantEnabled: false, wantDefined: false}, + } { + t.Run(tc.name, func(t *testing.T) { + gotEnabled, gotDefined := tc.getter() + if gotEnabled != tc.wantEnabled || gotDefined != tc.wantDefined { + t.Errorf("Get() = (%v, %v), want (%v, %v)", gotEnabled, gotDefined, tc.wantEnabled, tc.wantDefined) + } + }) } } diff --git a/internal/preview/request.go b/internal/preview/request.go index ae523bf471..e2a3a1178a 100644 --- a/internal/preview/request.go +++ b/internal/preview/request.go @@ -20,6 +20,8 @@ import ( "google.golang.org/grpc" "google.golang.org/grpc/metadata" + + "go.ate.dev/substrate/internal/apierror" ) // Header is the gRPC metadata key with which an API client says it intends @@ -52,10 +54,10 @@ func IsOptedOut(ctx context.Context) bool { return restricted } -// IsEnabledFor reports whether gate is enabled in this process and ctx has -// not opted-out of preview features. -func IsEnabledFor(ctx context.Context, gate Gate) bool { - return IsEnabled(gate) && !IsOptedOut(ctx) +// IsEnabledFor reports whether gate is enabled in g and ctx has not opted-out +// of preview features. +func (g *Gates) IsEnabledFor(ctx context.Context, gate Gate) bool { + return g.IsEnabled(gate) && !IsOptedOut(ctx) } // requestOptedIn reports whether the incoming request in ctx sent Header @@ -77,9 +79,18 @@ func optOutIfNotOptIn(ctx context.Context) context.Context { return ContextWithOptOut(ctx) } -// UnaryServerInterceptor restricts each request that did not send Header. -func UnaryServerInterceptor(ctx context.Context, req any, _ *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { - return handler(optOutIfNotOptIn(ctx), req) +// UnaryServerInterceptor returns an interceptor that restricts each request +// that did not send Header. It rejects a call to a method in methodGates, +// keyed by full method name, unless that method's gate is enabled in g for the +// request. +func (g *Gates) UnaryServerInterceptor(methodGates map[string]Gate) grpc.UnaryServerInterceptor { + return func(ctx context.Context, req any, info *grpc.UnaryServerInfo, handler grpc.UnaryHandler) (any, error) { + ctx = optOutIfNotOptIn(ctx) + if gate, ok := methodGates[info.FullMethod]; ok && !g.IsEnabledFor(ctx, gate) { + return nil, apierror.FailedPrecondition("%s requires the %s preview gate and the %s header", info.FullMethod, gate, Header) + } + return handler(ctx, req) + } } // StreamServerInterceptor restricts each stream that did not send Header. diff --git a/internal/preview/request_test.go b/internal/preview/request_test.go index 9cc2224543..58ca6f436f 100644 --- a/internal/preview/request_test.go +++ b/internal/preview/request_test.go @@ -26,9 +26,12 @@ import ( "google.golang.org/grpc/status" "google.golang.org/grpc/test/bufconn" "google.golang.org/protobuf/types/known/emptypb" + + "go.ate.dev/substrate/internal/apierror" ) func TestUnaryServerInterceptor(t *testing.T) { + g := NewForTest(t) for _, tc := range []struct { name string values []string @@ -50,7 +53,7 @@ func TestUnaryServerInterceptor(t *testing.T) { ctx = metadata.NewIncomingContext(ctx, md) } var got bool - _, err := UnaryServerInterceptor(ctx, nil, &grpc.UnaryServerInfo{}, func(ctx context.Context, _ any) (any, error) { + _, err := g.UnaryServerInterceptor(nil)(ctx, nil, &grpc.UnaryServerInfo{}, func(ctx context.Context, _ any) (any, error) { got = !IsOptedOut(ctx) return nil, nil }) @@ -64,6 +67,44 @@ func TestUnaryServerInterceptor(t *testing.T) { } } +func TestUnaryServerInterceptorMethodGates(t *testing.T) { + g := NewForTestFake(t, []Gate{"A", "B"}, "A") + methodGates := map[string]Gate{ + "/test.Svc/GatedByA": "A", + "/test.Svc/GatedByB": "B", + } + for _, tc := range []struct { + name string + method string + optIn bool + wantCode codes.Code + }{ + {name: "ungated method, no opt-in", method: "/test.Svc/Ungated", wantCode: codes.OK}, + {name: "enabled gate, opted in", method: "/test.Svc/GatedByA", optIn: true, wantCode: codes.OK}, + {name: "enabled gate, no opt-in", method: "/test.Svc/GatedByA", wantCode: codes.FailedPrecondition}, + {name: "disabled gate, opted in", method: "/test.Svc/GatedByB", optIn: true, wantCode: codes.FailedPrecondition}, + {name: "disabled gate, no opt-in", method: "/test.Svc/GatedByB", wantCode: codes.FailedPrecondition}, + } { + t.Run(tc.name, func(t *testing.T) { + ctx := t.Context() + if tc.optIn { + ctx = metadata.NewIncomingContext(ctx, metadata.Pairs(Header, "true")) + } + called := false + _, err := g.UnaryServerInterceptor(methodGates)(ctx, nil, &grpc.UnaryServerInfo{FullMethod: tc.method}, func(context.Context, any) (any, error) { + called = true + return nil, nil + }) + if got := apierror.Code(err); got != tc.wantCode { + t.Errorf("code = %v, want %v (err: %v)", got, tc.wantCode, err) + } + if wantCalled := tc.wantCode == codes.OK; called != wantCalled { + t.Errorf("handler called = %v, want %v", called, wantCalled) + } + }) + } +} + type fakeStream struct { grpc.ServerStream ctx context.Context @@ -111,7 +152,7 @@ func TestContextWithOptInOut(t *testing.T) { } func TestIsEnabledFor(t *testing.T) { - InitForTestFake(t, []Gate{"A", "B"}, "A") + g := NewForTestFake(t, []Gate{"A", "B"}, "A") for _, tc := range []struct { name string ctx context.Context @@ -124,7 +165,7 @@ func TestIsEnabledFor(t *testing.T) { {name: "disabled, opted in", ctx: ContextWithOptIn(context.Background()), gate: "B", want: false}, } { t.Run(tc.name, func(t *testing.T) { - if got := IsEnabledFor(tc.ctx, tc.gate); got != tc.want { + if got := g.IsEnabledFor(tc.ctx, tc.gate); got != tc.want { t.Errorf("IsEnabledFor(%s) = %v, want %v", tc.gate, got, tc.want) } }) diff --git a/internal/preview/testing.go b/internal/preview/testing.go index f6cb0b339d..1e12c0b61a 100644 --- a/internal/preview/testing.go +++ b/internal/preview/testing.go @@ -18,49 +18,24 @@ package preview // into non-test code. type testingTB interface { Helper() - Setenv(key, value string) - Cleanup(func()) Fatalf(format string, args ...any) Log(args ...any) } -// InitForTest sets the process-wide preview gates for the duration of tb, as -// Init would with values, and restores the previous state when tb ends. It may -// be called whether or not Init has been. Tests that use it must not run in -// parallel. -func InitForTest(tb testingTB, values ...string) { +// NewForTest returns the gates New would with values. It fails tb on an +// unknown gate. +func NewForTest(tb testingTB, values ...string) *Gates { tb.Helper() - InitForTestFake(tb, realKnownGates, values...) + return NewForTestFake(tb, realKnownGates, values...) } -// InitForTestFake is InitForTest with fake gate names. Tests of the preview -// gate system itself should use this to avoid depending on the real gate -// names. Tests that use it must not run in parallel. -func InitForTestFake(tb testingTB, fakeKnownGates []Gate, values ...string) { +// NewForTestFake is NewForTest with fakeKnownGates in place of the real ones. +func NewForTestFake(tb testingTB, fakeKnownGates []Gate, values ...string) *Gates { tb.Helper() - - // Setenv fails the test if it, or an ancestor, is parallel. - tb.Setenv("ATE_PREVIEW_SET_FOR_TEST", "1") - - globalInitLock.Lock() - defer globalInitLock.Unlock() - - prevInitialized := globalInitialized - prevKnownGates := globalKnownGates - prevStateMap := globalStateMap - prevDisabledMap := globalDisabledMap - - logFunc := func(state string) { - tb.Log("initialized preview gates for test:", state) - } - if err := doInit(fakeKnownGates, logFunc, values...); err != nil { - tb.Fatalf("preview.InitForTestFake: %v", err) + g, err := newGates(fakeKnownGates, values...) + if err != nil { + tb.Fatalf("preview.NewForTestFake: %v", err) } - - tb.Cleanup(func() { - globalInitialized = prevInitialized - globalKnownGates = prevKnownGates - globalStateMap = prevStateMap - globalDisabledMap = prevDisabledMap - }) + tb.Log("preview gates for test:", g) + return g } diff --git a/internal/proto/ateletpb/atelet.pb.go b/internal/proto/ateletpb/atelet.pb.go index 1a88aec7f5..1b7b42f312 100644 --- a/internal/proto/ateletpb/atelet.pb.go +++ b/internal/proto/ateletpb/atelet.pb.go @@ -1284,7 +1284,12 @@ type ReportActorCrashedRequest struct { // // +k8s:required // +k8s:maxLength=4096 - Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"` + Message string `protobuf:"bytes,4,opt,name=message,proto3" json:"message,omitempty"` + // The API server-assigned identity of the activation that exited. + // + // +k8s:optional + // +k8s:format=k8s-uuid + ActivationUid string `protobuf:"bytes,5,opt,name=activation_uid,json=activationUid,proto3" json:"activation_uid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -1347,6 +1352,13 @@ func (x *ReportActorCrashedRequest) GetMessage() string { return "" } +func (x *ReportActorCrashedRequest) GetActivationUid() string { + if x != nil { + return x.ActivationUid + } + return "" +} + type ReportActorCrashedResponse struct { state protoimpl.MessageState `protogen:"open.v1"` unknownFields protoimpl.UnknownFields @@ -2073,8 +2085,14 @@ type RunRequest struct { // // +k8s:required SandboxRuntime *ActorSandboxRuntime `protobuf:"bytes,12,opt,name=sandbox_runtime,json=sandboxRuntime,proto3" json:"sandbox_runtime,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // The API server assigns a new UUID for each Run call. + // Empty when called by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + ActivationUid string `protobuf:"bytes,13,opt,name=activation_uid,json=activationUid,proto3" json:"activation_uid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RunRequest) Reset() { @@ -2177,6 +2195,13 @@ func (x *RunRequest) GetSandboxRuntime() *ActorSandboxRuntime { return nil } +func (x *RunRequest) GetActivationUid() string { + if x != nil { + return x.ActivationUid + } + return "" +} + // EgressGateway configures tunneled egress for one actor activation. type EgressGateway struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -2333,12 +2358,17 @@ type ExternalVolumeSource struct { // sends volumes that finished provisioning. // // +k8s:required - // +k8s:maxLength=256 # matches ExternalVolumeStatus.storage_volume_id's bound - // +k8s:customValidation # no control characters + // +k8s:maxLength=256 # matches ActorExternalVolumeStatus.storage_volume_id's bound + // +k8s:format=ate-volume-storage-id StorageVolumeId string `protobuf:"bytes,1,opt,name=storage_volume_id,json=storageVolumeId,proto3" json:"storage_volume_id,omitempty"` + // CSI driver name. Must be a DNS subdomain of at most 63 characters. + // + // (-- Same rule as `CsiDriver.driver_name`, and the CSI spec's driver name + // limit. --) + // // +k8s:optional - // +k8s:maxLength=253 # matches ExternalVolumeStatus.volume_type's bound - // +k8s:customValidation # optional "substrate.io/" prefix + DNS subdomain + // +k8s:maxLength=63 + // +k8s:format=k8s-long-name VolumeType string `protobuf:"bytes,2,opt,name=volume_type,json=volumeType,proto3" json:"volume_type,omitempty"` // volume_context is the driver's provisioning metadata. Its entries are the // driver's own, so the map is only bounded, not validated. @@ -3162,7 +3192,7 @@ type EnvVar struct { // // +k8s:required // +k8s:maxLength=256 # guardrail - // +k8s:customValidation # printable ASCII except '=' + // +k8s:format=ate-env-var-name Name string `protobuf:"bytes,1,opt,name=name,proto3" json:"name,omitempty"` // +k8s:optional // +k8s:maxLength=32768 # guardrail @@ -3282,7 +3312,7 @@ type HttpGetAction struct { // // +k8s:required // +k8s:maxLength=1024 # matches the template probe path's bound - // +k8s:customValidation # RFC 3986 path shape; no regex/pattern tag exists + // +k8s:format=ate-http-probe-path Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"` // TCP port to connect to (1..65535). // @@ -4005,8 +4035,14 @@ type RestoreRequest struct { // // +k8s:required SandboxRuntime *ActorSandboxRuntime `protobuf:"bytes,12,opt,name=sandbox_runtime,json=sandboxRuntime,proto3" json:"sandbox_runtime,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // The API server assigns a new UUID for each Restore call. + // Empty when called by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + ActivationUid string `protobuf:"bytes,13,opt,name=activation_uid,json=activationUid,proto3" json:"activation_uid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RestoreRequest) Reset() { @@ -4116,6 +4152,13 @@ func (x *RestoreRequest) GetSandboxRuntime() *ActorSandboxRuntime { return nil } +func (x *RestoreRequest) GetActivationUid() string { + if x != nil { + return x.ActivationUid + } + return "" +} + type RestoreResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The epoch of the worker process that restored the workload, as it @@ -4475,13 +4518,14 @@ const file_internal_proto_ateletpb_atelet_proto_rawDesc = "" + "\n" + "actor_name\x18\x02 \x01(\tR\tactorName\x12\x1b\n" + "\tactor_uid\x18\x03 \x01(\tR\bactorUid\"\x1d\n" + - "\x1bRequestActorSuspendResponse\"\x98\x01\n" + + "\x1bRequestActorSuspendResponse\"\xbf\x01\n" + "\x19ReportActorCrashedRequest\x12%\n" + "\x0eactor_atespace\x18\x01 \x01(\tR\ractorAtespace\x12\x1d\n" + "\n" + "actor_name\x18\x02 \x01(\tR\tactorName\x12\x1b\n" + "\tactor_uid\x18\x03 \x01(\tR\bactorUid\x12\x18\n" + - "\amessage\x18\x04 \x01(\tR\amessage\"\x1c\n" + + "\amessage\x18\x04 \x01(\tR\amessage\x12%\n" + + "\x0eactivation_uid\x18\x05 \x01(\tR\ractivationUid\"\x1c\n" + "\x1aReportActorCrashedResponse\"c\n" + "\x1bGetActorEgressPolicyRequest\x12%\n" + "\x0eactor_atespace\x18\x01 \x01(\tR\ractorAtespace\x12\x1d\n" + @@ -4520,7 +4564,7 @@ const file_internal_proto_ateletpb_atelet_proto_rawDesc = "" + "\x17actor_template_atespace\x18\x05 \x01(\tR\x15actorTemplateAtespace\x12.\n" + "\x13actor_template_name\x18\x06 \x01(\tR\x11actorTemplateName\x12(\n" + "\x04spec\x18\a \x01(\v2\x14.atelet.WorkloadSpecR\x04spec\"\x13\n" + - "\x11TerminateResponse\"\xf4\x03\n" + + "\x11TerminateResponse\"\x9b\x04\n" + "\n" + "RunRequest\x12$\n" + "\x0eworker_pod_uid\x18\x01 \x01(\tR\fworkerPodUid\x12\x1a\n" + @@ -4534,7 +4578,8 @@ const file_internal_proto_ateletpb_atelet_proto_rawDesc = "" + "\x0eegress_gateway\x18\t \x01(\v2\x15.atelet.EgressGatewayH\x00R\regressGateway\x88\x01\x01\x12:\n" + "\tresources\x18\n" + " \x01(\v2\x1c.atelet.ResourceRequirementsR\tresources\x12D\n" + - "\x0fsandbox_runtime\x18\f \x01(\v2\x1b.atelet.ActorSandboxRuntimeR\x0esandboxRuntimeB\x11\n" + + "\x0fsandbox_runtime\x18\f \x01(\v2\x1b.atelet.ActorSandboxRuntimeR\x0esandboxRuntime\x12%\n" + + "\x0eactivation_uid\x18\r \x01(\tR\ractivationUidB\x11\n" + "\x0f_egress_gateway\")\n" + "\rEgressGateway\x12\x18\n" + "\aaddress\x18\x01 \x01(\tR\aaddress\"k\n" + @@ -4642,7 +4687,7 @@ const file_internal_proto_ateletpb_atelet_proto_rawDesc = "" + "\bsnapshot\x18\b \x01(\v2\x10.atelet.SnapshotR\bsnapshot\x129\n" + "\rupload_config\x18\t \x01(\v2\x14.atelet.UploadConfigR\fuploadConfig\"F\n" + "\x12CheckpointResponse\x120\n" + - "\x05state\x18\x01 \x01(\v2\x1a.atelet.ActorSnapshotStateR\x05state\"\xa6\x04\n" + + "\x05state\x18\x01 \x01(\v2\x1a.atelet.ActorSnapshotStateR\x05state\"\xcd\x04\n" + "\x0eRestoreRequest\x12$\n" + "\x0eworker_pod_uid\x18\x01 \x01(\tR\fworkerPodUid\x12\x1a\n" + "\batespace\x18\x02 \x01(\tR\batespace\x12\x1d\n" + @@ -4656,7 +4701,8 @@ const file_internal_proto_ateletpb_atelet_proto_rawDesc = "" + "\x0eegress_gateway\x18\t \x01(\v2\x15.atelet.EgressGatewayH\x00R\regressGateway\x88\x01\x01\x12:\n" + "\tresources\x18\n" + " \x01(\v2\x1c.atelet.ResourceRequirementsR\tresources\x12D\n" + - "\x0fsandbox_runtime\x18\f \x01(\v2\x1b.atelet.ActorSandboxRuntimeR\x0esandboxRuntimeB\x11\n" + + "\x0fsandbox_runtime\x18\f \x01(\v2\x1b.atelet.ActorSandboxRuntimeR\x0esandboxRuntime\x12%\n" + + "\x0eactivation_uid\x18\r \x01(\tR\ractivationUidB\x11\n" + "\x0f_egress_gateway\"4\n" + "\x0fRestoreResponse\x12!\n" + "\fworker_epoch\x18\x01 \x01(\x03R\vworkerEpoch\"\x86\x02\n" + diff --git a/internal/proto/ateletpb/atelet.proto b/internal/proto/ateletpb/atelet.proto index 536604385e..5643b5c2f0 100644 --- a/internal/proto/ateletpb/atelet.proto +++ b/internal/proto/ateletpb/atelet.proto @@ -344,6 +344,12 @@ message ReportActorCrashedRequest { // +k8s:required // +k8s:maxLength=4096 string message = 4; + + // The API server-assigned identity of the activation that exited. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string activation_uid = 5; } message ReportActorCrashedResponse { @@ -600,6 +606,13 @@ message RunRequest { // // +k8s:required ActorSandboxRuntime sandbox_runtime = 12; + + // The API server assigns a new UUID for each Run call. + // Empty when called by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string activation_uid = 13; } // EgressGateway configures tunneled egress for one actor activation. @@ -638,13 +651,18 @@ message ExternalVolumeSource { // sends volumes that finished provisioning. // // +k8s:required - // +k8s:maxLength=256 # matches ExternalVolumeStatus.storage_volume_id's bound - // +k8s:customValidation # no control characters + // +k8s:maxLength=256 # matches ActorExternalVolumeStatus.storage_volume_id's bound + // +k8s:format=ate-volume-storage-id string storage_volume_id = 1; + // CSI driver name. Must be a DNS subdomain of at most 63 characters. + // + // (-- Same rule as `CsiDriver.driver_name`, and the CSI spec's driver name + // limit. --) + // // +k8s:optional - // +k8s:maxLength=253 # matches ExternalVolumeStatus.volume_type's bound - // +k8s:customValidation # optional "substrate.io/" prefix + DNS subdomain + // +k8s:maxLength=63 + // +k8s:format=k8s-long-name string volume_type = 2; // volume_context is the driver's provisioning metadata. Its entries are the @@ -875,7 +893,7 @@ message EnvVar { // // +k8s:required // +k8s:maxLength=256 # guardrail - // +k8s:customValidation # printable ASCII except '=' + // +k8s:format=ate-env-var-name string name = 1; // +k8s:optional @@ -903,7 +921,7 @@ message HttpGetAction { // // +k8s:required // +k8s:maxLength=1024 # matches the template probe path's bound - // +k8s:customValidation # RFC 3986 path shape; no regex/pattern tag exists + // +k8s:format=ate-http-probe-path string path = 1; // TCP port to connect to (1..65535). @@ -1223,6 +1241,13 @@ message RestoreRequest { // // +k8s:required ActorSandboxRuntime sandbox_runtime = 12; + + // The API server assigns a new UUID for each Restore call. + // Empty when called by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string activation_uid = 13; } message RestoreResponse { diff --git a/internal/proto/ateworkerpb/ateworker.pb.go b/internal/proto/ateworkerpb/ateworker.pb.go index 8de8d66ac7..048ebc5333 100644 --- a/internal/proto/ateworkerpb/ateworker.pb.go +++ b/internal/proto/ateworkerpb/ateworker.pb.go @@ -502,7 +502,13 @@ type RunWorkloadRequest struct { // +k8s:optional Resources *ResourceRequirements `protobuf:"bytes,10,opt,name=resources,proto3" json:"resources,omitempty"` // +k8s:required - ActorDirs *ActorDirs `protobuf:"bytes,12,opt,name=actor_dirs,json=actorDirs,proto3" json:"actor_dirs,omitempty"` + ActorDirs *ActorDirs `protobuf:"bytes,12,opt,name=actor_dirs,json=actorDirs,proto3" json:"actor_dirs,omitempty"` + // The API server-assigned identity of this Run call, bound to its runtime. + // Empty when called by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + ActivationUid string `protobuf:"bytes,13,opt,name=activation_uid,json=activationUid,proto3" json:"activation_uid,omitempty"` unknownFields protoimpl.UnknownFields sizeCache protoimpl.SizeCache } @@ -614,6 +620,13 @@ func (x *RunWorkloadRequest) GetActorDirs() *ActorDirs { return nil } +func (x *RunWorkloadRequest) GetActivationUid() string { + if x != nil { + return x.ActivationUid + } + return "" +} + // EgressGateway configures tunneled egress for one actor activation. type EgressGateway struct { state protoimpl.MessageState `protogen:"open.v1"` @@ -1255,7 +1268,7 @@ type HttpGetAction struct { // // +k8s:required // +k8s:maxLength=1024 # matches ateapi.HttpGetAction.path - // +k8s:customValidation # RFC 3986 path shape; no regex/pattern tag exists + // +k8s:format=ate-http-probe-path Path string `protobuf:"bytes,1,opt,name=path,proto3" json:"path,omitempty"` // TCP port to connect to (1..65535). // @@ -1599,8 +1612,14 @@ type RestoreWorkloadRequest struct { // // +k8s:optional PreserveRestoreDir bool `protobuf:"varint,14,opt,name=preserve_restore_dir,json=preserveRestoreDir,proto3" json:"preserve_restore_dir,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // The API server-assigned identity of this Restore call, bound to its runtime. + // Empty when called by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + ActivationUid string `protobuf:"bytes,15,opt,name=activation_uid,json=activationUid,proto3" json:"activation_uid,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *RestoreWorkloadRequest) Reset() { @@ -1724,6 +1743,13 @@ func (x *RestoreWorkloadRequest) GetPreserveRestoreDir() bool { return false } +func (x *RestoreWorkloadRequest) GetActivationUid() string { + if x != nil { + return x.ActivationUid + } + return "" +} + type RestoreWorkloadResponse struct { state protoimpl.MessageState `protogen:"open.v1"` // The epoch this worker process registered with. @@ -1847,7 +1873,8 @@ type WorkloadStatsSample struct { // Measurements. All four are zero when source is STATS_SOURCE_UNSPECIFIED, // which means "not measured" rather than "measured as zero". // - // memory_current_bytes and memory_working_set_bytes are absolute. + // memory_current_bytes and memory_working_set_bytes are absolute. They are + // zero and not measured when memory_unmeasured is set. MemoryCurrentBytes uint64 `protobuf:"varint,8,opt,name=memory_current_bytes,json=memoryCurrentBytes,proto3" json:"memory_current_bytes,omitempty"` // High-water mark of memory_current_bytes, as the source reports it: the // cgroup source restarts it on a restore, the guest-agent source brings the @@ -1869,8 +1896,13 @@ type WorkloadStatsSample struct { // The activation this sample belongs to, as the unix-nano time it began. A // Run or Restore starts one. EpochUnixNano int64 `protobuf:"varint,13,opt,name=epoch_unix_nano,json=epochUnixNano,proto3" json:"epoch_unix_nano,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + // Set when memory_current_bytes and memory_working_set_bytes were not + // measured although source is set: the reading is of a gVisor sandbox with no + // process left, as after it died. Its cgroup keeps the CPU counter and the + // memory peak, but the memory went with the processes. + MemoryUnmeasured bool `protobuf:"varint,14,opt,name=memory_unmeasured,json=memoryUnmeasured,proto3" json:"memory_unmeasured,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *WorkloadStatsSample) Reset() { @@ -1994,6 +2026,13 @@ func (x *WorkloadStatsSample) GetEpochUnixNano() int64 { return 0 } +func (x *WorkloadStatsSample) GetMemoryUnmeasured() bool { + if x != nil { + return x.MemoryUnmeasured + } + return false +} + type GetWorkloadStatsResponse struct { state protoimpl.MessageState `protogen:"open.v1"` Sample *WorkloadStatsSample `protobuf:"bytes,1,opt,name=sample,proto3" json:"sample,omitempty"` @@ -2153,7 +2192,7 @@ const file_internal_proto_ateworkerpb_ateworker_proto_rawDesc = "" + "\x04spec\x18\a \x01(\v2\x17.ateworker.WorkloadSpecR\x04spec\x123\n" + "\n" + "actor_dirs\x18\b \x01(\v2\x14.ateworker.ActorDirsR\tactorDirs\"\x1b\n" + - "\x19TerminateWorkloadResponse\"\x99\x05\n" + + "\x19TerminateWorkloadResponse\"\xc0\x05\n" + "\x12RunWorkloadRequest\x12\x1a\n" + "\batespace\x18\x01 \x01(\tR\batespace\x12\x1d\n" + "\n" + @@ -2169,7 +2208,8 @@ const file_internal_proto_ateworkerpb_ateworker_proto_rawDesc = "" + "\tresources\x18\n" + " \x01(\v2\x1f.ateworker.ResourceRequirementsR\tresources\x123\n" + "\n" + - "actor_dirs\x18\f \x01(\v2\x14.ateworker.ActorDirsR\tactorDirs\x1aD\n" + + "actor_dirs\x18\f \x01(\v2\x14.ateworker.ActorDirsR\tactorDirs\x12%\n" + + "\x0eactivation_uid\x18\r \x01(\tR\ractivationUid\x1aD\n" + "\x16RuntimeAssetPathsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\x11\n" + @@ -2231,7 +2271,7 @@ const file_internal_proto_ateworkerpb_ateworker_proto_rawDesc = "" + "actor_dirs\x18\t \x01(\v2\x14.ateworker.ActorDirsR\tactorDirs\"s\n" + "\x1aCheckpointWorkloadResponse\x12%\n" + "\x0esnapshot_files\x18\x01 \x03(\tR\rsnapshotFiles\x12.\n" + - "\x13data_snapshot_files\x18\x02 \x03(\tR\x11dataSnapshotFiles\"\x8c\x06\n" + + "\x13data_snapshot_files\x18\x02 \x03(\tR\x11dataSnapshotFiles\"\xb3\x06\n" + "\x16RestoreWorkloadRequest\x12\x1a\n" + "\batespace\x18\x01 \x01(\tR\batespace\x12\x1d\n" + "\n" + @@ -2249,7 +2289,8 @@ const file_internal_proto_ateworkerpb_ateworker_proto_rawDesc = "" + "\tresources\x18\v \x01(\v2\x1f.ateworker.ResourceRequirementsR\tresources\x123\n" + "\n" + "actor_dirs\x18\r \x01(\v2\x14.ateworker.ActorDirsR\tactorDirs\x120\n" + - "\x14preserve_restore_dir\x18\x0e \x01(\bR\x12preserveRestoreDir\x1aD\n" + + "\x14preserve_restore_dir\x18\x0e \x01(\bR\x12preserveRestoreDir\x12%\n" + + "\x0eactivation_uid\x18\x0f \x01(\tR\ractivationUid\x1aD\n" + "\x16RuntimeAssetPathsEntry\x12\x10\n" + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + "\x05value\x18\x02 \x01(\tR\x05value:\x028\x01B\x11\n" + @@ -2257,7 +2298,7 @@ const file_internal_proto_ateworkerpb_ateworker_proto_rawDesc = "" + "\x17RestoreWorkloadResponse\x12!\n" + "\fworker_epoch\x18\x01 \x01(\x03R\vworkerEpoch\"6\n" + "\x17GetWorkloadStatsRequest\x12\x1b\n" + - "\tactor_uid\x18\x01 \x01(\tR\bactorUid\"\xc2\x04\n" + + "\tactor_uid\x18\x01 \x01(\tR\bactorUid\"\xef\x04\n" + "\x13WorkloadStatsSample\x12\x1a\n" + "\batespace\x18\x01 \x01(\tR\batespace\x12\x1d\n" + "\n" + @@ -2273,7 +2314,8 @@ const file_internal_proto_ateworkerpb_ateworker_proto_rawDesc = "" + " \x01(\x04R\x15memoryWorkingSetBytes\x12$\n" + "\x0ecpu_usage_usec\x18\v \x01(\x04R\fcpuUsageUsec\x121\n" + "\x15observed_at_unix_nano\x18\f \x01(\x03R\x12observedAtUnixNano\x12&\n" + - "\x0fepoch_unix_nano\x18\r \x01(\x03R\repochUnixNano\"R\n" + + "\x0fepoch_unix_nano\x18\r \x01(\x03R\repochUnixNano\x12+\n" + + "\x11memory_unmeasured\x18\x0e \x01(\bR\x10memoryUnmeasured\"R\n" + "\x18GetWorkloadStatsResponse\x126\n" + "\x06sample\x18\x01 \x01(\v2\x1e.ateworker.WorkloadStatsSampleR\x06sample\"\x1f\n" + "\x1dGetActiveWorkloadStatsRequest\"Z\n" + diff --git a/internal/proto/ateworkerpb/ateworker.proto b/internal/proto/ateworkerpb/ateworker.proto index 2a0ccd824b..bf14ae35ff 100644 --- a/internal/proto/ateworkerpb/ateworker.proto +++ b/internal/proto/ateworkerpb/ateworker.proto @@ -245,6 +245,13 @@ message RunWorkloadRequest { ResourceRequirements resources = 10; // +k8s:required ActorDirs actor_dirs = 12; + + // The API server-assigned identity of this Run call, bound to its runtime. + // Empty when called by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string activation_uid = 13; } // EgressGateway configures tunneled egress for one actor activation. @@ -426,7 +433,7 @@ message HttpGetAction { // // +k8s:required // +k8s:maxLength=1024 # matches ateapi.HttpGetAction.path - // +k8s:customValidation # RFC 3986 path shape; no regex/pattern tag exists + // +k8s:format=ate-http-probe-path string path = 1; // TCP port to connect to (1..65535). @@ -569,6 +576,13 @@ message RestoreWorkloadRequest { // // +k8s:optional bool preserve_restore_dir = 14; + + // The API server-assigned identity of this Restore call, bound to its runtime. + // Empty when called by an older API server. + // + // +k8s:optional + // +k8s:format=k8s-uuid + string activation_uid = 15; } message RestoreWorkloadResponse { @@ -633,7 +647,8 @@ message WorkloadStatsSample { // Measurements. All four are zero when source is STATS_SOURCE_UNSPECIFIED, // which means "not measured" rather than "measured as zero". // - // memory_current_bytes and memory_working_set_bytes are absolute. + // memory_current_bytes and memory_working_set_bytes are absolute. They are + // zero and not measured when memory_unmeasured is set. uint64 memory_current_bytes = 8; // High-water mark of memory_current_bytes, as the source reports it: the // cgroup source restarts it on a restore, the guest-agent source brings the @@ -657,6 +672,12 @@ message WorkloadStatsSample { // The activation this sample belongs to, as the unix-nano time it began. A // Run or Restore starts one. int64 epoch_unix_nano = 13; + + // Set when memory_current_bytes and memory_working_set_bytes were not + // measured although source is set: the reading is of a gVisor sandbox with no + // process left, as after it died. Its cgroup keeps the CPU counter and the + // memory peak, but the memory went with the processes. + bool memory_unmeasured = 14; } message GetWorkloadStatsResponse { diff --git a/internal/proto/clientsideboundarypb/boundary.pb.go b/internal/proto/clientsideboundarypb/boundary.pb.go new file mode 100644 index 0000000000..31a358cbbc --- /dev/null +++ b/internal/proto/clientsideboundarypb/boundary.pb.go @@ -0,0 +1,209 @@ +// Copyright 2026 The Agent Substrate 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. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11-devel +// protoc v4.25.3 +// source: internal/proto/clientsideboundarypb/boundary.proto + +package clientsideboundarypb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// ClientSideAccessBoundary is the Credential Access Boundary that +// gcsissuer encrypts into a locally minted token. Google's STS reads it, so +// the field numbers must match the generated classes in +// google-auth-library-java (cab-token-generator). +type ClientSideAccessBoundary struct { + state protoimpl.MessageState `protogen:"open.v1"` + AccessBoundaryRules []*ClientSideAccessBoundaryRule `protobuf:"bytes,1,rep,name=access_boundary_rules,json=accessBoundaryRules,proto3" json:"access_boundary_rules,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ClientSideAccessBoundary) Reset() { + *x = ClientSideAccessBoundary{} + mi := &file_internal_proto_clientsideboundarypb_boundary_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ClientSideAccessBoundary) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ClientSideAccessBoundary) ProtoMessage() {} + +func (x *ClientSideAccessBoundary) ProtoReflect() protoreflect.Message { + mi := &file_internal_proto_clientsideboundarypb_boundary_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ClientSideAccessBoundary.ProtoReflect.Descriptor instead. +func (*ClientSideAccessBoundary) Descriptor() ([]byte, []int) { + return file_internal_proto_clientsideboundarypb_boundary_proto_rawDescGZIP(), []int{0} +} + +func (x *ClientSideAccessBoundary) GetAccessBoundaryRules() []*ClientSideAccessBoundaryRule { + if x != nil { + return x.AccessBoundaryRules + } + return nil +} + +type ClientSideAccessBoundaryRule struct { + state protoimpl.MessageState `protogen:"open.v1"` + AvailableResource string `protobuf:"bytes,1,opt,name=available_resource,json=availableResource,proto3" json:"available_resource,omitempty"` + AvailablePermissions []string `protobuf:"bytes,2,rep,name=available_permissions,json=availablePermissions,proto3" json:"available_permissions,omitempty"` + // A serialized google.api.expr.Expr, the rule's condition parsed by CEL. + // Google's definition declares the message type. bytes is the same on the + // wire and needs no import of the CEL protos. + CompiledAvailabilityCondition []byte `protobuf:"bytes,4,opt,name=compiled_availability_condition,json=compiledAvailabilityCondition,proto3" json:"compiled_availability_condition,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *ClientSideAccessBoundaryRule) Reset() { + *x = ClientSideAccessBoundaryRule{} + mi := &file_internal_proto_clientsideboundarypb_boundary_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *ClientSideAccessBoundaryRule) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*ClientSideAccessBoundaryRule) ProtoMessage() {} + +func (x *ClientSideAccessBoundaryRule) ProtoReflect() protoreflect.Message { + mi := &file_internal_proto_clientsideboundarypb_boundary_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use ClientSideAccessBoundaryRule.ProtoReflect.Descriptor instead. +func (*ClientSideAccessBoundaryRule) Descriptor() ([]byte, []int) { + return file_internal_proto_clientsideboundarypb_boundary_proto_rawDescGZIP(), []int{1} +} + +func (x *ClientSideAccessBoundaryRule) GetAvailableResource() string { + if x != nil { + return x.AvailableResource + } + return "" +} + +func (x *ClientSideAccessBoundaryRule) GetAvailablePermissions() []string { + if x != nil { + return x.AvailablePermissions + } + return nil +} + +func (x *ClientSideAccessBoundaryRule) GetCompiledAvailabilityCondition() []byte { + if x != nil { + return x.CompiledAvailabilityCondition + } + return nil +} + +var File_internal_proto_clientsideboundarypb_boundary_proto protoreflect.FileDescriptor + +const file_internal_proto_clientsideboundarypb_boundary_proto_rawDesc = "" + + "\n" + + "2internal/proto/clientsideboundarypb/boundary.proto\x12\x12clientsideboundary\"\x80\x01\n" + + "\x18ClientSideAccessBoundary\x12d\n" + + "\x15access_boundary_rules\x18\x01 \x03(\v20.clientsideboundary.ClientSideAccessBoundaryRuleR\x13accessBoundaryRules\"\xca\x01\n" + + "\x1cClientSideAccessBoundaryRule\x12-\n" + + "\x12available_resource\x18\x01 \x01(\tR\x11availableResource\x123\n" + + "\x15available_permissions\x18\x02 \x03(\tR\x14availablePermissions\x12F\n" + + "\x1fcompiled_availability_condition\x18\x04 \x01(\fR\x1dcompiledAvailabilityConditionB:Z8go.ate.dev/substrate/internal/proto/clientsideboundarypbb\x06proto3" + +var ( + file_internal_proto_clientsideboundarypb_boundary_proto_rawDescOnce sync.Once + file_internal_proto_clientsideboundarypb_boundary_proto_rawDescData []byte +) + +func file_internal_proto_clientsideboundarypb_boundary_proto_rawDescGZIP() []byte { + file_internal_proto_clientsideboundarypb_boundary_proto_rawDescOnce.Do(func() { + file_internal_proto_clientsideboundarypb_boundary_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_internal_proto_clientsideboundarypb_boundary_proto_rawDesc), len(file_internal_proto_clientsideboundarypb_boundary_proto_rawDesc))) + }) + return file_internal_proto_clientsideboundarypb_boundary_proto_rawDescData +} + +var file_internal_proto_clientsideboundarypb_boundary_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_internal_proto_clientsideboundarypb_boundary_proto_goTypes = []any{ + (*ClientSideAccessBoundary)(nil), // 0: clientsideboundary.ClientSideAccessBoundary + (*ClientSideAccessBoundaryRule)(nil), // 1: clientsideboundary.ClientSideAccessBoundaryRule +} +var file_internal_proto_clientsideboundarypb_boundary_proto_depIdxs = []int32{ + 1, // 0: clientsideboundary.ClientSideAccessBoundary.access_boundary_rules:type_name -> clientsideboundary.ClientSideAccessBoundaryRule + 1, // [1:1] is the sub-list for method output_type + 1, // [1:1] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_internal_proto_clientsideboundarypb_boundary_proto_init() } +func file_internal_proto_clientsideboundarypb_boundary_proto_init() { + if File_internal_proto_clientsideboundarypb_boundary_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_internal_proto_clientsideboundarypb_boundary_proto_rawDesc), len(file_internal_proto_clientsideboundarypb_boundary_proto_rawDesc)), + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_internal_proto_clientsideboundarypb_boundary_proto_goTypes, + DependencyIndexes: file_internal_proto_clientsideboundarypb_boundary_proto_depIdxs, + MessageInfos: file_internal_proto_clientsideboundarypb_boundary_proto_msgTypes, + }.Build() + File_internal_proto_clientsideboundarypb_boundary_proto = out.File + file_internal_proto_clientsideboundarypb_boundary_proto_goTypes = nil + file_internal_proto_clientsideboundarypb_boundary_proto_depIdxs = nil +} diff --git a/internal/proto/clientsideboundarypb/boundary.proto b/internal/proto/clientsideboundarypb/boundary.proto new file mode 100644 index 0000000000..ae1b63eb49 --- /dev/null +++ b/internal/proto/clientsideboundarypb/boundary.proto @@ -0,0 +1,36 @@ +// Copyright 2026 The Agent Substrate 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. + +syntax = "proto3"; + +package clientsideboundary; + +option go_package = "go.ate.dev/substrate/internal/proto/clientsideboundarypb"; + +// ClientSideAccessBoundary is the Credential Access Boundary that +// gcsissuer encrypts into a locally minted token. Google's STS reads it, so +// the field numbers must match the generated classes in +// google-auth-library-java (cab-token-generator). +message ClientSideAccessBoundary { + repeated ClientSideAccessBoundaryRule access_boundary_rules = 1; +} + +message ClientSideAccessBoundaryRule { + string available_resource = 1; + repeated string available_permissions = 2; + // A serialized google.api.expr.Expr, the rule's condition parsed by CEL. + // Google's definition declares the message type. bytes is the same on the + // wire and needs no import of the CEL protos. + bytes compiled_availability_condition = 4; +} diff --git a/internal/proto/tokenexchangepb/cachekey.pb.go b/internal/proto/tokenexchangepb/cachekey.pb.go new file mode 100644 index 0000000000..7c5762c007 --- /dev/null +++ b/internal/proto/tokenexchangepb/cachekey.pb.go @@ -0,0 +1,278 @@ +// Copyright 2026 The Agent Substrate 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. + +// Code generated by protoc-gen-go. DO NOT EDIT. +// versions: +// protoc-gen-go v1.36.11-devel +// protoc v4.25.3 +// source: internal/proto/tokenexchangepb/cachekey.proto + +package tokenexchangepb + +import ( + protoreflect "google.golang.org/protobuf/reflect/protoreflect" + protoimpl "google.golang.org/protobuf/runtime/protoimpl" + reflect "reflect" + sync "sync" + unsafe "unsafe" +) + +const ( + // Verify that this generated code is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(20 - protoimpl.MinVersion) + // Verify that runtime/protoimpl is sufficiently up-to-date. + _ = protoimpl.EnforceVersion(protoimpl.MaxVersion - 20) +) + +// TokenCacheKey is the canonical in-process cache key input for the egress +// gateway's RFC 8693 token exchange broker. +type TokenCacheKey struct { + state protoimpl.MessageState `protogen:"open.v1"` + Atespace string `protobuf:"bytes,1,opt,name=atespace,proto3" json:"atespace,omitempty"` + ActorName string `protobuf:"bytes,2,opt,name=actor_name,json=actorName,proto3" json:"actor_name,omitempty"` + TokenUrl string `protobuf:"bytes,3,opt,name=token_url,json=tokenUrl,proto3" json:"token_url,omitempty"` + SubjectJwtAudiences []string `protobuf:"bytes,4,rep,name=subject_jwt_audiences,json=subjectJwtAudiences,proto3" json:"subject_jwt_audiences,omitempty"` + SubjectJwtExpirationSeconds int64 `protobuf:"varint,5,opt,name=subject_jwt_expiration_seconds,json=subjectJwtExpirationSeconds,proto3" json:"subject_jwt_expiration_seconds,omitempty"` + Resources []string `protobuf:"bytes,6,rep,name=resources,proto3" json:"resources,omitempty"` + Audiences []string `protobuf:"bytes,7,rep,name=audiences,proto3" json:"audiences,omitempty"` + Scopes []string `protobuf:"bytes,8,rep,name=scopes,proto3" json:"scopes,omitempty"` + RequestedTokenType string `protobuf:"bytes,9,opt,name=requested_token_type,json=requestedTokenType,proto3" json:"requested_token_type,omitempty"` + AdditionalParameters []*TokenCacheKey_FormEntry `protobuf:"bytes,10,rep,name=additional_parameters,json=additionalParameters,proto3" json:"additional_parameters,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *TokenCacheKey) Reset() { + *x = TokenCacheKey{} + mi := &file_internal_proto_tokenexchangepb_cachekey_proto_msgTypes[0] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *TokenCacheKey) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TokenCacheKey) ProtoMessage() {} + +func (x *TokenCacheKey) ProtoReflect() protoreflect.Message { + mi := &file_internal_proto_tokenexchangepb_cachekey_proto_msgTypes[0] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TokenCacheKey.ProtoReflect.Descriptor instead. +func (*TokenCacheKey) Descriptor() ([]byte, []int) { + return file_internal_proto_tokenexchangepb_cachekey_proto_rawDescGZIP(), []int{0} +} + +func (x *TokenCacheKey) GetAtespace() string { + if x != nil { + return x.Atespace + } + return "" +} + +func (x *TokenCacheKey) GetActorName() string { + if x != nil { + return x.ActorName + } + return "" +} + +func (x *TokenCacheKey) GetTokenUrl() string { + if x != nil { + return x.TokenUrl + } + return "" +} + +func (x *TokenCacheKey) GetSubjectJwtAudiences() []string { + if x != nil { + return x.SubjectJwtAudiences + } + return nil +} + +func (x *TokenCacheKey) GetSubjectJwtExpirationSeconds() int64 { + if x != nil { + return x.SubjectJwtExpirationSeconds + } + return 0 +} + +func (x *TokenCacheKey) GetResources() []string { + if x != nil { + return x.Resources + } + return nil +} + +func (x *TokenCacheKey) GetAudiences() []string { + if x != nil { + return x.Audiences + } + return nil +} + +func (x *TokenCacheKey) GetScopes() []string { + if x != nil { + return x.Scopes + } + return nil +} + +func (x *TokenCacheKey) GetRequestedTokenType() string { + if x != nil { + return x.RequestedTokenType + } + return "" +} + +func (x *TokenCacheKey) GetAdditionalParameters() []*TokenCacheKey_FormEntry { + if x != nil { + return x.AdditionalParameters + } + return nil +} + +type TokenCacheKey_FormEntry struct { + state protoimpl.MessageState `protogen:"open.v1"` + Key string `protobuf:"bytes,1,opt,name=key,proto3" json:"key,omitempty"` + Value string `protobuf:"bytes,2,opt,name=value,proto3" json:"value,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache +} + +func (x *TokenCacheKey_FormEntry) Reset() { + *x = TokenCacheKey_FormEntry{} + mi := &file_internal_proto_tokenexchangepb_cachekey_proto_msgTypes[1] + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + ms.StoreMessageInfo(mi) +} + +func (x *TokenCacheKey_FormEntry) String() string { + return protoimpl.X.MessageStringOf(x) +} + +func (*TokenCacheKey_FormEntry) ProtoMessage() {} + +func (x *TokenCacheKey_FormEntry) ProtoReflect() protoreflect.Message { + mi := &file_internal_proto_tokenexchangepb_cachekey_proto_msgTypes[1] + if x != nil { + ms := protoimpl.X.MessageStateOf(protoimpl.Pointer(x)) + if ms.LoadMessageInfo() == nil { + ms.StoreMessageInfo(mi) + } + return ms + } + return mi.MessageOf(x) +} + +// Deprecated: Use TokenCacheKey_FormEntry.ProtoReflect.Descriptor instead. +func (*TokenCacheKey_FormEntry) Descriptor() ([]byte, []int) { + return file_internal_proto_tokenexchangepb_cachekey_proto_rawDescGZIP(), []int{0, 0} +} + +func (x *TokenCacheKey_FormEntry) GetKey() string { + if x != nil { + return x.Key + } + return "" +} + +func (x *TokenCacheKey_FormEntry) GetValue() string { + if x != nil { + return x.Value + } + return "" +} + +var File_internal_proto_tokenexchangepb_cachekey_proto protoreflect.FileDescriptor + +const file_internal_proto_tokenexchangepb_cachekey_proto_rawDesc = "" + + "\n" + + "-internal/proto/tokenexchangepb/cachekey.proto\x12\rtokenexchange\"\xf8\x03\n" + + "\rTokenCacheKey\x12\x1a\n" + + "\batespace\x18\x01 \x01(\tR\batespace\x12\x1d\n" + + "\n" + + "actor_name\x18\x02 \x01(\tR\tactorName\x12\x1b\n" + + "\ttoken_url\x18\x03 \x01(\tR\btokenUrl\x122\n" + + "\x15subject_jwt_audiences\x18\x04 \x03(\tR\x13subjectJwtAudiences\x12C\n" + + "\x1esubject_jwt_expiration_seconds\x18\x05 \x01(\x03R\x1bsubjectJwtExpirationSeconds\x12\x1c\n" + + "\tresources\x18\x06 \x03(\tR\tresources\x12\x1c\n" + + "\taudiences\x18\a \x03(\tR\taudiences\x12\x16\n" + + "\x06scopes\x18\b \x03(\tR\x06scopes\x120\n" + + "\x14requested_token_type\x18\t \x01(\tR\x12requestedTokenType\x12[\n" + + "\x15additional_parameters\x18\n" + + " \x03(\v2&.tokenexchange.TokenCacheKey.FormEntryR\x14additionalParameters\x1a3\n" + + "\tFormEntry\x12\x10\n" + + "\x03key\x18\x01 \x01(\tR\x03key\x12\x14\n" + + "\x05value\x18\x02 \x01(\tR\x05valueB5Z3go.ate.dev/substrate/internal/proto/tokenexchangepbb\x06proto3" + +var ( + file_internal_proto_tokenexchangepb_cachekey_proto_rawDescOnce sync.Once + file_internal_proto_tokenexchangepb_cachekey_proto_rawDescData []byte +) + +func file_internal_proto_tokenexchangepb_cachekey_proto_rawDescGZIP() []byte { + file_internal_proto_tokenexchangepb_cachekey_proto_rawDescOnce.Do(func() { + file_internal_proto_tokenexchangepb_cachekey_proto_rawDescData = protoimpl.X.CompressGZIP(unsafe.Slice(unsafe.StringData(file_internal_proto_tokenexchangepb_cachekey_proto_rawDesc), len(file_internal_proto_tokenexchangepb_cachekey_proto_rawDesc))) + }) + return file_internal_proto_tokenexchangepb_cachekey_proto_rawDescData +} + +var file_internal_proto_tokenexchangepb_cachekey_proto_msgTypes = make([]protoimpl.MessageInfo, 2) +var file_internal_proto_tokenexchangepb_cachekey_proto_goTypes = []any{ + (*TokenCacheKey)(nil), // 0: tokenexchange.TokenCacheKey + (*TokenCacheKey_FormEntry)(nil), // 1: tokenexchange.TokenCacheKey.FormEntry +} +var file_internal_proto_tokenexchangepb_cachekey_proto_depIdxs = []int32{ + 1, // 0: tokenexchange.TokenCacheKey.additional_parameters:type_name -> tokenexchange.TokenCacheKey.FormEntry + 1, // [1:1] is the sub-list for method output_type + 1, // [1:1] is the sub-list for method input_type + 1, // [1:1] is the sub-list for extension type_name + 1, // [1:1] is the sub-list for extension extendee + 0, // [0:1] is the sub-list for field type_name +} + +func init() { file_internal_proto_tokenexchangepb_cachekey_proto_init() } +func file_internal_proto_tokenexchangepb_cachekey_proto_init() { + if File_internal_proto_tokenexchangepb_cachekey_proto != nil { + return + } + type x struct{} + out := protoimpl.TypeBuilder{ + File: protoimpl.DescBuilder{ + GoPackagePath: reflect.TypeOf(x{}).PkgPath(), + RawDescriptor: unsafe.Slice(unsafe.StringData(file_internal_proto_tokenexchangepb_cachekey_proto_rawDesc), len(file_internal_proto_tokenexchangepb_cachekey_proto_rawDesc)), + NumEnums: 0, + NumMessages: 2, + NumExtensions: 0, + NumServices: 0, + }, + GoTypes: file_internal_proto_tokenexchangepb_cachekey_proto_goTypes, + DependencyIndexes: file_internal_proto_tokenexchangepb_cachekey_proto_depIdxs, + MessageInfos: file_internal_proto_tokenexchangepb_cachekey_proto_msgTypes, + }.Build() + File_internal_proto_tokenexchangepb_cachekey_proto = out.File + file_internal_proto_tokenexchangepb_cachekey_proto_goTypes = nil + file_internal_proto_tokenexchangepb_cachekey_proto_depIdxs = nil +} diff --git a/internal/proto/tokenexchangepb/cachekey.proto b/internal/proto/tokenexchangepb/cachekey.proto new file mode 100644 index 0000000000..a7640858e2 --- /dev/null +++ b/internal/proto/tokenexchangepb/cachekey.proto @@ -0,0 +1,39 @@ +// Copyright 2026 The Agent Substrate 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. + +syntax = "proto3"; + +package tokenexchange; + +option go_package = "go.ate.dev/substrate/internal/proto/tokenexchangepb"; + +// TokenCacheKey is the canonical in-process cache key input for the egress +// gateway's RFC 8693 token exchange broker. +message TokenCacheKey { + message FormEntry { + string key = 1; + string value = 2; + } + + string atespace = 1; + string actor_name = 2; + string token_url = 3; + repeated string subject_jwt_audiences = 4; + int64 subject_jwt_expiration_seconds = 5; + repeated string resources = 6; + repeated string audiences = 7; + repeated string scopes = 8; + string requested_token_type = 9; + repeated FormEntry additional_parameters = 10; +} diff --git a/internal/protoredact/protoredact_test.go b/internal/protoredact/protoredact_test.go index 3f61efe3c4..2f13788cea 100644 --- a/internal/protoredact/protoredact_test.go +++ b/internal/protoredact/protoredact_test.go @@ -29,9 +29,11 @@ import ( ateenvv1alpha "go.ate.dev/substrate/internal/proto/ateenv/v1alpha" "go.ate.dev/substrate/internal/proto/ateletpb" "go.ate.dev/substrate/internal/proto/ateworkerpb" + "go.ate.dev/substrate/internal/proto/clientsideboundarypb" "go.ate.dev/substrate/internal/proto/glutton" "go.ate.dev/substrate/internal/proto/grpcechopb" "go.ate.dev/substrate/internal/proto/objectstoreexchangepb" + "go.ate.dev/substrate/internal/proto/tokenexchangepb" "go.ate.dev/substrate/internal/protoredact" "go.ate.dev/substrate/pkg/proto/ateconfigpb" "google.golang.org/protobuf/proto" @@ -364,11 +366,13 @@ var ourProtoFiles = []protoreflect.FileDescriptor{ ateletpb.File_internal_proto_ateletpb_atelet_proto, ateworkerpb.File_internal_proto_ateworkerpb_ateworker_proto, ateconfigpb.File_pkg_proto_ateconfigpb_apiconfig_proto, + clientsideboundarypb.File_internal_proto_clientsideboundarypb_boundary_proto, credprovider.File_api_credprovider_v1_credprovider_proto, glutton.File_internal_proto_glutton_glutton_proto, grpcechopb.File_internal_proto_grpcechopb_grpcecho_proto, objectstoreexchangepb.File_internal_proto_objectstoreexchangepb_exchange_proto, objectstore.File_api_objectstore_v1_objectstore_proto, + tokenexchangepb.File_internal_proto_tokenexchangepb_cachekey_proto, } // forEachField calls fn for every field of every message in ourProtoFiles, @@ -441,8 +445,16 @@ func TestSecretLikeFieldsAreLabeled(t *testing.T) { notSecret := map[string]string{ "page_token": "opaque list cursor", "next_page_token": "opaque list cursor", - "substrate.ateapi.v1.CredentialHeader.credential_uri": "ate-secret:// reference to a credential, not the value", - "substrate.ateapi.v1.CredentialHeader.actor_jwt": "ActorJwtSource: audiences and lifetime for minting, not a token", + "substrate.ateapi.v1.CredentialHeader.credential_uri": "ate-secret:// reference to a credential, not the value", + "substrate.ateapi.v1.CredentialHeader.actor_jwt": "ActorJwtSource: audiences and lifetime for minting, not a token", + "substrate.ateapi.v1.CredentialHeader.token_exchange": "TokenExchangeSource: endpoint, subject JWT config, and exchange parameters, not a token", + "substrate.ateapi.v1.TokenExchangeSource.token_url": "endpoint URL without userinfo or query, so it holds no credential", + "substrate.ateapi.v1.TokenExchangeSource.subject_actor_jwt": "ActorJwtSource: audiences and lifetime for minting the subject token, not a token", + "substrate.ateapi.v1.TokenExchangeSource.requested_token_type": "RFC 8693 token type identifier, not a token", + "tokenexchange.TokenCacheKey.token_url": "endpoint URL without userinfo or query, so it holds no credential", + "tokenexchange.TokenCacheKey.subject_jwt_audiences": "audience strings for minting the subject token, not a token", + "tokenexchange.TokenCacheKey.subject_jwt_expiration_seconds": "lifetime in seconds for minting the subject token, not a token", + "tokenexchange.TokenCacheKey.requested_token_type": "RFC 8693 token type identifier, not a token", } forEachField(func(fd protoreflect.FieldDescriptor) { if !secretLikeName.MatchString(string(fd.Name())) || isDebugRedact(fd) { diff --git a/internal/resources/resourceref.go b/internal/resources/resourceref.go index 6e449eb38c..d66777eab1 100644 --- a/internal/resources/resourceref.go +++ b/internal/resources/resourceref.go @@ -107,3 +107,11 @@ func TagRefFromTag(t *ateapi.Tag) TagRef { Name: t.GetMetadata().GetName(), } } + +// ExternalVolumeRef identifies an ExternalVolume by the (atespace, name). +type ExternalVolumeRef = ResourceRef[*ateapi.ExternalVolume] + +// ExternalVolumeRefFromObjectRef converts an ObjectRef to an ExternalVolumeRef. +func ExternalVolumeRefFromObjectRef(ref *ateapi.ObjectRef) ExternalVolumeRef { + return resourceRefFromObjectRef[*ateapi.ExternalVolume](ref) +} diff --git a/internal/resources/resourceref_test.go b/internal/resources/resourceref_test.go index 9303d68d42..6375ea45a5 100644 --- a/internal/resources/resourceref_test.go +++ b/internal/resources/resourceref_test.go @@ -27,9 +27,10 @@ import ( // is expected. func TestRefAliasesAreDistinctTypes(t *testing.T) { types := map[string]reflect.Type{ - "ActorRef": reflect.TypeFor[ActorRef](), - "ActorTemplateRef": reflect.TypeFor[ActorTemplateRef](), - "TagRef": reflect.TypeFor[TagRef](), + "ActorRef": reflect.TypeFor[ActorRef](), + "ActorTemplateRef": reflect.TypeFor[ActorTemplateRef](), + "TagRef": reflect.TypeFor[TagRef](), + "ExternalVolumeRef": reflect.TypeFor[ExternalVolumeRef](), } seen := make(map[reflect.Type]string) for name, typ := range types { @@ -59,6 +60,11 @@ func TestResourceRefLogValue(t *testing.T) { val: ActorTemplateRef{}.LogValue(), want: map[string]string{"type": "*ateapi.ActorTemplate", "atespace": "", "name": ""}, }, + { + name: "zero external volume ref", + val: ExternalVolumeRef{}.LogValue(), + want: map[string]string{"type": "*ateapi.ExternalVolume", "atespace": "", "name": ""}, + }, { name: "populated actor ref", val: ActorRef{Atespace: "team-a", Name: "act-1"}.LogValue(), @@ -215,3 +221,22 @@ func TestTagRefFromTag(t *testing.T) { }) } } + +func TestExternalVolumeRefString(t *testing.T) { + got := ExternalVolumeRef{Atespace: "team-a", Name: "vol-1"}.String() + if want := "team-a/vol-1"; got != want { + t.Errorf("String() = %q, want %q", got, want) + } +} + +func TestExternalVolumeRefObjectRefRoundTrip(t *testing.T) { + volumeRef := ExternalVolumeRef{Atespace: "team-a", Name: "vol-1"} + + obj := volumeRef.ToObjectRef() + if obj.GetAtespace() != "team-a" || obj.GetName() != "vol-1" { + t.Errorf("ToObjectRef() = (%q, %q), want (team-a, vol-1)", obj.GetAtespace(), obj.GetName()) + } + if got := ExternalVolumeRefFromObjectRef(obj); got != volumeRef { + t.Errorf("round-trip = %+v, want %+v", got, volumeRef) + } +} diff --git a/internal/resources/validate.go b/internal/resources/validate.go index cff8d9ecc3..f870bedb91 100644 --- a/internal/resources/validate.go +++ b/internal/resources/validate.go @@ -40,7 +40,6 @@ import ( "google.golang.org/protobuf/proto" "k8s.io/apimachinery/pkg/api/validate/content" "k8s.io/apimachinery/pkg/util/sets" - "k8s.io/apimachinery/pkg/util/validation" "k8s.io/apimachinery/pkg/util/validation/field" ) @@ -131,6 +130,10 @@ func DeepEqual[T any](a, b T) bool { return reflect.DeepEqual(a, b) } +// maxResourceNameLength is the longest resource name ValidateResourceName +// accepts. +const maxResourceNameLength = content.DNS1123LabelMaxLength + // ValidateResourceName checks that a string conforms to Agent Substrate's // rules for a resource name, which is a subset of the rules for an RFC-1123 // DNS label. This does not check for zero-length strings, which callers may @@ -269,6 +272,18 @@ func ValidateSandboxAssetsDir(actorUID, dir string, fldPath *field.Path) field.E // into another name. var snapshotLocationSegmentRE = regexp.MustCompile(`^[A-Za-z0-9_-]+$`) +// MaxGCSResourceName is the longest object prefix, as GCSResourceName writes +// it, that GCS accepts in the access boundary condition of a locally minted +// token, in bytes. GCS refuses a token with a longer one with a 401 that does +// not say why. We measured the limit. It is not documented. +const MaxGCSResourceName = 512 + +// GCSResourceName is the prefix an access boundary condition matches the +// objects under path in bucket by. path must end in "/". +func GCSResourceName(bucket, path string) string { + return "projects/_/buckets/" + bucket + "/objects/" + path +} + // ValidateSnapshotLocation checks ate-api-server's --snapshot-location, an // ActorTemplate's snapshotConfig.storageLocation on create, and the location a // tag is created under. The location must be a URI with a bucket, so a bad @@ -304,6 +319,33 @@ func ValidateSnapshotLocation(location string) error { return nil } +// ValidateGCSLocationLength checks that every actor's prefix under a gs:// +// location fits within MaxGCSResourceName, so its tokens can be minted +// locally. Under a longer location, the plugin gets a token from STS per +// actor instead. Other schemes pass. +func ValidateGCSLocationLength(location string) error { + // URL schemes are case-insensitive, and the prefixes built from a GS:// + // location are gs:// ones. + if !strings.HasPrefix(strings.ToLower(location), "gs://") { + return nil + } + // The longest prefix under the location is an actor's whose atespace and + // UID are as long as a resource name can be. + longestName := strings.Repeat("a", maxResourceNameLength) + longest, err := ActorSnapshotOwner(longestName, longestName).Prefix(location) + if err != nil { + return err + } + lu, err := url.Parse(longest.String()) + if err != nil { + return err + } + if name := GCSResourceName(lu.Host, strings.TrimPrefix(lu.Path, "/")+"/"); len(name) > MaxGCSResourceName { + return fmt.Errorf("the longest actor prefix under snapshot location %q is %d bytes, more than the %d GCS accepts in a locally minted token", location, len(name), MaxGCSResourceName) + } + return nil +} + // parseStorageURI checks the shape every snapshot location, owner prefix and // snapshot URI shares: a host (the bucket) and a path that appending names to // cannot redirect. It does not check the scheme, which may be empty @@ -544,37 +586,6 @@ func ValidateNestedMountPathsAt(paths []string, at func(i int) *field.Path) fiel return errs } -// httpGetPathRE constrains wakeup probe paths to RFC 3986 path-segment -// characters only, with well-formed percent-escapes, and no query string -// or fragment. -var httpGetPathRE = regexp.MustCompile(`^/([A-Za-z0-9\-._~!$&'()*+,;=:@/]|%[0-9A-Fa-f]{2})*$`) - -// ValidateHTTPGetPath checks a wakeup probe's HTTP path. -func ValidateHTTPGetPath(fldPath *field.Path, p string) field.ErrorList { - if p == "" { - return nil - } - if !httpGetPathRE.MatchString(p) { - return field.ErrorList{field.Invalid(fldPath, p, "must be a URL path starting with '/', using only RFC 3986 path-segment characters, without query or fragment")} - } - return nil -} - -// envVarNameRE constrains env var names to any printable ASCII character -// except '='. -var envVarNameRE = regexp.MustCompile(`^[ -<>-~]+$`) - -// ValidateEnvVarName checks an environment variable name. -func ValidateEnvVarName(fldPath *field.Path, name string) field.ErrorList { - if name == "" { - return nil - } - if !envVarNameRE.MatchString(name) { - return field.ErrorList{field.Invalid(fldPath, name, "may contain any printable ASCII character except '='")} - } - return nil -} - // ValidateProjectedPath applies volumepath.ValidateProjected to a file path // projected into a system-info volume. atelet re-checks it before writing to // the host. @@ -588,34 +599,6 @@ func ValidateProjectedPath(fldPath *field.Path, p string) field.ErrorList { return nil } -// ValidateStorageVolumeID rejects control characters (U+0000-U+0008, U+000B, -// U+000C, U+000E-U+001F, U+007F-U+009F) in an external volume's storage ID. -func ValidateStorageVolumeID(fldPath *field.Path, id string) field.ErrorList { - for _, r := range id { - if (r >= 0x0000 && r <= 0x0008) || - r == 0x000B || - r == 0x000C || - (r >= 0x000E && r <= 0x001F) || - (r >= 0x007F && r <= 0x009F) { - return field.ErrorList{field.Invalid(fldPath, id, "must not contain control characters (U+0000-U+0008, U+000B, U+000C, U+000E-U+001F, U+007F-U+009F)")} - } - } - return nil -} - -// ValidateVolumeType allows an optional "substrate.io/" prefix, followed by a -// valid DNS-1123 subdomain. -func ValidateVolumeType(fldPath *field.Path, volumeType string) field.ErrorList { - if volumeType == "" { - return nil - } - var errs field.ErrorList - for _, msg := range validation.IsDNS1123Subdomain(strings.TrimPrefix(volumeType, "substrate.io/")) { - errs = append(errs, field.Invalid(fldPath, volumeType, msg)) - } - return errs -} - // csiMapMaxBytes bounds a map a CSI driver produced. The CSI spec caps // map fields at 4 KiB; this allows ten times that so a future // revision of the limit does not turn compliant drivers away. It is a diff --git a/internal/resources/validate_test.go b/internal/resources/validate_test.go index f28777dfb9..ad5896c128 100644 --- a/internal/resources/validate_test.go +++ b/internal/resources/validate_test.go @@ -116,7 +116,8 @@ func TestIsValidResourceName(t *testing.T) { {"valid start number", "1actor", true}, {"invalid end hyphen", "actor-", false}, {"invalid special chars", "actor@1", false}, - {"invalid length", strings.Repeat("a", 64), false}, + {"longest", strings.Repeat("a", maxResourceNameLength), true}, + {"invalid length", strings.Repeat("a", maxResourceNameLength+1), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -204,6 +205,9 @@ func TestValidateSnapshotLocation(t *testing.T) { {"escaped atespaces", "gs://snaps/root/%61tespaces/team-a", true}, {"escaped separators", "gs://snaps/root%2Fatespaces%2Fteam-a", true}, {"atespaces as part of a segment", "gs://snaps/root/my-atespaces/atespaces_old", false}, + + // Too long to mint locally, which ValidateGCSLocationLength checks. + {"long gs path", "gs://bucket/" + strings.Repeat("a", 333), false}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { @@ -220,6 +224,27 @@ func TestValidateSnapshotLocation(t *testing.T) { } } +func TestValidateGCSLocationLength(t *testing.T) { + for _, tt := range []struct { + name string + location string + wantErr bool + }{ + {"longest gs path", "gs://bucket/" + strings.Repeat("a", 332), false}, + {"gs path one byte too long", "gs://bucket/" + strings.Repeat("a", 333), true}, + {"gs path too long with a trailing slash", "gs://bucket/" + strings.Repeat("a", 333) + "/", true}, + {"gs bucket alone too long", "gs://" + strings.Repeat("b", 340), true}, + {"upper-case GS path too long", "GS://bucket/" + strings.Repeat("a", 333), true}, + {"long s3 path", "s3://bucket/" + strings.Repeat("a", 333), false}, + } { + t.Run(tt.name, func(t *testing.T) { + if err := ValidateGCSLocationLength(tt.location); (err != nil) != tt.wantErr { + t.Errorf("ValidateGCSLocationLength(%q) err = %v, wantErr %v", tt.location, err, tt.wantErr) + } + }) + } +} + func TestValidateIP(t *testing.T) { tests := []struct { name string @@ -512,29 +537,6 @@ func TestValidateMountPath(t *testing.T) { }) } -func TestValidateHTTPGetPath(t *testing.T) { - runStringRule(t, ValidateHTTPGetPath, []stringRuleCase{ - {"empty is left to tags", "", false}, - {"simple", "/healthz", false}, - {"percent escape", "/a%20b", false}, - {"no leading slash", "healthz", true}, - {"query", "/healthz?x=1", true}, - {"fragment", "/healthz#x", true}, - {"bad percent escape", "/a%2", true}, - }) -} - -func TestValidateEnvVarName(t *testing.T) { - runStringRule(t, ValidateEnvVarName, []stringRuleCase{ - {"empty is left to tags", "", false}, - {"conventional", "HOME_DIR", false}, - {"printable punctuation", "a.b-c", false}, - {"equals sign", "A=B", true}, - {"control character", "A\tB", true}, - {"non-ASCII", "é", true}, - }) -} - func TestValidateProjectedPath(t *testing.T) { runStringRule(t, ValidateProjectedPath, []stringRuleCase{ {"empty is left to tags", "", false}, @@ -544,27 +546,6 @@ func TestValidateProjectedPath(t *testing.T) { }) } -func TestValidateStorageVolumeID(t *testing.T) { - runStringRule(t, ValidateStorageVolumeID, []stringRuleCase{ - {"empty", "", false}, - {"plain", "projects/p/disks/d-1", false}, - {"newline is allowed", "a\nb", false}, - {"NUL", "a\x00b", true}, - {"DEL", "a\x7fb", true}, - {"C1 control", "a\u0085b", true}, - }) -} - -func TestValidateVolumeType(t *testing.T) { - runStringRule(t, ValidateVolumeType, []stringRuleCase{ - {"empty", "", false}, - {"dns subdomain", "pd.csi.storage.gke.io", false}, - {"substrate prefix", "substrate.io/gcs", false}, - {"uppercase", "PD", true}, - {"other prefix", "example.io/gcs", true}, - }) -} - func TestValidateCapabilities(t *testing.T) { tests := []struct { name string diff --git a/internal/serverboot/envflags.go b/internal/serverboot/envflags.go new file mode 100644 index 0000000000..8bfe76fa13 --- /dev/null +++ b/internal/serverboot/envflags.go @@ -0,0 +1,51 @@ +// Copyright 2026 The Agent Substrate 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 serverboot + +import ( + "fmt" + "os" + + "github.com/spf13/pflag" +) + +// EnvFlag names a flag and the environment variable that sets it when the +// command line doesn't. +type EnvFlag struct { + Flag string + Env string +} + +// ApplyEnvFlags sets each flag the command line left unset from its +// environment variable, parsed as the flag's type. It skips unset and empty +// variables, and marks each flag it sets as changed. +func ApplyEnvFlags(fs *pflag.FlagSet, bindings []EnvFlag) error { + for _, b := range bindings { + if fs.Lookup(b.Flag) == nil { + return fmt.Errorf("unknown flag %q for %s", b.Flag, b.Env) + } + if fs.Changed(b.Flag) { + continue + } + val, ok := os.LookupEnv(b.Env) + if !ok || val == "" { + continue + } + if err := fs.Set(b.Flag, val); err != nil { + return fmt.Errorf("%s=%q: %w", b.Env, val, err) + } + } + return nil +} diff --git a/internal/serverboot/envflags_test.go b/internal/serverboot/envflags_test.go new file mode 100644 index 0000000000..ab692a79d9 --- /dev/null +++ b/internal/serverboot/envflags_test.go @@ -0,0 +1,177 @@ +// Copyright 2026 The Agent Substrate 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 serverboot + +import ( + "os" + "strings" + "testing" + + "github.com/spf13/pflag" +) + +func TestApplyEnvFlags(t *testing.T) { + const ( + envStr = "SERVERBOOT_TEST_STR" + envInt = "SERVERBOOT_TEST_INT" + envBool = "SERVERBOOT_TEST_BOOL" + ) + + newFlags := func() (*pflag.FlagSet, *string, *int, *bool) { + fs := pflag.NewFlagSet("test", pflag.ContinueOnError) + s := fs.String("str-flag", "default", "") + n := fs.Int("int-flag", 42, "") + b := fs.Bool("bool-flag", true, "") + return fs, s, n, b + } + + unset := func(t *testing.T, keys ...string) { + t.Helper() + for _, k := range keys { + t.Setenv(k, "") + if err := os.Unsetenv(k); err != nil { + t.Fatalf("Unsetenv(%s): %v", k, err) + } + } + } + + t.Run("populates string int and bool flags from env", func(t *testing.T) { + unset(t, envStr, envInt, envBool) + t.Setenv(envStr, ":6060") + t.Setenv(envInt, "10") + t.Setenv(envBool, "false") + + fs, s, n, b := newFlags() + bindings := []EnvFlag{ + {Flag: "str-flag", Env: envStr}, + {Flag: "int-flag", Env: envInt}, + {Flag: "bool-flag", Env: envBool}, + } + if err := ApplyEnvFlags(fs, bindings); err != nil { + t.Fatalf("ApplyEnvFlags() error = %v", err) + } + if *s != ":6060" || *n != 10 || *b { + t.Errorf("got (%q, %d, %v), want (%q, %d, %v)", *s, *n, *b, ":6060", 10, false) + } + for _, name := range []string{"str-flag", "int-flag", "bool-flag"} { + if !fs.Changed(name) { + t.Errorf("flag %q Changed = false, want true", name) + } + } + // Calling a second time is idempotent. + t.Setenv(envStr, ":7070") + if err := ApplyEnvFlags(fs, bindings); err != nil { + t.Fatalf("second ApplyEnvFlags() error = %v", err) + } + if *s != ":6060" { + t.Errorf("second ApplyEnvFlags() overwrote *s to %q, want %q", *s, ":6060") + } + }) + + t.Run("explicit CLI flag wins over valid or invalid env including zero and false", func(t *testing.T) { + unset(t, envStr, envInt, envBool) + t.Setenv(envStr, ":6060") + t.Setenv(envInt, "abc") + t.Setenv(envBool, "true") + + fs, s, n, b := newFlags() + if err := fs.Parse([]string{"--str-flag=cli", "--int-flag=0", "--bool-flag=false"}); err != nil { + t.Fatalf("Parse(): %v", err) + } + bindings := []EnvFlag{ + {Flag: "str-flag", Env: envStr}, + {Flag: "int-flag", Env: envInt}, + {Flag: "bool-flag", Env: envBool}, + } + if err := ApplyEnvFlags(fs, bindings); err != nil { + t.Fatalf("ApplyEnvFlags() error = %v", err) + } + if *s != "cli" || *n != 0 || *b { + t.Errorf("got (%q, %d, %v), want (%q, %d, %v)", *s, *n, *b, "cli", 0, false) + } + }) + + t.Run("unset and empty env leave defaults untouched", func(t *testing.T) { + unset(t, envStr, envInt, envBool) + t.Setenv(envStr, "") + t.Setenv(envInt, "") + + fs, s, n, b := newFlags() + bindings := []EnvFlag{ + {Flag: "str-flag", Env: envStr}, + {Flag: "int-flag", Env: envInt}, + {Flag: "bool-flag", Env: envBool}, + } + if err := ApplyEnvFlags(fs, bindings); err != nil { + t.Fatalf("ApplyEnvFlags() error = %v", err) + } + if *s != "default" || *n != 42 || !*b { + t.Errorf("got (%q, %d, %v), want (%q, %d, %v)", *s, *n, *b, "default", 42, true) + } + for _, name := range []string{"str-flag", "int-flag", "bool-flag"} { + if fs.Changed(name) { + t.Errorf("flag %q Changed = true, want false", name) + } + } + }) + + t.Run("zero int env succeeds", func(t *testing.T) { + unset(t, envInt) + t.Setenv(envInt, "0") + + fs, _, n, _ := newFlags() + if err := ApplyEnvFlags(fs, []EnvFlag{{Flag: "int-flag", Env: envInt}}); err != nil { + t.Fatalf("ApplyEnvFlags() error = %v", err) + } + if *n != 0 { + t.Errorf("*n = %d, want 0", *n) + } + }) + + t.Run("unknown flag fails even when env is unset", func(t *testing.T) { + unset(t, "SERVERBOOT_TEST_MISSING") + + fs, _, _, _ := newFlags() + err := ApplyEnvFlags(fs, []EnvFlag{{Flag: "no-such-flag", Env: "SERVERBOOT_TEST_MISSING"}}) + if err == nil || !strings.Contains(err.Error(), `unknown flag "no-such-flag"`) { + t.Fatalf("ApplyEnvFlags() error = %v, want unknown flag error", err) + } + }) + + t.Run("invalid int and bool env return error naming env and value in slice order", func(t *testing.T) { + unset(t, envInt, envBool) + t.Setenv(envInt, "bad") + t.Setenv(envBool, "badbool") + + fs, _, _, _ := newFlags() + err := ApplyEnvFlags(fs, []EnvFlag{ + {Flag: "int-flag", Env: envInt}, + {Flag: "bool-flag", Env: envBool}, + }) + if err == nil || !strings.Contains(err.Error(), envInt+`="bad"`) { + t.Fatalf("ApplyEnvFlags() error = %v, want first failing binding %s=\"bad\"", err, envInt) + } + + t.Setenv(envInt, "1") + fs2, _, _, _ := newFlags() + err2 := ApplyEnvFlags(fs2, []EnvFlag{ + {Flag: "int-flag", Env: envInt}, + {Flag: "bool-flag", Env: envBool}, + }) + if err2 == nil || !strings.Contains(err2.Error(), envBool+`="badbool"`) { + t.Fatalf("ApplyEnvFlags() error = %v, want %s=\"badbool\"", err2, envBool) + } + }) +} diff --git a/internal/serverboot/logging.go b/internal/serverboot/logging.go index 13d87fe852..fb80a5a5ca 100644 --- a/internal/serverboot/logging.go +++ b/internal/serverboot/logging.go @@ -19,8 +19,8 @@ import ( "fmt" "log/slog" + "go.opentelemetry.io/otel" "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc" - "go.opentelemetry.io/otel/log/global" sdklog "go.opentelemetry.io/otel/sdk/log" "google.golang.org/grpc" @@ -90,7 +90,7 @@ func InitLogging(ctx context.Context, opts LoggingOptions) (*sdklog.LoggerProvid if err != nil { return nil, err } - global.SetLoggerProvider(lp) + otel.SetLoggerProvider(lp) slog.InfoContext(ctx, "Logging initialized", slog.String("exporter", opts.Exporter.String())) return lp, nil } diff --git a/internal/serverboot/logging_test.go b/internal/serverboot/logging_test.go index 5678da246b..bdff39f399 100644 --- a/internal/serverboot/logging_test.go +++ b/internal/serverboot/logging_test.go @@ -21,8 +21,8 @@ import ( "strings" "testing" + "go.opentelemetry.io/otel" otellog "go.opentelemetry.io/otel/log" - "go.opentelemetry.io/otel/log/global" sdklog "go.opentelemetry.io/otel/sdk/log" "go.opentelemetry.io/otel/sdk/resource" "google.golang.org/grpc" @@ -58,10 +58,10 @@ func TestResolveLogsExporter(t *testing.T) { } func TestInitLoggingDisabled(t *testing.T) { - // global.SetLoggerProvider has no undo, so assert on the provider this + // otel.SetLoggerProvider has no undo, so assert on the provider this // returns rather than on the global. A nil provider is what proves // InitLogging left the global alone. - before := global.GetLoggerProvider() + before := otel.GetLoggerProvider() lp, err := InitLogging(context.Background(), LoggingOptions{ ServiceName: "test", @@ -73,7 +73,7 @@ func TestInitLoggingDisabled(t *testing.T) { if lp != nil { t.Errorf("InitLogging() with the exporter disabled = %v, want nil", lp) } - if got := global.GetLoggerProvider(); got != before { + if got := otel.GetLoggerProvider(); got != before { t.Errorf("InitLogging() with the exporter disabled replaced the global provider") } } @@ -209,7 +209,7 @@ func TestInitLoggingOTLPAndConsole(t *testing.T) { if lp == nil { t.Fatal("InitLogging() with otlp,console returned no provider") } - if global.GetLoggerProvider() != lp { + if otel.GetLoggerProvider() != lp { t.Error("InitLogging() with otlp,console did not install its provider as the global") } t.Cleanup(func() { diff --git a/internal/serverboot/namespace.go b/internal/serverboot/namespace.go new file mode 100644 index 0000000000..ab3ba190e5 --- /dev/null +++ b/internal/serverboot/namespace.go @@ -0,0 +1,32 @@ +// Copyright 2026 The Agent Substrate 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 serverboot + +import ( + "fmt" + "strings" + + "k8s.io/apimachinery/pkg/util/validation" +) + +// ValidateWatchNamespace accepts a Kubernetes namespace or the empty all-namespaces scope. +func ValidateWatchNamespace(namespace string) error { + if namespace != "" { + if problems := validation.IsDNS1123Label(namespace); len(problems) > 0 { + return fmt.Errorf("--watch-namespace=%q: %s", namespace, strings.Join(problems, "; ")) + } + } + return nil +} diff --git a/internal/serverboot/namespace_test.go b/internal/serverboot/namespace_test.go new file mode 100644 index 0000000000..5b3c517c44 --- /dev/null +++ b/internal/serverboot/namespace_test.go @@ -0,0 +1,48 @@ +// Copyright 2026 The Agent Substrate 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 serverboot + +import ( + "strings" + "testing" +) + +func TestValidateWatchNamespace(t *testing.T) { + for _, tt := range []struct { + namespace string + valid bool + }{ + {"", true}, + {"agent-workloads", true}, + {"123", true}, + {strings.Repeat("a", 63), true}, + {"Agent_Workloads", false}, + {"agent.workloads", false}, + {"-workloads", false}, + {"workloads-", false}, + {" workloads", false}, + {strings.Repeat("a", 64), false}, + } { + t.Run(tt.namespace, func(t *testing.T) { + err := ValidateWatchNamespace(tt.namespace) + if (err == nil) != tt.valid { + t.Fatalf("ValidateWatchNamespace(%q) = %v, valid = %v", tt.namespace, err, tt.valid) + } + if err != nil && !strings.Contains(err.Error(), "--watch-namespace=") { + t.Fatalf("error does not identify the flag: %v", err) + } + }) + } +} diff --git a/internal/serverboot/pprofserver/pprof.go b/internal/serverboot/pprofserver/pprof.go new file mode 100644 index 0000000000..bca8c0bb1f --- /dev/null +++ b/internal/serverboot/pprofserver/pprof.go @@ -0,0 +1,120 @@ +// Copyright 2026 The Agent Substrate 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 pprofserver serves Go runtime pprof profiles on an explicit HTTP mux. +package pprofserver + +import ( + "context" + "fmt" + "log/slog" + "net/http" + "net/http/pprof" + "os" + "runtime" + "time" + + "github.com/spf13/pflag" + "go.ate.dev/substrate/internal/serverboot" +) + +const httpServerReadHeaderTimeout = 10 * time.Second + +// Config holds pprof server settings populated via RegisterFlags. +type Config struct { + ListenAddr string + MutexFraction int + BlockRate int + + fs *pflag.FlagSet +} + +// RegisterFlags registers --pprof-listen-addr, --pprof-mutex-fraction, and +// --pprof-block-rate on fs and returns the Config they fill once fs is parsed. +func RegisterFlags(fs *pflag.FlagSet) *Config { + cfg := &Config{fs: fs} + fs.StringVar(&cfg.ListenAddr, "pprof-listen-addr", "", + "Listen address for net/http/pprof (e.g. :6060; disabled when empty). "+ + "Defaults to ATE_PPROF_LISTEN_ADDR. "+ + "For benchmarking only: never enable pprof on a cluster that serves real actors.") + fs.IntVar(&cfg.MutexFraction, "pprof-mutex-fraction", 0, + "Mutex contention sampling rate for runtime.SetMutexProfileFraction (0 = disabled). Defaults to ATE_PPROF_MUTEX_FRACTION.") + fs.IntVar(&cfg.BlockRate, "pprof-block-rate", 0, + "Blocking profile rate in nanoseconds for runtime.SetBlockProfileRate (0 = disabled). Defaults to ATE_PPROF_BLOCK_RATE.") + return cfg +} + +// Validate applies ATE_PPROF_* environment defaults for flags not explicitly +// set on the command line and rejects negative rates. +func (c *Config) Validate() error { + if c == nil { + return nil + } + if c.fs != nil { + if err := serverboot.ApplyEnvFlags(c.fs, []serverboot.EnvFlag{ + {Flag: "pprof-listen-addr", Env: "ATE_PPROF_LISTEN_ADDR"}, + {Flag: "pprof-mutex-fraction", Env: "ATE_PPROF_MUTEX_FRACTION"}, + {Flag: "pprof-block-rate", Env: "ATE_PPROF_BLOCK_RATE"}, + }); err != nil { + return err + } + } + if c.MutexFraction < 0 { + return fmt.Errorf("--pprof-mutex-fraction (ATE_PPROF_MUTEX_FRACTION) must not be negative, got %d", c.MutexFraction) + } + if c.BlockRate < 0 { + return fmt.Errorf("--pprof-block-rate (ATE_PPROF_BLOCK_RATE) must not be negative, got %d", c.BlockRate) + } + return nil +} + +func newMux() *http.ServeMux { + mux := http.NewServeMux() + mux.HandleFunc("/debug/pprof/", pprof.Index) + mux.HandleFunc("/debug/pprof/cmdline", pprof.Cmdline) + mux.HandleFunc("/debug/pprof/profile", pprof.Profile) + mux.HandleFunc("/debug/pprof/symbol", pprof.Symbol) + mux.HandleFunc("/debug/pprof/trace", pprof.Trace) + return mux +} + +func newHTTPServer(addr string) *http.Server { + return &http.Server{ + Addr: addr, + Handler: newMux(), + ReadHeaderTimeout: httpServerReadHeaderTimeout, + // WriteTimeout is intentionally 0 so ?seconds=N CPU/allocs/trace requests are not cut off. + } +} + +// Start runs a dedicated pprof HTTP server on cfg.ListenAddr. Blocks until the +// server stops; designed to be go-launched. If cfg is nil or cfg.ListenAddr is +// empty, Start is a no-op. +func Start(ctx context.Context, cfg *Config) { + if cfg == nil || cfg.ListenAddr == "" { + return + } + if cfg.MutexFraction > 0 { + runtime.SetMutexProfileFraction(cfg.MutexFraction) + } + if cfg.BlockRate > 0 { + runtime.SetBlockProfileRate(cfg.BlockRate) + } + + slog.InfoContext(ctx, "Starting pprof HTTP server", slog.String("addr", cfg.ListenAddr)) + if err := newHTTPServer(cfg.ListenAddr).ListenAndServe(); err != nil { + slog.ErrorContext(ctx, "Pprof HTTP server failed", slog.Any("err", err)) + os.Exit(1) + } +} diff --git a/internal/serverboot/pprofserver/pprof_test.go b/internal/serverboot/pprofserver/pprof_test.go new file mode 100644 index 0000000000..d9d980811b --- /dev/null +++ b/internal/serverboot/pprofserver/pprof_test.go @@ -0,0 +1,207 @@ +// Copyright 2026 The Agent Substrate 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 pprofserver + +import ( + "context" + "net/http" + "net/http/httptest" + "runtime" + "strings" + "testing" + + "github.com/google/go-cmp/cmp" + "github.com/google/go-cmp/cmp/cmpopts" + "github.com/spf13/pflag" +) + +func TestRegisterFlags(t *testing.T) { + tests := []struct { + name string + env map[string]string + args []string + want Config + wantErr string + }{ + { + name: "unset env leaves zero config", + want: Config{}, + }, + { + name: "defaults from ATE_PPROF env vars", + env: map[string]string{ + "ATE_PPROF_LISTEN_ADDR": ":6060", + "ATE_PPROF_MUTEX_FRACTION": "10", + "ATE_PPROF_BLOCK_RATE": "1000000", + }, + want: Config{ + ListenAddr: ":6060", + MutexFraction: 10, + BlockRate: 1000000, + }, + }, + { + name: "explicit flags override invalid env vars", + env: map[string]string{ + "ATE_PPROF_LISTEN_ADDR": ":6060", + "ATE_PPROF_MUTEX_FRACTION": "abc", + "ATE_PPROF_BLOCK_RATE": "0", + }, + args: []string{ + "--pprof-listen-addr=:7070", + "--pprof-mutex-fraction=20", + "--pprof-block-rate=500", + }, + want: Config{ + ListenAddr: ":7070", + MutexFraction: 20, + BlockRate: 500, + }, + }, + { + name: "explicit zero mutex fraction disables env var", + env: map[string]string{ + "ATE_PPROF_MUTEX_FRACTION": "10", + }, + args: []string{ + "--pprof-mutex-fraction=0", + }, + want: Config{ + MutexFraction: 0, + }, + }, + { + name: "zero mutex fraction env var disables sampling", + env: map[string]string{ + "ATE_PPROF_MUTEX_FRACTION": "0", + }, + want: Config{ + MutexFraction: 0, + }, + }, + { + name: "negative block rate env var fails validation", + env: map[string]string{ + "ATE_PPROF_BLOCK_RATE": "-5", + }, + wantErr: "--pprof-block-rate (ATE_PPROF_BLOCK_RATE) must not be negative", + }, + { + name: "non-integer mutex fraction env var fails validation", + env: map[string]string{ + "ATE_PPROF_MUTEX_FRACTION": "abc", + }, + wantErr: `ATE_PPROF_MUTEX_FRACTION="abc"`, + }, + { + name: "negative mutex fraction flag fails validation", + args: []string{ + "--pprof-mutex-fraction=-1", + }, + wantErr: "--pprof-mutex-fraction (ATE_PPROF_MUTEX_FRACTION) must not be negative", + }, + { + name: "negative block rate flag fails validation", + args: []string{ + "--pprof-block-rate=-1", + }, + wantErr: "--pprof-block-rate (ATE_PPROF_BLOCK_RATE) must not be negative", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + for _, k := range []string{"ATE_PPROF_LISTEN_ADDR", "ATE_PPROF_MUTEX_FRACTION", "ATE_PPROF_BLOCK_RATE"} { + t.Setenv(k, tt.env[k]) + } + + pf := pflag.NewFlagSet("pflag", pflag.ContinueOnError) + cfg := RegisterFlags(pf) + if err := pf.Parse(tt.args); err != nil { + t.Fatalf("Parse(%v): %v", tt.args, err) + } + err := cfg.Validate() + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("Validate() error = %v, want substring %q", err, tt.wantErr) + } + return + } + if err != nil { + t.Fatalf("Validate() unexpected error: %v", err) + } + if diff := cmp.Diff(tt.want, *cfg, cmpopts.IgnoreUnexported(Config{})); diff != "" { + t.Errorf("Config mismatch (-want +got):\n%s", diff) + } + }) + } + + t.Run("nil config validate is nil", func(t *testing.T) { + var cfg *Config + if err := cfg.Validate(); err != nil { + t.Fatalf("(*Config)(nil).Validate() = %v, want nil", err) + } + }) +} + +func TestStartNoOp(t *testing.T) { + prev := runtime.SetMutexProfileFraction(-1) + t.Cleanup(func() { + runtime.SetMutexProfileFraction(prev) + runtime.SetBlockProfileRate(0) + }) + + Start(context.Background(), nil) + Start(context.Background(), &Config{}) + Start(context.Background(), &Config{MutexFraction: 10, BlockRate: 1000}) + + if got := runtime.SetMutexProfileFraction(-1); got != prev { + t.Errorf("mutex profile fraction = %d, want unchanged %d", got, prev) + } +} + +func TestPprofMuxAndServer(t *testing.T) { + srv := newHTTPServer(":0") + if srv.ReadHeaderTimeout != httpServerReadHeaderTimeout { + t.Errorf("ReadHeaderTimeout = %v, want %v", srv.ReadHeaderTimeout, httpServerReadHeaderTimeout) + } + if srv.WriteTimeout != 0 { + t.Errorf("WriteTimeout = %v, want 0", srv.WriteTimeout) + } + + if srv.Handler == nil || srv.Handler == http.DefaultServeMux { + t.Fatalf("srv.Handler = %v, want dedicated non-nil ServeMux", srv.Handler) + } + + for _, tc := range []struct { + path string + want int + }{ + {path: "/debug/pprof/", want: http.StatusOK}, + {path: "/debug/pprof/cmdline", want: http.StatusOK}, + {path: "/debug/pprof/symbol", want: http.StatusOK}, + {path: "/metrics", want: http.StatusNotFound}, + {path: "/readyz", want: http.StatusNotFound}, + } { + t.Run(tc.path, func(t *testing.T) { + req := httptest.NewRequest(http.MethodGet, tc.path, nil) + rec := httptest.NewRecorder() + srv.Handler.ServeHTTP(rec, req) + if rec.Code != tc.want { + t.Errorf("GET %s = %d, want %d", tc.path, rec.Code, tc.want) + } + }) + } +} diff --git a/internal/snapshotcache/snapshotcache.go b/internal/snapshotcache/snapshotcache.go index 985186c42a..12277eeac3 100644 --- a/internal/snapshotcache/snapshotcache.go +++ b/internal/snapshotcache/snapshotcache.go @@ -123,12 +123,15 @@ func DropFiles(files []File) bool { return dropped } -// StartWriteback opens paths and, in the background, waits for each file's -// dirty pages to be written back or for the file to be unlinked, then calls done -// once. If a path can't be opened it returns the error, holds nothing, and never -// calls done. -func StartWriteback(paths []string, done func()) error { - return startWriteback(kernelPageCache{}, writebackPollDelays, paths, done) +// StartWriteback opens paths and monitors them in the background until their +// dirty pages reach disk or the files are unlinked, then calls done once. +// While flush returns false on kernels with cachestat, dirty pages stay in page +// cache instead of being pushed to disk; flush is re-checked on each poll or +// immediately when its returned channel closes. A nil flush starts disk +// write-out right away. If any path cannot be opened, StartWriteback returns +// the error without calling done. +func StartWriteback(paths []string, flush func() (bool, <-chan struct{}), done func()) error { + return startWriteback(kernelPageCache{}, writebackPollDelays, paths, flush, done) } // pageCache is the page cache state and write-out startWriteback uses @@ -156,7 +159,10 @@ func (kernelPageCache) writeOut(f *os.File) error { return unix.SyncFileRange(int(f.Fd()), 0, 0, unix.SYNC_FILE_RANGE_WAIT_BEFORE|unix.SYNC_FILE_RANGE_WRITE|unix.SYNC_FILE_RANGE_WAIT_AFTER) } -func startWriteback(pc pageCache, delays []time.Duration, paths []string, done func()) error { +func startWriteback(pc pageCache, delays []time.Duration, paths []string, flush func() (bool, <-chan struct{}), done func()) error { + if flush == nil { + flush = func() (bool, <-chan struct{}) { return true, nil } + } var files []*os.File for _, p := range paths { f, err := os.Open(p) @@ -179,18 +185,34 @@ func startWriteback(pc pageCache, delays []time.Duration, paths []string, done f done() } }() - // poll instead of waiting on write-out, so a file unlinked meanwhile is - // closed and its dirty pages dropped instead of written back - for i := 0; pollWritebackFiles(pc, files); i++ { + // Keep dirty pages in cache while memory isn't tight, still closing any + // files that were unlinked or flushed by the kernel in the meantime. + for i := 0; ; i++ { + tight, recheck := flush() + if tight { + break + } + if !pollWritebackFiles(pc, files, false) { + return + } + select { + case <-time.After(delays[min(i, len(delays)-1)]): + case <-recheck: + } + } + // Memory is tight now: push remaining dirty pages to disk, starting from + // the fast initial poll interval. + for i := 0; pollWritebackFiles(pc, files, true); i++ { time.Sleep(delays[min(i, len(delays)-1)]) } }() return nil } -// pollWritebackFiles closes and clears each file that is clean or unlinked, -// starts write-out of any that are still dirty, and reports whether any are left. -func pollWritebackFiles(pc pageCache, files []*os.File) bool { +// pollWritebackFiles closes and clears each file that is clean or unlinked, and +// reports whether any are left. If flush is true, it also starts write-out of +// files that are still dirty. +func pollWritebackFiles(pc pageCache, files []*os.File, flush bool) bool { anyRemaining := false for i, f := range files { if f == nil { @@ -215,7 +237,7 @@ func pollWritebackFiles(pc pageCache, files []*os.File) bool { files[i] = nil continue } - if cstat.Dirty > 0 && !startWriteOut(pc, f) { + if cstat.Dirty > 0 && flush && !startWriteOut(pc, f) { _ = f.Close() files[i] = nil continue diff --git a/internal/snapshotcache/snapshotcache_test.go b/internal/snapshotcache/snapshotcache_test.go index 37bf55dbcd..0ddb9c86c1 100644 --- a/internal/snapshotcache/snapshotcache_test.go +++ b/internal/snapshotcache/snapshotcache_test.go @@ -19,6 +19,7 @@ package snapshotcache import ( "os" "path/filepath" + "sync" "sync/atomic" "testing" "time" @@ -210,7 +211,7 @@ func TestStartWriteback(t *testing.T) { t.Fatal(err) } done := make(chan struct{}) - if err := StartWriteback([]string{p}, func() { close(done) }); err != nil { + if err := StartWriteback([]string{p}, nil, func() { close(done) }); err != nil { t.Fatalf("StartWriteback: %v", err) } select { @@ -258,7 +259,7 @@ func startFakeWriteback(t *testing.T, pc pageCache) (string, <-chan struct{}) { t.Fatal(err) } done := make(chan struct{}) - if err := startWriteback(pc, []time.Duration{time.Millisecond}, []string{p}, func() { close(done) }); err != nil { + if err := startWriteback(pc, []time.Duration{time.Millisecond}, []string{p}, nil, func() { close(done) }); err != nil { t.Fatalf("startWriteback: %v", err) } return p, done @@ -311,6 +312,176 @@ func TestStartWritebackDropsUnlinkedDirtyFile(t *testing.T) { } } +func TestStartWritebackFlushesOnlyWhenAsked(t *testing.T) { + p := filepath.Join(t.TempDir(), "memory-ranges") + if err := os.WriteFile(p, make([]byte, 4<<10), 0o600); err != nil { + t.Fatal(err) + } + started := make(chan struct{}) + pc := &fakePageCache{onWriteOut: sync.OnceFunc(func() { close(started) })} + var tight atomic.Bool + // Pause each poll pass until the test tells it to proceed. + passes, proceed, stop := make(chan struct{}), make(chan struct{}), make(chan struct{}) + flush := func() (bool, <-chan struct{}) { + select { + case passes <- struct{}{}: + case <-stop: + return true, nil + } + select { + case <-proceed: + case <-stop: + return true, nil + } + return tight.Load(), nil + } + done := make(chan struct{}) + if err := startWriteback(pc, []time.Duration{time.Millisecond}, []string{p}, flush, func() { close(done) }); err != nil { + t.Fatalf("startWriteback: %v", err) + } + t.Cleanup(func() { + pc.clean.Store(true) + close(stop) + <-done + }) + receive(t, passes, "no first pass") + proceed <- struct{}{} + // Once pass 2 starts, pass 1 has finished polling without flushing. + receive(t, passes, "no second pass") + if got := pc.writeOuts.Load(); got != 0 { + t.Fatalf("write-out started %d times before flush returned true, want 0", got) + } + tight.Store(true) + proceed <- struct{}{} + receive(t, started, "write-out didn't start once flush returned true") + pc.clean.Store(true) + receive(t, done, "done never ran once the file was clean") +} + +func TestStartWritebackFinishesWithoutFlushing(t *testing.T) { + for _, tc := range []struct { + name string + clear func(t *testing.T, path string, pc *fakePageCache) + }{ + { + name: "unlinked", + clear: func(t *testing.T, path string, _ *fakePageCache) { + t.Helper() + if err := os.Remove(path); err != nil { + t.Fatal(err) + } + }, + }, + { + name: "cleaned by kernel", + clear: func(_ *testing.T, _ string, pc *fakePageCache) { + pc.clean.Store(true) + }, + }, + } { + t.Run(tc.name, func(t *testing.T) { + p := filepath.Join(t.TempDir(), "memory-ranges") + if err := os.WriteFile(p, make([]byte, 4<<10), 0o600); err != nil { + t.Fatal(err) + } + pc := &fakePageCache{} + recheck := make(chan struct{}) + parked := make(chan struct{}, 1) + var calls atomic.Int32 + flush := func() (bool, <-chan struct{}) { + switch calls.Add(1) { + case 1: + return false, recheck + case 2: + // Pass 1 has now polled the dirty file without flushing. + parked <- struct{}{} + return false, recheck + default: + return false, nil + } + } + done := make(chan struct{}) + if err := startWriteback(pc, []time.Duration{0, time.Hour}, []string{p}, flush, func() { close(done) }); err != nil { + t.Fatalf("startWriteback: %v", err) + } + t.Cleanup(func() { + pc.clean.Store(true) + select { + case <-recheck: + default: + close(recheck) + } + }) + receive(t, parked, "flush never reached second pass") + if got := pc.writeOuts.Load(); got != 0 { + t.Fatalf("write-out started %d times while dirty and flush=false, want 0", got) + } + tc.clear(t, p, pc) + close(recheck) + receive(t, done, "done never ran while flush stayed false") + if got := pc.writeOuts.Load(); got != 0 { + t.Errorf("write-out started %d times while flush stayed false, want 0", got) + } + }) + } +} + +func TestStartWritebackAsksAgainOnRecheck(t *testing.T) { + p := filepath.Join(t.TempDir(), "memory-ranges") + if err := os.WriteFile(p, make([]byte, 4<<10), 0o600); err != nil { + t.Fatal(err) + } + // Mark clean on the first write-out so the write-out loop must sleep once + // before seeing clean pages. Using {0, 1h} verifies both that recheck wakes + // the 1h deferred sleep and that write-out resets to delays[0] (0). + pc := &fakePageCache{} + pc.onWriteOut = func() { pc.clean.Store(true) } + recheck := make(chan struct{}) + parked := make(chan struct{}, 1) + woken := make(chan struct{}, 1) + var calls atomic.Int32 + flush := func() (bool, <-chan struct{}) { + switch calls.Add(1) { + case 1: + return false, recheck + case 2: + parked <- struct{}{} + return false, recheck + default: + woken <- struct{}{} + return true, nil + } + } + done := make(chan struct{}) + if err := startWriteback(pc, []time.Duration{0, time.Hour}, []string{p}, flush, func() { close(done) }); err != nil { + t.Fatalf("startWriteback: %v", err) + } + t.Cleanup(func() { + pc.clean.Store(true) + select { + case <-recheck: + default: + close(recheck) + } + }) + receive(t, parked, "flush never backed off to the long poll interval") + close(recheck) + receive(t, woken, "flush not asked again once recheck was closed") + receive(t, done, "done never ran") + if got := pc.writeOuts.Load(); got != 1 { + t.Errorf("write-out started %d times, want 1", got) + } +} + +func receive(t *testing.T, ch <-chan struct{}, msg string) { + t.Helper() + select { + case <-ch: + case <-time.After(10 * time.Second): + t.Fatal(msg) + } +} + func TestStartWritebackStopsWriteOutOnUnlink(t *testing.T) { p := filepath.Join(t.TempDir(), "memory-ranges") if err := os.WriteFile(p, nil, 0o600); err != nil { @@ -321,7 +492,7 @@ func TestStartWritebackStopsWriteOutOnUnlink(t *testing.T) { } pc := &fakePageCache{onWriteOut: func() { _ = os.Remove(p) }} done := make(chan struct{}) - if err := startWriteback(pc, []time.Duration{time.Millisecond}, []string{p}, func() { close(done) }); err != nil { + if err := startWriteback(pc, []time.Duration{time.Millisecond}, []string{p}, nil, func() { close(done) }); err != nil { t.Fatalf("startWriteback: %v", err) } select { @@ -341,7 +512,7 @@ func TestStartWritebackStartsWriteOutRightAway(t *testing.T) { } pc := &fakePageCache{} t.Cleanup(func() { pc.clean.Store(true) }) - if err := startWriteback(pc, []time.Duration{30 * time.Second}, []string{p}, nil); err != nil { + if err := startWriteback(pc, []time.Duration{30 * time.Second}, []string{p}, nil, nil); err != nil { t.Fatalf("startWriteback: %v", err) } deadline := time.Now().Add(10 * time.Second) diff --git a/internal/tarutil/owner.go b/internal/tarutil/owner.go index f5a07da4cb..364762af90 100644 --- a/internal/tarutil/owner.go +++ b/internal/tarutil/owner.go @@ -47,7 +47,17 @@ func Mode(hdr *tar.Header) os.FileMode { // EPERM is tolerated there and the extracted files belong to the extracting // user. func Lchown(root *os.Root, name string, hdr *tar.Header) error { - err := root.Lchown(name, hdr.Uid, hdr.Gid) + return chownErr(root.Lchown(name, hdr.Uid, hdr.Gid), name, hdr) +} + +// Fchown applies hdr's numeric owner to an open file, avoiding a second path +// walk through root when the caller just created f. See Lchown for why EPERM +// is tolerated when running unprivileged. +func Fchown(f *os.File, hdr *tar.Header) error { + return chownErr(f.Chown(hdr.Uid, hdr.Gid), f.Name(), hdr) +} + +func chownErr(err error, name string, hdr *tar.Header) error { if err == nil { return nil } diff --git a/internal/testenv/testenv.go b/internal/testenv/testenv.go index 6dfe9bc9aa..88086b1927 100644 --- a/internal/testenv/testenv.go +++ b/internal/testenv/testenv.go @@ -62,6 +62,11 @@ func Start() (*rest.Config, func()) { CRDDirectoryPaths: []string{filepath.Join(root, "manifests", "ate-install", "generated")}, BinaryAssetsDirectory: binDir, } + // Match the ClusterTrustBundle API enabled in the kind deployment. The + // pinned Kubernetes 1.36 server serves this resource through v1beta1. + env.ControlPlane.GetAPIServer().Configure(). + Set("feature-gates", "ClusterTrustBundle=true"). + Set("runtime-config", "certificates.k8s.io/v1beta1/clustertrustbundles=true") cfg, err := env.Start() if err != nil { fatal(fmt.Errorf("envtest start: %w", err)) @@ -82,8 +87,8 @@ func fatal(err error) { // downloading it on first use via `setup-envtest`, and returns its path. // // The setup is guarded by a cross-process file lock. `go test ./...` runs the -// envtest-backed packages (cmd/ateapi/internal/controlapi, -// cmd/atecontroller/internal/controllers, api/infra/k8s/ate/v1) as separate test +// envtest-backed packages (cmd/atecontroller/internal/controllers, +// api/infra/k8s/ate/v1) as separate test // binaries in parallel, and each one calls this during TestMain. On a cold // cache, concurrent `setup-envtest use` invocations would otherwise race to // download, extract, and exec the *shared* kubebuilder binaries — intermittently diff --git a/internal/testgolden/golden.go b/internal/testgolden/golden.go new file mode 100644 index 0000000000..bd6222833a --- /dev/null +++ b/internal/testgolden/golden.go @@ -0,0 +1,46 @@ +// Copyright 2026 The Agent Substrate 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 testgolden + +import ( + "bytes" + "os" + "path/filepath" + "strconv" + "testing" +) + +// Check compares got with a golden file under the caller's testdata directory. +func Check(t testing.TB, name string, got []byte) []byte { + t.Helper() + path := filepath.Join("testdata", name) + refresh, err := strconv.ParseBool(os.Getenv("REFRESH_GOLDENS")) + if err != nil && os.Getenv("REFRESH_GOLDENS") != "" { + t.Fatalf("REFRESH_GOLDENS: %v", err) + } + if refresh { + if err := os.WriteFile(path, got, 0o644); err != nil { + t.Fatal(err) + } + } + want, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(got, want) { + t.Errorf("output differs from %s (run hack/verify-goldens.sh to regenerate):\n%s", path, got) + } + return want +} diff --git a/internal/volume/csi/client.go b/internal/volume/csi/client.go index 51a6bfb863..59e3acf5dd 100644 --- a/internal/volume/csi/client.go +++ b/internal/volume/csi/client.go @@ -18,9 +18,13 @@ import ( "crypto/tls" "fmt" "net/url" + "time" "github.com/container-storage-interface/spec/lib/go/csi" + "go.ate.dev/substrate/internal/grpclb" + "go.ate.dev/substrate/internal/pluginsocket" "google.golang.org/grpc" + "google.golang.org/grpc/backoff" "google.golang.org/grpc/credentials" "google.golang.org/grpc/credentials/insecure" ) @@ -56,10 +60,51 @@ func parseEndpoint(endpoint string) (string, string, error) { } } +// controllerConnectParams caps the reconnect back-off to a tcp or dns +// endpoint. round_robin reconnects as soon as a connection drops, and gRPC's +// default back-off grows to two minutes, so calls could fail long after the +// controller is back. MinConnectTimeout keeps gRPC's default. +var controllerConnectParams = grpc.ConnectParams{ + Backoff: backoff.Config{ + BaseDelay: backoff.DefaultConfig.BaseDelay, + Multiplier: backoff.DefaultConfig.Multiplier, + Jitter: backoff.DefaultConfig.Jitter, + MaxDelay: 5 * time.Second, + }, + MinConnectTimeout: 20 * time.Second, +} + +// dialOptions returns the options to dial an endpoint with the given scheme. +// +// tcp and dns endpoints use round_robin, so RPCs spread over every address +// the endpoint resolves to, such as each ready pod behind a headless Service. +// The dns resolver looks up addresses again only after a connection fails or +// drops, and ate-api-server keeps its client for the life of the process. So +// RPCs spread only over the pods resolved when the client connected, and a +// pod added later gets no RPCs until a connection breaks. +// +// A unix socket has one address, so it keeps gRPC's default, pick_first, +// which goes idle when the connection drops and reconnects on the next RPC. +func dialOptions(scheme string, creds credentials.TransportCredentials) []grpc.DialOption { + opts := []grpc.DialOption{grpc.WithTransportCredentials(creds)} + switch scheme { + case "unix": + // A unary call waits for a local driver to come back, so a node + // plugin restart does not fail the volume operations that start + // during it. + opts = append(opts, pluginsocket.ReadyWaitOptions(pluginsocket.ReadyWait)...) + case "tcp", "dns": + opts = append(opts, + grpc.WithDefaultServiceConfig(grpclb.RoundRobinServiceConfig), + grpc.WithConnectParams(controllerConnectParams)) + } + return opts +} + // NewCSIClient establishes a gRPC connection to the CSI driver over UDS or TCP // and returns a client initialized with Identity, Controller, and Node service clients. func NewCSIClient(endpoint string, tlsCfg *tls.Config) (*Client, error) { - _, target, err := parseEndpoint(endpoint) + scheme, target, err := parseEndpoint(endpoint) if err != nil { return nil, err } @@ -71,7 +116,7 @@ func NewCSIClient(endpoint string, tlsCfg *tls.Config) (*Client, error) { creds = insecure.NewCredentials() } - conn, err := grpc.NewClient(target, grpc.WithTransportCredentials(creds)) + conn, err := grpc.NewClient(target, dialOptions(scheme, creds)...) if err != nil { return nil, fmt.Errorf("failed to dial CSI endpoint %q: %w", target, err) } diff --git a/internal/volume/csi/client_test.go b/internal/volume/csi/client_test.go index 01c22213b9..c18da4c583 100644 --- a/internal/volume/csi/client_test.go +++ b/internal/volume/csi/client_test.go @@ -17,10 +17,18 @@ package csi import ( "context" "net" + "os" + "path/filepath" + "sync/atomic" "testing" + "time" "github.com/container-storage-interface/spec/lib/go/csi" "google.golang.org/grpc" + "google.golang.org/grpc/connectivity" + "google.golang.org/grpc/credentials/insecure" + "google.golang.org/grpc/resolver" + "google.golang.org/grpc/resolver/manual" ) func TestParseEndpoint(t *testing.T) { @@ -154,3 +162,140 @@ func TestNewCSIClient_TCP(t *testing.T) { t.Errorf("expected driver name 'mock-driver', got %q", resp.GetName()) } } + +// A call that starts while the driver socket is down succeeds once the driver +// comes back, as when kubelet restarts a CSI node plugin. +func TestNewCSIClient_WaitsForDriverRestart(t *testing.T) { + // Unix socket paths are length-limited; t.TempDir can exceed that on macOS. + dir, err := os.MkdirTemp("", "csisock") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { os.RemoveAll(dir) }) + sock := filepath.Join(dir, "csi.sock") + + client, err := NewCSIClient("unix://"+sock, nil) + if err != nil { + t.Fatalf("failed to create CSI client: %v", err) + } + defer client.Close() + + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + defer cancel() + + // Wait for the connection to fail against the missing socket, so the call + // below starts on a lost connection. + client.conn.Connect() + for state := client.conn.GetState(); state != connectivity.TransientFailure; state = client.conn.GetState() { + if !client.conn.WaitForStateChange(ctx, state) { + t.Fatalf("connection to a missing socket is %s, want %s", state, connectivity.TransientFailure) + } + } + + errc := make(chan error, 1) + go func() { + _, err := client.GetPluginInfo(ctx, &csi.GetPluginInfoRequest{}) + errc <- err + }() + + lis, err := net.Listen("unix", sock) + if err != nil { + t.Fatalf("failed to listen: %v", err) + } + grpcServer := grpc.NewServer() + csi.RegisterIdentityServer(grpcServer, &mockIdentityServer{}) + go func() { + _ = grpcServer.Serve(lis) + }() + defer grpcServer.Stop() + + if err := <-errc; err != nil { + t.Errorf("GetPluginInfo across a driver restart = %v, want success", err) + } +} + +// countingIdentityServer counts its GetPluginInfo calls. +type countingIdentityServer struct { + csi.UnimplementedIdentityServer + calls atomic.Int64 +} + +func (s *countingIdentityServer) GetPluginInfo(ctx context.Context, req *csi.GetPluginInfoRequest) (*csi.GetPluginInfoResponse, error) { + s.calls.Add(1) + return &csi.GetPluginInfoResponse{Name: "mock-driver"}, nil +} + +// startCountingServer serves a countingIdentityServer on a local TCP port. +func startCountingServer(t *testing.T) (*countingIdentityServer, string) { + t.Helper() + lis, err := net.Listen("tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("failed to listen: %v", err) + } + srv := &countingIdentityServer{} + grpcServer := grpc.NewServer() + csi.RegisterIdentityServer(grpcServer, srv) + go func() { + _ = grpcServer.Serve(lis) + }() + t.Cleanup(grpcServer.Stop) + return srv, lis.Addr().String() +} + +// An endpoint that resolves to two addresses spreads calls over both for tcp +// and dns, and sends every call to one address for unix. +func TestDialOptionsLoadBalancing(t *testing.T) { + tests := []struct { + scheme string + wantSpread bool + }{ + {scheme: "tcp", wantSpread: true}, + {scheme: "dns", wantSpread: true}, + {scheme: "unix", wantSpread: false}, + } + for _, tt := range tests { + t.Run(tt.scheme, func(t *testing.T) { + srv1, addr1 := startCountingServer(t) + srv2, addr2 := startCountingServer(t) + + r := manual.NewBuilderWithScheme("csitest") + r.InitialState(resolver.State{Addresses: []resolver.Address{{Addr: addr1}, {Addr: addr2}}}) + opts := append(dialOptions(tt.scheme, insecure.NewCredentials()), grpc.WithResolvers(r)) + conn, err := grpc.NewClient(r.Scheme()+":///csi", opts...) + if err != nil { + t.Fatalf("failed to create client: %v", err) + } + defer conn.Close() + client := csi.NewIdentityClient(conn) + + ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) + defer cancel() + call := func() { + t.Helper() + if _, err := client.GetPluginInfo(ctx, &csi.GetPluginInfoRequest{}, grpc.WaitForReady(true)); err != nil { + t.Fatalf("GetPluginInfo failed: %v", err) + } + } + + if tt.wantSpread { + // round_robin adds each address once it connects, so call + // until both have served one. + deadline := time.Now().Add(5 * time.Second) + for srv1.calls.Load() == 0 || srv2.calls.Load() == 0 { + if time.Now().After(deadline) { + t.Fatalf("calls per server = [%d %d], want both above 0", srv1.calls.Load(), srv2.calls.Load()) + } + call() + } + return + } + const n = 20 + for range n { + call() + } + if got1, got2 := srv1.calls.Load(), srv2.calls.Load(); got1 != n && got2 != n { + t.Errorf("calls per server = [%d %d], want all %d on one server", got1, got2, n) + } + }) + } +} diff --git a/internal/volume/csi/controller.go b/internal/volume/csi/controller.go index e83f569e76..7ff30ebfad 100644 --- a/internal/volume/csi/controller.go +++ b/internal/volume/csi/controller.go @@ -44,3 +44,20 @@ func (c *Client) ControllerUnpublishVolume(ctx context.Context, req *csi.Control func (c *Client) ControllerGetCapabilities(ctx context.Context, req *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) { return c.controller.ControllerGetCapabilities(ctx, req) } + +// CreateSnapshot captures a point-in-time copy of a volume. +func (c *Client) CreateSnapshot(ctx context.Context, req *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) { + return c.controller.CreateSnapshot(ctx, req) +} + +// DeleteSnapshot releases a snapshot. +func (c *Client) DeleteSnapshot(ctx context.Context, req *csi.DeleteSnapshotRequest) (*csi.DeleteSnapshotResponse, error) { + return c.controller.DeleteSnapshot(ctx, req) +} + +// ListSnapshots lists snapshots, optionally filtered to one snapshot or source +// volume. It is used to read a snapshot's state after CreateSnapshot returns +// because far more drivers implement it than the newer GetSnapshot RPC. +func (c *Client) ListSnapshots(ctx context.Context, req *csi.ListSnapshotsRequest) (*csi.ListSnapshotsResponse, error) { + return c.controller.ListSnapshots(ctx, req) +} diff --git a/internal/volume/csi/plugin.go b/internal/volume/csi/plugin.go index 39a17207fb..5ce7db7084 100644 --- a/internal/volume/csi/plugin.go +++ b/internal/volume/csi/plugin.go @@ -16,8 +16,11 @@ package csi import ( "context" + "crypto/sha256" "crypto/tls" "crypto/x509" + "encoding/hex" + "errors" "fmt" "log/slog" "os" @@ -53,6 +56,7 @@ var defaultTLSPaths = tlsPaths{ // Plugin implements volume.VolumePluginWorkerPlane using the CSI Client. type Plugin struct { client *Client + driverName string stagingDirPrefix string // capsMu guards controllerCaps and nodeCaps. The maps are built by @@ -69,9 +73,10 @@ var _ volume.VolumePluginWorkerPlane = (*Plugin)(nil) // NewPlugin creates a new Plugin adapter. Call InitControllerCapabilities or // InitNodeCapabilities before use; until then, no optional RPC is reported as supported. -func NewPlugin(client *Client) *Plugin { +func NewPlugin(client *Client, driverName string) *Plugin { return &Plugin{ client: client, + driverName: driverName, stagingDirPrefix: filepath.Join(nodepath.BasePath, "staging"), } } @@ -134,7 +139,9 @@ func (p *Plugin) InitControllerCapabilities(ctx context.Context) { } // InitNodeCapabilities queries and caches NodeGetCapabilities from the driver. -// If the query fails or reports no capabilities, every node RPC is assumed supported. +// If the query fails or reports no capabilities, every node RPC is assumed +// supported, but VOLUME_MOUNT_GROUP is not. A driver without it ignores or +// rejects the group, and unlike an RPC it can't be turned off later. func (p *Plugin) InitNodeCapabilities(ctx context.Context) { caps := make(map[csi.NodeServiceCapability_RPC_Type]bool) resp, err := p.client.NodeGetCapabilities(ctx, &csi.NodeGetCapabilitiesRequest{}) @@ -144,9 +151,9 @@ func (p *Plugin) InitNodeCapabilities(ctx context.Context) { } } if err != nil || len(caps) == 0 { - slog.WarnContext(ctx, "CSI NodeGetCapabilities failed or reported no capabilities; assuming all node RPCs are supported", slog.Any("error", err)) + slog.WarnContext(ctx, "CSI NodeGetCapabilities failed or reported no capabilities; assuming all node RPCs except VOLUME_MOUNT_GROUP are supported", slog.Any("error", err)) for v := range csi.NodeServiceCapability_RPC_Type_name { - if rpc := csi.NodeServiceCapability_RPC_Type(v); rpc != csi.NodeServiceCapability_RPC_UNKNOWN { + if rpc := csi.NodeServiceCapability_RPC_Type(v); rpc != csi.NodeServiceCapability_RPC_UNKNOWN && rpc != csi.NodeServiceCapability_RPC_VOLUME_MOUNT_GROUP { caps[rpc] = true } } @@ -175,6 +182,20 @@ func (p *Plugin) CreateVolume(ctx context.Context, req volume.CreateVolumeReques VolumeCapabilities: getStandardCapabilities(), Parameters: req.Parameters, } + if req.SourceSnapshotID != "" { + // Like CreateSnapshot, refuse locally rather than ask a driver that + // cannot handle snapshots to restore from one. + if !p.SupportsControllerCapability(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT) { + return volume.CreateVolumeResponse{}, fmt.Errorf("CSI driver does not support restoring from snapshot %q", req.SourceSnapshotID) + } + csiReq.VolumeContentSource = &csi.VolumeContentSource{ + Type: &csi.VolumeContentSource_Snapshot{ + Snapshot: &csi.VolumeContentSource_SnapshotSource{ + SnapshotId: req.SourceSnapshotID, + }, + }, + } + } resp, err := p.client.CreateVolume(ctx, csiReq) if err != nil { @@ -185,9 +206,32 @@ func (p *Plugin) CreateVolume(ctx context.Context, req volume.CreateVolumeReques return volume.CreateVolumeResponse{}, fmt.Errorf("CSI CreateVolume response returned nil volume") } + restoredFrom := resp.GetVolume().GetContentSource().GetSnapshot().GetSnapshotId() + if req.SourceSnapshotID != "" && restoredFrom == "" { + // A driver that ignores the requested source returns an empty volume + // and reports success, which for a restore is silent data loss. + // + // Only the presence of a snapshot ID is checked, not that it + // matches the request: drivers may report the source in their own + // format. GCE PD, for example, reports the disk's numeric + // sourceSnapshotId rather than the projects/.../snapshots/... handle + // it was given. Kubernetes' external-provisioner checks the same way. + // + // The caller only knows the volume by its requested name, not the ID + // the driver issued, so delete it here rather than leak it. NotFound + // means the volume is already gone. + volumeID := resp.GetVolume().GetVolumeId() + if delErr := p.DeleteVolume(ctx, volumeID); delErr != nil && status.Code(delErr) != codes.NotFound { + // %v keeps DeleteVolume's gRPC code out of the CreateVolume error. + return volume.CreateVolumeResponse{}, fmt.Errorf("CSI CreateVolume did not report restoring from requested snapshot %q, and deleting volume %q failed: %v", req.SourceSnapshotID, volumeID, delErr) + } + return volume.CreateVolumeResponse{}, fmt.Errorf("CSI CreateVolume did not report restoring from requested snapshot %q", req.SourceSnapshotID) + } + return volume.CreateVolumeResponse{ - VolumeID: resp.GetVolume().GetVolumeId(), - VolumeContext: resp.GetVolume().GetVolumeContext(), + VolumeID: resp.GetVolume().GetVolumeId(), + VolumeContext: resp.GetVolume().GetVolumeContext(), + ContentSourceSnapshotID: restoredFrom, }, nil } @@ -255,6 +299,111 @@ func (p *Plugin) DetachVolume(ctx context.Context, volumeID string, node string) return nil } +// CreateSnapshot maps to CSI Controller CreateSnapshot. +func (p *Plugin) CreateSnapshot(ctx context.Context, req volume.CreateSnapshotRequest) (volume.Snapshot, error) { + if !p.SupportsControllerCapability(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT) { + return volume.Snapshot{}, fmt.Errorf("CSI driver does not support CreateSnapshot") + } + resp, err := p.client.CreateSnapshot(ctx, &csi.CreateSnapshotRequest{ + Name: req.Name, + SourceVolumeId: req.SourceVolumeID, + Parameters: req.Parameters, + }) + if err != nil { + if status.Code(err) == codes.Unimplemented { + p.disableControllerCap(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT) + } + return volume.Snapshot{}, fmt.Errorf("CSI CreateSnapshot failed: %w", err) + } + if resp.GetSnapshot().GetSnapshotId() == "" { + return volume.Snapshot{}, fmt.Errorf("CSI CreateSnapshot response returned no snapshot ID") + } + return snapshotFromCSI(resp.GetSnapshot()), nil +} + +// GetSnapshot maps to CSI Controller ListSnapshots filtered to one handle. +// ListSnapshots is used rather than the newer GetSnapshot RPC because far more +// drivers implement it. A driver without ListSnapshots returns an error +// wrapping errors.ErrUnsupported. +func (p *Plugin) GetSnapshot(ctx context.Context, snapshotID string) (volume.Snapshot, bool, error) { + if snapshotID == "" { + // An empty filter would list every snapshot the driver holds. + return volume.Snapshot{}, false, fmt.Errorf("snapshot ID is required") + } + if !p.SupportsControllerCapability(csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS) { + return volume.Snapshot{}, false, fmt.Errorf("CSI driver does not support ListSnapshots: %w", errors.ErrUnsupported) + } + resp, err := p.client.ListSnapshots(ctx, &csi.ListSnapshotsRequest{ + SnapshotId: snapshotID, + }) + if err != nil { + if status.Code(err) == codes.Unimplemented { + p.disableControllerCap(csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS) + return volume.Snapshot{}, false, fmt.Errorf("CSI ListSnapshots is unimplemented by driver: %w", errors.ErrUnsupported) + } + // Some drivers answer NotFound for an unknown snapshot_id filter + // instead of an empty list. + if status.Code(err) == codes.NotFound { + return volume.Snapshot{}, false, nil + } + return volume.Snapshot{}, false, fmt.Errorf("CSI ListSnapshots failed: %w", err) + } + // Filtering by snapshot_id yields at most one entry, and an empty list for + // a handle the driver no longer has. + for _, entry := range resp.GetEntries() { + if snap := entry.GetSnapshot(); snap.GetSnapshotId() == snapshotID { + return snapshotFromCSI(snap), true, nil + } + } + return volume.Snapshot{}, false, nil +} + +// DeleteSnapshot maps to CSI Controller DeleteSnapshot. +// +// Unlike CreateSnapshot, it is not skipped when the cached capabilities say +// the driver cannot snapshot: the caller holds a handle the driver issued, and +// skipping the call would leak it. +func (p *Plugin) DeleteSnapshot(ctx context.Context, snapshotID string) error { + if snapshotID == "" { + return fmt.Errorf("snapshot ID is required") + } + // The CSI spec requires DeleteSnapshot to succeed for a snapshot that does + // not exist, but not every driver honors that, and cleanup must stay + // retryable either way. + _, err := p.client.DeleteSnapshot(ctx, &csi.DeleteSnapshotRequest{ + SnapshotId: snapshotID, + }) + if err != nil && status.Code(err) != codes.NotFound { + return fmt.Errorf("CSI DeleteSnapshot failed: %w", err) + } + return nil +} + +// ControllerCapabilities reports the snapshot capabilities cached by +// InitControllerCapabilities, narrowed by any RPC the driver has since +// returned Unimplemented for. It does not call the driver. +func (p *Plugin) ControllerCapabilities(context.Context) (volume.Capabilities, error) { + return volume.Capabilities{ + CreateDeleteSnapshot: p.SupportsControllerCapability(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + ListSnapshots: p.SupportsControllerCapability(csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS), + }, nil +} + +func snapshotFromCSI(snap *csi.Snapshot) volume.Snapshot { + return volume.Snapshot{ + SnapshotID: snap.GetSnapshotId(), + SourceVolumeID: snap.GetSourceVolumeId(), + ReadyToUse: snap.GetReadyToUse(), + SizeBytes: snap.GetSizeBytes(), + } +} + +// SupportsVolumeMountGroup reports whether the driver reports the +// VOLUME_MOUNT_GROUP node capability. +func (p *Plugin) SupportsVolumeMountGroup() bool { + return p.SupportsNodeCapability(csi.NodeServiceCapability_RPC_VOLUME_MOUNT_GROUP) +} + // MountVolume maps to CSI Node NodePublishVolume. // It also handles NodeStageVolume staging if required by the driver. func (p *Plugin) MountVolume(ctx context.Context, req volume.MountVolumeRequest) error { @@ -267,7 +416,7 @@ func (p *Plugin) MountVolume(ctx context.Context, req volume.MountVolumeRequest) VolumeId: req.VolumeID, StagingTargetPath: stagingPath, TargetPath: req.TargetPath, - VolumeCapability: getStandardCapabilities()[0], + VolumeCapability: mountCapability(req.VolumeMountGroup), Readonly: false, VolumeContext: req.VolumeContext, PublishContext: req.PublishContext, @@ -286,15 +435,17 @@ func (p *Plugin) stageVolume(ctx context.Context, req volume.MountVolumeRequest) return "", nil } - stagingPath := filepath.Join(p.stagingDirPrefix, req.VolumeID) + stagingPath := p.stagingDir(req.VolumeID) if err := os.MkdirAll(stagingPath, 0750); err != nil { return "", fmt.Errorf("failed to create staging directory %q: %w", stagingPath, err) } + // Staging dirs are named by a hash, so log which volume this one is for. + slog.InfoContext(ctx, "Staging CSI volume", slog.String("volume_id", req.VolumeID), slog.String("staging_path", stagingPath)) csiReq := &csi.NodeStageVolumeRequest{ VolumeId: req.VolumeID, StagingTargetPath: stagingPath, - VolumeCapability: getStandardCapabilities()[0], // Use primary capability + VolumeCapability: mountCapability(req.VolumeMountGroup), VolumeContext: req.VolumeContext, PublishContext: req.PublishContext, } @@ -334,7 +485,7 @@ func (p *Plugin) unstageVolume(ctx context.Context, volumeID string) error { return nil } - stagingPath := filepath.Join(p.stagingDirPrefix, volumeID) + stagingPath := p.stagingDir(volumeID) req := &csi.NodeUnstageVolumeRequest{ VolumeId: volumeID, StagingTargetPath: stagingPath, @@ -352,10 +503,22 @@ func (p *Plugin) unstageVolume(ctx context.Context, volumeID string) error { return nil } -// removeStagingDir removes an empty staging directory, logging any failure. +// stagingDir returns the staging directory for volumeID. The directory is named +// by a hash of the ID, which is the driver's own string, and is scoped to the +// driver because IDs are only unique within one. +func (p *Plugin) stagingDir(volumeID string) string { + sum := sha256.Sum256([]byte(volumeID)) + return filepath.Join(p.stagingDirPrefix, p.driverName, hex.EncodeToString(sum[:]), "mount") +} + +// removeStagingDir removes an empty staging directory and its per-volume +// parent, logging any failure. func removeStagingDir(ctx context.Context, stagingPath string) { - if err := os.Remove(stagingPath); err != nil && !os.IsNotExist(err) { - slog.WarnContext(ctx, "failed to remove staging directory", slog.String("path", stagingPath), slog.Any("error", err)) + for _, dir := range []string{stagingPath, filepath.Dir(stagingPath)} { + if err := os.Remove(dir); err != nil && !os.IsNotExist(err) { + slog.WarnContext(ctx, "failed to remove staging directory", slog.String("path", dir), slog.Any("error", err)) + return // The parent cannot be empty either. + } } } @@ -375,6 +538,14 @@ func getStandardCapabilities() []*csi.VolumeCapability { } } +// mountCapability is the primary standard capability with volumeMountGroup, +// which NodeStageVolume and NodePublishVolume both take. +func mountCapability(volumeMountGroup string) *csi.VolumeCapability { + capability := getStandardCapabilities()[0] + capability.GetMount().VolumeMountGroup = volumeMountGroup + return capability +} + // CSIDriverConfigGetter provides access to retrieve a CSIDriverConfig by name. // Both atelisters.CSIDriverConfigLister and direct client getters implement this interface. type CSIDriverConfigGetter interface { @@ -420,7 +591,7 @@ func newCSIPlugin(ctx context.Context, getter CSIDriverConfigGetter, driverName if err != nil { return nil, fmt.Errorf("failed to initialize CSI client from endpoint %q: %w", endpoint, err) } - csiPlugin := NewPlugin(csiClient) + csiPlugin := NewPlugin(csiClient, driverName) // Verify CSI plugin reported name matches requested name. reportedName, err := csiPlugin.DriverName(ctx) diff --git a/internal/volume/csi/plugin_snapshot_test.go b/internal/volume/csi/plugin_snapshot_test.go new file mode 100644 index 0000000000..51721a57e5 --- /dev/null +++ b/internal/volume/csi/plugin_snapshot_test.go @@ -0,0 +1,543 @@ +// Copyright 2026 The Agent Substrate 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 csi + +import ( + "context" + "errors" + "slices" + "strings" + "testing" + + "github.com/container-storage-interface/spec/lib/go/csi" + "go.ate.dev/substrate/internal/volume" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +type controllerCapsFunc func(context.Context, *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) + +// reportCaps returns a ControllerGetCapabilities handler that reports rpcs. +func reportCaps(rpcs ...csi.ControllerServiceCapability_RPC_Type) controllerCapsFunc { + return func(context.Context, *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) { + resp := &csi.ControllerGetCapabilitiesResponse{} + for _, rpc := range rpcs { + resp.Capabilities = append(resp.Capabilities, &csi.ControllerServiceCapability{ + Type: &csi.ControllerServiceCapability_Rpc{Rpc: &csi.ControllerServiceCapability_RPC{Type: rpc}}, + }) + } + return resp, nil + } +} + +// failCaps is a ControllerGetCapabilities handler that fails, so the plugin +// assumes every RPC is supported. +func failCaps(context.Context, *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) { + return nil, status.Error(codes.Unavailable, "down") +} + +// newSnapshotTestPlugin serves driver on a unix socket and returns a plugin +// for it whose controller capabilities have been initialized. +func newSnapshotTestPlugin(t *testing.T, driver *mockCSIDriver) *Plugin { + t.Helper() + endpoint, cleanup := startMockCSIDriver(t, driver) + t.Cleanup(cleanup) + + client, err := NewCSIClient(endpoint, nil) + if err != nil { + t.Fatalf("failed to create CSI client: %v", err) + } + t.Cleanup(func() { client.Close() }) + + plugin := NewPlugin(client, mockDriverName) + plugin.InitControllerCapabilities(context.Background()) + return plugin +} + +func TestPlugin_ControllerCapabilities(t *testing.T) { + tests := []struct { + name string + caps controllerCapsFunc + want volume.Capabilities + }{ + { + name: "create and delete only", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME, csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + want: volume.Capabilities{CreateDeleteSnapshot: true}, + }, + { + name: "create, delete and list", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT, csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS), + want: volume.Capabilities{CreateDeleteSnapshot: true, ListSnapshots: true}, + }, + { + name: "no snapshot support", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME), + want: volume.Capabilities{}, + }, + { + // Discovery is best-effort: a driver that cannot report its + // capabilities is assumed to support everything. + name: "query fails", + caps: failCaps, + want: volume.Capabilities{CreateDeleteSnapshot: true, ListSnapshots: true}, + }, + { + name: "reports nothing", + caps: reportCaps(), + want: volume.Capabilities{CreateDeleteSnapshot: true, ListSnapshots: true}, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + plugin := newSnapshotTestPlugin(t, &mockCSIDriver{controllerGetCapabilitiesFunc: tt.caps}) + got, err := plugin.ControllerCapabilities(context.Background()) + if err != nil { + t.Fatalf("ControllerCapabilities: %v", err) + } + if got != tt.want { + t.Errorf("ControllerCapabilities = %+v, want %+v", got, tt.want) + } + }) + } +} + +func TestPlugin_ControllerCapabilities_Uninitialized(t *testing.T) { + got, err := NewPlugin(nil, mockDriverName).ControllerCapabilities(context.Background()) + if err != nil { + t.Fatalf("ControllerCapabilities: %v", err) + } + if got != (volume.Capabilities{}) { + t.Errorf("ControllerCapabilities before init = %+v, want none", got) + } +} + +func TestPlugin_CreateSnapshot(t *testing.T) { + tests := []struct { + name string + caps controllerCapsFunc + // driverID is the snapshot ID the driver returns. + driverID string + driverErr error + wantErr bool + wantCalls int + // wantCap is whether CreateDeleteSnapshot is reported afterwards. + wantCap bool + }{ + { + name: "creates", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + driverID: "snap-s", + wantCalls: 1, + wantCap: true, + }, + { + name: "refused without the capability", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME), + wantErr: true, + }, + { + name: "empty ID from the driver", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + wantErr: true, + wantCalls: 1, + wantCap: true, + }, + { + name: "Unimplemented disables the capability", + caps: failCaps, + driverErr: status.Error(codes.Unimplemented, "unimplemented"), + wantErr: true, + wantCalls: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var calls int + plugin := newSnapshotTestPlugin(t, &mockCSIDriver{ + controllerGetCapabilitiesFunc: tt.caps, + createSnapshotFunc: func(_ context.Context, req *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) { + calls++ + if tt.driverErr != nil { + return nil, tt.driverErr + } + return &csi.CreateSnapshotResponse{Snapshot: &csi.Snapshot{ + SnapshotId: tt.driverID, + SourceVolumeId: req.GetSourceVolumeId(), + ReadyToUse: true, + }}, nil + }, + }) + ctx := context.Background() + + snap, err := plugin.CreateSnapshot(ctx, volume.CreateSnapshotRequest{Name: "s", SourceVolumeID: "v"}) + if gotErr := err != nil; gotErr != tt.wantErr { + t.Fatalf("CreateSnapshot error = %v, wantErr %v", err, tt.wantErr) + } + if want := (volume.Snapshot{SnapshotID: "snap-s", SourceVolumeID: "v", ReadyToUse: true}); !tt.wantErr && snap != want { + t.Errorf("CreateSnapshot = %+v, want %+v", snap, want) + } + if calls != tt.wantCalls { + t.Errorf("CreateSnapshot reached the driver %d times, want %d", calls, tt.wantCalls) + } + if caps, _ := plugin.ControllerCapabilities(ctx); caps.CreateDeleteSnapshot != tt.wantCap { + t.Errorf("CreateDeleteSnapshot = %v afterwards, want %v", caps.CreateDeleteSnapshot, tt.wantCap) + } + }) + } +} + +func TestPlugin_GetSnapshot(t *testing.T) { + tests := []struct { + name string + caps controllerCapsFunc + snapshotID string + listErr error + // emptyList makes ListSnapshots return no entries. + emptyList bool + wantFound bool + wantErr bool + wantUnsupported bool + wantCalls int + // wantCap is whether ListSnapshots is reported afterwards. + wantCap bool + }{ + { + name: "found", + caps: reportCaps(csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS), + snapshotID: "snap-1", + wantFound: true, + wantCalls: 1, + wantCap: true, + }, + { + name: "empty list is not found", + caps: reportCaps(csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS), + snapshotID: "snap-1", + emptyList: true, + wantCalls: 1, + wantCap: true, + }, + { + name: "NotFound from the driver is not found", + caps: reportCaps(csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS), + snapshotID: "snap-1", + listErr: status.Error(codes.NotFound, "no such snapshot"), + wantCalls: 1, + wantCap: true, + }, + { + name: "other driver errors are returned", + caps: reportCaps(csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS), + snapshotID: "snap-1", + listErr: status.Error(codes.Unavailable, "down"), + wantErr: true, + wantCalls: 1, + wantCap: true, + }, + { + name: "unsupported without the capability", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + snapshotID: "snap-1", + wantErr: true, + wantUnsupported: true, + }, + { + name: "Unimplemented is unsupported and disables the capability", + caps: failCaps, + snapshotID: "snap-1", + listErr: status.Error(codes.Unimplemented, "unimplemented"), + wantErr: true, + wantUnsupported: true, + wantCalls: 1, + }, + { + name: "empty ID is rejected", + caps: reportCaps(csi.ControllerServiceCapability_RPC_LIST_SNAPSHOTS), + wantErr: true, + wantCap: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var calls int + plugin := newSnapshotTestPlugin(t, &mockCSIDriver{ + controllerGetCapabilitiesFunc: tt.caps, + listSnapshotsFunc: func(_ context.Context, req *csi.ListSnapshotsRequest) (*csi.ListSnapshotsResponse, error) { + calls++ + if tt.listErr != nil { + return nil, tt.listErr + } + if tt.emptyList { + return &csi.ListSnapshotsResponse{}, nil + } + return &csi.ListSnapshotsResponse{Entries: []*csi.ListSnapshotsResponse_Entry{ + {Snapshot: &csi.Snapshot{SnapshotId: req.GetSnapshotId(), ReadyToUse: true}}, + }}, nil + }, + }) + ctx := context.Background() + + snap, found, err := plugin.GetSnapshot(ctx, tt.snapshotID) + if gotErr := err != nil; gotErr != tt.wantErr { + t.Fatalf("GetSnapshot error = %v, wantErr %v", err, tt.wantErr) + } + if got := errors.Is(err, errors.ErrUnsupported); got != tt.wantUnsupported { + t.Errorf("GetSnapshot error = %v, want ErrUnsupported %v", err, tt.wantUnsupported) + } + if found != tt.wantFound { + t.Errorf("GetSnapshot found = %v, want %v", found, tt.wantFound) + } + if want := (volume.Snapshot{SnapshotID: tt.snapshotID, ReadyToUse: true}); found && snap != want { + t.Errorf("GetSnapshot = %+v, want %+v", snap, want) + } + if calls != tt.wantCalls { + t.Errorf("ListSnapshots reached the driver %d times, want %d", calls, tt.wantCalls) + } + if caps, _ := plugin.ControllerCapabilities(ctx); caps.ListSnapshots != tt.wantCap { + t.Errorf("ListSnapshots = %v afterwards, want %v", caps.ListSnapshots, tt.wantCap) + } + }) + } +} + +func TestPlugin_DeleteSnapshot(t *testing.T) { + tests := []struct { + name string + caps controllerCapsFunc + snapshotID string + driverErr error + wantErr bool + wantCalls int + }{ + { + name: "deletes", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + snapshotID: "snap-1", + wantCalls: 1, + }, + { + name: "not found is success", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + snapshotID: "snap-1", + driverErr: status.Error(codes.NotFound, "gone"), + wantCalls: 1, + }, + { + name: "other errors are returned", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + snapshotID: "snap-1", + driverErr: status.Error(codes.Internal, "boom"), + wantErr: true, + wantCalls: 1, + }, + { + // The caller holds a handle the driver issued, and skipping the + // call would leak it. + name: "sent without the capability", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME), + snapshotID: "snap-1", + wantCalls: 1, + }, + { + name: "empty ID is rejected", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT), + wantErr: true, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var calls int + plugin := newSnapshotTestPlugin(t, &mockCSIDriver{ + controllerGetCapabilitiesFunc: tt.caps, + deleteSnapshotFunc: func(context.Context, *csi.DeleteSnapshotRequest) (*csi.DeleteSnapshotResponse, error) { + calls++ + if tt.driverErr != nil { + return nil, tt.driverErr + } + return &csi.DeleteSnapshotResponse{}, nil + }, + }) + + err := plugin.DeleteSnapshot(context.Background(), tt.snapshotID) + if gotErr := err != nil; gotErr != tt.wantErr { + t.Errorf("DeleteSnapshot error = %v, wantErr %v", err, tt.wantErr) + } + if calls != tt.wantCalls { + t.Errorf("DeleteSnapshot reached the driver %d times, want %d", calls, tt.wantCalls) + } + }) + } +} + +func TestPlugin_CreateVolume_RestoreSource(t *testing.T) { + snapshotCaps := reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_SNAPSHOT) + tests := []struct { + name string + caps controllerCapsFunc + source string + // reportedSource, if set, replaces the content source the driver + // reports. dropSource reports none, as a driver that ignores the + // requested source would. emptySourceID reports a snapshot source + // with no ID. + reportedSource string + dropSource bool + emptySourceID bool + deleteErr error + wantErr bool + // wantErrContains is a substring the error must contain. + wantErrContains string + // wantErrNotContain is a substring the error must not contain. + wantErrNotContain string + wantSource string + wantCreateCalls int + wantDeleted []string + }{ + { + name: "no source", + caps: snapshotCaps, + wantCreateCalls: 1, + }, + { + name: "driver reports the requested source", + caps: snapshotCaps, + source: "snap-1", + wantSource: "snap-1", + wantCreateCalls: 1, + }, + { + name: "driver reports no source", + caps: snapshotCaps, + source: "snap-1", + dropSource: true, + wantErr: true, + wantCreateCalls: 1, + wantDeleted: []string{"vol-v"}, + }, + { + name: "driver reports a snapshot source with no ID", + caps: snapshotCaps, + source: "snap-1", + emptySourceID: true, + wantErr: true, + wantCreateCalls: 1, + wantDeleted: []string{"vol-v"}, + }, + { + name: "deleting the unrestored volume fails", + caps: snapshotCaps, + source: "snap-1", + dropSource: true, + deleteErr: status.Error(codes.Internal, "boom"), + wantErr: true, + wantErrContains: "vol-v", + wantCreateCalls: 1, + wantDeleted: []string{"vol-v"}, + }, + { + name: "unrestored volume is already gone", + caps: snapshotCaps, + source: "snap-1", + dropSource: true, + deleteErr: status.Error(codes.NotFound, "gone"), + wantErr: true, + wantErrNotContain: "deleting volume", + wantCreateCalls: 1, + wantDeleted: []string{"vol-v"}, + }, + { + // Drivers may report the source in their own format, as GCE PD + // reports a numeric ID for a projects/.../snapshots/... handle. + name: "driver reports the source in its own format", + caps: snapshotCaps, + source: "projects/p/global/snapshots/snap-1", + reportedSource: "8123456789012345678", + wantSource: "8123456789012345678", + wantCreateCalls: 1, + }, + { + name: "restore refused without snapshot support", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME), + source: "snap-1", + wantErr: true, + }, + { + name: "empty volume needs no snapshot support", + caps: reportCaps(csi.ControllerServiceCapability_RPC_CREATE_DELETE_VOLUME), + wantCreateCalls: 1, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + var createCalls int + var deleted []string + plugin := newSnapshotTestPlugin(t, &mockCSIDriver{ + controllerGetCapabilitiesFunc: tt.caps, + createVolumeFunc: func(_ context.Context, req *csi.CreateVolumeRequest) (*csi.CreateVolumeResponse, error) { + createCalls++ + vol := &csi.Volume{VolumeId: "vol-" + req.GetName()} + source := req.GetVolumeContentSource().GetSnapshot().GetSnapshotId() + if tt.reportedSource != "" { + source = tt.reportedSource + } + if tt.emptySourceID { + vol.ContentSource = &csi.VolumeContentSource{Type: &csi.VolumeContentSource_Snapshot{ + Snapshot: &csi.VolumeContentSource_SnapshotSource{}, + }} + } else if source != "" && !tt.dropSource { + vol.ContentSource = &csi.VolumeContentSource{Type: &csi.VolumeContentSource_Snapshot{ + Snapshot: &csi.VolumeContentSource_SnapshotSource{SnapshotId: source}, + }} + } + return &csi.CreateVolumeResponse{Volume: vol}, nil + }, + deleteVolumeFunc: func(_ context.Context, req *csi.DeleteVolumeRequest) (*csi.DeleteVolumeResponse, error) { + deleted = append(deleted, req.GetVolumeId()) + if tt.deleteErr != nil { + return nil, tt.deleteErr + } + return &csi.DeleteVolumeResponse{}, nil + }, + }) + + resp, err := plugin.CreateVolume(context.Background(), volume.CreateVolumeRequest{ + Name: "v", + CapacityBytes: 1 << 30, + SourceSnapshotID: tt.source, + }) + if gotErr := err != nil; gotErr != tt.wantErr { + t.Fatalf("CreateVolume error = %v, wantErr %v", err, tt.wantErr) + } + if tt.wantErrContains != "" && !strings.Contains(err.Error(), tt.wantErrContains) { + t.Errorf("CreateVolume error = %v, want it to contain %q", err, tt.wantErrContains) + } + if tt.wantErrNotContain != "" && strings.Contains(err.Error(), tt.wantErrNotContain) { + t.Errorf("CreateVolume error = %v, want it not to contain %q", err, tt.wantErrNotContain) + } + if tt.deleteErr != nil && status.Code(err) != codes.Unknown { + t.Errorf("CreateVolume error code = %v, want %v so the cleanup's code doesn't leak", status.Code(err), codes.Unknown) + } + if resp.ContentSourceSnapshotID != tt.wantSource { + t.Errorf("ContentSourceSnapshotID = %q, want %q", resp.ContentSourceSnapshotID, tt.wantSource) + } + if createCalls != tt.wantCreateCalls { + t.Errorf("CreateVolume reached the driver %d times, want %d", createCalls, tt.wantCreateCalls) + } + if !slices.Equal(deleted, tt.wantDeleted) { + t.Errorf("deleted volumes = %v, want %v", deleted, tt.wantDeleted) + } + }) + } +} diff --git a/internal/volume/csi/plugin_test.go b/internal/volume/csi/plugin_test.go index 9e9ad33916..bd14170f2a 100644 --- a/internal/volume/csi/plugin_test.go +++ b/internal/volume/csi/plugin_test.go @@ -16,10 +16,13 @@ package csi import ( "context" + "crypto/sha256" + "encoding/hex" "fmt" "net" "os" "path/filepath" + "strings" "testing" "github.com/container-storage-interface/spec/lib/go/csi" @@ -43,6 +46,9 @@ type mockCSIDriver struct { nodeUnstageVolumeFunc func(context.Context, *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) nodePublishVolumeFunc func(context.Context, *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) nodeUnpublishVolumeFunc func(context.Context, *csi.NodeUnpublishVolumeRequest) (*csi.NodeUnpublishVolumeResponse, error) + createSnapshotFunc func(context.Context, *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) + listSnapshotsFunc func(context.Context, *csi.ListSnapshotsRequest) (*csi.ListSnapshotsResponse, error) + deleteSnapshotFunc func(context.Context, *csi.DeleteSnapshotRequest) (*csi.DeleteSnapshotResponse, error) controllerGetCapabilitiesFunc func(context.Context, *csi.ControllerGetCapabilitiesRequest) (*csi.ControllerGetCapabilitiesResponse, error) nodeGetCapabilitiesFunc func(context.Context, *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) @@ -176,6 +182,33 @@ func (m *mockCSIDriver) NodeUnpublishVolume(ctx context.Context, req *csi.NodeUn return &csi.NodeUnpublishVolumeResponse{}, nil } +func (m *mockCSIDriver) CreateSnapshot(ctx context.Context, req *csi.CreateSnapshotRequest) (*csi.CreateSnapshotResponse, error) { + if m.createSnapshotFunc != nil { + return m.createSnapshotFunc(ctx, req) + } + return &csi.CreateSnapshotResponse{Snapshot: &csi.Snapshot{ + SnapshotId: "snap-" + req.GetName(), + SourceVolumeId: req.GetSourceVolumeId(), + ReadyToUse: true, + }}, nil +} + +func (m *mockCSIDriver) ListSnapshots(ctx context.Context, req *csi.ListSnapshotsRequest) (*csi.ListSnapshotsResponse, error) { + if m.listSnapshotsFunc != nil { + return m.listSnapshotsFunc(ctx, req) + } + return &csi.ListSnapshotsResponse{Entries: []*csi.ListSnapshotsResponse_Entry{ + {Snapshot: &csi.Snapshot{SnapshotId: req.GetSnapshotId(), ReadyToUse: true}}, + }}, nil +} + +func (m *mockCSIDriver) DeleteSnapshot(ctx context.Context, req *csi.DeleteSnapshotRequest) (*csi.DeleteSnapshotResponse, error) { + if m.deleteSnapshotFunc != nil { + return m.deleteSnapshotFunc(ctx, req) + } + return &csi.DeleteSnapshotResponse{}, nil +} + func startMockCSIDriver(t *testing.T, driver *mockCSIDriver) (string, func()) { tmpDir, err := os.MkdirTemp("", "csi-test-*") if err != nil { @@ -220,7 +253,7 @@ func TestPlugin_CreateVolume(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) ctx := context.Background() resp, err := plugin.CreateVolume(ctx, volume.CreateVolumeRequest{ @@ -247,7 +280,7 @@ func TestPlugin_DeleteVolume(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) ctx := context.Background() err = plugin.DeleteVolume(ctx, "test-vol") @@ -267,7 +300,7 @@ func TestPlugin_AttachVolume(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) ctx := context.Background() plugin.InitControllerCapabilities(ctx) @@ -326,7 +359,7 @@ func TestPlugin_DetachVolume(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) ctx := context.Background() plugin.InitControllerCapabilities(ctx) @@ -377,7 +410,7 @@ func TestPlugin_MountVolume(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) tmpDir, err := os.MkdirTemp("", "csi-mount-test-*") if err != nil { t.Fatalf("failed to create temp dir: %v", err) @@ -399,7 +432,7 @@ func TestPlugin_MountVolume(t *testing.T) { } // Verify staging directory was created - stagingPath := filepath.Join(plugin.stagingDirPrefix, "test-vol") + stagingPath := plugin.stagingDir("test-vol") if _, err := os.Stat(stagingPath); os.IsNotExist(err) { t.Errorf("staging directory %q was not created", stagingPath) } @@ -418,6 +451,137 @@ func TestPlugin_MountVolume(t *testing.T) { } } +func TestPlugin_StagingDir(t *testing.T) { + // The layout is on-disk state shared across atelet builds, so pin it. + p := &Plugin{stagingDirPrefix: "/staging", driverName: "d.example.com"} + want := "/staging/d.example.com/d2e8363faaac7ae76def3b14091d8eb5755f6b92e9531627aeec833a8731cc49/mount" + if got := p.stagingDir("vol-1"); got != want { + t.Errorf("stagingDir(%q) = %q, want %q", "vol-1", got, want) + } + + tests := []struct { + name string + volumeID string + }{ + {name: "plain", volumeID: "vol-1"}, + {name: "slashes", volumeID: "projects/p/disks/d-1"}, + {name: "parent", volumeID: "../x"}, + {name: "dot-dot", volumeID: ".."}, + {name: "absolute", volumeID: "/x"}, + {name: "absolute root", volumeID: "/"}, + {name: "dot", volumeID: "."}, + {name: "longest", volumeID: strings.Repeat("a", 256)}, + } + for _, tc := range tests { + t.Run(tc.name, func(t *testing.T) { + var stagedAt, publishedFrom, unstagedAt string + driver := &mockCSIDriver{ + nodeStageVolumeFunc: func(_ context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) { + stagedAt = req.GetStagingTargetPath() + return &csi.NodeStageVolumeResponse{}, nil + }, + nodePublishVolumeFunc: func(_ context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) { + publishedFrom = req.GetStagingTargetPath() + return &csi.NodePublishVolumeResponse{}, nil + }, + nodeUnstageVolumeFunc: func(_ context.Context, req *csi.NodeUnstageVolumeRequest) (*csi.NodeUnstageVolumeResponse, error) { + unstagedAt = req.GetStagingTargetPath() + return &csi.NodeUnstageVolumeResponse{}, nil + }, + } + endpoint, cleanup := startMockCSIDriver(t, driver) + defer cleanup() + client, err := NewCSIClient(endpoint, nil) + if err != nil { + t.Fatalf("failed to create CSI client: %v", err) + } + defer client.Close() + + root := t.TempDir() + plugin := NewPlugin(client, mockDriverName) + plugin.stagingDirPrefix = filepath.Join(root, "staging") + ctx := context.Background() + plugin.InitNodeCapabilities(ctx) + + sum := sha256.Sum256([]byte(tc.volumeID)) + driverDir := filepath.Join(plugin.stagingDirPrefix, mockDriverName) + wantPath := filepath.Join(driverDir, hex.EncodeToString(sum[:]), "mount") + + req := volume.MountVolumeRequest{VolumeID: tc.volumeID, TargetPath: filepath.Join(root, "target")} + if err := plugin.MountVolume(ctx, req); err != nil { + t.Fatalf("MountVolume() error = %v", err) + } + if stagedAt != wantPath || publishedFrom != wantPath { + t.Errorf("staged at %q, published from %q, want both %q", stagedAt, publishedFrom, wantPath) + } + if !strings.HasPrefix(wantPath, plugin.stagingDirPrefix+string(os.PathSeparator)) { + t.Errorf("staging path %q is not under prefix %q", wantPath, plugin.stagingDirPrefix) + } + if err := plugin.UnmountVolume(ctx, tc.volumeID, req.TargetPath); err != nil { + t.Fatalf("UnmountVolume() error = %v", err) + } + if unstagedAt != wantPath { + t.Errorf("unstaged at %q, want %q", unstagedAt, wantPath) + } + // Unmount removes the per-volume directory, keeps the driver directory, + // and creates nothing outside the prefix. + if _, err := os.Stat(filepath.Dir(wantPath)); !os.IsNotExist(err) { + t.Errorf("per-volume directory %q was not removed, err: %v", filepath.Dir(wantPath), err) + } + if _, err := os.Stat(driverDir); err != nil { + t.Errorf("driver directory %q was not kept: %v", driverDir, err) + } + entries, err := os.ReadDir(root) + if err != nil { + t.Fatal(err) + } + if len(entries) != 1 || entries[0].Name() != "staging" { + t.Errorf("unexpected entries under %q: %v", root, entries) + } + }) + } + + t.Run("non-empty mount directory is kept", func(t *testing.T) { + endpoint, cleanup := startMockCSIDriver(t, &mockCSIDriver{}) + defer cleanup() + client, err := NewCSIClient(endpoint, nil) + if err != nil { + t.Fatalf("failed to create CSI client: %v", err) + } + defer client.Close() + + plugin := NewPlugin(client, mockDriverName) + plugin.stagingDirPrefix = filepath.Join(t.TempDir(), "staging") + ctx := context.Background() + plugin.InitNodeCapabilities(ctx) + + mount := plugin.stagingDir("vol-1") + if err := os.MkdirAll(mount, 0750); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(mount, "data"), nil, 0600); err != nil { + t.Fatal(err) + } + if err := plugin.unstageVolume(ctx, "vol-1"); err != nil { + t.Fatalf("unstageVolume() error = %v", err) + } + if _, err := os.Stat(filepath.Join(mount, "data")); err != nil { + t.Errorf("non-empty mount directory was removed: %v", err) + } + }) + + t.Run("volume IDs map to distinct directories per driver", func(t *testing.T) { + a := &Plugin{stagingDirPrefix: "/s", driverName: "d1"} + b := &Plugin{stagingDirPrefix: "/s", driverName: "d2"} + if a.stagingDir("a/b") == a.stagingDir("a//b") || a.stagingDir("a") == a.stagingDir("a/b") { + t.Error("different volume IDs share a staging directory") + } + if a.stagingDir("v") == b.stagingDir("v") { + t.Error("different drivers share a staging directory") + } + }) +} + func TestPlugin_UnmountVolume(t *testing.T) { driver := &mockCSIDriver{} endpoint, cleanup := startMockCSIDriver(t, driver) @@ -429,7 +593,7 @@ func TestPlugin_UnmountVolume(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) tmpDir, err := os.MkdirTemp("", "csi-unmount-test-*") if err != nil { t.Fatalf("failed to create temp dir: %v", err) @@ -440,7 +604,7 @@ func TestPlugin_UnmountVolume(t *testing.T) { targetPath := filepath.Join(tmpDir, "target") // Pre-create staging directory to test cleanup - stagingPath := filepath.Join(plugin.stagingDirPrefix, "test-vol") + stagingPath := plugin.stagingDir("test-vol") if err := os.MkdirAll(stagingPath, 0750); err != nil { t.Fatalf("failed to create staging path: %v", err) } @@ -544,7 +708,7 @@ func TestPlugin_Capabilities_SkipAttachDetachWhenUnsupported(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) ctx := context.Background() plugin.InitControllerCapabilities(ctx) @@ -605,7 +769,7 @@ func TestPlugin_Capabilities_SkipStageUnstageWhenUnsupported(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) ctx := context.Background() plugin.InitNodeCapabilities(ctx) @@ -671,7 +835,7 @@ func TestPlugin_Capabilities_AllEnabledWhenQueryFailsOrEmpty(t *testing.T) { } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) ctx := context.Background() plugin.InitControllerCapabilities(ctx) plugin.InitNodeCapabilities(ctx) @@ -682,6 +846,9 @@ func TestPlugin_Capabilities_AllEnabledWhenQueryFailsOrEmpty(t *testing.T) { if !plugin.SupportsNodeCapability(csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME) { t.Errorf("expected STAGE_UNSTAGE_VOLUME to be true") } + if plugin.SupportsVolumeMountGroup() { + t.Errorf("expected VOLUME_MOUNT_GROUP to be false") + } }) } } @@ -707,7 +874,7 @@ func TestPlugin_Capabilities_DisableAttachDetachAfterUnimplemented(t *testing.T) } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) ctx := context.Background() plugin.InitControllerCapabilities(ctx) @@ -731,6 +898,51 @@ func TestPlugin_Capabilities_DisableAttachDetachAfterUnimplemented(t *testing.T) } } +func TestPlugin_MountVolume_VolumeMountGroup(t *testing.T) { + var stageGroup, publishGroup string + driver := &mockCSIDriver{ + nodeGetCapabilitiesFunc: func(ctx context.Context, req *csi.NodeGetCapabilitiesRequest) (*csi.NodeGetCapabilitiesResponse, error) { + var caps []*csi.NodeServiceCapability + for _, rpc := range []csi.NodeServiceCapability_RPC_Type{csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME, csi.NodeServiceCapability_RPC_VOLUME_MOUNT_GROUP} { + caps = append(caps, &csi.NodeServiceCapability{Type: &csi.NodeServiceCapability_Rpc{Rpc: &csi.NodeServiceCapability_RPC{Type: rpc}}}) + } + return &csi.NodeGetCapabilitiesResponse{Capabilities: caps}, nil + }, + nodeStageVolumeFunc: func(ctx context.Context, req *csi.NodeStageVolumeRequest) (*csi.NodeStageVolumeResponse, error) { + stageGroup = req.GetVolumeCapability().GetMount().GetVolumeMountGroup() + return &csi.NodeStageVolumeResponse{}, nil + }, + nodePublishVolumeFunc: func(ctx context.Context, req *csi.NodePublishVolumeRequest) (*csi.NodePublishVolumeResponse, error) { + publishGroup = req.GetVolumeCapability().GetMount().GetVolumeMountGroup() + return &csi.NodePublishVolumeResponse{}, nil + }, + } + endpoint, cleanup := startMockCSIDriver(t, driver) + defer cleanup() + + client, err := NewCSIClient(endpoint, nil) + if err != nil { + t.Fatalf("failed to create CSI client: %v", err) + } + defer client.Close() + + plugin := NewPlugin(client, mockDriverName) + tmpDir := t.TempDir() + plugin.stagingDirPrefix = filepath.Join(tmpDir, "staging") + ctx := context.Background() + plugin.InitNodeCapabilities(ctx) + if !plugin.SupportsVolumeMountGroup() { + t.Fatal("SupportsVolumeMountGroup() = false, want true") + } + + if err := plugin.MountVolume(ctx, volume.MountVolumeRequest{VolumeID: "test-vol", TargetPath: filepath.Join(tmpDir, "target"), VolumeMountGroup: "500"}); err != nil { + t.Fatalf("MountVolume failed: %v", err) + } + if stageGroup != "500" || publishGroup != "500" { + t.Errorf("volume_mount_group: NodeStageVolume %q, NodePublishVolume %q, want \"500\" for both", stageGroup, publishGroup) + } +} + func TestPlugin_Capabilities_DisableStageUnstageAfterUnimplemented(t *testing.T) { var stageCalled, unstageCalled int driver := &mockCSIDriver{ @@ -758,7 +970,7 @@ func TestPlugin_Capabilities_DisableStageUnstageAfterUnimplemented(t *testing.T) } defer client.Close() - plugin := NewPlugin(client) + plugin := NewPlugin(client, mockDriverName) tmpDir := t.TempDir() plugin.stagingDirPrefix = filepath.Join(tmpDir, "staging") targetPath := filepath.Join(tmpDir, "target") @@ -776,10 +988,13 @@ func TestPlugin_Capabilities_DisableStageUnstageAfterUnimplemented(t *testing.T) if plugin.SupportsNodeCapability(csi.NodeServiceCapability_RPC_STAGE_UNSTAGE_VOLUME) { t.Errorf("expected STAGE_UNSTAGE_VOLUME to be false after Unimplemented") } - stagingPath := filepath.Join(plugin.stagingDirPrefix, "test-vol") + stagingPath := plugin.stagingDir("test-vol") if _, err := os.Stat(stagingPath); !os.IsNotExist(err) { t.Errorf("expected staging directory %q to be removed, got err: %v", stagingPath, err) } + if _, err := os.Stat(filepath.Dir(stagingPath)); !os.IsNotExist(err) { + t.Errorf("expected per-volume hash directory %q to be removed, got err: %v", filepath.Dir(stagingPath), err) + } if err := plugin.UnmountVolume(ctx, "test-vol", targetPath); err != nil { t.Errorf("UnmountVolume failed: %v", err) @@ -811,6 +1026,10 @@ func TestNewCSIPlugin_CapabilityQueryFailureIsNotFatal(t *testing.T) { } defer plugin.client.Close() + if plugin.driverName != mockDriverName { + t.Errorf("driverName = %q, want %q", plugin.driverName, mockDriverName) + } + if isController && !plugin.SupportsControllerCapability(csi.ControllerServiceCapability_RPC_PUBLISH_UNPUBLISH_VOLUME) { t.Errorf("expected PUBLISH_UNPUBLISH_VOLUME to be true") } diff --git a/internal/volume/mock.go b/internal/volume/mock.go index 42938bc72e..a7394904db 100644 --- a/internal/volume/mock.go +++ b/internal/volume/mock.go @@ -58,14 +58,18 @@ func NewMockVolumePlugin() *MockVolumePlugin { // DriverName returns the driver name for mock plugin. func (p *MockVolumePlugin) DriverName(ctx context.Context) (string, error) { - return "substrate.io/mock", nil + return "mock.ate.dev", nil } // CreateVolume simulates volume provisioning. func (p *MockVolumePlugin) CreateVolume(ctx context.Context, req CreateVolumeRequest) (CreateVolumeResponse, error) { volumeID := "mock-vol-" + req.Name slog.InfoContext(ctx, "MockVolumePlugin.CreateVolume", slog.String("name", req.Name), slog.Int64("capacity_bytes", req.CapacityBytes), slog.String("volumeID", volumeID)) - return CreateVolumeResponse{VolumeID: volumeID, VolumeContext: req.Parameters}, nil + return CreateVolumeResponse{ + VolumeID: volumeID, + VolumeContext: req.Parameters, + ContentSourceSnapshotID: req.SourceSnapshotID, + }, nil } // DeleteVolume simulates volume deletion. @@ -80,8 +84,8 @@ func (p *MockVolumePlugin) AttachVolume(ctx context.Context, req AttachVolumeReq slog.InfoContext(ctx, "MockVolumePlugin.AttachVolume", slog.String("volumeID", req.VolumeID), slog.String("node", req.Node)) return AttachVolumeResponse{ PublishContext: map[string]string{ - "mock.substrate.io/attached-node": req.Node, - "mock.substrate.io/device-path": "/dev/mock-" + req.VolumeID, + "mock.ate.dev/attached-node": req.Node, + "mock.ate.dev/device-path": "/dev/mock-" + req.VolumeID, }, }, nil } @@ -92,6 +96,41 @@ func (p *MockVolumePlugin) DetachVolume(ctx context.Context, volumeID string, no return nil } +// CreateSnapshot simulates snapshotting a volume. Like the other control-plane +// methods it keeps no state, so the handle is derived from the request and the +// snapshot is immediately ready. +func (p *MockVolumePlugin) CreateSnapshot(ctx context.Context, req CreateSnapshotRequest) (Snapshot, error) { + snapshotID := "mock-snap-" + req.Name + slog.InfoContext(ctx, "MockVolumePlugin.CreateSnapshot", slog.String("name", req.Name), slog.String("sourceVolumeID", req.SourceVolumeID), slog.String("snapshotID", snapshotID)) + return Snapshot{ + SnapshotID: snapshotID, + SourceVolumeID: req.SourceVolumeID, + ReadyToUse: true, + }, nil +} + +// GetSnapshot reports any handle as present and ready. Being stateless, the +// mock cannot tell a handle it issued from one it did not. +func (p *MockVolumePlugin) GetSnapshot(ctx context.Context, snapshotID string) (Snapshot, bool, error) { + slog.InfoContext(ctx, "MockVolumePlugin.GetSnapshot", slog.String("snapshotID", snapshotID)) + return Snapshot{ + SnapshotID: snapshotID, + ReadyToUse: true, + }, true, nil +} + +// DeleteSnapshot simulates releasing a snapshot. +func (p *MockVolumePlugin) DeleteSnapshot(ctx context.Context, snapshotID string) error { + slog.InfoContext(ctx, "MockVolumePlugin.DeleteSnapshot", slog.String("snapshotID", snapshotID)) + return nil +} + +// ControllerCapabilities reports snapshot support, so that the mock exercises +// the same paths a snapshot-capable driver does. +func (p *MockVolumePlugin) ControllerCapabilities(ctx context.Context) (Capabilities, error) { + return Capabilities{CreateDeleteSnapshot: true, ListSnapshots: true}, nil +} + // MountVolume simulates mounting volume on the host. func (p *MockVolumePlugin) MountVolume(ctx context.Context, req MountVolumeRequest) error { slog.InfoContext(ctx, "MockVolumePlugin.MountVolume", slog.String("volumeID", req.VolumeID), slog.String("targetPath", req.TargetPath)) @@ -116,6 +155,11 @@ func (p *MockVolumePlugin) MountVolume(ctx context.Context, req MountVolumeReque return nil } +// SupportsVolumeMountGroup reports false, so atelet sets the group itself. +func (p *MockVolumePlugin) SupportsVolumeMountGroup() bool { + return false +} + // UnmountVolume simulates unmounting volume from the host. func (p *MockVolumePlugin) UnmountVolume(ctx context.Context, volumeID string, targetPath string) error { slog.InfoContext(ctx, "MockVolumePlugin.UnmountVolume", slog.String("volumeID", volumeID), slog.String("targetPath", targetPath)) diff --git a/internal/volume/plugin.go b/internal/volume/plugin.go index a3f9ca3aa9..a093511f95 100644 --- a/internal/volume/plugin.go +++ b/internal/volume/plugin.go @@ -26,6 +26,10 @@ type CreateVolumeRequest struct { CapacityBytes int64 // Parameters are the driver-specific parameters from the StorageClass. Parameters map[string]string + // SourceSnapshotID seeds the new volume from an existing snapshot. Empty + // provisions an empty volume. The snapshot must belong to the same driver: + // a handle means nothing to any other one. + SourceSnapshotID string } // CreateVolumeResponse describes a provisioned volume. @@ -35,6 +39,13 @@ type CreateVolumeResponse struct { // VolumeContext is driver-defined metadata that the node plugin needs to // mount the volume. VolumeContext map[string]string + // ContentSourceSnapshotID is the snapshot the driver reports it restored + // from, empty for an empty volume. It is in the driver's own format and + // need not equal SourceSnapshotID. A driver that ignores a requested source + // returns an empty volume and reports success, which for a restore is + // silent data loss, so plugins fail CreateVolume when a source was + // requested and none is reported. + ContentSourceSnapshotID string } // AttachVolumeRequest describes a volume to attach to a node. @@ -65,6 +76,54 @@ type MountVolumeRequest struct { // PublishContext is the metadata returned when the volume was attached to // this node. It is empty for drivers that do not implement attachment. PublishContext map[string]string + // VolumeMountGroup is the group ID the driver gives the volume's files, + // as a decimal string. Set only for drivers whose + // SupportsVolumeMountGroup reports true. Empty leaves ownership to the + // driver. + VolumeMountGroup string +} + +// CreateSnapshotRequest describes a snapshot to take. +type CreateSnapshotRequest struct { + // Name is the caller's name for the snapshot. Like volume provisioning, + // this is idempotent on Name: calling again with the same Name and + // SourceVolumeID returns the existing snapshot, which lets cleanup recover + // a handle it never recorded. + Name string + // SourceVolumeID is the volume to capture. + SourceVolumeID string + // Parameters are opaque driver parameters, passed through as the CSI + // CreateSnapshot parameters. No caller sets them yet, so drivers use their + // default snapshot settings. They can be expanded in the future to carry + // the parameters of a VolumeSnapshotClass-like object selected per volume. + Parameters map[string]string +} + +// Snapshot is a point-in-time copy of a volume held by the storage system. +type Snapshot struct { + // SnapshotID is the storage system's handle for the snapshot. + SnapshotID string + // SourceVolumeID is the volume it was captured from. + SourceVolumeID string + // ReadyToUse is whether the storage system has finished the copy. Drivers + // may return a handle before it is usable and finish in the background, so + // this is a point-in-time observation rather than a durable property. + ReadyToUse bool + // SizeBytes is the snapshot's size, or 0 if the driver did not report one. + SizeBytes int64 +} + +// Capabilities are the optional operations a driver's controller supports. +// These are a property of the driver, not of any one volume, so a plugin +// queries the driver once and reports them from its cached view. +type Capabilities struct { + // CreateDeleteSnapshot is whether the driver can snapshot volumes. Without + // it, a volume it provisions can never back a tag that captures volumes. + CreateDeleteSnapshot bool + // ListSnapshots is whether the driver can report a snapshot's state after + // creating it. Without it, readiness can only be observed in the + // CreateSnapshot response. + ListSnapshots bool } // VolumePluginControlPlane abstracts storage operations performed on the control plane. @@ -74,10 +133,27 @@ type VolumePluginControlPlane interface { DeleteVolume(ctx context.Context, volumeID string) error AttachVolume(ctx context.Context, req AttachVolumeRequest) (AttachVolumeResponse, error) DetachVolume(ctx context.Context, volumeID string, node string) error + // CreateSnapshot captures a volume. It may return before the copy is + // complete, with ReadyToUse false. + CreateSnapshot(ctx context.Context, req CreateSnapshotRequest) (Snapshot, error) + // GetSnapshot looks a snapshot up by handle, reporting whether the storage + // system still has it. A snapshot deleted out from under us is a missing + // snapshot, not an error. A driver that cannot look snapshots up returns + // an error wrapping errors.ErrUnsupported. + GetSnapshot(ctx context.Context, snapshotID string) (snapshot Snapshot, found bool, err error) + // DeleteSnapshot releases a snapshot. Deleting one that is already gone + // succeeds, so that cleanup can be retried. + DeleteSnapshot(ctx context.Context, snapshotID string) error + // ControllerCapabilities reports which optional operations the driver + // supports. + ControllerCapabilities(ctx context.Context) (Capabilities, error) } // VolumePluginWorkerPlane abstracts storage operations performed on worker nodes. type VolumePluginWorkerPlane interface { MountVolume(ctx context.Context, req MountVolumeRequest) error UnmountVolume(ctx context.Context, volumeID string, targetPath string) error + // SupportsVolumeMountGroup reports whether the driver applies + // MountVolumeRequest.VolumeMountGroup itself. + SupportsVolumeMountGroup() bool } diff --git a/internal/wakeupprobe/wakeupprobe.go b/internal/wakeupprobe/wakeupprobe.go index fc9c805770..308acd6bb8 100644 --- a/internal/wakeupprobe/wakeupprobe.go +++ b/internal/wakeupprobe/wakeupprobe.go @@ -28,6 +28,8 @@ import ( "log/slog" "net" "net/http" + "net/url" + "strconv" "strings" "time" @@ -185,5 +187,14 @@ func URL(probe *ateworkerpb.WakeupProbe, actorIP string) (string, error) { if !strings.HasPrefix(path, "/") { path = "/" + path } - return fmt.Sprintf("http://%s:%d%s", actorIP, port, path), nil + decodedPath, err := url.PathUnescape(path) + if err != nil { + return "", fmt.Errorf("invalid path %q: %w", path, err) + } + return (&url.URL{ + Scheme: "http", + Host: net.JoinHostPort(actorIP, strconv.Itoa(int(port))), + Path: decodedPath, + RawPath: path, + }).String(), nil } diff --git a/internal/wakeupprobe/wakeupprobe_test.go b/internal/wakeupprobe/wakeupprobe_test.go index 9ecf0798cd..67cc2b7c41 100644 --- a/internal/wakeupprobe/wakeupprobe_test.go +++ b/internal/wakeupprobe/wakeupprobe_test.go @@ -55,6 +55,12 @@ func TestURL(t *testing.T) { actorIP: "10.0.0.1", want: "http://10.0.0.1:80/ready", }, + { + name: "escaped path", + probe: &ateworkerpb.WakeupProbe{HttpGet: &ateworkerpb.HttpGetAction{Path: "/ready%20now", Port: 80}}, + actorIP: "169.254.17.2", + want: "http://169.254.17.2:80/ready%20now", + }, { name: "missing httpGet", probe: &ateworkerpb.WakeupProbe{}, diff --git a/internal/workerstats/usage.go b/internal/workerstats/usage.go index 4058dbcb8a..55cedced74 100644 --- a/internal/workerstats/usage.go +++ b/internal/workerstats/usage.go @@ -83,11 +83,13 @@ func UsageAttrs(pool Pool, kind string, s *ateworkerpb.WorkloadStatsSample) []sl if s.GetSource() == ateworkerpb.StatsSource_STATS_SOURCE_UNSPECIFIED { return attrs } - attrs = append(attrs, - slog.Uint64(string(ateattr.StatsMemoryUsageKey), s.GetMemoryCurrentBytes()), - slog.Uint64(string(ateattr.StatsMemoryWorkingSetKey), s.GetMemoryWorkingSetBytes()), - slog.Float64(string(ateattr.StatsCPUTimeKey), float64(s.GetCpuUsageUsec())/1e6), - ) + // Not measured after a gVisor sandbox died: measured CPU, no memory. + if !s.GetMemoryUnmeasured() { + attrs = append(attrs, + slog.Uint64(string(ateattr.StatsMemoryUsageKey), s.GetMemoryCurrentBytes()), + slog.Uint64(string(ateattr.StatsMemoryWorkingSetKey), s.GetMemoryWorkingSetBytes())) + } + attrs = append(attrs, slog.Float64(string(ateattr.StatsCPUTimeKey), float64(s.GetCpuUsageUsec())/1e6)) if peak := s.GetMemoryPeakBytes(); peak > 0 { attrs = append(attrs, slog.Uint64(string(ateattr.StatsMemoryPeakKey), peak)) } diff --git a/internal/workerstats/usage_test.go b/internal/workerstats/usage_test.go index 10826379e6..1285b94f11 100644 --- a/internal/workerstats/usage_test.go +++ b/internal/workerstats/usage_test.go @@ -23,6 +23,8 @@ import ( "testing/synctest" "time" + "go.opentelemetry.io/otel/attribute" + "go.ate.dev/substrate/internal/actorevent" "go.ate.dev/substrate/internal/ateattr" "go.ate.dev/substrate/internal/proto/ateworkerpb" @@ -98,6 +100,27 @@ func TestUsageAttrsMeasured(t *testing.T) { } } +// TestUsageAttrsMemoryUnmeasured pins that a measured sample whose memory was +// not measured, as after a gVisor sandbox died, writes its CPU and peak but no +// memory usage or working set, rather than measured zeros. +func TestUsageAttrsMemoryUnmeasured(t *testing.T) { + t.Parallel() + s := measuredSample() + s.MemoryCurrentBytes, s.MemoryWorkingSetBytes, s.MemoryUnmeasured = 0, 0, true + got := attrMap(UsageAttrs(testPool, ateattr.StatsKindFinal, s)) + checkShape(t, got) + for _, k := range []attribute.Key{ateattr.StatsMemoryUsageKey, ateattr.StatsMemoryWorkingSetKey} { + if _, ok := got[string(k)]; ok { + t.Errorf("record carries %q, want it absent", k) + } + } + for _, k := range []attribute.Key{ateattr.StatsCPUTimeKey, ateattr.StatsMemoryPeakKey} { + if _, ok := got[string(k)]; !ok { + t.Errorf("record is missing %q", k) + } + } +} + func TestUsageAttrsPendingHasNoMeasurements(t *testing.T) { t.Parallel() s := measuredSample() diff --git a/internal/workerstats/workerstatstest/workerstatstest.go b/internal/workerstats/workerstatstest/workerstatstest.go index 01e5072357..0238ef0c62 100644 --- a/internal/workerstats/workerstatstest/workerstatstest.go +++ b/internal/workerstats/workerstatstest/workerstatstest.go @@ -24,11 +24,12 @@ import ( "go.ate.dev/substrate/internal/workerstats" ) -// Recorder is a stdout handler that keeps the kind and source of each record. +// Recorder is a stdout handler that keeps the attributes of each record. type Recorder struct { mu sync.Mutex kinds []string srcs []string + attrs []map[string]string } // NewEmitter returns an emitter that writes every record to a new Recorder. @@ -51,12 +52,22 @@ func (r *Recorder) Sources() []string { return append([]string(nil), r.srcs...) } +// Value is the attribute key of the i-th record, or "" when it is absent. +func (r *Recorder) Value(i int, key string) string { + r.mu.Lock() + defer r.mu.Unlock() + return r.attrs[i][key] +} + func (r *Recorder) Enabled(context.Context, slog.Level) bool { return true } func (r *Recorder) Handle(_ context.Context, rec slog.Record) error { r.mu.Lock() defer r.mu.Unlock() + attrs := map[string]string{} + r.attrs = append(r.attrs, attrs) rec.Attrs(func(a slog.Attr) bool { + attrs[a.Key] = a.Value.String() switch a.Key { case string(ateattr.StatsKindKey): r.kinds = append(r.kinds, a.Value.String()) diff --git a/logo/README.md b/logo/README.md index 00caed0439..06477c23fc 100644 --- a/logo/README.md +++ b/logo/README.md @@ -5,4 +5,9 @@ This is Yolo the octopus, the logo and mascot of the Agent Substrate project. Yolo is a friendly and intelligent octopus that represents the project's focus on adaptability, intelligence, and versatility in building AI agents. +Yolo's 3 robot puppets are named: + - b5d48c9b-f990-e499-ecd4-a691f086e4d4 (blue) + - dd91bdd4-b583-a580-f69c-e4d4e19cad87 (yellow) + - c29ca580-d69b-b198-f1b3-aba3e79baa93 (pink) + Yolo was designed and donated to the project by Nan Hockin. diff --git a/logo/ate-logo-with-border.png b/logo/ate-logo-with-border.png index 203375c9f4..2b2e880a63 100644 Binary files a/logo/ate-logo-with-border.png and b/logo/ate-logo-with-border.png differ diff --git a/logo/ate-logo-with-border.svg b/logo/ate-logo-with-border.svg index ea7cd6cf14..d5c8e35b6f 100644 --- a/logo/ate-logo-with-border.svg +++ b/logo/ate-logo-with-border.svg @@ -31,831 +31,21 @@ inkscape:pagecheckerboard="0" inkscape:deskcolor="#d1d1d1" inkscape:document-units="mm" - inkscape:zoom="1" - inkscape:cx="176.5" - inkscape:cy="602" - inkscape:window-width="3440" - inkscape:window-height="1363" + inkscape:zoom="0.74687968" + inkscape:cx="436.48262" + inkscape:cy="362.84291" + inkscape:window-width="1920" + inkscape:window-height="1123" inkscape:window-x="0" inkscape:window-y="0" inkscape:window-maximized="1" - inkscape:current-layer="g124" + inkscape:current-layer="layer2" showgrid="false" showguides="false" />Yolo the octopusNan HockinThe Agent Substrate ProjectTim HockinAugust 23, 2026 + rdf:resource="http://creativecommons.org/ns#DerivativeWorks" /> diff --git a/logo/ate-logo.png b/logo/ate-logo.png index d27443c0ff..8bc4a9225f 100644 Binary files a/logo/ate-logo.png and b/logo/ate-logo.png differ diff --git a/logo/ate-logo.svg b/logo/ate-logo.svg index 94b960ca63..822c2198d7 100644 --- a/logo/ate-logo.svg +++ b/logo/ate-logo.svg @@ -31,15 +31,15 @@ inkscape:pagecheckerboard="0" inkscape:deskcolor="#d1d1d1" inkscape:document-units="mm" - inkscape:zoom="0.7071068" - inkscape:cx="2.1213203" - inkscape:cy="496.38895" - inkscape:window-width="3440" - inkscape:window-height="1363" + inkscape:zoom="0.85031784" + inkscape:cx="403.96659" + inkscape:cy="606.83191" + inkscape:window-width="1920" + inkscape:window-height="1123" inkscape:window-x="0" inkscape:window-y="0" inkscape:window-maximized="1" - inkscape:current-layer="svg1" + inkscape:current-layer="layer1" showgrid="false" showguides="false" /> diff --git a/manifests/ate-install/ate-api-server.yaml b/manifests/ate-install/ate-api-server.yaml index 2d55f435d4..4732f13325 100644 --- a/manifests/ate-install/ate-api-server.yaml +++ b/manifests/ate-install/ate-api-server.yaml @@ -27,6 +27,9 @@ rules: - apiGroups: [""] resources: ["nodes"] verbs: ["get"] +# ate-api-server no longer reads WorkerPools, but ate-setup deploy apiserver +# applies this ClusterRole before rolling the Deployment. Keep workerpools +# until the next minor release so older replicas still start during an upgrade. - apiGroups: ["ate.dev"] resources: ["workerpools", "csidriverconfigs"] verbs: ["get", "watch", "list"] @@ -81,6 +84,9 @@ spec: spec: # TODO: Add topologySpreadConstraints to spread replicas across nodes and zones. serviceAccountName: ate-api-server + # Only ate-api-server calls the Kubernetes API, so only it mounts the + # token (kube-api-access below). + automountServiceAccountToken: false # Budget for the full shutdown sequence: --drain-delay (sized to cover # the readinessProbe below reaching NotReady, plus propagation) + # --drain-timeout. @@ -194,6 +200,7 @@ spec: # Run/Restore, ateworker hands it to atunnel, and actor TCP egress is # transparently redirected (nftables) into atunnel, which wraps it in # mTLS + HTTP CONNECT to the egress gateway. + # ate-setup replaces the value with its --default-egress-gateway-address setting. - --default-egress-gateway-address=atenet-egress.ate-system.svc:443 # Graceful shutdown knobs. The sum must fit within terminationGracePeriodSeconds. - --drain-delay=13s @@ -277,6 +284,9 @@ spec: - name: "postgres-server-ca" mountPath: "/run/postgres-server-ca" readOnly: true + - name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true ports: - containerPort: 443 - name: prometheus @@ -386,6 +396,21 @@ spec: secret: secretName: "postgres-server-ca" optional: true + - name: kube-api-access + projected: + sources: + - serviceAccountToken: + path: token + - configMap: + name: kube-root-ca.crt + items: + - key: ca.crt + path: ca.crt + - downwardAPI: + items: + - path: namespace + fieldRef: + fieldPath: metadata.namespace --- # Allow voluntary disruptions (node drains, cluster upgrades) to take # at most one API server pod at a time, at any replica count. diff --git a/manifests/ate-install/ate-idp-server.yaml b/manifests/ate-install/ate-idp-server.yaml index 58f3bd8460..21a2a4982f 100644 --- a/manifests/ate-install/ate-idp-server.yaml +++ b/manifests/ate-install/ate-idp-server.yaml @@ -41,6 +41,7 @@ spec: app: ate-idp-server spec: serviceAccountName: ate-idp-server + automountServiceAccountToken: false containers: - name: ate-idp-server image: ko://go.ate.dev/substrate/cmd/ate-idp-server diff --git a/manifests/ate-install/ate-otel-config.yaml b/manifests/ate-install/ate-otel-config.yaml index ac0f3e2315..9a36f6bff5 100644 --- a/manifests/ate-install/ate-otel-config.yaml +++ b/manifests/ate-install/ate-otel-config.yaml @@ -14,7 +14,10 @@ # Single source of truth for the OTLP exporter settings shared by every control # plane component (ate-api-server, ate-controller, atelet, atenet-router, -# atenet-egress), which consume it via `envFrom`. ate-controller additionally propagates these values +# atenet-egress, k8s-credential-provider), which consume it via `envFrom`. +# k8s-credential-provider exists only when the k8s.io credential provider is +# selected, and comes from manifests/egress-credential-injection, so a restart +# of the bundle workloads does not restart it. ate-controller additionally propagates these values # to the worker pods it creates, which have no other way to receive them, # and atenet-router's --otlp-collector-address defaults to the endpoint below, # so Envoy's own spans follow it too. The exporter selection is the exception: diff --git a/manifests/ate-install/atelet.yaml b/manifests/ate-install/atelet.yaml index 7036665b2a..0d1e9b9ce2 100644 --- a/manifests/ate-install/atelet.yaml +++ b/manifests/ate-install/atelet.yaml @@ -31,10 +31,10 @@ rules: - apiGroups: ["ate.dev"] resources: ["csidriverconfigs"] verbs: ["get", "list", "watch"] -# SandboxConfigs are watched to pre-download sandbox assets into the node's -# cache before the first actor needs them (see cmd/atelet/sandbox_prewarm.go), -# and to write the runtimes of the configs local workers use to each worker's -# sandbox runtimes file (see cmd/atelet/worker_sandbox_syncer.go). +# SandboxConfigs are watched to write the runtimes of the configs local +# workers use to each worker's sandbox runtimes file, with the default +# runtime's assets fetched into the node's cache and linked under the +# worker's directory (see cmd/atelet/worker_sandbox_syncer.go). - apiGroups: ["ate.dev"] resources: ["sandboxconfigs"] verbs: ["get", "list", "watch"] @@ -143,6 +143,9 @@ spec: prometheus.io/port: "9090" spec: serviceAccountName: atelet + # Only atelet calls the Kubernetes API, so only it mounts the token + # (kube-api-access below). + automountServiceAccountToken: false priorityClassName: system-cluster-critical # Budget for the full shutdown sequence: --drain-delay (0 for atelet) + # --drain-timeout (5m). Sized long because Checkpoint/Restore stream @@ -383,6 +386,9 @@ spec: - name: image-credential-provider-config mountPath: /run/image-credential-provider/config.yaml readOnly: true + - name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true volumes: - name: objectstore-plugin emptyDir: {} @@ -454,3 +460,18 @@ spec: matchLabels: podcert.ate.dev/canarying: live path: trust-bundle.pem + - name: kube-api-access + projected: + sources: + - serviceAccountToken: + path: token + - configMap: + name: kube-root-ca.crt + items: + - key: ca.crt + path: ca.crt + - downwardAPI: + items: + - path: namespace + fieldRef: + fieldPath: metadata.namespace diff --git a/manifests/ate-install/atenet-egress.yaml b/manifests/ate-install/atenet-egress.yaml index 5e8745027e..93cbdf9e31 100644 --- a/manifests/ate-install/atenet-egress.yaml +++ b/manifests/ate-install/atenet-egress.yaml @@ -31,6 +31,7 @@ kind: ServiceAccount metadata: name: atenet-egress namespace: ate-system +automountServiceAccountToken: false # # No RBAC is bound to this ServiceAccount on purpose: the ext_proc sidecar runs # with --mode=egress, which serves the egress ext_proc handler and nothing else @@ -54,11 +55,29 @@ data: admin: address: # Loopback only. The admin API is unauthenticated and includes - # /quitquitquit, /drain_listeners, /runtime_modify and /config_dump, - # so it must not be reachable on the pod IP. The ext_proc sidecar's - # drain sequence dials it on 127.0.0.1; the kubelet probes go through - # the envoy_metrics listener below. + # /drain_listeners and /runtime_modify, so it must not be reachable on + # the pod IP. The ext_proc sidecar's drain sequence dials it on + # 127.0.0.1; the kubelet probes go through the envoy_metrics listener + # below. socket_address: { address: 127.0.0.1, port_value: 15000 } + # Any other admin path, such as /quitquitquit or /config_dump, answers + # 403. Envoy matches an entry against the path with its query string, so + # a path that takes parameters needs a prefix. + allow_paths: + # The gateway needs these four to run and to shut down. + - exact: /ready # Read-only. The kubelet probes. + - prefix: /stats # Read-only. Scrapes and the drain sequence. + - exact: /healthcheck/fail # The drain sequence. + - prefix: /drain_listeners # The drain sequence. + # Operators use these two for the access_log runtime keys. + - exact: /runtime # Read-only. + - prefix: /runtime_modify # Sets any runtime key. + + # /runtime_modify writes to the admin layer. + layered_runtime: + layers: + - name: admin + admin_layer: {} # Required by the mitm_listener below. An internal listener has no socket, # so it is reachable only through a cluster with an envoy_internal_address; @@ -77,6 +96,14 @@ data: socket_address: { address: "::", ipv4_compat: true, port_value: 443 } # Limit single I/O read to 64 Kb to prevent overly active actors from starving other actors. per_connection_buffer_limit_bytes: 65535 + # TCP_NOTSENT_LOWAT on the sockets from atunnel, as on the forward + # proxy clusters below. + socket_options: + - description: TCP_NOTSENT_LOWAT + level: 6 # IPPROTO_TCP + name: 25 # TCP_NOTSENT_LOWAT + int_value: 16384 + state: STATE_PREBIND filter_chains: # Named so ext_proc can read it back as xds.filter_chain_name. Must # match EgressFilterChainName in @@ -400,14 +427,25 @@ data: typed_config: "@type": type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager stat_prefix: mitm_http - # The egress request filter returns the explanatory 403. Keep - # the HCM default disabled as a defense if a request ever gets - # past that decision. + # WebSocket is the only upgrade supported. The egress request + # filter is the only gate: it refuses any other. upgrade_configs: - upgrade_type: websocket - enabled: false # Disable stream_idle_timeout as there is already an overall timeout in the outer tunnel in the HCM. stream_idle_timeout: 0s + # Tells a denied address (resolved_address_filter below) apart + # from a name that failed to resolve. Both are 503 otherwise. + local_reply_config: &address_denied_reply + mappers: + - filter: + extension_filter: + name: envoy.access_loggers.extension_filters.cel + typed_config: + "@type": type.googleapis.com/envoy.extensions.access_loggers.filters.cel.v3.ExpressionFilter + expression: "response.code_details.contains('address_denied')" + status_code: 403 + body: + inline_string: "egress gateway does not connect to loopback, link-local or metadata addresses\n" # This is the leg that knows where the traffic actually went. # REQUESTED_SERVER_NAME is the SNI the leaf was minted for and it # should equal the authority, which is what the routes resolve @@ -418,7 +456,10 @@ data: # wrong, including gRPC errors sent with HTTP 200, and a sample # of the rest. The runtime keys let an operator turn full # logging back on at the admin port: - # /runtime_modify?access_log.min_status=0. + # POST /runtime_modify?access_log.min_status=0. + # An empty value removes the override: + # POST /runtime_modify?access_log.min_status=. + # GET /runtime shows the active values. filter: or_filter: filters: @@ -454,6 +495,7 @@ data: status: "%RESPONSE_CODE%" grpc_status: "%GRPC_STATUS%" flags: "%RESPONSE_FLAGS%" + details: "%RESPONSE_CODE_DETAILS%" duration_ms: "%DURATION%" bytes_sent: "%BYTES_SENT%" bytes_rcvd: "%BYTES_RECEIVED%" @@ -467,14 +509,31 @@ data: domains: ["*"] routes: # There is no default route: the initial route lookup cannot - # match before ext_proc supplies dev.ate.egress:dial. This - # lets the request filter return the unsupported-upgrade - # response before route-level upgrade rejection. Each route - # also needs the answered name (dev.ate.egress:host); without - # it the forward proxy would dial the Host's port. + # match before ext_proc supplies dev.ate.egress:dial. Each + # route also needs the answered name (dev.ate.egress:host); + # without it the forward proxy would dial the Host's port. + # + # WebSocket uses HTTP/1.1 only between the gateway and the + # origin. This route keeps Envoy's default 15s timeout, which + # covers only the handshake: Envoy stops it at the 101. + - match: + prefix: "/" + headers: + - name: upgrade + string_match: + exact: websocket + ignore_case: true + dynamic_metadata: + - filter: dev.ate.egress + path: [{ key: dial }] + value: { string_match: { exact: name } } + - filter: dev.ate.egress + path: [{ key: host }] + value: { present_match: true } + route: + cluster: egress_forward_proxy_websocket # Native gRPC uses upstream ALPN to negotiate h2 and carry - # status in trailers. Other requests stay on HTTP/1.1; the - # content-type match keeps those protocol choices separate. + # status in trailers. - match: prefix: "/" headers: @@ -490,9 +549,6 @@ data: value: { present_match: true } route: cluster: egress_forward_proxy_grpc - upgrade_configs: - - upgrade_type: websocket - enabled: false timeout: 0s - match: prefix: "/" @@ -505,9 +561,6 @@ data: value: { present_match: true } route: cluster: egress_forward_proxy - upgrade_configs: - - upgrade_type: websocket - enabled: false # The route timeout runs until the response completes, which # for SSE or long-poll is never, so 0. timeout: 0s @@ -575,12 +628,40 @@ data: typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.dynamic_forward_proxy.v3.FilterConfig allow_dynamic_host_from_filter_state: true - dns_cache_config: + # Every forward proxy filter and cluster below uses this + # cache through the alias, and Envoy rejects two different + # configs under one cache name. + dns_cache_config: &egress_dns_cache name: egress_dns_cache # V4_ONLY resolves nothing on an IPv6-only cluster. ALL # returns both families and enables Happy Eyeballs, so # neither family is stranded. dns_lookup_family: ALL + # The gateway never dials these, even for a "*" rule or a + # name that resolves to them: loopback (this pod's admin + # and ext_proc ports), link-local, unspecified, and the + # cloud metadata servers. The filter also applies to IP + # literals. A name that resolves only to these fails with + # 503 (dns_resolution_failure{address_denied}). + resolved_address_filter: + ranges: + - { address_prefix: 0.0.0.0, prefix_len: 8 } + - { address_prefix: 127.0.0.0, prefix_len: 8 } + - { address_prefix: 169.254.0.0, prefix_len: 16 } + - { address_prefix: "::", prefix_len: 128 } + - { address_prefix: "::1", prefix_len: 128 } + - { address_prefix: "fe80::", prefix_len: 10 } + # IPv4-mapped forms of the ranges above. + - { address_prefix: "::ffff:0.0.0.0", prefix_len: 104 } + - { address_prefix: "::ffff:127.0.0.0", prefix_len: 104 } + - { address_prefix: "::ffff:169.254.0.0", prefix_len: 112 } + # IPv6 metadata servers. + # GCE: https://cloud.google.com/compute/docs/metadata/querying-metadata + - { address_prefix: "fd20:ce::254", prefix_len: 128 } + # AWS: https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/instancedata-data-retrieval.html + - { address_prefix: "fd00:ec2::254", prefix_len: 128 } + # EKS Pod Identity: https://docs.aws.amazon.com/eks/latest/userguide/pod-identities.html + - { address_prefix: "fd00:ec2::23", prefix_len: 128 } - name: envoy.filters.http.router typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router @@ -633,20 +714,22 @@ data: # answers it 426 before any filter runs. http_protocol_options: accept_http_10: true - # The egress request filter returns the explanatory 403. Keep - # the HCM default disabled as a defense if a request ever gets - # past that decision. + # WebSocket is the only upgrade supported. The egress request + # filter is the only gate: it refuses any other. upgrade_configs: - upgrade_type: websocket - enabled: false stream_idle_timeout: 0s + local_reply_config: *address_denied_reply access_log: - name: envoy.access_loggers.file # Every actor request lands here, so log the ones that went # wrong, including gRPC errors sent with HTTP 200, and a sample # of the rest. The runtime keys let an operator turn full # logging back on at the admin port: - # /runtime_modify?access_log.min_status=0. + # POST /runtime_modify?access_log.min_status=0. + # An empty value removes the override: + # POST /runtime_modify?access_log.min_status=. + # GET /runtime shows the active values. filter: or_filter: filters: @@ -681,6 +764,7 @@ data: status: "%RESPONSE_CODE%" grpc_status: "%GRPC_STATUS%" flags: "%RESPONSE_FLAGS%" + details: "%RESPONSE_CODE_DETAILS%" duration_ms: "%DURATION%" bytes_sent: "%BYTES_SENT%" bytes_rcvd: "%BYTES_RECEIVED%" @@ -697,6 +781,10 @@ data: # no route. The route also needs the answered name # (dev.ate.egress:host); without it the forward proxy would # dial the Host's port. + # + # A WebSocket handshake needs no route of its own here: the + # cluster speaks the protocol the actor did, and a handshake + # arrives over HTTP/1.1. routes: - match: prefix: "/" @@ -709,9 +797,6 @@ data: value: { present_match: true } route: cluster: egress_forward_proxy_cleartext - upgrade_configs: - - upgrade_type: websocket - enabled: false timeout: 0s http_filters: # Every request on this chain is authorized against the actor's @@ -777,9 +862,7 @@ data: typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.dynamic_forward_proxy.v3.FilterConfig allow_dynamic_host_from_filter_state: true - dns_cache_config: - name: egress_dns_cache - dns_lookup_family: ALL + dns_cache_config: *egress_dns_cache - name: envoy.filters.http.router typed_config: "@type": type.googleapis.com/envoy.extensions.filters.http.router.v3.Router @@ -788,15 +871,13 @@ data: # The gateway resolves the SNI itself and relays the bytes to it unread, # on the port the actor dialed. The address the actor dialed plays no # part: an SNI only authorizes a dial to the name it claims - # (docs/network-egress.md). + # (docs/guides/egress-traffic.md). - name: egress_passthrough filters: - name: envoy.filters.network.sni_dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.filters.network.sni_dynamic_forward_proxy.v3.FilterConfig - dns_cache_config: - name: egress_dns_cache - dns_lookup_family: ALL + dns_cache_config: *egress_dns_cache # Fallback when envoy.upstream.dynamic_port is absent; the CONNECT # leg always sets it. port_value: 443 @@ -990,6 +1071,17 @@ data: - name: egress_forward_proxy lb_policy: CLUSTER_PROVIDED connect_timeout: 5s + # TCP_NOTSENT_LOWAT: accept writes only while fewer than 16 KiB wait + # unsent, so data for a slow destination stays upstream instead of in + # the kernel. SO_SNDBUF and SO_RCVBUF stay unset: a fixed size turns + # off autotuning and caps a connection at about the size per round trip. + upstream_bind_config: + socket_options: + - description: TCP_NOTSENT_LOWAT + level: 6 # IPPROTO_TCP + name: 25 # TCP_NOTSENT_LOWAT + int_value: 16384 + state: STATE_PREBIND # Fits 1000 destinations x 32 worker threads x 2 requests at once per # destination per thread = 64000 connections. circuit_breakers: @@ -1002,14 +1094,12 @@ data: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig - dns_cache_config: - name: egress_dns_cache - dns_lookup_family: ALL + dns_cache_config: *egress_dns_cache # The MITM must not weaken upstream authentication. Envoy decrypted the # actor's TLS with a leaf of its own; it still sends the real SNI here - # and still validates the real origin's certificate against the public - # roots. Without this the re-originated request would leave the pod in - # plaintext. + # and still validates the real origin's certificate against the roots in + # sds-egress-upstream-validation.yaml. Without this the re-originated + # request would leave the pod in plaintext. # # Spelled through typed_extension_protocol_options because the # cluster-level upstream_http_protocol_options field is deprecated. @@ -1032,20 +1122,37 @@ data: typed_config: "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext common_tls_context: - validation_context: - trusted_ca: - filename: /etc/ssl/certs/ca-certificates.crt + validation_context_sds_secret_config: + name: egress_upstream_validation_context + sds_config: + resource_api_version: V3 + path_config_source: + path: /etc/envoy/sds-egress-upstream-validation.yaml - name: egress_forward_proxy_grpc lb_policy: CLUSTER_PROVIDED connect_timeout: 5s + # TCP_NOTSENT_LOWAT, as on egress_forward_proxy. + upstream_bind_config: + socket_options: + - description: TCP_NOTSENT_LOWAT + level: 6 # IPPROTO_TCP + name: 25 # TCP_NOTSENT_LOWAT + int_value: 16384 + state: STATE_PREBIND + # Sized like egress_forward_proxy. A streaming call counts toward + # max_requests until it ends. + circuit_breakers: + thresholds: + - priority: DEFAULT + max_connections: 65536 + max_pending_requests: 65536 + max_requests: 65536 cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig - dns_cache_config: - name: egress_dns_cache - dns_lookup_family: ALL + dns_cache_config: *egress_dns_cache typed_extension_protocol_options: envoy.extensions.upstreams.http.v3.HttpProtocolOptions: "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions @@ -1060,9 +1167,59 @@ data: typed_config: "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext common_tls_context: - validation_context: - trusted_ca: - filename: /etc/ssl/certs/ca-certificates.crt + validation_context_sds_secret_config: + name: egress_upstream_validation_context + sds_config: + resource_api_version: V3 + path_config_source: + path: /etc/envoy/sds-egress-upstream-validation.yaml + + # The MITM leg's forward proxy for WebSocket handshakes. It is + # egress_forward_proxy limited to HTTP/1.1, so ALPN cannot select h2. + - name: egress_forward_proxy_websocket + lb_policy: CLUSTER_PROVIDED + connect_timeout: 5s + # At most 65536 WebSockets can be open through one gateway pod. Past + # that, a new handshake waits for a connection to free up or fails + # with 503, depending on whether its pool already has connections. + circuit_breakers: + thresholds: + - priority: DEFAULT + max_connections: 65536 + max_pending_requests: 65536 + max_requests: 65536 + # TCP_NOTSENT_LOWAT, as on egress_forward_proxy. + upstream_bind_config: + socket_options: + - description: TCP_NOTSENT_LOWAT + level: 6 # IPPROTO_TCP + name: 25 # TCP_NOTSENT_LOWAT + int_value: 16384 + state: STATE_PREBIND + cluster_type: + name: envoy.clusters.dynamic_forward_proxy + typed_config: + "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig + dns_cache_config: *egress_dns_cache + typed_extension_protocol_options: + envoy.extensions.upstreams.http.v3.HttpProtocolOptions: + "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions + upstream_http_protocol_options: + auto_sni: true + auto_san_validation: true + explicit_http_config: + http_protocol_options: {} + transport_socket: + name: envoy.transport_sockets.tls + typed_config: + "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.UpstreamTlsContext + common_tls_context: + validation_context_sds_secret_config: + name: egress_upstream_validation_context + sds_config: + resource_api_version: V3 + path_config_source: + path: /etc/envoy/sds-egress-upstream-validation.yaml # The cleartext chain's upstream. Identical to egress_forward_proxy but # without the TLS transport socket: the actor sent plaintext and this @@ -1075,6 +1232,14 @@ data: - name: egress_forward_proxy_cleartext lb_policy: CLUSTER_PROVIDED connect_timeout: 5s + # TCP_NOTSENT_LOWAT, as on egress_forward_proxy. + upstream_bind_config: + socket_options: + - description: TCP_NOTSENT_LOWAT + level: 6 # IPPROTO_TCP + name: 25 # TCP_NOTSENT_LOWAT + int_value: 16384 + state: STATE_PREBIND # Sized like egress_forward_proxy, for the same reason. circuit_breakers: thresholds: @@ -1086,9 +1251,7 @@ data: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig - dns_cache_config: - name: egress_dns_cache - dns_lookup_family: ALL + dns_cache_config: *egress_dns_cache # Envoy refuses to build a dynamic forward proxy cluster without # auto_sni and auto_san_validation unless this is set, because for # the usual TLS case resolving the host from a header and then not @@ -1112,13 +1275,26 @@ data: - name: egress_forward_proxy_passthrough lb_policy: CLUSTER_PROVIDED connect_timeout: 5s + # TCP_NOTSENT_LOWAT, as on egress_forward_proxy. + upstream_bind_config: + socket_options: + - description: TCP_NOTSENT_LOWAT + level: 6 # IPPROTO_TCP + name: 25 # TCP_NOTSENT_LOWAT + int_value: 16384 + state: STATE_PREBIND + # Sized like egress_forward_proxy, for the same reason. + circuit_breakers: + thresholds: + - priority: DEFAULT + max_connections: 65536 + max_pending_requests: 65536 + max_requests: 65536 cluster_type: name: envoy.clusters.dynamic_forward_proxy typed_config: "@type": type.googleapis.com/envoy.extensions.clusters.dynamic_forward_proxy.v3.ClusterConfig - dns_cache_config: - name: egress_dns_cache - dns_lookup_family: ALL + dns_cache_config: *egress_dns_cache #ATE_MITM_EXTPROC_CLUSTER -- Don't modify this line. # SDS resource for the gateway serving cert. kubelet rotates the projected @@ -1141,6 +1317,15 @@ data: validation_context: trusted_ca: { filename: /run/actor-id-ca-certs/ca.crt } watched_directory: { path: /run/actor-id-ca-certs } + # SDS resource for the roots the forward proxy clusters trust when they open + # TLS to an origin: the public roots in the Envoy image. ate-setup replaces + # this key when --egress-upstream-ca-bundle-configmap is set. + sds-egress-upstream-validation.yaml: | + resources: + - "@type": type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.Secret + name: egress_upstream_validation_context + validation_context: + trusted_ca: { filename: /etc/ssl/certs/ca-certificates.crt } # The next two keys are used only by the additional_egress_ext_proc cluster # spliced over the #ATE_MITM_EXTPROC_CLUSTER marker. They ship # unconditionally because the splice can only rewrite envoy.yaml, not add @@ -1179,6 +1364,7 @@ spec: app: atenet-egress spec: serviceAccountName: atenet-egress + automountServiceAccountToken: false # sdsmint and envoy containers must share a UID: sdsmint creates the SDS socket mode # 0600, and Envoy has to be able to open it. The stock Envoy image runs as # UID 101 and ko's distroless base as 65532, so left alone they would not diff --git a/manifests/ate-install/atenet-router.yaml b/manifests/ate-install/atenet-router.yaml index 35b630c470..0ab61b4666 100644 --- a/manifests/ate-install/atenet-router.yaml +++ b/manifests/ate-install/atenet-router.yaml @@ -154,8 +154,7 @@ data: port_value: 9901 - name: xds_cluster connect_timeout: 0.25s - type: STRICT_DNS - lb_policy: ROUND_ROBIN + type: STATIC typed_extension_protocol_options: envoy.extensions.upstreams.http.v3.HttpProtocolOptions: "@type": type.googleapis.com/envoy.extensions.upstreams.http.v3.HttpProtocolOptions @@ -192,6 +191,9 @@ spec: prometheus.io/port: "9090" spec: serviceAccountName: atenet-router + # Only the atenet-router container calls the Kubernetes API, so only it + # mounts the token (kube-api-access below). + automountServiceAccountToken: false # Budget for the full shutdown sequence: --drain-delay (13s, readiness # propagation) + the Envoy drain window (~15s) + the derived # --drain-timeout (park budget + the drain route budget + margin, ~20s at @@ -316,6 +318,9 @@ spec: # releasing Envoy's preStop poll. - name: "drain-signal" mountPath: "/var/run/atenet" + - name: kube-api-access + mountPath: /var/run/secrets/kubernetes.io/serviceaccount + readOnly: true - name: envoy # ENVOY_DATAPLANE_IMAGE is substituted for the image URI by ate-setup image: ${ENVOY_DATAPLANE_IMAGE} @@ -411,6 +416,21 @@ spec: matchLabels: podcert.ate.dev/canarying: live path: trust-bundle.pem + - name: kube-api-access + projected: + sources: + - serviceAccountToken: + path: token + - configMap: + name: kube-root-ca.crt + items: + - key: ca.crt + path: ca.crt + - downwardAPI: + items: + - path: namespace + fieldRef: + fieldPath: metadata.namespace --- apiVersion: v1 kind: Service diff --git a/manifests/ate-install/components/agentgateway-egress/kustomization.yaml b/manifests/ate-install/components/agentgateway-egress/kustomization.yaml index 00efa57ae9..861b5f37ea 100644 --- a/manifests/ate-install/components/agentgateway-egress/kustomization.yaml +++ b/manifests/ate-install/components/agentgateway-egress/kustomization.yaml @@ -31,6 +31,9 @@ patches: metadata: name: atenet-egress namespace: ate-system + # Lets component patches skip the agentgateway dataplane. + labels: + ate.dev/dataplane: agentgateway spec: template: spec: diff --git a/manifests/ate-install/components/agentgateway/kustomization.yaml b/manifests/ate-install/components/agentgateway/kustomization.yaml index 62cd1c5b7b..1a045ca165 100644 --- a/manifests/ate-install/components/agentgateway/kustomization.yaml +++ b/manifests/ate-install/components/agentgateway/kustomization.yaml @@ -97,6 +97,9 @@ patches: metadata: name: atenet-router namespace: ate-system + # Lets component patches skip the agentgateway dataplane. + labels: + ate.dev/dataplane: agentgateway spec: template: metadata: diff --git a/manifests/ate-install/components/fake-data-plane/kustomization.yaml b/manifests/ate-install/components/fake-data-plane/kustomization.yaml index bf79700ddd..457947d8aa 100644 --- a/manifests/ate-install/components/fake-data-plane/kustomization.yaml +++ b/manifests/ate-install/components/fake-data-plane/kustomization.yaml @@ -38,6 +38,10 @@ patches: kind: DaemonSet labelSelector: app=atelet patch: |- + # Lets component patches skip fake-atelet. + - op: add + path: /metadata/labels/ate.dev~1fake-atelet + value: "true" - op: add path: /spec/template/metadata/labels/ate.dev~1fake-atelet value: "true" @@ -45,9 +49,6 @@ patches: path: /spec/template/metadata/annotations/prometheus.io~1scrape - op: remove path: /spec/template/metadata/annotations/prometheus.io~1port - - op: add - path: /spec/template/spec/automountServiceAccountToken - value: false # objectstore-plugin is atelet's only init container. - op: copy from: /spec/template/spec/initContainers/0/env diff --git a/manifests/ate-install/components/pprof-contention/kustomization.yaml b/manifests/ate-install/components/pprof-contention/kustomization.yaml new file mode 100644 index 0000000000..53b62b27f4 --- /dev/null +++ b/manifests/ate-install/components/pprof-contention/kustomization.yaml @@ -0,0 +1,140 @@ +# Copyright 2026 The Agent Substrate 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. + +# Enables mutex and block contention profiling alongside components/pprof. +# Samples 1 in 10 mutex contention events and ~1 blocking event per 1ms +# (1,000,000ns) spent blocked. Does nothing without components/pprof. +# Never install this on a cluster that serves real actors. + +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component + +patches: + - target: + group: apps + version: v1 + kind: Deployment + name: ate-api-server + namespace: ate-system + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: ate-api-server + namespace: ate-system + spec: + template: + spec: + containers: + - name: ate-api-server + env: + - name: ATE_PPROF_MUTEX_FRACTION + value: "10" + - name: ATE_PPROF_BLOCK_RATE + value: "1000000" + - target: + group: apps + version: v1 + kind: DaemonSet + name: atelet + namespace: ate-system + labelSelector: ate.dev/fake-atelet notin (true) + patch: |- + apiVersion: apps/v1 + kind: DaemonSet + metadata: + name: atelet + namespace: ate-system + spec: + template: + spec: + containers: + - name: atelet + env: + - name: ATE_PPROF_MUTEX_FRACTION + value: "10" + - name: ATE_PPROF_BLOCK_RATE + value: "1000000" + - target: + group: apps + version: v1 + kind: Deployment + name: ate-controller + namespace: ate-system + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: ate-controller + namespace: ate-system + spec: + template: + spec: + containers: + - name: ate-controller + env: + - name: ATE_PPROF_MUTEX_FRACTION + value: "10" + - name: ATE_PPROF_BLOCK_RATE + value: "1000000" + - name: ATE_WORKER_PPROF_MUTEX_FRACTION + value: "10" + - name: ATE_WORKER_PPROF_BLOCK_RATE + value: "1000000" + - target: + group: apps + version: v1 + kind: Deployment + name: atenet-router + namespace: ate-system + labelSelector: ate.dev/dataplane notin (agentgateway) + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: atenet-router + namespace: ate-system + spec: + template: + spec: + containers: + - name: atenet-router + env: + - name: ATE_PPROF_MUTEX_FRACTION + value: "10" + - name: ATE_PPROF_BLOCK_RATE + value: "1000000" + - target: + group: apps + version: v1 + kind: Deployment + name: atenet-egress + namespace: ate-system + labelSelector: ate.dev/dataplane notin (agentgateway) + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: atenet-egress + namespace: ate-system + spec: + template: + spec: + containers: + - name: ext-proc + env: + - name: ATE_PPROF_MUTEX_FRACTION + value: "10" + - name: ATE_PPROF_BLOCK_RATE + value: "1000000" diff --git a/manifests/ate-install/components/pprof/kustomization.yaml b/manifests/ate-install/components/pprof/kustomization.yaml new file mode 100644 index 0000000000..84a68124b0 --- /dev/null +++ b/manifests/ate-install/components/pprof/kustomization.yaml @@ -0,0 +1,179 @@ +# Copyright 2026 The Agent Substrate 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. + +# Enables net/http/pprof (:6060) on ate-api-server, ate-controller, atelet, +# atenet-router, and atenet-egress (ext-proc). Also configures ate-controller +# to enable pprof on worker pods. Skips agentgateway and fake-atelet workloads. +# Never install this on a cluster that serves real actors. + +apiVersion: kustomize.config.k8s.io/v1alpha1 +kind: Component + +patches: + - target: + group: apps + version: v1 + kind: Deployment + name: ate-api-server + namespace: ate-system + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: ate-api-server + namespace: ate-system + spec: + template: + spec: + containers: + - name: ate-api-server + env: + - name: ATE_PPROF_LISTEN_ADDR + value: ":6060" + - name: GRPC_GO_SERVER_GOROUTINE_LABELS + value: "grpc.method=true" + ports: + - name: pprof + containerPort: 6060 + protocol: TCP + - target: + group: apps + version: v1 + kind: DaemonSet + name: atelet + namespace: ate-system + labelSelector: ate.dev/fake-atelet notin (true) + patch: |- + apiVersion: apps/v1 + kind: DaemonSet + metadata: + name: atelet + namespace: ate-system + spec: + template: + spec: + containers: + - name: atelet + env: + - name: ATE_PPROF_LISTEN_ADDR + value: ":6060" + - name: GRPC_GO_SERVER_GOROUTINE_LABELS + value: "grpc.method=true" + ports: + - name: pprof + containerPort: 6060 + protocol: TCP + - target: + group: apps + version: v1 + kind: Deployment + name: ate-controller + namespace: ate-system + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: ate-controller + namespace: ate-system + spec: + template: + spec: + containers: + - name: ate-controller + env: + - name: ATE_PPROF_LISTEN_ADDR + value: ":6060" + - name: ATE_WORKER_PPROF + value: "true" + ports: + - name: pprof + containerPort: 6060 + protocol: TCP + - target: + group: apps + version: v1 + kind: Deployment + name: atenet-router + namespace: ate-system + labelSelector: ate.dev/dataplane notin (agentgateway) + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: atenet-router + namespace: ate-system + spec: + template: + spec: + containers: + - name: atenet-router + env: + - name: ATE_PPROF_LISTEN_ADDR + value: ":6060" + - name: GRPC_GO_SERVER_GOROUTINE_LABELS + value: "grpc.method=true" + ports: + - name: pprof + containerPort: 6060 + protocol: TCP + - target: + group: apps + version: v1 + kind: Deployment + name: atenet-egress + namespace: ate-system + labelSelector: ate.dev/dataplane notin (agentgateway) + patch: |- + apiVersion: apps/v1 + kind: Deployment + metadata: + name: atenet-egress + namespace: ate-system + spec: + template: + spec: + containers: + - name: ext-proc + env: + - name: ATE_PPROF_LISTEN_ADDR + value: ":6060" + - name: GRPC_GO_SERVER_GOROUTINE_LABELS + value: "grpc.method=true" + ports: + - name: pprof + containerPort: 6060 + protocol: TCP + - target: + group: networking.k8s.io + version: v1 + kind: NetworkPolicy + name: ate-system-observability + namespace: ate-system + patch: |- + # Mirrors ate-api-server's api-access peer so worker pods and arbitrary + # cluster pods cannot scrape pprof. + - op: add + path: /spec/ingress/- + value: + from: + - namespaceSelector: + matchLabels: + ate.dev/api-access: "true" + podSelector: + matchExpressions: + - key: ate.dev/worker-pool + operator: DoesNotExist + ports: + - port: pprof + protocol: TCP diff --git a/manifests/ate-install/generated/ate.dev_csidriverconfigs.yaml b/manifests/ate-install/generated/ate.dev_csidriverconfigs.yaml index ea605923ce..47217ba40b 100644 --- a/manifests/ate-install/generated/ate.dev_csidriverconfigs.yaml +++ b/manifests/ate-install/generated/ate.dev_csidriverconfigs.yaml @@ -74,7 +74,7 @@ spec: Matches the StorageClass referenced in ActorTemplate volume definitions. maxLength: 63 minLength: 1 - pattern: ^(substrate\.io/)?([a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*)$ + pattern: ^[a-z0-9]([-a-z0-9]*[a-z0-9])?(\.[a-z0-9]([-a-z0-9]*[a-z0-9])?)*$ type: string nodeSocketOverride: description: |- diff --git a/manifests/ate-install/generated/ate.dev_workerpools.yaml b/manifests/ate-install/generated/ate.dev_workerpools.yaml index 8c76630c8f..bba0a85c68 100644 --- a/manifests/ate-install/generated/ate.dev_workerpools.yaml +++ b/manifests/ate-install/generated/ate.dev_workerpools.yaml @@ -168,7 +168,7 @@ spec: properties: preferredDuringSchedulingIgnoredDuringExecution: description: |- - The scheduler will prefer to schedule pods to nodes that satisfy + preferredDuringSchedulingIgnoredDuringExecution specifies that the scheduler will prefer to schedule pods to nodes that satisfy the affinity expressions specified by this field, but it may choose a node that violates one or more of the expressions. The node that is most preferred is the one with the greatest sum of weights, i.e. @@ -183,29 +183,29 @@ spec: (i.e. it's a no-op). A null preferred scheduling term matches no objects (i.e. is also a no-op). properties: preference: - description: A node selector term, associated with the - corresponding weight. + description: preference is a node selector term, associated + with the corresponding weight. properties: matchExpressions: - description: A list of node selector requirements - by node's labels. + description: matchExpressions is a list of node + selector requirements by node's labels. items: description: |- A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: key: - description: The label key that the selector - applies to. + description: key is the label key that the + selector applies to. type: string operator: description: |- - Represents a key's relationship to a set of values. + operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. type: string values: description: |- - An array of string values. If the operator is In or NotIn, + values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. @@ -221,25 +221,25 @@ spec: type: array x-kubernetes-list-type: atomic matchFields: - description: A list of node selector requirements - by node's fields. + description: matchFields is a list of node selector + requirements by node's fields. items: description: |- A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: key: - description: The label key that the selector - applies to. + description: key is the label key that the + selector applies to. type: string operator: description: |- - Represents a key's relationship to a set of values. + operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. type: string values: description: |- - An array of string values. If the operator is In or NotIn, + values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. @@ -257,8 +257,8 @@ spec: type: object x-kubernetes-map-type: atomic weight: - description: Weight associated with matching the corresponding - nodeSelectorTerm, in the range 1-100. + description: weight is the weight associated with matching + the corresponding nodeSelectorTerm, in the range 1-100. format: int32 type: integer required: @@ -269,15 +269,16 @@ spec: x-kubernetes-list-type: atomic requiredDuringSchedulingIgnoredDuringExecution: description: |- - If the affinity requirements specified by this field are not met at + requiredDuringSchedulingIgnoredDuringExecution specifies that if the affinity requirements specified by this field are not met at scheduling time, the pod will not be scheduled onto the node. If the affinity requirements specified by this field cease to be met at some point during pod execution (e.g. due to an update), the system may or may not try to eventually evict the pod from its node. properties: nodeSelectorTerms: - description: Required. A list of node selector terms. - The terms are ORed. + description: |- + nodeSelectorTerms is a list of node selector terms. The terms are ORed. + Required. A list of node selector terms. The terms are ORed. items: description: |- A null or empty node selector term matches no objects. The requirements of @@ -285,25 +286,25 @@ spec: The TopologySelectorTerm type implements a subset of the NodeSelectorTerm. properties: matchExpressions: - description: A list of node selector requirements - by node's labels. + description: matchExpressions is a list of node + selector requirements by node's labels. items: description: |- A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: key: - description: The label key that the selector - applies to. + description: key is the label key that the + selector applies to. type: string operator: description: |- - Represents a key's relationship to a set of values. + operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. type: string values: description: |- - An array of string values. If the operator is In or NotIn, + values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. @@ -319,25 +320,25 @@ spec: type: array x-kubernetes-list-type: atomic matchFields: - description: A list of node selector requirements - by node's fields. + description: matchFields is a list of node selector + requirements by node's fields. items: description: |- A node selector requirement is a selector that contains values, a key, and an operator that relates the key and values. properties: key: - description: The label key that the selector - applies to. + description: key is the label key that the + selector applies to. type: string operator: description: |- - Represents a key's relationship to a set of values. + operator represents a key's relationship to a set of values. Valid operators are In, NotIn, Exists, DoesNotExist. Gt, and Lt. type: string values: description: |- - An array of string values. If the operator is In or NotIn, + values is an array of string values. If the operator is In or NotIn, the values array must be non-empty. If the operator is Exists or DoesNotExist, the values array must be empty. If the operator is Gt or Lt, the values array must have a single element, which will be interpreted as an integer. @@ -376,25 +377,22 @@ spec: properties: claims: description: |- - Claims lists the names of resources, defined in spec.resourceClaims, + claims lists the names of resources, defined in spec.resourceClaims, that are used by this container. - This field depends on the - DynamicResourceAllocation feature gate. - This field is immutable. It can only be set for containers. items: description: ResourceClaim references one entry in PodSpec.ResourceClaims. properties: name: description: |- - Name must match the name of one entry in pod.spec.resourceClaims of + name must match the name of one entry in pod.spec.resourceClaims of the Pod where this field is used. It makes that resource available inside a container. type: string request: description: |- - Request is the name chosen for a request in the referenced claim. + request is the name chosen for a request in the referenced claim. If empty, everything from the claim is made available, otherwise only the result of this request. type: string @@ -413,8 +411,12 @@ spec: pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true description: |- - Limits describes the maximum amount of compute resources allowed. - More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ + limits describes the maximum amount of compute resources allowed. + For kubelet cgroup enforcement: + - cpu and memory: a limit of 0 is treated the same as an unspecified limit. If + neither the container nor the pod specifies a limit, the resource is not limited. + - hugepages: an unspecified limit is treated the same as a limit of 0. + More details: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ type: object requests: additionalProperties: @@ -424,7 +426,7 @@ spec: pattern: ^(\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))(([KMGTPE]i)|[numkMGTPE]|([eE](\+|-)?(([0-9]+(\.[0-9]*)?)|(\.[0-9]+))))?$ x-kubernetes-int-or-string: true description: |- - Requests describes the minimum amount of compute resources required. + requests describes the minimum amount of compute resources required. If Requests is omitted for a container, it defaults to Limits if that is explicitly specified, otherwise to an implementation-defined value. Requests cannot exceed Limits. More info: https://kubernetes.io/docs/concepts/configuration/manage-resources-containers/ @@ -434,7 +436,8 @@ spec: description: |- serviceAccountName for the worker pods. The ServiceAccount must exist in the WorkerPool's namespace. When omitted, the pods run as the - "ateworker" ServiceAccount, which the controller creates. + "ateworker" ServiceAccount, which the controller creates. Worker pods + never get a ServiceAccount token, whichever ServiceAccount they use. minLength: 1 type: string tolerations: @@ -446,17 +449,17 @@ spec: properties: effect: description: |- - Effect indicates the taint effect to match. Empty means match all taint effects. + effect indicates the taint effect to match. Empty means match all taint effects. When specified, allowed values are NoSchedule, PreferNoSchedule and NoExecute. type: string key: description: |- - Key is the taint key that the toleration applies to. Empty means match all taint keys. + key is the taint key that the toleration applies to. Empty means match all taint keys. If the key is empty, operator must be Exists; this combination means to match all values and all keys. type: string operator: description: |- - Operator represents a key's relationship to the value. + operator represents a key's relationship to the value. Valid operators are Exists, Equal, Lt, and Gt. Defaults to Equal. Exists is equivalent to wildcard for value, so that a pod can tolerate all taints of a particular category. @@ -464,7 +467,7 @@ spec: type: string tolerationSeconds: description: |- - TolerationSeconds represents the period of time the toleration (which must be + tolerationSeconds represents the period of time the toleration (which must be of effect NoExecute, otherwise this field is ignored) tolerates the taint. By default, it is not set, which means tolerate the taint forever (do not evict). Zero and negative values will be treated as 0 (evict immediately) by the system. @@ -472,7 +475,7 @@ spec: type: integer value: description: |- - Value is the taint value the toleration matches to. + value is the taint value the toleration matches to. If the operator is Exists, the value should be empty, otherwise just a regular string. type: string type: object diff --git a/manifests/ate-install/kind/rustfs.yaml b/manifests/ate-install/kind/rustfs.yaml index 6183258861..012d883fd8 100644 --- a/manifests/ate-install/kind/rustfs.yaml +++ b/manifests/ate-install/kind/rustfs.yaml @@ -56,6 +56,7 @@ spec: labels: app: rustfs spec: + automountServiceAccountToken: false securityContext: runAsUser: 10001 runAsGroup: 10001 @@ -99,6 +100,7 @@ spec: backoffLimit: 10 template: spec: + automountServiceAccountToken: false restartPolicy: OnFailure containers: - name: create-bucket diff --git a/manifests/ate-install/postgres/postgres.yaml b/manifests/ate-install/postgres/postgres.yaml index 7e41652b6b..b40b3c97fd 100644 --- a/manifests/ate-install/postgres/postgres.yaml +++ b/manifests/ate-install/postgres/postgres.yaml @@ -102,6 +102,7 @@ spec: labels: app: postgres spec: + automountServiceAccountToken: false securityContext: # Group ownership of the projected certificate below, and of the data # volume so that a freshly provisioned one is writable. OnRootMismatch diff --git a/manifests/ate-install/sandboxconfig-gvisor.yaml b/manifests/ate-install/sandboxconfig-gvisor.yaml index 09e4c21119..7fbbd1c8ff 100644 --- a/manifests/ate-install/sandboxconfig-gvisor.yaml +++ b/manifests/ate-install/sandboxconfig-gvisor.yaml @@ -31,7 +31,7 @@ metadata: sandboxconfig.ate.dev/is-class-default: "true" spec: sandboxClass: gvisor - defaultVersion: v7 + defaultVersion: v8 versions: # gVisor release 20261026.0. ateworker-gvisor saves container rootfs overlays # (rootfs/) and durable-dir volumes (fs/) as separate checkpoint bundles. That @@ -62,3 +62,17 @@ spec: gvisor: url: "gs://gvisor/releases/release/20261102.0/aarch64/gvisor.tar.zstd" sha256: "f702ae92ad7a0c4134be34ca23f52966dbb696db0c0f5b8ec439210ab2cd7c6a" + # gVisor nightly 2026-12-02 (google/gvisor@ce0884fa5472), which includes + # google/gvisor@61d3a87e5a4f (fixing sub-container start in a restoring + # sandbox). + - name: v8 + state: Enabled + assets: + amd64: + gvisor: + url: "gs://gvisor/releases/nightly/2026-12-02/x86_64/gvisor.tar.zstd" + sha256: "e4bb791370872192ea91211a5d9f0e7b3cb6d55248c1168ce82dd76ffef73e64" + arm64: + gvisor: + url: "gs://gvisor/releases/nightly/2026-12-02/aarch64/gvisor.tar.zstd" + sha256: "54c4357298d1f12122b6cc18078ecf7b5cc1ac2ee1ef7032f170cb6e7c5ef75d" diff --git a/manifests/egress-credential-injection/k8s-credential-provider.yaml b/manifests/egress-credential-injection/k8s-credential-provider.yaml index ebab478fd9..969eb2ea7f 100644 --- a/manifests/egress-credential-injection/k8s-credential-provider.yaml +++ b/manifests/egress-credential-injection/k8s-credential-provider.yaml @@ -87,6 +87,29 @@ spec: # Enforce the atespace→namespace authorization policy (default-deny). - "--namespace-policy-file=/etc/k8s-credential-provider/namespace-policy.yaml" - "--log-level=info" + env: + - name: POD_NAME + valueFrom: + fieldRef: + fieldPath: metadata.name + - name: POD_NAMESPACE + valueFrom: + fieldRef: + fieldPath: metadata.namespace + - name: POD_UID + valueFrom: + fieldRef: + fieldPath: metadata.uid + - name: OTEL_RESOURCE_ATTRIBUTES + value: k8s.namespace.name=$(POD_NAMESPACE),k8s.pod.name=$(POD_NAME),k8s.pod.uid=$(POD_UID),service.instance.id=$(POD_UID) + # OTLP exporter settings shared by every control plane component; see + # manifests/ate-install/ate-otel-config.yaml. Without this the SDK + # falls back to localhost:4317 and the provider's metrics are lost: + # the NetworkPolicy below admits no scraper, so the OTLP push is the + # only path they have off the pod. + envFrom: + - configMapRef: + name: ate-otel-config ports: - name: grpc containerPort: 50051 diff --git a/manifests/egress-credential-injection/namespace-policy.yaml b/manifests/egress-credential-injection/namespace-policy.yaml index be81de8d6f..0a43b26ac2 100644 --- a/manifests/egress-credential-injection/namespace-policy.yaml +++ b/manifests/egress-credential-injection/namespace-policy.yaml @@ -16,10 +16,7 @@ # atespace may only resolve Secrets whose URI namespace is listed for it here. # Enforcement is default-deny — an atespace absent from this file resolves # nothing. The install creates this ConfigMap only when it is absent, granting -# nothing; the provider needs it to start. -# -# TODO: k8s-credential-provider loads this once at startup, so editing this ConfigMap -# requires restarting the k8s-credential-provider Deployment. Make it reload dynamically. +# nothing; the provider needs it to start, and rereads it when it changes. apiVersion: v1 kind: ConfigMap metadata: diff --git a/pkg/client/clientset/versioned/typed/ate/v1/csidriverconfig.go b/pkg/client/clientset/versioned/typed/ate/v1/csidriverconfig.go index 6122a1f28d..bdb085c7be 100644 --- a/pkg/client/clientset/versioned/typed/ate/v1/csidriverconfig.go +++ b/pkg/client/clientset/versioned/typed/ate/v1/csidriverconfig.go @@ -38,6 +38,7 @@ type CSIDriverConfigInterface interface { Create(ctx context.Context, cSIDriverConfig *atev1.CSIDriverConfig, opts metav1.CreateOptions) (*atev1.CSIDriverConfig, error) Update(ctx context.Context, cSIDriverConfig *atev1.CSIDriverConfig, opts metav1.UpdateOptions) (*atev1.CSIDriverConfig, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteWithResult(ctx context.Context, name string, opts metav1.DeleteOptions) (metav1.APIResult, error) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*atev1.CSIDriverConfig, error) List(ctx context.Context, opts metav1.ListOptions) (*atev1.CSIDriverConfigList, error) diff --git a/pkg/client/clientset/versioned/typed/ate/v1/sandboxconfig.go b/pkg/client/clientset/versioned/typed/ate/v1/sandboxconfig.go index 5b9cea4932..0c93ed9185 100644 --- a/pkg/client/clientset/versioned/typed/ate/v1/sandboxconfig.go +++ b/pkg/client/clientset/versioned/typed/ate/v1/sandboxconfig.go @@ -38,6 +38,7 @@ type SandboxConfigInterface interface { Create(ctx context.Context, sandboxConfig *atev1.SandboxConfig, opts metav1.CreateOptions) (*atev1.SandboxConfig, error) Update(ctx context.Context, sandboxConfig *atev1.SandboxConfig, opts metav1.UpdateOptions) (*atev1.SandboxConfig, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteWithResult(ctx context.Context, name string, opts metav1.DeleteOptions) (metav1.APIResult, error) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*atev1.SandboxConfig, error) List(ctx context.Context, opts metav1.ListOptions) (*atev1.SandboxConfigList, error) diff --git a/pkg/client/clientset/versioned/typed/ate/v1/workerpool.go b/pkg/client/clientset/versioned/typed/ate/v1/workerpool.go index d0a8eb5bbb..92620d7740 100644 --- a/pkg/client/clientset/versioned/typed/ate/v1/workerpool.go +++ b/pkg/client/clientset/versioned/typed/ate/v1/workerpool.go @@ -40,6 +40,7 @@ type WorkerPoolInterface interface { // Add a +genclient:noStatus comment above the type to avoid generating UpdateStatus(). UpdateStatus(ctx context.Context, workerPool *atev1.WorkerPool, opts metav1.UpdateOptions) (*atev1.WorkerPool, error) Delete(ctx context.Context, name string, opts metav1.DeleteOptions) error + DeleteWithResult(ctx context.Context, name string, opts metav1.DeleteOptions) (metav1.APIResult, error) DeleteCollection(ctx context.Context, opts metav1.DeleteOptions, listOpts metav1.ListOptions) error Get(ctx context.Context, name string, opts metav1.GetOptions) (*atev1.WorkerPool, error) List(ctx context.Context, opts metav1.ListOptions) (*atev1.WorkerPoolList, error) diff --git a/pkg/client/informers/externalversions/factory.go b/pkg/client/informers/externalversions/factory.go index 449ac35858..1c1f9052d9 100644 --- a/pkg/client/informers/externalversions/factory.go +++ b/pkg/client/informers/externalversions/factory.go @@ -28,6 +28,7 @@ import ( v1 "k8s.io/apimachinery/pkg/apis/meta/v1" runtime "k8s.io/apimachinery/pkg/runtime" schema "k8s.io/apimachinery/pkg/runtime/schema" + sharding "k8s.io/apimachinery/pkg/sharding" wait "k8s.io/apimachinery/pkg/util/wait" cache "k8s.io/client-go/tools/cache" ) @@ -43,6 +44,7 @@ type sharedInformerFactory struct { defaultResync time.Duration customResync map[reflect.Type]time.Duration transform cache.TransformFunc + shardSelector sharding.Selector informerName *cache.InformerName informers map[reflect.Type]cache.SharedIndexInformer @@ -90,6 +92,14 @@ func WithTransform(transform cache.TransformFunc) SharedInformerOption { } } +// WithShardSelector sets a shard selector on all informers. +func WithShardSelector(shardSelector sharding.Selector) SharedInformerOption { + return func(factory *sharedInformerFactory) *sharedInformerFactory { + factory.shardSelector = shardSelector + return factory + } +} + // WithInformerName sets the InformerName for informer identity used in metrics. // The InformerName must be created via cache.NewInformerName() at startup, // which validates global uniqueness. Each informer type will register its @@ -238,6 +248,9 @@ func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internal if f.transform != nil { informer.SetTransform(f.transform) } + if f.shardSelector != nil { + informer.SetShardSelector(f.shardSelector) + } f.informers[informerType] = informer return informer @@ -254,17 +267,17 @@ func (f *sharedInformerFactory) InformerFor(obj runtime.Object, newFunc internal // defer factory.Shutdown() // Returns immediately if nothing was started. // genericInformer := factory.ForResource(resource) // typedInformer := factory.SomeAPIGroup().V1().SomeType() -// handle, err := typeInformer.Informer().AddEventHandler(...) +// handle, err := typedInformer.Informer().AddEventHandler(...) // if err != nil { // return fmt.Errorf("register event handler: %v", err) // } -// defer typeInformer.Informer().RemoveEventHandler(handle) // Avoids leaking goroutines. +// defer typedInformer.Informer().RemoveEventHandler(handle) // Avoids leaking goroutines. // factory.StartWithContext(ctx) // Start processing these informers. // synced := factory.WaitForCacheSyncWithContext(ctx) // if err := synced.AsError(); err != nil { // return err // } -// for v := range synced { +// for v := range synced.Synced { // // Only if desired log some information similar to this. // fmt.Fprintf(os.Stdout, "cache synced: %s", v) // } diff --git a/pkg/kagent/install/installer.go b/pkg/kagent/install/installer.go index 393495a0b0..b4354ecccd 100644 --- a/pkg/kagent/install/installer.go +++ b/pkg/kagent/install/installer.go @@ -22,7 +22,7 @@ import ( "io/fs" "time" - apiextclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" + apiextclient "k8s.io/apiextensions-api/pkg/client/clientset/clientset" "k8s.io/client-go/dynamic" "k8s.io/client-go/kubernetes" "k8s.io/client-go/rest" diff --git a/pkg/kagent/install/upgrade.go b/pkg/kagent/install/upgrade.go index 1762a61938..19d80c8098 100644 --- a/pkg/kagent/install/upgrade.go +++ b/pkg/kagent/install/upgrade.go @@ -25,8 +25,8 @@ import ( "github.com/Masterminds/semver/v3" "github.com/pmezard/go-difflib/difflib" - apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apiextclient "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset" + apiextv1 "k8s.io/apiextensions-api/pkg/apis/apiextensions/v1" + apiextclient "k8s.io/apiextensions-api/pkg/client/clientset/clientset" apierrors "k8s.io/apimachinery/pkg/api/errors" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" utilyaml "k8s.io/apimachinery/pkg/util/yaml" diff --git a/pkg/kagent/install/upgrade_test.go b/pkg/kagent/install/upgrade_test.go index 3a3bbfcc2c..b43150dc33 100644 --- a/pkg/kagent/install/upgrade_test.go +++ b/pkg/kagent/install/upgrade_test.go @@ -20,8 +20,8 @@ import ( "strings" "testing" - apiextv1 "k8s.io/apiextensions-apiserver/pkg/apis/apiextensions/v1" - apiextfake "k8s.io/apiextensions-apiserver/pkg/client/clientset/clientset/fake" + apiextv1 "k8s.io/apiextensions-api/pkg/apis/apiextensions/v1" + apiextfake "k8s.io/apiextensions-api/pkg/client/clientset/clientset/fake" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" chartsfs "go.ate.dev/substrate/charts" diff --git a/pkg/objectstorage/gcscompose.go b/pkg/objectstorage/gcscompose.go index edc82747f4..16ef3c6d4b 100644 --- a/pkg/objectstorage/gcscompose.go +++ b/pkg/objectstorage/gcscompose.go @@ -36,7 +36,8 @@ import ( // measured on a GKE worker node at 8 streams, 334 MB/s shared against 518 MB/s with a // connection each. The same holds for the many small objects a node moves at once: // each snapshot below the part and range thresholds is a single request, so the -// single-request paths draw on this pool too (see nextClient). +// single-request paths draw on this pool too (see nextClient). Callers that pass +// option.WithHTTPClient share that HTTP client across every pooled storage.Client. const uploadPoolSize = 8 // newPool builds the uploadPoolSize clients transfers are spread over, from the diff --git a/pkg/objectstorage/gcssparse.go b/pkg/objectstorage/gcssparse.go index 9943a32083..ce404ee821 100644 --- a/pkg/objectstorage/gcssparse.go +++ b/pkg/objectstorage/gcssparse.go @@ -52,7 +52,7 @@ func (g *gcsClient) PutSparseFile(ctx context.Context, bucket, object string, f } res = writeContentResult{logicalBytes: size, populatedBytes: populated, sparse: true} - n := min(sparsePartCount(populated), maxParts) + n := min(sparsePartCount(populated, len(exts)), maxParts) if n < 2 { // Too small to be worth splitting; the plain streaming path handles it. return res, errSparseTooSmall diff --git a/pkg/objectstorage/sparsebench_test.go b/pkg/objectstorage/sparsebench_test.go index b786210f31..4a4a8774de 100644 --- a/pkg/objectstorage/sparsebench_test.go +++ b/pkg/objectstorage/sparsebench_test.go @@ -108,7 +108,7 @@ func snapshotParts(tb testing.TB, src *os.File, logical int64) (groups [][]exten if err != nil { tb.Fatal(err) } - return planSparseParts(exts, populated, sparsePartCount(populated)), populated + return planSparseParts(exts, populated, sparsePartCount(populated, len(exts))), populated } func rangesBytes(ranges []extentRange) (n int64) { diff --git a/pkg/objectstorage/sparseparts.go b/pkg/objectstorage/sparseparts.go index 6d2a373d49..b02448c2af 100644 --- a/pkg/objectstorage/sparseparts.go +++ b/pkg/objectstorage/sparseparts.go @@ -29,8 +29,10 @@ import ( // 622 — so the node is nowhere near a ceiling and what limits a snapshot upload is how // early the streams can all start. const ( - // sparsePartTarget is the populated source bytes per part. Parts smaller than this - // stop amortizing the ~0.25s a part upload costs before it transfers anything. + // sparsePartTarget is the populated bytes each part aims for. Every part costs + // about 0.25s before it sends anything, so smaller parts waste time. The exception + // is a file under twice this size, which still splits into two smaller parts. + // Uploading it as one stream would reserve the node's whole upload budget. sparsePartTarget = 64 << 20 // sparseMaxParts caps the fan-out: past a dozen streams per-stream throughput falls // faster than the extra parallelism gains. @@ -102,13 +104,14 @@ func planSparseParts(exts []extentRange, populated int64, n int) [][]extentRange return groups } -// sparsePartCount picks how many parts to split a snapshot into. -func sparsePartCount(populated int64) int { - n := int(populated / sparsePartTarget) - if n < 1 { - n = 1 +// sparsePartCount picks how many parts to split a snapshot into. A snapshot +// whose encoded stream can reach uploadCompositeMin splits into at least two +// range parts so it does not fall back to a single-stream composite upload. +func sparsePartCount(populated int64, extents int) int { + if populated < sparsePartTarget && sparseEncodedBound(populated, extents) < uploadCompositeMin { + return 1 } - return min(n, sparseMaxParts) + return min(max(int(populated/sparsePartTarget), 2), sparseMaxParts) } // sparseCopyPool holds the 1 MiB buffers parts read the source through. diff --git a/pkg/objectstorage/upload.go b/pkg/objectstorage/upload.go index aac94f8ebd..06bdc298b1 100644 --- a/pkg/objectstorage/upload.go +++ b/pkg/objectstorage/upload.go @@ -133,7 +133,7 @@ func (u *Uploader) planStream(content io.Reader) (uploadPlan, int64, io.Reader, } // Holes never enter the compressor or range uploads. workers = min(workers, populated/parZstdChunk+1) - parts = min(sparsePartCount(populated), int(u.budget.capacity/sparseUploadMemory)) + parts = min(sparsePartCount(populated, len(exts)), int(u.budget.capacity/sparseUploadMemory)) if _, ok := u.client.(sparseFilePutter); ok && parts >= 2 { // PutSparseFile splits a file into parts whenever it has two or // more (see errSparseTooSmall), so the streaming fallback never diff --git a/pkg/objectstorage/upload_gcs_test.go b/pkg/objectstorage/upload_gcs_test.go index 25ee622879..0371ec8e1f 100644 --- a/pkg/objectstorage/upload_gcs_test.go +++ b/pkg/objectstorage/upload_gcs_test.go @@ -192,7 +192,7 @@ func TestUploaderGCSSnapshotBurstFitsDefaultBudget(t *testing.T) { smallFiles = append(smallFiles, f) } pagesPath := filepath.Join(dir, "pages.img") - writeSparseSource(t, pagesPath, 2<<30, []region{{0, 2 * sparsePartTarget, 0x7f}}) + writeSparseSource(t, pagesPath, 2<<30, []region{{0, sparsePartTarget + 16<<20, 0x7f}}) pages, err := os.Open(pagesPath) if err != nil { t.Fatal(err) diff --git a/pkg/objectstorage/upload_test.go b/pkg/objectstorage/upload_test.go index 0eab6914a1..ffe3fe4d55 100644 --- a/pkg/objectstorage/upload_test.go +++ b/pkg/objectstorage/upload_test.go @@ -78,6 +78,7 @@ func TestUploaderPlansFromPopulatedBytes(t *testing.T) { {"all_holes", 0, uploadPlan{1, 1, 8<<20 + 512<<10}, uploadPlan{1, 1, 168 << 20}}, {"small", 1, uploadPlan{1, 1, 8<<20 + 2560<<10}, uploadPlan{1, 1, 168 << 20}}, {"two_chunks", 9, uploadPlan{2, 1, 146<<20 + 512<<10}, uploadPlan{2, 1, 288 << 20}}, + {"two_ranges", 80, uploadPlan{3, 2, 96 << 20}, uploadPlan{5, 2, 480 << 20}}, {"multiple_ranges", 192, uploadPlan{3, 3, 144 << 20}, uploadPlan{5, 3, 480 << 20}}, } { t.Run(tc.name, func(t *testing.T) { @@ -118,6 +119,63 @@ func TestUploaderPlansFromPopulatedBytes(t *testing.T) { } } +func TestUploaderSplitsFragmentedSparseNearCompositeMin(t *testing.T) { + // 254 * 256 KiB = 63.5 MiB populated: below sparsePartTarget and below + // uploadCompositeMin as a single extent, but per-extent framing pushes the + // encoded bound past uploadCompositeMin when split across 254 extents. + const ( + extentCount = 254 + extentBytes = 256 << 10 + populated = extentCount * extentBytes + ) + if sparseEncodedBound(populated, 1) >= uploadCompositeMin { + t.Fatalf("single-extent bound %d already >= %d", sparseEncodedBound(populated, 1), uploadCompositeMin) + } + if sparseEncodedBound(populated, extentCount) < uploadCompositeMin { + t.Fatalf("fragmented bound %d < %d", sparseEncodedBound(populated, extentCount), uploadCompositeMin) + } + + dir := t.TempDir() + contigPath := filepath.Join(dir, "contiguous") + writeSparseSource(t, contigPath, 2<<30, []region{{0, populated, 0x5a}}) + contig, err := os.Open(contigPath) + if err != nil { + t.Fatal(err) + } + defer contig.Close() + + regions := make([]region, extentCount) + for i := range regions { + regions[i] = region{off: int64(i) * (512 << 10), len: extentBytes, fill: 0x5a} + } + fragPath := filepath.Join(dir, "fragmented") + writeSparseSource(t, fragPath, 2<<30, regions) + frag, err := os.Open(fragPath) + if err != nil { + t.Fatal(err) + } + defer frag.Close() + + u, err := NewUploader(&gcsClient{}, DefaultUploadMemory) + if err != nil { + t.Fatal(err) + } + contigPlan, err := u.plan(contig) + if err != nil { + t.Fatal(err) + } + if contigPlan.parts != 1 { + t.Errorf("contiguous 63.5 MiB plan = %+v, want 1 part", contigPlan) + } + fragPlan, err := u.plan(frag) + if err != nil { + t.Fatal(err) + } + if fragPlan.parts != 2 || fragPlan.memory != 2*sparseUploadMemory { + t.Errorf("fragmented 63.5 MiB plan = %+v, want 2 parts reserving %d", fragPlan, 2*sparseUploadMemory) + } +} + func TestUploaderReservesOnlyTheChosenPath(t *testing.T) { previous := runtime.GOMAXPROCS(192) defer runtime.GOMAXPROCS(previous) diff --git a/pkg/oidcjwt/oidcjwt.go b/pkg/oidcjwt/oidcjwt.go new file mode 100644 index 0000000000..5ce4d8fc05 --- /dev/null +++ b/pkg/oidcjwt/oidcjwt.go @@ -0,0 +1,260 @@ +// Copyright 2026 The Agent Substrate 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 oidcjwt provides a high-level OIDC JWT verifier for Substrate Actor +// tokens. External sandbox gateways and compute drivers (such as out-of-tree +// microVM or OpenShell drivers) use it to verify egress-injected Actor JWTs +// against ate-idp-server OIDC discovery and JWKS endpoints and extract actor +// claims without duplicating internal JWT verification logic. +// +// This package imports packages under internal/, so that an external driver +// runs the same verification logic as in-tree components and only this package's +// API is public. Go allows it: the internal rule checks the importer's path, and +// every package under go.ate.dev/substrate may import +// go.ate.dev/substrate/internal/..., while code outside the module may import +// this package. +package oidcjwt + +import ( + "context" + "crypto/tls" + "crypto/x509" + "errors" + "fmt" + "log/slog" + "net/url" + "strings" + "time" + + "go.ate.dev/substrate/internal/actoridjwt" + "go.ate.dev/substrate/internal/credbundle" + internaloidc "go.ate.dev/substrate/internal/oidcjwt" +) + +// MaxJWTSize is the largest token, in bytes, Verify accepts. +const MaxJWTSize = 8 << 10 + +// issuerCheckTimeout bounds the start-time JWKS fetch from the OIDC issuer. +const issuerCheckTimeout = 10 * time.Second + +// ErrSigningKeysUnavailable is wrapped by Verify errors caused by transient +// failures fetching the issuer's OIDC discovery document or JWKS keys. +// Callers can match it with errors.Is to return Unavailable instead of +// Unauthenticated. +var ErrSigningKeysUnavailable = internaloidc.ErrSigningKeysUnavailable + +// Kind represents who an actor token speaks for. +type Kind int + +const ( + // KindUnspecified is the zero value indicating an unrecognized token kind. + KindUnspecified Kind = iota + + // KindActor represents a token minted for an actor itself. Egress gateways + // inject KindActor tokens into outbound requests matching an ActorJwtSource + // egress rule. + KindActor + + // KindWorkerForActor represents a token minted for a Substrate component + // or worker acting on behalf of an actor (e.g. transfer and storage exchanges). + KindWorkerForActor +) + +func (k Kind) String() string { + switch k { + case KindActor: + return "actor" + case KindWorkerForActor: + return "worker-for-actor" + default: + return "unspecified" + } +} + +// ActorClaims contains Substrate-specific actor identity and placement claims. +type ActorClaims struct { + Atespace string + ActorName string + ActorUID string + Node string +} + +// Claims contains the verified standard JWT claims and Substrate actor claims. +type Claims struct { + // Standard claims from RFC 7519 + Issuer string + Subject string + Audiences []string + Expiration time.Time + NotBefore time.Time + IssuedAt time.Time + JTI string + + // Substrate-specific claims + Kind Kind + ActorClaims *ActorClaims +} + +// Config configures the Verifier. +type Config struct { + // Issuer is the OIDC issuer URL (e.g. "https://ate-idp-server.ate-system.svc"). + // It is required. It must be https:// followed by a host and optional port, + // with no path, query or fragment. + Issuer string + + // IssuerCAFile is the path to a PEM CA bundle that verifies the issuer's + // serving certificate. For an issuer whose host ends in .svc, it is the + // only trusted bundle. For external issuers, system roots are trusted as + // well. It is required. It is re-read when the file changes. + IssuerCAFile string + + // Audiences is the list of acceptable audiences. At least one audience is required. + Audiences []string +} + +// Verifier verifies Substrate actor tokens using OIDC discovery. It is safe for +// concurrent use. +type Verifier struct { + inner *internaloidc.Verifier +} + +// New returns a Verifier configured with cfg. It checks the issuer's OIDC +// discovery and JWKS endpoints once with a short timeout: it fails immediately +// if IssuerCAFile cannot be read or holds no certificates, or if the issuer's +// TLS certificate fails verification. Other startup fetch errors (such as an +// issuer that is not reachable yet) are logged and Verify retries on demand. +func New(ctx context.Context, cfg Config) (*Verifier, error) { + if cfg.Issuer == "" { + return nil, errors.New("oidcjwt: Issuer is required") + } + if err := actoridjwt.ValidateIssuer(cfg.Issuer); err != nil { + return nil, fmt.Errorf("oidcjwt: %w", err) + } + if cfg.IssuerCAFile == "" { + return nil, errors.New("oidcjwt: IssuerCAFile is required") + } + if len(cfg.Audiences) == 0 { + return nil, errors.New("oidcjwt: at least one audience is required") + } + for _, aud := range cfg.Audiences { + if aud == "" { + return nil, errors.New("oidcjwt: Audiences must not contain empty strings") + } + } + + loadRoots, trusted, err := issuerRoots(cfg.Issuer, cfg.IssuerCAFile) + if err != nil { + return nil, fmt.Errorf("oidcjwt: %w", err) + } + client, err := internaloidc.NewHTTPClientWithRoots(loadRoots) + if err != nil { + return nil, fmt.Errorf("oidcjwt: setting up HTTP client: %w", err) + } + + opts := []internaloidc.Option{ + internaloidc.WithSubstrateClaims(), + } + + keySource := internaloidc.HTTPKeySource(cfg.Issuer, client) + inner := internaloidc.NewVerifier(cfg.Issuer, cfg.Audiences, keySource, opts...) + + checkCtx, cancel := context.WithTimeout(ctx, issuerCheckTimeout) + defer cancel() + if err := inner.Refresh(checkCtx, time.Now()); err != nil { + var certErr *tls.CertificateVerificationError + if errors.As(err, &certErr) { + client.CloseIdleConnections() + return nil, fmt.Errorf("oidcjwt: issuer serves a certificate that does not verify against %s: %w", trusted, err) + } + slog.WarnContext(ctx, "Could not fetch actor JWT signing keys at start; Verify retries the fetch", slog.String("issuer", cfg.Issuer), slog.Any("err", err)) + } + + return &Verifier{ + inner: inner, + }, nil +} + +// Verify validates rawJWT against the issuer's keys and returns the parsed claims. +// +// Callers must check Claims.Kind so KindActor and KindWorkerForActor tokens are +// not confused: both carry ActorClaims, and a KindActor token can share the +// same audience as a KindWorkerForActor token. +// +// Transient OIDC discovery or JWKS fetch errors wrap ErrSigningKeysUnavailable. +func (v *Verifier) Verify(ctx context.Context, rawJWT string) (*Claims, error) { + if rawJWT == "" { + return nil, errors.New("oidcjwt: rawJWT is required") + } + if len(rawJWT) > MaxJWTSize { + return nil, fmt.Errorf("oidcjwt: rawJWT is longer than %d bytes", MaxJWTSize) + } + + parsed, err := v.inner.Verify(ctx, rawJWT, time.Now()) + if err != nil { + return nil, err + } + + var kind Kind + switch parsed.SubstrateClaims.Kind { + case actoridjwt.KindActor: + kind = KindActor + case actoridjwt.KindWorkerForActor: + kind = KindWorkerForActor + default: + return nil, errors.New("oidcjwt: token carries neither actor.ate.dev nor worker-for-actor.ate.dev claim") + } + + sub := parsed.SubstrateClaims.Substrate + if sub == nil || sub.Atespace == "" || sub.ActorName == "" || sub.ActorUID == "" { + return nil, errors.New("oidcjwt: actor token must carry atespace, actor name, and actor UID") + } + if kind == KindWorkerForActor && sub.Node == "" { + return nil, errors.New("oidcjwt: worker-for-actor token must carry node") + } + if kind == KindActor && sub.Node != "" { + return nil, errors.New("oidcjwt: an actor token carries no node") + } + + actorClaims := &ActorClaims{ + Atespace: sub.Atespace, + ActorName: sub.ActorName, + ActorUID: sub.ActorUID, + Node: sub.Node, + } + + return &Claims{ + Issuer: parsed.Issuer, + Subject: parsed.Subject, + Audiences: parsed.Audiences, + Expiration: parsed.Expiration, + NotBefore: parsed.NotBefore, + IssuedAt: parsed.IssuedAt, + JTI: parsed.JTI, + Kind: kind, + ActorClaims: actorClaims, + }, nil +} + +// issuerRoots loads certificates based on whether the issuer is an in-cluster .svc or external. +func issuerRoots(issuer, caFile string) (func() (*x509.CertPool, error), string, error) { + u, err := url.Parse(issuer) + if err != nil { + return nil, "", fmt.Errorf("invalid issuer URL: %w", err) + } + host := strings.ToLower(strings.TrimSuffix(u.Hostname(), ".")) + if strings.HasSuffix(host, ".svc") { + return credbundle.PoolLoader(caFile), caFile, nil + } + return credbundle.SystemPoolLoader(caFile), "the system roots or " + caFile, nil +} diff --git a/pkg/oidcjwt/oidcjwt_test.go b/pkg/oidcjwt/oidcjwt_test.go new file mode 100644 index 0000000000..9403b6e630 --- /dev/null +++ b/pkg/oidcjwt/oidcjwt_test.go @@ -0,0 +1,562 @@ +// Copyright 2026 The Agent Substrate 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 oidcjwt_test + +import ( + "crypto" + "crypto/rand" + "crypto/rsa" + "crypto/sha256" + "crypto/tls" + "crypto/x509" + "crypto/x509/pkix" + "encoding/base64" + "encoding/json" + "encoding/pem" + "errors" + "math/big" + "net/http" + "net/http/httptest" + "os" + "path/filepath" + "strings" + "testing" + "time" + + "go.ate.dev/substrate/pkg/oidcjwt" +) + +const testAudience = "driver.openshell.dev" + +func b64url(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) } + +type jwkT struct { + KeyType string `json:"kty"` + KeyID string `json:"kid"` + RSAN string `json:"n,omitempty"` + RSAE string `json:"e,omitempty"` +} + +type jwkSetT struct { + Keys []jwkT `json:"keys"` +} + +type testIssuer struct { + server *httptest.Server + caFile string + jwks jwkSetT +} + +func newTestIssuer(t *testing.T) *testIssuer { + t.Helper() + ti := &testIssuer{} + mux := http.NewServeMux() + mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(map[string]any{ + "issuer": ti.server.URL, + "jwks_uri": ti.server.URL + "/jwks", + }) + }) + mux.HandleFunc("/jwks", func(w http.ResponseWriter, _ *http.Request) { + w.Header().Set("Content-Type", "application/json") + _ = json.NewEncoder(w).Encode(ti.jwks) + }) + ti.server = httptest.NewUnstartedServer(mux) + ti.server.StartTLS() + t.Cleanup(ti.server.Close) + + caCert := pem.EncodeToMemory(&pem.Block{ + Type: "CERTIFICATE", + Bytes: ti.server.Certificate().Raw, + }) + caPath := filepath.Join(t.TempDir(), "ca.pem") + if err := os.WriteFile(caPath, caCert, 0o600); err != nil { + t.Fatalf("writing CA: %v", err) + } + ti.caFile = caPath + + return ti +} + +func (ti *testIssuer) addRSAKey(kid string, pub *rsa.PublicKey) { + ti.jwks.Keys = append(ti.jwks.Keys, jwkT{ + KeyType: "RSA", + KeyID: kid, + RSAN: b64url(pub.N.Bytes()), + RSAE: b64url(big.NewInt(int64(pub.E)).Bytes()), + }) +} + +func mintTestJWT(t *testing.T, kid string, priv *rsa.PrivateKey, claims map[string]any) string { + t.Helper() + header := map[string]string{"alg": "RS256", "typ": "JWT", "kid": kid} + hb, err := json.Marshal(header) + if err != nil { + t.Fatalf("marshaling header: %v", err) + } + cb, err := json.Marshal(claims) + if err != nil { + t.Fatalf("marshaling claims: %v", err) + } + signingInput := b64url(hb) + "." + b64url(cb) + hashed := sha256.Sum256([]byte(signingInput)) + sig, err := rsa.SignPKCS1v15(rand.Reader, priv, crypto.SHA256, hashed[:]) + if err != nil { + t.Fatalf("signing: %v", err) + } + return signingInput + "." + b64url(sig) +} + +func TestVerifyActorToken(t *testing.T) { + ti := newTestIssuer(t) + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generating key: %v", err) + } + ti.addRSAKey("test-key", &key.PublicKey) + + cfg := oidcjwt.Config{ + Issuer: ti.server.URL, + IssuerCAFile: ti.caFile, + Audiences: []string{testAudience}, + } + + verifier, err := oidcjwt.New(t.Context(), cfg) + if err != nil { + t.Fatalf("New() failed: %v", err) + } + + now := time.Now() + claims := map[string]any{ + "iss": ti.server.URL, + "sub": "actor/test-atespace/test-actor", + "aud": []string{testAudience}, + "exp": now.Add(time.Hour).Unix(), + "nbf": now.Add(-time.Minute).Unix(), + "iat": now.Add(-time.Minute).Unix(), + "jti": "jwt-12345", + "actor.ate.dev": map[string]any{ + "atespace": "test-atespace", + "actorName": "test-actor", + "actorUID": "uid-9999", + }, + } + + rawJWT := mintTestJWT(t, "test-key", key, claims) + + verified, err := verifier.Verify(t.Context(), rawJWT) + if err != nil { + t.Fatalf("Verify() failed: %v", err) + } + + if verified.Issuer != ti.server.URL { + t.Errorf("got Issuer %q, want %q", verified.Issuer, ti.server.URL) + } + if verified.Subject != "actor/test-atespace/test-actor" { + t.Errorf("got Subject %q, want actor/test-atespace/test-actor", verified.Subject) + } + if verified.Kind != oidcjwt.KindActor { + t.Errorf("got Kind %v, want KindActor", verified.Kind) + } + if verified.ActorClaims == nil { + t.Fatal("ActorClaims is nil, expected populated claims") + } + if verified.ActorClaims.Atespace != "test-atespace" { + t.Errorf("got Atespace %q, want test-atespace", verified.ActorClaims.Atespace) + } + if verified.ActorClaims.ActorName != "test-actor" { + t.Errorf("got ActorName %q, want test-actor", verified.ActorClaims.ActorName) + } + if verified.ActorClaims.ActorUID != "uid-9999" { + t.Errorf("got ActorUID %q, want uid-9999", verified.ActorClaims.ActorUID) + } + if verified.ActorClaims.Node != "" { + t.Errorf("got Node %q, want empty for actor token", verified.ActorClaims.Node) + } +} + +func TestVerifyWorkerForActorToken(t *testing.T) { + ti := newTestIssuer(t) + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generating key: %v", err) + } + ti.addRSAKey("worker-key", &key.PublicKey) + + cfg := oidcjwt.Config{ + Issuer: ti.server.URL, + IssuerCAFile: ti.caFile, + Audiences: []string{testAudience}, + } + + verifier, err := oidcjwt.New(t.Context(), cfg) + if err != nil { + t.Fatalf("New() failed: %v", err) + } + + now := time.Now() + claims := map[string]any{ + "iss": ti.server.URL, + "sub": "worker-for-actor/test-atespace/test-actor", + "aud": []string{testAudience}, + "exp": now.Add(time.Hour).Unix(), + "nbf": now.Add(-time.Minute).Unix(), + "iat": now.Add(-time.Minute).Unix(), + "jti": "worker-jwt-54321", + "worker-for-actor.ate.dev": map[string]any{ + "atespace": "test-atespace", + "actorName": "test-actor", + "actorUID": "uid-9999", + "node": "worker-node-1", + }, + } + + rawJWT := mintTestJWT(t, "worker-key", key, claims) + + verified, err := verifier.Verify(t.Context(), rawJWT) + if err != nil { + t.Fatalf("Verify() failed: %v", err) + } + + if verified.Kind != oidcjwt.KindWorkerForActor { + t.Errorf("got Kind %v, want KindWorkerForActor", verified.Kind) + } + if verified.ActorClaims == nil { + t.Fatal("ActorClaims is nil") + } + if verified.ActorClaims.Node != "worker-node-1" { + t.Errorf("got Node %q, want worker-node-1", verified.ActorClaims.Node) + } +} + +func TestVerifyRejectsUnspecifiedOrMissingActorClaims(t *testing.T) { + ti := newTestIssuer(t) + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generating key: %v", err) + } + ti.addRSAKey("test-key", &key.PublicKey) + + cfg := oidcjwt.Config{ + Issuer: ti.server.URL, + IssuerCAFile: ti.caFile, + Audiences: []string{testAudience}, + } + + verifier, err := oidcjwt.New(t.Context(), cfg) + if err != nil { + t.Fatalf("New() failed: %v", err) + } + + now := time.Now() + + tests := []struct { + name string + claims map[string]any + }{ + { + name: "token with neither actor nor worker-for-actor claim", + claims: map[string]any{ + "iss": ti.server.URL, + "sub": "some-subject", + "aud": []string{testAudience}, + "exp": now.Add(time.Hour).Unix(), + }, + }, + { + name: "actor claim is empty object", + claims: map[string]any{ + "iss": ti.server.URL, + "sub": "actor/test-atespace/test-actor", + "aud": []string{testAudience}, + "exp": now.Add(time.Hour).Unix(), + "actor.ate.dev": map[string]any{}, + }, + }, + { + name: "actor claim missing actorUID", + claims: map[string]any{ + "iss": ti.server.URL, + "sub": "actor/test-atespace/test-actor", + "aud": []string{testAudience}, + "exp": now.Add(time.Hour).Unix(), + "actor.ate.dev": map[string]any{ + "atespace": "test-atespace", + "actorName": "test-actor", + }, + }, + }, + { + name: "worker-for-actor claim missing node", + claims: map[string]any{ + "iss": ti.server.URL, + "sub": "worker-for-actor/test-atespace/test-actor", + "aud": []string{testAudience}, + "exp": now.Add(time.Hour).Unix(), + "worker-for-actor.ate.dev": map[string]any{ + "atespace": "test-atespace", + "actorName": "test-actor", + "actorUID": "uid-9999", + }, + }, + }, + { + name: "actor claim carries node", + claims: map[string]any{ + "iss": ti.server.URL, + "sub": "actor/test-atespace/test-actor", + "aud": []string{testAudience}, + "exp": now.Add(time.Hour).Unix(), + "actor.ate.dev": map[string]any{ + "atespace": "test-atespace", + "actorName": "test-actor", + "actorUID": "uid-9999", + "node": "forbidden-node", + }, + }, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + rawJWT := mintTestJWT(t, "test-key", key, tt.claims) + if claims, err := verifier.Verify(t.Context(), rawJWT); err == nil { + t.Fatalf("expected Verify() to fail for %s, got claims: %+v", tt.name, claims) + } + }) + } +} + +func TestVerifyRejectsEmptyAndOversizedToken(t *testing.T) { + ti := newTestIssuer(t) + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generating key: %v", err) + } + ti.addRSAKey("test-key", &key.PublicKey) + + cfg := oidcjwt.Config{ + Issuer: ti.server.URL, + IssuerCAFile: ti.caFile, + Audiences: []string{testAudience}, + } + + verifier, err := oidcjwt.New(t.Context(), cfg) + if err != nil { + t.Fatalf("New() failed: %v", err) + } + + t.Run("empty token", func(t *testing.T) { + if _, err := verifier.Verify(t.Context(), ""); err == nil { + t.Fatal("expected error for empty token, got nil") + } + }) + + t.Run("oversized token exceeding MaxJWTSize", func(t *testing.T) { + oversized := strings.Repeat("a", oidcjwt.MaxJWTSize+1) + if _, err := verifier.Verify(t.Context(), oversized); err == nil { + t.Fatal("expected error for oversized token, got nil") + } + }) +} + +func TestVerifyRejectsAudienceMismatch(t *testing.T) { + ti := newTestIssuer(t) + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generating key: %v", err) + } + ti.addRSAKey("aud-key", &key.PublicKey) + + cfg := oidcjwt.Config{ + Issuer: ti.server.URL, + IssuerCAFile: ti.caFile, + Audiences: []string{"expected-audience"}, + } + + verifier, err := oidcjwt.New(t.Context(), cfg) + if err != nil { + t.Fatalf("New() failed: %v", err) + } + + claims := map[string]any{ + "iss": ti.server.URL, + "sub": "actor/test/bot", + "aud": []string{"wrong-audience"}, + "exp": time.Now().Add(time.Hour).Unix(), + "actor.ate.dev": map[string]any{ + "atespace": "test", + "actorName": "bot", + "actorUID": "uid-1", + }, + } + rawJWT := mintTestJWT(t, "aud-key", key, claims) + + if _, err := verifier.Verify(t.Context(), rawJWT); err == nil { + t.Fatal("expected error for audience mismatch, got nil") + } +} + +func TestVerifyRejectsExpiredToken(t *testing.T) { + ti := newTestIssuer(t) + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generating key: %v", err) + } + ti.addRSAKey("exp-key", &key.PublicKey) + + cfg := oidcjwt.Config{ + Issuer: ti.server.URL, + IssuerCAFile: ti.caFile, + Audiences: []string{testAudience}, + } + + verifier, err := oidcjwt.New(t.Context(), cfg) + if err != nil { + t.Fatalf("New() failed: %v", err) + } + + // More than 5 minutes skew in the past + expiredAt := time.Now().Add(-10 * time.Minute) + claims := map[string]any{ + "iss": ti.server.URL, + "sub": "actor/test/bot", + "aud": []string{testAudience}, + "exp": expiredAt.Unix(), + "actor.ate.dev": map[string]any{ + "atespace": "test", + "actorName": "bot", + "actorUID": "uid-1", + }, + } + rawJWT := mintTestJWT(t, "exp-key", key, claims) + + if _, err := verifier.Verify(t.Context(), rawJWT); err == nil { + t.Fatal("expected error for expired token, got nil") + } +} + +func TestConfigValidation(t *testing.T) { + ctx := t.Context() + + // Missing Issuer + if _, err := oidcjwt.New(ctx, oidcjwt.Config{IssuerCAFile: "ca.pem", Audiences: []string{"aud"}}); err == nil { + t.Error("expected error for missing Issuer, got nil") + } + + // Invalid Issuer scheme + if _, err := oidcjwt.New(ctx, oidcjwt.Config{Issuer: "http://insecure.example.com", IssuerCAFile: "ca.pem", Audiences: []string{"aud"}}); err == nil { + t.Error("expected error for non-https Issuer, got nil") + } + + // Missing IssuerCAFile + if _, err := oidcjwt.New(ctx, oidcjwt.Config{Issuer: "https://example.com", Audiences: []string{"aud"}}); err == nil { + t.Error("expected error for missing IssuerCAFile, got nil") + } + + // Missing Audiences + if _, err := oidcjwt.New(ctx, oidcjwt.Config{Issuer: "https://example.com", IssuerCAFile: "ca.pem"}); err == nil { + t.Error("expected error for missing Audiences, got nil") + } + + // Empty string inside Audiences + if _, err := oidcjwt.New(ctx, oidcjwt.Config{Issuer: "https://example.com", IssuerCAFile: "ca.pem", Audiences: []string{testAudience, ""}}); err == nil { + t.Error("expected error for empty audience string, got nil") + } +} + +func TestNewAllowsTransientStartupErrorAndVerifyReturnsKeysUnavailable(t *testing.T) { + srv := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { + http.Error(w, "idp starting up", http.StatusServiceUnavailable) + })) + defer srv.Close() + + caFile := filepath.Join(t.TempDir(), "ca.pem") + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: srv.Certificate().Raw}) + if err := os.WriteFile(caFile, certPEM, 0o600); err != nil { + t.Fatalf("writing CA file: %v", err) + } + + verifier, err := oidcjwt.New(t.Context(), oidcjwt.Config{ + Issuer: srv.URL, + IssuerCAFile: caFile, + Audiences: []string{testAudience}, + }) + if err != nil { + t.Fatalf("New() should tolerate transient startup fetch failure, got: %v", err) + } + + key, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generating key: %v", err) + } + rawJWT := mintTestJWT(t, "k1", key, map[string]any{ + "iss": srv.URL, + "sub": "actor/test/bot", + "aud": []string{testAudience}, + "exp": time.Now().Add(time.Hour).Unix(), + "actor.ate.dev": map[string]any{ + "atespace": "test", + "actorName": "bot", + "actorUID": "uid-1", + }, + }) + + _, err = verifier.Verify(t.Context(), rawJWT) + if !errors.Is(err, oidcjwt.ErrSigningKeysUnavailable) { + t.Fatalf("Verify() error = %v, want errors.Is(_, ErrSigningKeysUnavailable)", err) + } +} + +func TestNewFailsOnUntrustedTLSCertificate(t *testing.T) { + srv := httptest.NewTLSServer(http.NotFoundHandler()) + defer srv.Close() + + // Generate an unrelated self-signed CA cert so srv's cert fails TLS verification. + caKey, err := rsa.GenerateKey(rand.Reader, 2048) + if err != nil { + t.Fatalf("generating unrelated CA key: %v", err) + } + tmpl := &x509.Certificate{ + SerialNumber: big.NewInt(999), + Subject: pkix.Name{CommonName: "unrelated-test-ca"}, + NotBefore: time.Now().Add(-time.Hour), + NotAfter: time.Now().Add(time.Hour), + KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign, + BasicConstraintsValid: true, + IsCA: true, + } + der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &caKey.PublicKey, caKey) + if err != nil { + t.Fatalf("creating unrelated CA cert: %v", err) + } + + wrongCAFile := filepath.Join(t.TempDir(), "wrong-ca.pem") + certPEM := pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: der}) + if err := os.WriteFile(wrongCAFile, certPEM, 0o600); err != nil { + t.Fatalf("writing CA file: %v", err) + } + + _, err = oidcjwt.New(t.Context(), oidcjwt.Config{ + Issuer: srv.URL, + IssuerCAFile: wrongCAFile, + Audiences: []string{testAudience}, + }) + var certErr *tls.CertificateVerificationError + if !errors.As(err, &certErr) { + t.Fatalf("New() error = %v, want *tls.CertificateVerificationError", err) + } +} diff --git a/pkg/proto/ateconfigpb/apiconfig.pb.go b/pkg/proto/ateconfigpb/apiconfig.pb.go index 16f5ebd0c2..8004148e95 100644 --- a/pkg/proto/ateconfigpb/apiconfig.pb.go +++ b/pkg/proto/ateconfigpb/apiconfig.pb.go @@ -37,10 +37,13 @@ const ( // The unified configuration object for ate-api-server. type APIConfig struct { - state protoimpl.MessageState `protogen:"open.v1"` - Logging *APILogging `protobuf:"bytes,1,opt,name=logging,proto3" json:"logging,omitempty"` - unknownFields protoimpl.UnknownFields - sizeCache protoimpl.SizeCache + state protoimpl.MessageState `protogen:"open.v1"` + Logging *APILogging `protobuf:"bytes,1,opt,name=logging,proto3" json:"logging,omitempty"` + // When true, ate-api-server attaches the full server-side error as a + // google.rpc.DebugInfo detail on gRPC error responses. Defaults to false. + IncludeErrorDebugInfo bool `protobuf:"varint,2,opt,name=include_error_debug_info,json=includeErrorDebugInfo,proto3" json:"include_error_debug_info,omitempty"` + unknownFields protoimpl.UnknownFields + sizeCache protoimpl.SizeCache } func (x *APIConfig) Reset() { @@ -80,6 +83,13 @@ func (x *APIConfig) GetLogging() *APILogging { return nil } +func (x *APIConfig) GetIncludeErrorDebugInfo() bool { + if x != nil { + return x.IncludeErrorDebugInfo + } + return false +} + type APILogging struct { state protoimpl.MessageState `protogen:"open.v1"` // debug, info, warn, or error @@ -129,9 +139,10 @@ var File_pkg_proto_ateconfigpb_apiconfig_proto protoreflect.FileDescriptor const file_pkg_proto_ateconfigpb_apiconfig_proto_rawDesc = "" + "\n" + - "%pkg/proto/ateconfigpb/apiconfig.proto\x12\vateconfigpb\">\n" + + "%pkg/proto/ateconfigpb/apiconfig.proto\x12\vateconfigpb\"w\n" + "\tAPIConfig\x121\n" + - "\alogging\x18\x01 \x01(\v2\x17.ateconfigpb.APILoggingR\alogging\"\"\n" + + "\alogging\x18\x01 \x01(\v2\x17.ateconfigpb.APILoggingR\alogging\x127\n" + + "\x18include_error_debug_info\x18\x02 \x01(\bR\x15includeErrorDebugInfo\"\"\n" + "\n" + "APILogging\x12\x14\n" + "\x05level\x18\x01 \x01(\tR\x05levelB,Z*go.ate.dev/substrate/pkg/proto/ateconfigpbb\x06proto3" diff --git a/pkg/proto/ateconfigpb/apiconfig.proto b/pkg/proto/ateconfigpb/apiconfig.proto index b787ddc9b6..18d289cbbb 100644 --- a/pkg/proto/ateconfigpb/apiconfig.proto +++ b/pkg/proto/ateconfigpb/apiconfig.proto @@ -21,6 +21,10 @@ option go_package = "go.ate.dev/substrate/pkg/proto/ateconfigpb"; // The unified configuration object for ate-api-server. message APIConfig { APILogging logging = 1; + + // When true, ate-api-server attaches the full server-side error as a + // google.rpc.DebugInfo detail on gRPC error responses. Defaults to false. + bool include_error_debug_info = 2; } message APILogging { diff --git a/site/README.md b/site/README.md index e4157b0da2..b53c9d15a1 100644 --- a/site/README.md +++ b/site/README.md @@ -100,7 +100,7 @@ All three share `layouts/_partials/raw-markdown.html` with the per-page On doc pages, the first mention of each glossary term gets a hover card with its definition and a link to the term on the glossary page. Terms and -definitions come only from `docs/glossary.md`: each term is a top-level +definitions come only from `docs/reference/glossary.md`: each term is a top-level bullet like ```markdown diff --git a/site/assets/scss/_styles_project.scss b/site/assets/scss/_styles_project.scss index 47ba7a00e8..8248115769 100644 --- a/site/assets/scss/_styles_project.scss +++ b/site/assets/scss/_styles_project.scss @@ -2665,9 +2665,9 @@ footer { } &--preview { - background: #21162d; - border-color: #58397a; - color: #d2a8ff; + background: $substrate-preview-bg; + border-color: $substrate-preview-border; + color: $substrate-preview-fg; } &--experimental { @@ -2707,8 +2707,8 @@ footer { vertical-align: middle; &--preview { - background: #21162d; - color: #d2a8ff; + background: $substrate-preview-bg; + color: $substrate-preview-fg; } &--experimental { @@ -3896,11 +3896,18 @@ footer { } } +.as-apiref-controls { + display: flex; + align-items: center; + flex-wrap: wrap; + gap: 12px 24px; + margin-bottom: 16px; +} + .as-apiref-version { display: flex; align-items: center; gap: 10px; - margin-bottom: 16px; font-size: 13px; color: $substrate-muted; @@ -3920,6 +3927,116 @@ footer { } } +.as-apiref-preview-control { + display: inline-flex; + align-items: center; + gap: 6px; + font-size: 13px; + color: $substrate-muted; +} + +.as-apiref-toggle { + display: inline-flex; + align-items: center; + gap: 8px; + margin: 0; + cursor: pointer; + user-select: none; + transition: color 0.15s ease; + + &:hover { + color: $substrate-text; + } + + input { + position: absolute; + opacity: 0; + width: 0; + height: 0; + + &:focus-visible + .as-apiref-toggle__track { + outline: 2px solid $substrate-green; + outline-offset: 2px; + } + + &:checked + .as-apiref-toggle__track { + background: rgba($substrate-green, 0.2); + border-color: $substrate-green; + + &::after { + transform: translateX(14px); + background: $substrate-green; + } + } + } +} + +.as-apiref-toggle__track { + position: relative; + display: inline-block; + flex-shrink: 0; + width: 32px; + height: 18px; + border-radius: 999px; + background: $substrate-surface; + border: 1px solid $substrate-border; + transition: background 0.15s ease, border-color 0.15s ease; + + &::after { + content: ""; + position: absolute; + top: 2px; + left: 2px; + width: 12px; + height: 12px; + border-radius: 50%; + background: $substrate-muted; + transition: transform 0.15s ease, background 0.15s ease; + } +} + +.as-apiref-info { + position: relative; + display: inline-flex; + align-items: center; + justify-content: center; + color: $substrate-muted; + text-decoration: none; + transition: color 0.15s ease; + + &:hover, + &:focus-visible { + color: $substrate-green; + text-decoration: none; + } + + &::after { + content: attr(data-tooltip); + position: absolute; + bottom: calc(100% + 6px); + left: 50%; + transform: translateX(-50%); + padding: 3px 8px; + border-radius: 5px; + border: 1px solid $substrate-border; + background: $substrate-surface-elevated; + color: $substrate-text; + font-size: 12px; + line-height: 1.3; + white-space: nowrap; + box-shadow: 0 4px 12px rgba(0, 0, 0, 0.4); + opacity: 0; + pointer-events: none; + transition: opacity 0.12s ease; + z-index: 20; + } + + &:hover::after, + &:focus-visible::after { + opacity: 1; + } +} + .as-sb__tree { list-style: none; margin: 2px 0 6px 10px; @@ -3981,4 +4098,7 @@ footer { --apiref-code-number: #{$substrate-yellow}; --apiref-code-keyword: #{$substrate-blue}; --apiref-code-punct: #{$substrate-muted}; + --apiref-preview-bg: #{$substrate-preview-bg}; + --apiref-preview-fg: #{$substrate-preview-fg}; + --apiref-preview-border: #{$substrate-preview-border}; } diff --git a/site/assets/scss/_variables_project.scss b/site/assets/scss/_variables_project.scss index d41678cf97..e0019a137c 100644 --- a/site/assets/scss/_variables_project.scss +++ b/site/assets/scss/_variables_project.scss @@ -36,6 +36,10 @@ $substrate-heading: #f4f8f5; $substrate-muted: #9aa89f; $substrate-subtle: #6e7d73; +$substrate-preview-bg: #21162d; +$substrate-preview-border: #58397a; +$substrate-preview-fg: #d2a8ff; + $primary: $substrate-green-dark; $secondary: #fff; $dark: #0e130f; diff --git a/site/layouts/docs/api-reference.html b/site/layouts/docs/api-reference.html index 51c5919386..8497f6ccc7 100644 --- a/site/layouts/docs/api-reference.html +++ b/site/layouts/docs/api-reference.html @@ -39,19 +39,35 @@ {{- range where site.RegularPages "Layout" "api-reference" -}} {{- $urls = merge $urls (dict (.Params.api_version | default "latest") .RelPermalink) -}} {{- end -}} +{{- $previewGatesURL := "docs/reference/preview-gates/" | relURL -}} +{{- with site.GetPage "/docs/reference/preview-gates" -}} + {{- $previewGatesURL = .RelPermalink -}} +{{- end -}} -{{- with resources.Get "api-reference/versions.json" }} -{{/* Switching versions keeps the anchor, so the reader stays on the same - resource when the other version has it. */ -}} -
- - + -{{- end }} {{ $files.body.Content | safeHTML }} {{ end -}} diff --git a/site/package-lock.json b/site/package-lock.json index 8cc1525fda..0742a88cd7 100644 --- a/site/package-lock.json +++ b/site/package-lock.json @@ -521,13 +521,13 @@ } }, "node_modules/source-map-js": { - "version": "1.2.1", - "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz", - "integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==", + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", "dev": true, "license": "BSD-3-Clause", "engines": { - "node": ">=0.10.0" + "node": ">=6.0.0" } }, "node_modules/string-width": { diff --git a/tools/apitool/go.mod b/tools/apitool/go.mod index c2aec00e01..106ab9e389 100644 --- a/tools/apitool/go.mod +++ b/tools/apitool/go.mod @@ -2,7 +2,7 @@ module go.ate.dev/substrate/tools/apitool go 1.27.0 -toolchain go1.27.3 +toolchain go1.27.4 replace go.ate.dev/substrate => ../.. @@ -14,67 +14,59 @@ require ( github.com/yuin/goldmark v1.8.5 go.ate.dev/substrate v0.0.0-00010101000000-000000000000 google.golang.org/protobuf v1.36.12 - k8s.io/apiextensions-apiserver v0.37.1 + k8s.io/apiextensions-apiserver v0.38.0-beta.0 + k8s.io/gengo/v2 v2.0.0-20260408192533-25e2208e0dc3 sigs.k8s.io/yaml v1.6.0 ) require ( - cel.dev/expr v0.25.2 // indirect + cel.dev/cel-go v0.33.2 // indirect + cel.dev/expr v0.25.3 // indirect github.com/antlr4-go/antlr/v4 v4.13.1 // indirect github.com/beorn7/perks v1.0.1 // indirect github.com/blang/semver/v4 v4.0.0 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/dlclark/regexp2/v2 v2.2.1 // indirect - github.com/fxamacker/cbor/v2 v2.9.1 // indirect + github.com/fxamacker/cbor/v2 v2.9.4 // indirect github.com/go-logr/logr v1.4.4 // indirect - github.com/go-openapi/jsonpointer v1.0.0 // indirect - github.com/go-openapi/jsonreference v1.0.0 // indirect - github.com/go-openapi/swag v0.28.0 // indirect - github.com/go-openapi/swag/cmdutils v0.28.0 // indirect - github.com/go-openapi/swag/conv v0.28.0 // indirect - github.com/go-openapi/swag/fileutils v0.28.0 // indirect - github.com/go-openapi/swag/jsonutils v0.28.0 // indirect - github.com/go-openapi/swag/loading v0.28.0 // indirect - github.com/go-openapi/swag/mangling v0.28.0 // indirect - github.com/go-openapi/swag/netutils v0.28.0 // indirect - github.com/go-openapi/swag/pools v0.28.0 // indirect - github.com/go-openapi/swag/stringutils v0.28.0 // indirect - github.com/go-openapi/swag/typeutils v0.28.0 // indirect - github.com/go-openapi/swag/yamlutils v0.28.0 // indirect - github.com/google/cel-go v0.31.0 // indirect + github.com/go-openapi/jsonpointer v1.0.2 // indirect + github.com/go-openapi/jsonreference v1.0.2 // indirect + github.com/go-openapi/swag/conv v0.29.2 // indirect + github.com/go-openapi/swag/jsonutils v0.29.2 // indirect + github.com/go-openapi/swag/pools v0.29.2 // indirect + github.com/go-openapi/swag/typeutils v0.29.2 // indirect github.com/google/gnostic-models v0.7.1 // indirect github.com/inconshreveable/mousetrap v1.1.0 // indirect - github.com/json-iterator/go v1.1.12 // 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/prometheus/client_golang v1.24.1 // indirect - github.com/prometheus/client_model v0.6.2 // indirect - github.com/prometheus/common v0.70.1 // indirect - github.com/prometheus/procfs v0.21.1 // indirect + github.com/pandatix/go-abnf v0.5.5 // indirect + github.com/prometheus/client_golang v1.25.0 // indirect + github.com/prometheus/client_model v0.6.3 // indirect + github.com/prometheus/common v0.73.1 // indirect + github.com/prometheus/procfs v0.22.0 // indirect github.com/spf13/pflag v1.0.10 // indirect github.com/x448/float16 v0.8.4 // indirect - go.opentelemetry.io/otel v1.45.0 // indirect - go.opentelemetry.io/otel/trace v1.45.0 // indirect + go.opentelemetry.io/otel v1.47.0 // indirect + go.opentelemetry.io/otel/trace v1.47.0 // indirect go.yaml.in/yaml/v2 v2.4.4 // indirect go.yaml.in/yaml/v3 v3.0.5 // indirect - golang.org/x/exp v0.0.0-20260718201538-764159d718ef // indirect - golang.org/x/net v0.60.0 // indirect + golang.org/x/exp v0.0.0-20260908205506-85c1c2202aba // indirect + golang.org/x/net v0.62.0 // indirect golang.org/x/sync v0.24.0 // indirect golang.org/x/sys v0.49.0 // indirect golang.org/x/text v0.43.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect - google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect - google.golang.org/grpc v1.83.2 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 // indirect + google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc // indirect + google.golang.org/grpc v1.85.0 // indirect gopkg.in/inf.v0 v0.9.1 // indirect - k8s.io/api v0.37.1 // indirect - k8s.io/apimachinery v0.37.1 // indirect - k8s.io/apiserver v0.37.1 // indirect - k8s.io/component-base v0.37.1 // indirect + k8s.io/api v0.38.0-beta.0 // indirect + k8s.io/apiextensions-api v0.38.0-beta.0 // indirect + k8s.io/apimachinery v0.38.0-beta.0 // indirect + k8s.io/apiserver v0.38.0-beta.0 // indirect + k8s.io/component-base v0.38.0-beta.0 // indirect k8s.io/klog/v2 v2.140.0 // indirect - k8s.io/kube-openapi v0.0.0-20260721132016-d427ff9ee9ad // indirect + k8s.io/kube-openapi v0.0.0-20261014044854-ca3452a79603 // indirect k8s.io/utils v0.0.0-20260626114624-be93311217bd // indirect sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 // indirect sigs.k8s.io/randfill v1.0.0 // indirect - sigs.k8s.io/structured-merge-diff/v6 v6.4.2 // indirect + sigs.k8s.io/structured-merge-diff/v7 v7.0.1 // indirect ) diff --git a/tools/apitool/go.sum b/tools/apitool/go.sum index cd3700580c..459e6ce6d8 100644 --- a/tools/apitool/go.sum +++ b/tools/apitool/go.sum @@ -1,5 +1,7 @@ -cel.dev/expr v0.25.2 h1:K6j46C81hXtZQfuX60cVWQFBJahKSE2gfRbNuvr5bFs= -cel.dev/expr v0.25.2/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= +cel.dev/cel-go v0.33.2 h1:eAcEdBguc6AFrGbPOyE0g168Uey4kKFW9J6qsBLSeMU= +cel.dev/cel-go v0.33.2/go.mod h1:DnVip7tpJSsgZymwfT+m1tnEVy3ivAjSMXPx12YrMkU= +cel.dev/expr v0.25.3 h1:A2jO8jwOugrrovveCWfj0KEZOfqiLgAcwjpHPhzIGw0= +cel.dev/expr v0.25.3/go.mod h1:hrXvqGP6G6gyx8UAHSHJ5RGk//1Oj5nXQ2NI02Nrsg4= github.com/alecthomas/assert/v2 v2.11.0 h1:2Q9r3ki8+JYXvGsDyBXwH3LcJ+WK5D0gc5E8vS6K3D0= github.com/alecthomas/assert/v2 v2.11.0/go.mod h1:Bze95FyfUr7x34QZrjL+XP+0qgp/zg8yS+TtBj1WA3k= github.com/alecthomas/chroma/v2 v2.27.0 h1:FodwmyOBgJULFYmDqibcp9pvfDLWdtPRh9v/r5BXYZs= @@ -23,65 +25,44 @@ github.com/coreos/go-semver v0.3.1/go.mod h1:irMmmIw/7yzSRPWryHsK7EYSg09caPQL03V 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/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g= -github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= -github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM= github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/dlclark/regexp2/v2 v2.2.1 h1:mf4KkFUj0gJuarK8P+LgiS+Lit7m9N1yAwEfPbee7R0= github.com/dlclark/regexp2/v2 v2.2.1/go.mod h1:avUrQvPaLz2DrFNHJF0taWAFFX2C1GMSSoeiqFjcBmU= -github.com/emicklei/go-restful/v3 v3.13.0 h1:C4Bl2xDndpU6nJ4bc1jXd+uTmYPVUwkD6bFY/oTyCes= -github.com/emicklei/go-restful/v3 v3.13.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= +github.com/emicklei/go-restful/v3 v3.14.0 h1:6V6Ba8/5W1Z7amPinklZeCMlHBMwj53thpfxazCLMX4= +github.com/emicklei/go-restful/v3 v3.14.0/go.mod h1:6n3XBCmQQb25CM2LCACGz8ukIrRry+4bhvbpWn3mrbc= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= -github.com/fxamacker/cbor/v2 v2.9.1 h1:2rWm8B193Ll4VdjsJY28jxs70IdDsHRWgQYAI80+rMQ= -github.com/fxamacker/cbor/v2 v2.9.1/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= +github.com/fxamacker/cbor/v2 v2.9.4 h1:xwjVlxEMR3S605oUlgBjKLTTeGFciYPGYCtF/35LKGo= +github.com/fxamacker/cbor/v2 v2.9.4/go.mod h1:vM4b+DJCtHn+zz7h3FFp/hDAI9WNWCsZj23V5ytsSxQ= 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= github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag= github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE= -github.com/go-openapi/jsonpointer v1.0.0 h1:kR9tHqY0CtZaOPVFm622dPVNhrvYpwr4uCxgL3h1H8s= -github.com/go-openapi/jsonpointer v1.0.0/go.mod h1:Z3rw7dWu1p9IgitXCFamSlA5lmDiklEB6vkaxcNZW5Y= -github.com/go-openapi/jsonreference v1.0.0 h1:jlmTr6torcd1YgDQvSfNmRtKzYDO4FGBkrAdlAVWnpY= -github.com/go-openapi/jsonreference v1.0.0/go.mod h1:jtwdyGbJk0Xhe5Y+rwtglQP6Sb1WZST4rT32LWB+sv0= -github.com/go-openapi/swag v0.28.0 h1:xkgbOSKj6DZziNpyqRRAOt3GJGtgjgsd2RoyT30VWuw= -github.com/go-openapi/swag v0.28.0/go.mod h1:4qYnT3Cqr1p1VknOdPo70evN4rgQnAg6jwApHyxSGIg= -github.com/go-openapi/swag/cmdutils v0.28.0 h1:7TOeNtkYru1SG8Y34tDh9WBbLsMqGnptuxWiHREPZ4Q= -github.com/go-openapi/swag/cmdutils v0.28.0/go.mod h1:Sm1MVFMkF6guJJ+pQqHnQA3N0j9qALV3NxzDSv6bETM= -github.com/go-openapi/swag/conv v0.28.0 h1:GtqqbyFe7vR5Y7ehxG9W6/OvrSFdf1OLeTGp40TqxH8= -github.com/go-openapi/swag/conv v0.28.0/go.mod h1:mbUE+mzctnhxi864m0Q07SpN8OowD9JhxmxuYvZZD/k= -github.com/go-openapi/swag/fileutils v0.28.0 h1:Z04XWQD7R8Eq+7GnOrjovBxPPmZzsS4gt2H2GPGIViU= -github.com/go-openapi/swag/fileutils v0.28.0/go.mod h1:VvJFZLTZS0AI854gEQz5tk7dBESdLjiNUMSZ/th2ry8= -github.com/go-openapi/swag/jsonutils v0.28.0 h1:YIch6FwO7RXzeAnbO8Tu7dWBZeUEH+4nA0HXltVTnv4= -github.com/go-openapi/swag/jsonutils v0.28.0/go.mod h1:CYM3WlTUcagR2ZoHdz54di/cbBqt82tuxuXgAjxw+mg= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0 h1:qV+VVUAx5Oro8WjVWpZeql7YReTKhT4smR4zhcOQZr0= -github.com/go-openapi/swag/jsonutils/fixtures_test v0.28.0/go.mod h1:mofwUWx70wvskwESqRJ//k/9kURmCgyJl5m5Ppoh5kY= -github.com/go-openapi/swag/loading v0.28.0 h1:td8QZdZC9MIYGGSnSPKShKiK22I2tU5UQvuUhIBPRLU= -github.com/go-openapi/swag/loading v0.28.0/go.mod h1:rXB0QiQX5mMveXEA7ouM4KiiM9jVJe4K6BVbwhD1M4k= -github.com/go-openapi/swag/mangling v0.28.0 h1:pH8eyeNO9SLYsTMWJrurnNfKmDa28XrlA+HePVD53VM= -github.com/go-openapi/swag/mangling v0.28.0/go.mod h1:jtBE2+V+3pILxOR7Vgce+Cwp6A2PgZbvVqfNntbVs0w= -github.com/go-openapi/swag/netutils v0.28.0 h1:YXN6TALEi2pzts8/8GNm6T61HTAZsieukGZidap989k= -github.com/go-openapi/swag/netutils v0.28.0/go.mod h1:J+WYyFMLtvtCGqa6jLv+YNUmIKI3ZRQRrvfNDMoQoEQ= -github.com/go-openapi/swag/pools v0.28.0 h1:HPMZWSAfce3rdVTFcjFiCIBtDg9h4x2QlRrHipwhxeU= -github.com/go-openapi/swag/pools v0.28.0/go.mod h1:kVQefhSK5RWuRe7BXsL8htgBPAMpN7HDGpGEknqugeE= -github.com/go-openapi/swag/stringutils v0.28.0 h1:ixsc9iYgDPubHL/8nSkbnryEHpD2VRlBMLKpQyPXcDU= -github.com/go-openapi/swag/stringutils v0.28.0/go.mod h1:lzRN95CxXmA03XcDWHLOb6nOMcxCqR5rGY0lOgsfRoM= -github.com/go-openapi/swag/typeutils v0.28.0 h1:nRBKSBXjDgf01VDPB3fWeD9nQuhCOVeIYAkUx2tbkyY= -github.com/go-openapi/swag/typeutils v0.28.0/go.mod h1:Srm0xFNRZ1Y+vCxJclo5qzx8aj+1pAKda/YfFPrG0dQ= -github.com/go-openapi/swag/yamlutils v0.28.0 h1:TV3JXH6DS46KUroDtMLAYHGkdWf5VDq3wVWFirmzROY= -github.com/go-openapi/swag/yamlutils v0.28.0/go.mod h1:x0q/yndZHEgk9Rx3DyDqzFUmHy55KTvIZldvF2dTJXs= -github.com/go-openapi/testify/enable/yaml/v2 v2.6.0 h1:gGHwAJ0R/5jU8BEGDbfRNR3hL68dAVi84WuOApp29B0= -github.com/go-openapi/testify/enable/yaml/v2 v2.6.0/go.mod h1:tY+St1SGq4NFl0QIqdTY4aEdbChAHxhyB77XQi9iJCo= -github.com/go-openapi/testify/v2 v2.6.0 h1:5PKH2HE7YJ/LuRPQGvSxBRlFXNQhSetBLlGAgUEu3ug= -github.com/go-openapi/testify/v2 v2.6.0/go.mod h1:SgsVHtfooshd0tublTtJ50FPKhujf47YRqauXXOUxfw= +github.com/go-openapi/jsonpointer v1.0.2 h1:NbW7xT2b+l7x+JefiPGDsZWsrLk1ogrz4AHK1TTzMt8= +github.com/go-openapi/jsonpointer v1.0.2/go.mod h1:N0rI4MbNKD7xAFTiHtB+5Nhrg2j/wwYg7m7Fmb4/jk8= +github.com/go-openapi/jsonreference v1.0.2 h1:oS4et8FOf3p3UQxEo4Xt0esijmBUM+F259Xl72OSZsc= +github.com/go-openapi/jsonreference v1.0.2/go.mod h1:TbUNSOo+fcorZjFaNoiSDSoaNnnZtqJtLGR1PuvE/Cs= +github.com/go-openapi/swag/conv v0.29.2 h1:8c9shoB8l0QRSR6ymq1llHdBWDqpIgJfjTGHx3Vuhm0= +github.com/go-openapi/swag/conv v0.29.2/go.mod h1:AZS0YigTNf8qNtD6WqJz/N4RUNmpr76SyjFGkq4+p6Q= +github.com/go-openapi/swag/jsonutils v0.29.2 h1:uZNSD2/rJDYAfvsLYkykTzXuyxM3QpDKV9jhRHrMu6k= +github.com/go-openapi/swag/jsonutils v0.29.2/go.mod h1:ONTdNvj3Y+IXRzfa17E+Rgt2ns/qiSOYjIo2K7v2yDs= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2 h1:w+Fd6EBOMGlC74GYGHqCLGyb3Bpams8TtNrgM/SG4jo= +github.com/go-openapi/swag/jsonutils/fixtures_test v0.29.2/go.mod h1:HC2egPORFzbj/gf05Zrfgz8Mgplx3oW7hgGi7pjZVhM= +github.com/go-openapi/swag/pools v0.29.2 h1:PlGoDRF8WtSyXkedZZkpW3f9wDhFf3u8KtaBcmgmh8c= +github.com/go-openapi/swag/pools v0.29.2/go.mod h1:V3lhxVT4qDYRqc2MRSSbLsTYIYV/2HlHafhyEkmzLIc= +github.com/go-openapi/swag/typeutils v0.29.2 h1:O7aVvkTs3pXwikgtrPLenigEMdQFgONKRooQA9pgf2I= +github.com/go-openapi/swag/typeutils v0.29.2/go.mod h1:7+GDG+uz9Ke+eVt4rClZg7wklSDp8hT/mKNh/pC26TE= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0 h1:wPW6YRgx3+SID1yUy/Xwa17L8kFEaEKod2VRbJDZNUs= +github.com/go-openapi/testify/enable/yaml/v2 v2.7.0/go.mod h1:mI1M88etYbc3PhgHsWQK2kwvNwW5aGFqMPbmib+SGIs= +github.com/go-openapi/testify/v2 v2.8.0 h1:19QDx5b57p8KjO2E4sgs/woL4Akp+FGLRlVm2xn0Rho= +github.com/go-openapi/testify/v2 v2.8.0/go.mod h1:4gUN8jC+RqOE2qjW/vDmfyTvl5BCht4qL7oca0odrak= github.com/golang/protobuf v1.5.4 h1:i7eJL8qZTpSEXOPTxNKhASYpMn+8e5Q6AdndVa1dWek= github.com/golang/protobuf v1.5.4/go.mod h1:lnTiLA8Wa4RWRcIUkrtSVa5nRhsEGBg48fD6rSs7xps= -github.com/google/cel-go v0.31.0 h1:H0bhpFTqOvmHrBGrWKp7ZlhBm5Hh8PYUEXnwxT1LL7A= -github.com/google/cel-go v0.31.0/go.mod h1:X0bD6iVNR8pkROSOoHVdgTkzmRcosof7WQqCD6wcMc8= github.com/google/gnostic-models v0.7.1 h1:SisTfuFKJSKM5CPZkffwi6coztzzeYUhc3v4yxLWH8c= github.com/google/gnostic-models v0.7.1/go.mod h1:whL5G0m6dmc5cPxKc5bdKdEN3UjI7OUGxBlw57miDrQ= github.com/google/go-cmp v0.7.0 h1:wk8382ETsv4JYUZwIsn6YpYiWiBsYLSJiTsyBybVuN8= github.com/google/go-cmp v0.7.0/go.mod h1:pXiqmnSA92OHEEa9HXL2W4E7lf9JzCmGVUdgjX3N/iU= -github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= 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/grpc-ecosystem/go-grpc-middleware v1.4.0 h1:UH//fgunKIs4JdUbpDl1VZCDaL56wXCB/5+wF6uHfaI= @@ -95,71 +76,64 @@ github.com/hexops/gotextdiff v1.0.3 h1:gitA9+qJrrTCsiCl7+kh75nPqQt1cx4ZkudSTLoUq github.com/hexops/gotextdiff v1.0.3/go.mod h1:pSWU5MAI3yDq+fZBTazCSJysOMbxWL1BSow5/V2vxeg= github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8= github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw= -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/klauspost/compress v1.19.1 h1:VsB4HPswih7mmZ8WleSFQ75c/Ui1M4trX5oAsJnhSlk= -github.com/klauspost/compress v1.19.1/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= github.com/kylelemons/godebug v1.1.0 h1:RPNrshWIDI6G2gRW9EHilWtl7Z6Sb1BR0xunSBf0SNc= github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+fNqagV/RAw= -github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= -github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= -github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= -github.com/modern-go/reflect2 v1.0.3-0.20250322232337-35a7c28c31ee h1:W5t00kpgFdJifH4BDsTlE89Zl93FEloxaWZfGcifgq8= -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/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/onsi/gomega v1.44.0 h1:eAiGl3Pw5jz5GQdDff0BcxYpAX1JxW8xD7mFUuwNfZQ= +github.com/onsi/gomega v1.44.0/go.mod h1:e/C2HwaZ1DhvjzXXuFhcR7hY7Sh9pl7MmoWKEjzwcdA= +github.com/pandatix/go-abnf v0.5.5 h1:EXex5KkRQx4Dm6GnpAcQnIMBs9KiK0uf8p/wq+4t9PM= +github.com/pandatix/go-abnf v0.5.5/go.mod h1:AE0KD3/VNoCjGzc1gqetRKshbI4SYErXQ/8kPenR5mc= 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= -github.com/prometheus/client_golang v1.24.1 h1:JnJkREXzWxUdCuPFpIWZiPispT9xVV59uiuyR2bPlnU= -github.com/prometheus/client_golang v1.24.1/go.mod h1:F+oSRECHg4sse5ucfYpYDeIv/hu68Zo0uoHKetWnzcE= -github.com/prometheus/client_model v0.6.2 h1:oBsgwpGs7iVziMvrGhE53c/GrLUsZdHnqNwqPLxwZyk= -github.com/prometheus/client_model v0.6.2/go.mod h1:y3m2F6Gdpfy6Ut/GBsUqTWZqCUvMVzSfMLjcu6wAwpE= -github.com/prometheus/common v0.70.1 h1:1HvjP4D5oL3t8RsPlwxA9onvvStjtIHYE5XuuwOi/PY= -github.com/prometheus/common v0.70.1/go.mod h1:VdFUQDMZK3VLkurFUVhia6uys/0suUp86TJz5qbJRhc= -github.com/prometheus/procfs v0.21.1 h1:GljZCt+zSTS+NZq88cyQ1LjZ+RCHp3uVuabBWA5+OJI= -github.com/prometheus/procfs v0.21.1/go.mod h1:aB55Cww9pdSJVHk0hUf0inxWyyjPogFIjmHKYgMKmtY= +github.com/prometheus/client_golang v1.25.0 h1:cDtW1TcFsMi1RJc8khwCKB4VhzwV04aKqbYtNOXuiK0= +github.com/prometheus/client_golang v1.25.0/go.mod h1:j2X/4/kaQHLPnmyEU8zjmkndo1T317VpCIQEml8LTKk= +github.com/prometheus/client_model v0.6.3 h1:O0jaTVAYNxTHYInEPFJt5I3+sN8zqBtVMPTB1qyxiEo= +github.com/prometheus/client_model v0.6.3/go.mod h1:gpN5P9S7Rr6Yr92PiQ+Ixvhf6JZEkF1dnxsYL2aPBEM= +github.com/prometheus/common v0.73.1 h1:SZWh/j4AvhCdhX8jvYSnxvPxhWlC9QZkjJ+tOrEr7kU= +github.com/prometheus/common v0.73.1/go.mod h1:I9aA/Ukz9s1olOobh8KtCkU7B1mQPQsB9UvQPsUQ1Dk= +github.com/prometheus/procfs v0.22.0 h1:6q9+/JL9IKAPbCmBrv9n5O5Ty3NKnciV5X7YGw0oics= +github.com/prometheus/procfs v0.22.0/go.mod h1:CvmFr/GVhIjIvWJZW3tgkODBQMRIf0EyWMQLHCHab58= github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM= github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU= github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4= github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk= github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg= -github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= -github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= github.com/stretchr/testify v1.12.1 h1:EuwCh5fleGS7H32xRwO3wRGT7DxrDhLAT6FF8MpWDWE= github.com/stretchr/testify v1.12.1/go.mod h1:MDEgiDPPsNp5cuIrHPPCyornHKgEVbtFUmoNlxoYthg= 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/yuin/goldmark v1.8.5 h1:r6N5afV5qj/5S4UTch8agZHJ8UxNCMwX7WjkkJam2NA= github.com/yuin/goldmark v1.8.5/go.mod h1:ip/1k0VRfGynBgxOz0yCqHrbZXhcjxyuS66Brc7iBKg= -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/api/v3 v3.7.3 h1:2tumepXe+wi7Wab64uUO71K7ISQyUWLGC1DJbbc59sY= +go.etcd.io/etcd/api/v3 v3.7.3/go.mod h1:HOR9Qn4gb/1/hVAmYprmlLpvTe6ZgfgNS9Z/+Ty65po= +go.etcd.io/etcd/client/pkg/v3 v3.7.3 h1:5zMwNu3ycrzCeA5NwOfQbxFRhqq974chq1DrYMua4QI= +go.etcd.io/etcd/client/pkg/v3 v3.7.3/go.mod h1:/OhzqYrF0U7d1NOk55VMyUQGbYD1WoIe4bJwxb47wOk= +go.etcd.io/etcd/client/v3 v3.7.3 h1:UrXcetgkuSEocaBlQlulQRJlXLEnUAHuBRbHh0lue1Q= +go.etcd.io/etcd/client/v3 v3.7.3/go.mod h1:DcPxpqcpV8WIaRi/2waPCx0/Uq8rQUweDJaDYZk1gEE= 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.70.0 h1:oECp5f+hN7nkwjU/8BxQ/q23bGPb8FIrD839owX222E= -go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.70.0/go.mod h1:DqEFwLumhzMBDQv9PcWbyoDxHI/4lAk6CM4nJBH39sc= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0 h1:LMuyCAyfalSjDyjdC65nK6N0zoTT63+E/u95X0JovZI= -go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.70.0/go.mod h1:085m8qbm4hgc8rZWGDEa4vmyyo2c3nPxUslYUKUIU04= -go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU= -go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0 h1:QRefszxJmfPdjXUUm3j6iDzY03mTPXMjqErFqQ67vUg= -go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.45.0/go.mod h1:Tiz03lTBVBrm7eWZBOidzEaYaJa8tjwGUGv6d8mlTyk= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0 h1:Tq+E65HaNbZTeqcLw6QUhsV+/EIWdkfUH2CQzcrlE5M= +go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.72.0/go.mod h1:A+EVhDakAj1waJBPhmTszZaSr08ww8MRRKy1nB1rqck= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s= +go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0/go.mod h1:tOsftB4SslBwwErVEPaenU2RpThXWPIU8DoJHEC4dyw= +go.opentelemetry.io/otel v1.47.0 h1:j7ALJ/zgkS7Z6aeJW09p8VC9804bC+PpeTfCD4XPnOM= +go.opentelemetry.io/otel v1.47.0/go.mod h1:8wS9O2qfXrYrzp6hIF/HOYJJf/wIhFPhR2xLuP+iXQU= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 h1:julhjPeUH/q/7hinbSdDdqt5h7Zw9YWmRlWRhI0jd54= +go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0/go.mod h1:Ao2mz688LH/tFf0yMAenidq6k2YNSx6SIY2q6jDACck= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0 h1:fG5MCxGz8+2VtrN/WgqSpJFctVz24gpxj8CxkKmc8Ww= go.opentelemetry.io/otel/exporters/otlp/otlptrace/otlptracegrpc v1.45.0/go.mod h1:BmAYTn+3ysbRe+IU2msxmf5Rx3g6DHvex+tWI3LdhYI= -go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M= -go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s= -go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw= -go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA= -go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o= -go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA= -go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag= -go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc= +go.opentelemetry.io/otel/log v1.47.0 h1:cOTS1CcLbSQeZKanGJ+0JpF/+t4PELi3O3bbl2lqCcI= +go.opentelemetry.io/otel/log v1.47.0/go.mod h1:9byitSQ5pLC6PpqwGXjqdMKya6ZTswHRZh2vvXT33nw= +go.opentelemetry.io/otel/metric v1.47.0 h1:4PptaldXx3Eat1XjMZ68pPJEs5wrhlemctZE9a3UdWY= +go.opentelemetry.io/otel/metric v1.47.0/go.mod h1:ADGSXxRrXM6bjbvLo535EstVFlPpPYZm4LBKixjDHwU= +go.opentelemetry.io/otel/sdk v1.47.0 h1:zWXEr4j2lFefG87TU6Yg8a7ngfohIKFZHKp0Hf5hC6I= +go.opentelemetry.io/otel/sdk v1.47.0/go.mod h1:VUc24kiOeoGsxG8G9ULx3fWKvB7jMhnGE8Oi607lgR0= +go.opentelemetry.io/otel/trace v1.47.0 h1:JOjX/Oci8K94QHddo+bbfya/Ai/nf6/dt9ZfrFNWSrM= +go.opentelemetry.io/otel/trace v1.47.0/go.mod h1:jNaSLa2PZEYFG6fRjJABAu+bw4FS08uDmPg28lTghu0= go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk= go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E= go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto= @@ -173,12 +147,12 @@ 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/exp v0.0.0-20260718201538-764159d718ef h1:LkZ48HFgy/TvhTI0bcWkjgFkgLyKUwcTbDjS0DUjw+A= -golang.org/x/exp v0.0.0-20260718201538-764159d718ef/go.mod h1:EdfpwwqSu+0Li0mzskwHU6FWDV3t9Q+RZDo3QMUtL3Q= -golang.org/x/net v0.60.0 h1:79p50tfZlm0J9YfoDsSi639qSXNGVwEzOPLCxM2FsYU= -golang.org/x/net v0.60.0/go.mod h1:2DA/G1UfVbCpQPeWTmMPGY7Cs2PkBkwu743bVX5PIVg= -golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs= -golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q= +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/net v0.62.0 h1:18ELalfM5+XNRwzM2nYqXsZQ9ByS1uhj2O/U7+5jqRY= +golang.org/x/net v0.62.0/go.mod h1:WgDCOTH8iwtB66T4/GfI94AHo/hhdb7Hah9NDseQfiI= +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.24.0 h1:iqiDrGoDgyuvAKrhLQthUEzU/R378N78gXbBjxed7oA= golang.org/x/sync v0.24.0/go.mod h1:sUUOizhqBxiL6pEWpqNLUiaJn1ShEbZ6BBqskPbjZm0= golang.org/x/sys v0.49.0 h1:XbzkgYJHdqh/8m2Uu0W/dQv8nktxx4BFHp1M0gROTXA= @@ -187,16 +161,16 @@ golang.org/x/term v0.47.0 h1:cpyOwQkr2Nzxe2p6KnrTG7Ei2wtzjsuSjhpXXepZ/BM= golang.org/x/term v0.47.0/go.mod h1:efAfAuG6RKABvg1ArGebRkvX6LXul14SM67o2e4mUCY= golang.org/x/text v0.43.0 h1:1QivrlhwAsnMOcqgOdl9my7s9OyZl8O5/UGUTJVXoWc= golang.org/x/text v0.43.0/go.mod h1:hbSIYA/amXcRXTFSZqh8tWHEoqRvvbKPJ2uz/KU+a+s= -golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U= -golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno= +golang.org/x/time v0.16.0 h1:vMb6ptszcQMkcwiRTAuNNU50gom6++Q/6gY2hDM6VDE= +golang.org/x/time v0.16.0/go.mod h1:rVKOqvZeKvrDKTQiAHJ7wmwP0RzleSphoEA9RcdLA0s= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc= -google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8= -google.golang.org/grpc v1.83.2 h1:EManeRomTObA0BU7I8vXgg/78uE5MJ9M8B39EX2WscU= -google.golang.org/grpc v1.83.2/go.mod h1:YPI1hK3kDked6iHvgX3tR0y+nX/qpMFKhPgFsokw1S8= +google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1 h1:lrupDmKL3p5kEX1M92oan027eCKcouzjuPbH6YBK+Rs= +google.golang.org/genproto/googleapis/api v0.0.0-20260817212433-ac3dfec99bb1/go.mod h1:q/3oV3jAi5vwelxsVAprMBC8BcM2zmNe+IjRGd+9/ks= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc h1:4bNTbnb44EqGVy9HaQxSY2jnafSUdgV3qHtedvNpDKg= +google.golang.org/genproto/googleapis/rpc v0.0.0-20260928230214-8a89bd6388cc/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= +google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= @@ -204,31 +178,37 @@ gopkg.in/evanphx/json-patch.v4 v4.13.0 h1:czT3CmqEaQ1aanPc5SdlgQrrEIb8w/wwCvWWnf gopkg.in/evanphx/json-patch.v4 v4.13.0/go.mod h1:p8EYWUEYMpynmqDbY58zCKCFZw8pRWMG4EsWvDvM72M= gopkg.in/inf.v0 v0.9.1 h1:73M5CoZyi3ZLMOyDlQh031Cx6N9NDJ2Vvfl76EDAgDc= gopkg.in/inf.v0 v0.9.1/go.mod h1:cWUDdTG/fYaXco+Dcufb5Vnc6Gp2YChqWtbxRZE0mXw= -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/api v0.38.0-beta.0 h1:XNdTOZpYukwZVGtrPpCJL8NdXcUcD1O10qPJysD97z4= +k8s.io/api v0.38.0-beta.0/go.mod h1:g2MZyHPSQpJ1zxJ7JhY9wCHmkgeQOuG0Cpsa2sE6Ebo= +k8s.io/apiextensions-api v0.38.0-beta.0 h1:ke50na8OeqEVfhYxa3WfJ7i4TxScQn/smux137Argvo= +k8s.io/apiextensions-api v0.38.0-beta.0/go.mod h1:8IizFVJhXKzRc3EiuM/6RUU2cFZv3qHs1mysqyCSmuM= +k8s.io/apiextensions-apiserver v0.38.0-beta.0 h1:P/otRhWvvCa/fJ6xMMVjQG0hrnl65U71AD0m3xfrNHA= +k8s.io/apiextensions-apiserver v0.38.0-beta.0/go.mod h1:IpzXx3wNm12chepPRiQ8sWsr0C13jzUlJBWDs0BVX/Y= +k8s.io/apimachinery v0.38.0-beta.0 h1:CS7Bz3Pac/I0lb6nhzJHjT98PPUf/YgYMYaC3aroFO0= +k8s.io/apimachinery v0.38.0-beta.0/go.mod h1:KGRxGxSx+JnNcp6M3neG7/bzPdeeE7uPDiEItuUEiWg= +k8s.io/apiserver v0.38.0-beta.0 h1:LGpXWlBzJEwiPedcveOGnW0OGVx4l6qdj7+zEqLyNBM= +k8s.io/apiserver v0.38.0-beta.0/go.mod h1:R3fruOmkiYpNCSIUiWHMqcLaKuzsH2cQOzYyisieejU= +k8s.io/client-go v0.38.0-beta.0 h1:ONJZQR2ZQ+P1kfrL4wbh79nG+acdpsGc8RZo587J0WE= +k8s.io/client-go v0.38.0-beta.0/go.mod h1:cfRLvdmNrwDjZAoT74/b4x4nxpUCplmbj1e1hOvZNOc= +k8s.io/component-base v0.38.0-beta.0 h1:Lv/oDBlP7jliE33Xc98UKiEsNyrVZT4UD/aFj8bUG2s= +k8s.io/component-base v0.38.0-beta.0/go.mod h1:QapRFf0V3uqMbKI3+8Cx9ozTf72Hie+3XIL3VKRr49U= +k8s.io/gengo/v2 v2.0.0-20260408192533-25e2208e0dc3 h1:3L6PNkMLXkU/pz3jWzaaIUz0Rs2V9h+5O51AeRC7poc= +k8s.io/gengo/v2 v2.0.0-20260408192533-25e2208e0dc3/go.mod h1:yvyl3l9E+UxlqOMUULdKTAYB0rEhsmjr7+2Vb/1pCSo= k8s.io/klog/v2 v2.140.0 h1:Tf+J3AH7xnUzZyVVXhTgGhEKnFqye14aadWv7bzXdzc= k8s.io/klog/v2 v2.140.0/go.mod h1:o+/RWfJ6PwpnFn7OyAG3QnO47BFsymfEfrz6XyYSSp0= -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/ktesting v0.38.0-beta.0 h1:z8tGty777Eks5T5QJVvdjXpKoLJiyXkmbv2gxYIRqdY= +k8s.io/ktesting v0.38.0-beta.0/go.mod h1:5cuEyae81HMpIwUx1JX78204Zhmrj4J1yqRc2aE060o= +k8s.io/kube-openapi v0.0.0-20261014044854-ca3452a79603 h1:9zl8YVFBvuURO1ZrSa1SFWyfbnzyll2ivV163KCkRs0= +k8s.io/kube-openapi v0.0.0-20261014044854-ca3452a79603/go.mod h1:ijAJHxCK/9OftZdcKwI5BHyIeRUeoKe1ldIyM4JHMts= k8s.io/utils v0.0.0-20260626114624-be93311217bd h1:Ea7fgQ5we8Y9T0OX5o0dAHzQOBRI07D/dEYRaB9ZZEs= k8s.io/utils v0.0.0-20260626114624-be93311217bd/go.mod h1:xDxuJ0whA3d0I4mf/C4ppKHxXynQ+fxnkmQH0vTHnuk= -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/apiserver-network-proxy/konnectivity-client v0.37.0 h1:NWrO5vJ1Dw7gy2JS/iY98JEEvtmQ3lXqNwwCzzOC1gk= +sigs.k8s.io/apiserver-network-proxy/konnectivity-client v0.37.0/go.mod h1:x/fWe7nc0XDKUqK5XZ5nqmWKdQxvouWB7OmEAsxltiI= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730 h1:IpInykpT6ceI+QxKBbEflcR5EXP7sU1kvOlxwZh5txg= sigs.k8s.io/json v0.0.0-20250730193827-2d320260d730/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.4.2 h1:qdOxHwrl2Kaag1aQEarlYcOA9vSyGCp3CIki3aW8c4Q= -sigs.k8s.io/structured-merge-diff/v6 v6.4.2/go.mod h1:M3W8sfWvn2HhQDIbGWj3S099YozAsymCo/wrT5ohRUE= +sigs.k8s.io/structured-merge-diff/v7 v7.0.1 h1:mjAf8oNt6P6M9/uHoZLY2x/iQj/U5YFe0ke1VL/XjeY= +sigs.k8s.io/structured-merge-diff/v7 v7.0.1/go.mod h1:xKoMSgtnJnkfRR+CTNSQ1dBVhkKJR5OQl5RxX/OqHbI= 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/tools/apitool/internal/docsite/docsite.go b/tools/apitool/internal/docsite/docsite.go index b585649bca..7097a248b7 100644 --- a/tools/apitool/internal/docsite/docsite.go +++ b/tools/apitool/internal/docsite/docsite.go @@ -54,6 +54,7 @@ type indexEntry struct { Name string `json:"name"` FullName string `json:"fullName"` Anchor string `json:"anchor"` + Preview bool `json:"preview,omitempty"` } type pageData struct { @@ -176,6 +177,7 @@ func parsePageTemplate(anchors resourceAnchors) (*template.Template, error) { "methodAnchor": methodAnchor, "msgAnchor": msgAnchor, "enumAnchor": enumAnchor, + "childAnchor": childAnchor[protoreflect.Name], "typeAnchor": anchors.typeAnchor, "fieldAnchor": anchors.fieldAnchor, "highlightYAML": highlightYAML, @@ -218,7 +220,7 @@ func (b viewBuilder) resourceView(page resourcePage) resourceView { FieldsAnchor: fieldsAnchor(page), ParentAnchor: b.anchors.parentAnchor(page), Subresources: subresourceLinks(b.pages, page), - Attrs: b.attrTree(page.Message.Fields), + Attrs: b.attrTree(page.Message.Fields, pageAnchor(page)), Example: trimLicenseHeader(b.examples[page.Message.Name]), } for _, m := range page.Methods { @@ -244,14 +246,14 @@ func (b viewBuilder) methodView(page resourcePage, m model.Method) methodView { OutputAnchor: b.anchors.typeAnchorOn(page, m.OutputName), } if req, ok := b.messages[m.InputName]; ok { - mv.Params = b.attrTree(req.Fields) + mv.Params = b.attrTree(req.Fields, methodAnchor(m.ServiceFullName, m.Name)+".request") mv.Sources = append(mv.Sources, req) } if resp, ok := b.messages[m.OutputName]; ok { if resp.IsResource() { mv.ReturnsResource = true } else { - mv.Response = b.attrTree(resp.Fields) + mv.Response = b.attrTree(resp.Fields, methodAnchor(m.ServiceFullName, m.Name)+".response") mv.Sources = append(mv.Sources, resp) } } @@ -264,11 +266,17 @@ func (b viewBuilder) methodView(page resourcePage, m model.Method) methodView { // such as google.protobuf.Timestamp. type attrNode struct { Name string + // ID is the row's element id: its parent row's id, or its section's + // prefix at the top level, then "." and Name. + ID string // Type is the field's type as shown, such as "string" or "[]object". Type string // TypeAnchor is the anchor Type links to, or "" if it links nowhere. TypeAnchor string Doc string + // PreviewGate is the preview gate the field requires, or "" when it is + // not gated. + PreviewGate string // Tags label the row, such as "optional" or a Kubernetes field's // "required". Tags []string @@ -279,21 +287,26 @@ type attrNode struct { const maxAttrTreeDepth = 6 // attrTree turns fields into a tree of attrNode, resolving message types -// against b.messages. A type already on the path from the root isn't expanded -// again, so a recursive message doesn't recurse forever. -func (b viewBuilder) attrTree(fields []model.Field) []attrNode { - return b.attrNodes(fields, map[protoreflect.FullName]bool{}, 0) +// against b.messages, with ids under idPrefix. A type already on the path from +// the root isn't expanded again, so a recursive message doesn't recurse +// forever. +func (b viewBuilder) attrTree(fields []model.Field, idPrefix string) []attrNode { + return b.attrNodes(fields, idPrefix, map[protoreflect.FullName]bool{}, 0) } -func (b viewBuilder) attrNodes(fields []model.Field, ancestors map[protoreflect.FullName]bool, depth int) []attrNode { +func (b viewBuilder) attrNodes(fields []model.Field, idPrefix string, ancestors map[protoreflect.FullName]bool, depth int) []attrNode { nodes := make([]attrNode, len(fields)) for i, f := range fields { nodes[i] = attrNode{ Name: string(f.Name), + ID: childAnchor(idPrefix, f.Name), Type: f.TypeDisplay, TypeAnchor: b.anchors.fieldAnchor(f), Doc: f.Comment, } + if f.PreviewGate != nil { + nodes[i].PreviewGate = f.PreviewGate.Name + } if f.OneofName != "" { nodes[i].Tags = append(nodes[i].Tags, "oneof "+string(f.OneofName)) } @@ -320,7 +333,7 @@ func (b viewBuilder) attrNodes(fields []model.Field, ancestors map[protoreflect. nextAncestors := maps.Clone(ancestors) nextAncestors[childTypeName] = true - nodes[i].Children = b.attrNodes(child.Fields, nextAncestors, depth+1) + nodes[i].Children = b.attrNodes(child.Fields, nodes[i].ID, nextAncestors, depth+1) } return nodes } @@ -481,7 +494,13 @@ func resourcePageEntries(page resourcePage) []indexEntry { entries := []indexEntry{{Kind: "resource", Name: page.Message.Name, FullName: string(path), Anchor: anchor}} entries = append(entries, fieldEntries(page.Message.Fields, path, anchor)...) for _, m := range page.Methods { - entries = append(entries, indexEntry{Kind: "method", Name: string(m.Name), FullName: string(m.ServiceFullName.Append(m.Name)), Anchor: methodAnchor(m.ServiceFullName, m.Name)}) + entries = append(entries, indexEntry{ + Kind: "method", + Name: string(m.Name), + FullName: string(m.ServiceFullName.Append(m.Name)), + Anchor: methodAnchor(m.ServiceFullName, m.Name), + Preview: m.PreviewGate != "", + }) } return entries } @@ -492,10 +511,17 @@ func messageEntries(msg model.Message) []indexEntry { return append(entries, fieldEntries(msg.Fields, msg.FullName, anchor)...) } -func fieldEntries(fields []model.Field, parentFullName protoreflect.FullName, anchor string) []indexEntry { +// fieldEntries indexes fields, each linking to its row under parentAnchor. +func fieldEntries(fields []model.Field, parentFullName protoreflect.FullName, parentAnchor string) []indexEntry { var entries []indexEntry for _, f := range fields { - entries = append(entries, indexEntry{Kind: "field", Name: string(f.Name), FullName: string(parentFullName.Append(f.Name)), Anchor: anchor}) + entries = append(entries, indexEntry{ + Kind: "field", + Name: string(f.Name), + FullName: string(parentFullName.Append(f.Name)), + Anchor: childAnchor(parentAnchor, f.Name), + Preview: f.PreviewGate != nil, + }) } return entries } @@ -504,7 +530,7 @@ func enumEntries(e model.Enum) []indexEntry { anchor := enumAnchor(e.FullName) entries := []indexEntry{{Kind: "enum", Name: e.Name, FullName: string(e.FullName), Anchor: anchor}} for _, v := range e.Values { - entries = append(entries, indexEntry{Kind: "enum value", Name: string(v.Name), FullName: string(e.FullName.Append(v.Name)), Anchor: anchor}) + entries = append(entries, indexEntry{Kind: "enum value", Name: string(v.Name), FullName: string(e.FullName.Append(v.Name)), Anchor: childAnchor(anchor, v.Name)}) } return entries } @@ -517,6 +543,10 @@ func enumAnchor(fullName protoreflect.FullName) string { return "enum-" + string func pageAnchor(page resourcePage) string { return "resource-" + string(resourcePath(page)) } func fieldsAnchor(page resourcePage) string { return pageAnchor(page) + "-fields" } +// childAnchor is the anchor of a field or enum value named name, whose row is +// under the element with id parent. +func childAnchor[N ~string](parent string, name N) string { return parent + "." + string(name) } + // resourcePath names page by its resource's full name, with the parent // inserted before the resource's name for a subresource. For example, // "substrate.ateapi.v1.Actor", or "substrate.ateapi.v1.Atespace.AccessPolicy". diff --git a/tools/apitool/internal/docsite/docsite_test.go b/tools/apitool/internal/docsite/docsite_test.go index 8764e0a425..0ad88c4038 100644 --- a/tools/apitool/internal/docsite/docsite_test.go +++ b/tools/apitool/internal/docsite/docsite_test.go @@ -60,7 +60,7 @@ var fixtureK8sExamples = map[string]string{ func fixtureAPI(t *testing.T) *model.API { do := model.Method{Name: "Do", Comment: "Do it.\n\nIn detail.", InputName: "test.DoRequest", OutputName: "test.DoResponse", Resource: "Widget", ServiceFullName: "test.Svc", ServiceName: "Svc"} getGlobalGadget := model.Method{Name: "GetGlobalGadget", InputName: "test.GetGlobalGadgetRequest", OutputName: "test.Gadget", Resource: "Gadget", ServiceFullName: "test.Svc", ServiceName: "Svc"} - getWidgetGadget := model.Method{Name: "GetWidgetGadget", InputName: "test.GetWidgetGadgetRequest", OutputName: "test.Gadget", Resource: "Gadget", ServiceFullName: "test.Svc", ServiceName: "Svc"} + getWidgetGadget := model.Method{Name: "GetWidgetGadget", InputName: "test.GetWidgetGadgetRequest", OutputName: "test.Gadget", Resource: "Gadget", PreviewGate: "MethodGate", ServiceFullName: "test.Svc", ServiceName: "Svc"} return &model.API{ Services: []model.Service{ { @@ -76,16 +76,18 @@ func fixtureAPI(t *testing.T) *model.API { Name: "Foo", Comment: `Dangerous: & "quotes"`, Fields: []model.Field{ - {Name: "scalar_field", TypeDisplay: "string", Kind: protoreflect.StringKind}, + {Name: "scalar_field", TypeDisplay: "string", Kind: protoreflect.StringKind, PreviewGate: &model.FieldPreviewGate{Name: "MyGate"}}, {Name: "message_field", TypeDisplay: "DoRequest", Kind: protoreflect.MessageKind, TypeFullName: "test.DoRequest"}, {Name: "enum_field", TypeDisplay: "Color", Kind: protoreflect.EnumKind, TypeFullName: "test.Color"}, }, }, {FullName: "test.DoRequest", Name: "DoRequest", Fields: []model.Field{ - {Name: "token", Number: 1, TypeDisplay: "string", Kind: protoreflect.StringKind, Redacted: true}, + {Name: "token", Number: 1, TypeDisplay: "string", Kind: protoreflect.StringKind, Redacted: true, PreviewGate: &model.FieldPreviewGate{Name: "TokenGate"}}, }}, {FullName: "test.DoResponse", Name: "DoResponse"}, - {FullName: "test.Widget", Name: "Widget", ResourceAnnotation: &model.ResourceAnnotation{Scope: ateapi.Scope_SCOPE_ATESPACE, Plural: "Widgets"}}, + {FullName: "test.Widget", Name: "Widget", ResourceAnnotation: &model.ResourceAnnotation{Scope: ateapi.Scope_SCOPE_ATESPACE, Plural: "Widgets"}, Fields: []model.Field{ + {Name: "foo", TypeDisplay: "Foo", Kind: protoreflect.MessageKind, TypeFullName: "test.Foo"}, + }}, {FullName: "test.Gadget", Name: "Gadget", ResourceAnnotation: &model.ResourceAnnotation{Parents: []string{"Global", "Widget"}, Singleton: true, Plural: "Gadgets"}}, }, Enums: []model.Enum{ @@ -106,25 +108,34 @@ func TestRender_Anchors(t *testing.T) { html := string(out.Body) for _, id := range []string{ - `id="method-test.Svc.Do"`, - `id="method-test.Svc.GetGlobalGadget"`, - `id="method-test.Svc.GetWidgetGadget"`, - `id="resource-test.Widget"`, - `id="resource-test.Global.Gadget"`, - `id="resource-test.Widget.Gadget"`, - `id="resource-test.Widget-fields"`, - `id="resource-test.Global.Gadget-fields"`, - `id="resource-test.Widget.Gadget-fields"`, - `id="msg-test.Foo"`, - `id="msg-test.DoRequest"`, - `id="msg-test.DoResponse"`, - `id="enum-test.Color"`, - `id="resource-test.dev.v1.Sprocket"`, - `id="resource-test.dev.v1.Sprocket-fields"`, + "method-test.Svc.Do", + "method-test.Svc.GetGlobalGadget", + "method-test.Svc.GetWidgetGadget", + "resource-test.Widget", + "resource-test.Global.Gadget", + "resource-test.Widget.Gadget", + "resource-test.Widget-fields", + "resource-test.Global.Gadget-fields", + "resource-test.Widget.Gadget-fields", + "msg-test.Foo", + "msg-test.DoRequest", + "msg-test.DoResponse", + "enum-test.Color", + "resource-test.dev.v1.Sprocket", + "resource-test.dev.v1.Sprocket-fields", + "resource-test.Widget.foo", + "resource-test.Widget.foo.message_field.token", + "method-test.Svc.Do.request.token", + "msg-test.Foo.scalar_field", + "enum-test.Color.RED", + "resource-test.dev.v1.Sprocket.spec.teeth", } { - if !strings.Contains(html, id) { + if !strings.Contains(html, `id="`+id+`"`) { t.Errorf("output missing anchor %s", id) } + if !strings.Contains(html, `DoRequest`}, {"field links its enum type", `Color`}, {"scalar field type is not a link", `string`}, + {"attr row marks preview field for toggling", `
`}, + {"attr row shows preview gate badge", `token preview: TokenGate`}, + {"message table row marks preview field for toggling", ``}, + {"message table shows preview gate badge", `scalar_field preview: MyGateGetWidgetGadget preview: MethodGate`}, + {"method section marks preview method for toggling", `
`}, + {"method heading shows preview gate badge", `

GetWidgetGadget preview: MethodGate`}, {"Kubernetes page is marked", `