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 @@
[](https://github.com/agent-substrate/substrate/actions/workflows/govulncheck.yaml)
[](https://github.com/agent-substrate/substrate/stargazers)
-
-
[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}}
-| atespace | allowed namespaces |
-{{range $atespace, $namespaces := .PolicyGrants}}
-| {{$atespace}} | {{range $namespaces}}{{.}} {{end}} |
+| atespace | namespace | secret selector |
+{{range $atespace, $grants := .PolicyGrantDetails}}
+{{range $grants}}
+| {{$atespace}} | {{.Namespace}} | {{if .MatchLabels}}{{range $k, $v := .MatchLabels}}{{$k}}={{$v}} {{end}}{{else}}*{{end}} |
+{{end}}
{{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-a | ns1 | app=web env=prod |
",
+ "| team-a | ns1 | team=x |
",
+ "| team-b | ns2 | * |
",
+ }
+ 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