From 9d4809e05be9ade16129e5d1f2104ff90749895d Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Thu, 29 Oct 2026 11:11:28 +1000 Subject: [PATCH 01/24] Add workload identity webhook benchmark pipeline Use a pinned kperf profile for an exploratory H2 600-create/sec benchmark, with smoke checks, bounded execution, result artifacts, and explicit cluster retention. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 137 ++++++ kcl/workload_identity_webhook/benchmark.py | 368 ++++++++++++++ .../load-profile.yaml | 27 ++ kcl/workload_identity_webhook/pipeline.k | 356 ++++++++++++++ kcl/workload_identity_webhook/pipeline.yaml | 456 ++++++++++++++++++ kcl/workload_identity_webhook/preflight.py | 35 ++ .../test_benchmark.py | 367 ++++++++++++++ kcl/workload_identity_webhook/workload.yaml | 107 ++++ 8 files changed, 1853 insertions(+) create mode 100644 kcl/workload_identity_webhook/README.md create mode 100644 kcl/workload_identity_webhook/benchmark.py create mode 100644 kcl/workload_identity_webhook/load-profile.yaml create mode 100644 kcl/workload_identity_webhook/pipeline.k create mode 100755 kcl/workload_identity_webhook/pipeline.yaml create mode 100644 kcl/workload_identity_webhook/preflight.py create mode 100644 kcl/workload_identity_webhook/test_benchmark.py create mode 100644 kcl/workload_identity_webhook/workload.yaml diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md new file mode 100644 index 0000000000..29be722490 --- /dev/null +++ b/kcl/workload_identity_webhook/README.md @@ -0,0 +1,137 @@ +# Workload Identity webhook benchmark + +A manual, exploratory benchmark on a dedicated AKS Standard H2 cluster in +`westus2`, subscription `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`. + +The cluster has three `Standard_D2_v4` system nodes and three +`Standard_D8s_v5` worker nodes. One generator Job runs on the worker pool. +Benchmark Pods remain unscheduled and do not need worker Pod slots. +Webhook replicas and resources are not tuned by this pipeline. + +## Custom load profile + +[load-profile.yaml](./load-profile.yaml) is the source of truth: + +- 600 Pod CREATEs/sec ceiling, 600-second generation window. +- `total: 0`, `deleteRatio: 0`, `maxRetries: 0`. +- 600 synchronous request workers and 20 transports, not 600/sec per worker. +- WI opt-in, a dedicated annotated ServiceAccount, run/phase labels, and + `schedulerName: kperf-admission-only`. +- `payloadSize: 3650` pads an environment variable; it is **not** submitted + JSON size. Metadata, defaulting, and WI mutation change object size. + +The pipeline renders run identifiers, mounts the profile through a ConfigMap, +and invokes `/kperf runner run --config /etc/kperf/load-profile.yaml` without +CLI traffic overrides. Separate smoke and warm-up profiles reuse the same +Pod configuration without changing the measurement profile. + +The pinned custom image is: + +```text +ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 +``` + +This is the public Linux amd64 image published as `sha-8e8e961`, corresponding +to [Azure/kperf#260](https://github.com/Azure/kperf/pull/260) source commit +`8e8e9617073fa7f0a9a51789923afa96d4d90121`. It is an intentional custom-image +exception; replace it with an upstream release when available. + +## Workflow and safety + +1. Check Kubernetes 1.36 availability, SKU eligibility and regional/family + vCPU quota. Provision the H2 cluster, worker pool, and user-assigned identity. +2. **Manual storage preflight:** before any load, inspect current H2 telemetry. + Record the telemetry source, observation time, available storage, and + approved safety margin in the ADO validation comments. Reject if unavailable. + Confirm no installed scheduler handles `kperf-admission-only`. +3. Check six Ready nodes and expected SKUs. Create isolated runner credentials + with namespace-scoped Pod-create permission. No administrator kubeconfig is + mounted into the runner. The benchmark identity needs neither Azure role + assignments nor a federated credential because no token exchange is tested. +4. Smoke-test three Pods; verify WI environment/projected token mutation, + ownership, and unscheduled state. Warm up at 5/sec for 30 seconds. +5. Execute one measurement Job. `backoffLimit: 0` prevents retries, and a + 900-second outer deadline bounds startup, generation, and drain. +6. Collect results and diagnostics, then finalize according to `keep_cluster`. + +There is **no ResourceQuota** and no claimed 400,000-Pod H2 limit. At the target, +measurement alone retains approximately 360,000 Pods: about 1.37 GiB of +submitted JSON at 4 KiB each, before mutation, history, events, and storage +overhead. Warm-up and outstanding requests add more. Available vCPU quota is +not proof of physical regional capacity or control-plane storage headroom. + +The storage preflight is an agentless ADO manual-validation job, with timeout +set to reject. It is not an automated storage-byte monitor. This first version +has bounded execution, not the original design's full continuous telemetry +and safety-stop implementation. Managed webhook configuration and storage +signals may require ASI/control-plane access beyond `kubectl`; do not infer +their values from worker nodes or substitute defaults. + +### Retention + +`keep_cluster` defaults to **false**: + +- **false:** collect/publish artifacts, then delete only the resource group + whose run and pipeline-definition ownership tags match. +- **true:** retain the cluster, managed identity, namespaces, completed Jobs, + and benchmark Pods for inspection. Attempt to suspend unfinished generators; + Job deadlines remain the fallback if the agent/API is unavailable. + +Retained resources incur charges. The finalization artifact prints their IDs +and an explicit `az group delete` command. Failed or canceled runs attempt +collection/finalization using `always()`; a hard agent interruption can still +prevent these steps. Check the pipeline and Azure before assuming cleanup +completed. A setup failure before resource-group creation needs no deletion; +ownership-check failures deliberately block deletion. + +## Results and limitations + +ADO publishes setup, benchmark, and finalization artifacts containing: + +- Resolved profiles, pinned image, identity client ID (not credentials), cluster + configuration, and before/after platform and admission configuration. +- Per-phase orchestration timestamps, Job status, logs, original kperf JSON, + latency percentiles in seconds, and request error counts. +- Post-run retained-Pod counts and a small set of admitted Pod samples/sizes. + Enumeration is paginated outside measurement; full 360,000-Pod bodies are + neither accumulated in memory nor uploaded. +- Collection failures, retention decisions, and deletion verification. + +The pinned runner's `aggregated.total` and per-spec `total` mirror the configured +total; duration-based runs report **0** there. They are **not successful-request +counts**. Preserve them as `runner_reported_total`; separately report observed +retained Pods. A timeout/error response can still have created a Pod, so these +counts are not interchangeable. + +The runner reports duration including drain. It does not expose per-10-second +dispatch rates, inflight backlog, actual WI invocation rates, exact generation/ +drain boundaries, or submitted-body sizes. Successful exploratory execution +does **not** prove sustained offered load of 600/sec. Reported request errors, +missing/invalid results, smoke failures, and deadlines fail the pipeline rather +than being retried or silently accepted. + +## Development and registration + +The scenario's Python scripts use the repository's existing PyYAML dependency. +Run focused checks after regenerating: + +```sh +kcl run kcl/workload_identity_webhook/pipeline.k -S output \ + -o kcl/workload_identity_webhook/pipeline.yaml +PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover \ + -s kcl/workload_identity_webhook -p 'test_*.py' -v +``` + +Registration target: + +- Organization/project: `https://dev.azure.com/akstelescope` / `telescope`. +- Folder: `\AKS\Telescope\v2`. +- Definition name: `Workload Identitiy Webhook Benchmark` (requested spelling). +- Source: `Azure/telescope`, branch `wi-web-bench`. +- YAML: [pipeline.yaml](./pipeline.yaml). +- Existing GitHub connection: `telescope (1)`. +- Azure connection: `Azure-for-Telescope-internal`. +- Agent pool: `AKS-Telescope-Airlock`. + +Keep CI/PR triggers disabled and register with `--skip-first-run true`. +Registration does not queue a benchmark or create Azure resources. diff --git a/kcl/workload_identity_webhook/benchmark.py b/kcl/workload_identity_webhook/benchmark.py new file mode 100644 index 0000000000..53b5f7f75e --- /dev/null +++ b/kcl/workload_identity_webhook/benchmark.py @@ -0,0 +1,368 @@ +"""Prepare and observe the scenario without changing kperf's traffic contract.""" + +import argparse +import copy +import json +import math +import re +import signal +import subprocess +import sys +import time +import uuid +from datetime import datetime, timezone +from pathlib import Path +from urllib.parse import urlencode + +import yaml + + +ROOT = Path(__file__).parent +BEGIN = "KPERF_RESULT_BEGIN" +END = "KPERF_RESULT_END" +PHASES = ("smoke", "warmup", "measure") + + +def kubectl(*args, stdin=None): + return subprocess.run( + ["kubectl", "--request-timeout=30s", *args], + input=stdin, text=True, capture_output=True, check=True, timeout=90, + ).stdout + + +def write_json(path, value): + path.write_text(json.dumps(value, indent=2) + "\n") + + +def timestamp(): + return datetime.now(timezone.utc).isoformat() + + +def render(value, replacements): + if isinstance(value, dict): + return {key: render(item, replacements) for key, item in value.items()} + if isinstance(value, list): + return [render(item, replacements) for item in value] + if isinstance(value, str): + for key, replacement in replacements.items(): + value = value.replace(f"__{key}__", replacement) + if re.search(r"__[A-Z_]+__", value): + raise ValueError(f"Unresolved placeholder: {value}") + return value + + +def profile_for_phase(template, run_id, phase): + profile = render(copy.deepcopy(template), { + "RUN_NAMESPACE": run_id, "RUN_ID": run_id, + }) + spec = profile["specs"][0] + spec["requests"][0]["postDel"]["pod"]["labels"]["benchmark-phase"] = phase + if phase == "smoke": + spec.update(rate=1, total=3, duration=0, client=1, conns=1) + elif phase == "warmup": + spec.update(rate=5, total=0, duration=30, client=5, conns=1) + elif phase != "measure": + raise ValueError(f"Unknown phase: {phase}") + return profile + + +def extract_result(log): + if log.count(BEGIN) != 1 or log.count(END) != 1: + raise ValueError("Missing or repeated kperf result delimiters") + start = log.index(BEGIN) + len(BEGIN) + stop = log.index(END) + if stop <= start: + raise ValueError("Invalid kperf result delimiter order") + result = json.loads(log[start:stop]) + if not isinstance(result, dict): + raise ValueError("kperf result must be an object") + return result + + +def evaluate_result(result, duration): + specs = result.get("perSpecResults") + aggregate = result.get("aggregated") + if not isinstance(specs, list) or len(specs) != 1 or not isinstance(aggregate, dict): + raise ValueError("Expected one perSpecResults entry and an aggregated report") + for report in [specs[0], aggregate]: + if not isinstance(report, dict): + raise ValueError("Invalid report object") + for field in ("total", "duration", "totalReceivedBytes"): + if field not in report: + raise ValueError(f"Missing report field: {field}") + if any(type(report[field]) is not int or report[field] < 0 + for field in ("total", "totalReceivedBytes")): + raise ValueError("Invalid report total or received bytes") + errors = report.get("errorStats", {}) + if not isinstance(errors, dict) or any( + type(count) is not int or count < 0 for count in errors.values() + ): + raise ValueError("Invalid errorStats") + if sum(errors.values()): + raise ValueError(f"kperf reported request failures: {errors}") + latencies = report.get("percentileLatencies") + if not isinstance(latencies, list) or not latencies: + raise ValueError("No successful-request latency observations") + if any(not isinstance(pair, list) or len(pair) != 2 or any( + type(value) not in (int, float) or not math.isfinite(value) or value < 0 + for value in pair + ) or pair[0] > 1 for pair in latencies): + raise ValueError("Invalid latency percentile pairs") + elapsed = parse_duration(report["duration"]) + if elapsed < duration: + raise ValueError(f"Runner duration {elapsed}s is shorter than {duration}s") + if specs[0] != aggregate: + raise ValueError("Single-spec and aggregate reports disagree") + return { + "classification": "exploratory-completed", + "sustained_rate_acceptance": "not-evaluated", + "configured_rate_per_second": 600 if duration == 600 else None, + "runner_reported_total": aggregate["total"], + "runner_total_semantics": "configured total, NOT observed successful requests", + "runner_duration_including_drain": aggregate["duration"], + "error_stats": aggregate.get("errorStats", {}), + "percentile_latencies_seconds": aggregate["percentileLatencies"], + "limitations": [ + "No per-interval dispatch rate, inflight backlog, or WI invocation count.", + "Retained Pod count is an observation, not successful-response accounting.", + "Submitted body size and exact generation/drain boundaries are unavailable.", + ], + } + + +def parse_duration(value): + if not isinstance(value, str): + raise ValueError("Runner duration must be a Go duration string") + parts = re.findall(r"(\d+(?:\.\d+)?)(ns|us|\u00b5s|ms|s|m|h)", value) + if not parts or "".join(number + unit for number, unit in parts) != value: + raise ValueError(f"Invalid runner duration: {value}") + scales = {"ns": 1e-9, "us": 1e-6, "\u00b5s": 1e-6, "ms": 1e-3, + "s": 1, "m": 60, "h": 3600} + return sum(float(number) * scales[unit] for number, unit in parts) + + +def verify_pod(pod, run_id, phase, client_id): + metadata, spec = pod["metadata"], pod["spec"] + expected = { + "azure.workload.identity/use": "true", + "benchmark": "workload-identity-webhook", + "benchmark-run": run_id, + "benchmark-phase": phase, + } + if any(metadata.get("labels", {}).get(key) != value for key, value in expected.items()): + raise ValueError("Generated Pod labels do not match the benchmark") + if spec.get("schedulerName") != "kperf-admission-only" or spec.get("nodeName"): + raise ValueError("Benchmark Pod is bound or uses the wrong scheduler") + if spec.get("serviceAccountName") != "pod-benchmark" or len(spec["containers"]) != 1: + raise ValueError("Unexpected ServiceAccount or container count") + if spec.get("initContainers"): + raise ValueError("Unexpected init containers") + container = spec["containers"][0] + env = {item["name"]: item.get("value") for item in container.get("env", [])} + if env.get("AZURE_CLIENT_ID") != client_id or not all(env.get(key) for key in ( + "AZURE_TENANT_ID", "AZURE_AUTHORITY_HOST", "AZURE_FEDERATED_TOKEN_FILE", + )): + raise ValueError("Missing or incorrect WI environment mutation") + token_file = env["AZURE_FEDERATED_TOKEN_FILE"] + for volume in spec.get("volumes", []): + for source in volume.get("projected", {}).get("sources", []): + token = source.get("serviceAccountToken", {}) + if token.get("audience") != "api://AzureADTokenExchange": + continue + for mount in container.get("volumeMounts", []): + if (mount["name"] == volume["name"] and mount.get("readOnly") + and token_file == mount["mountPath"].rstrip("/") + "/" + token["path"]): + return + raise ValueError("Missing WI projected token volume/mount") + + +def prepare(args): + nodes = json.loads(kubectl("get", "nodes", "-o", "json")) + for pool, sku in (("systempool", "Standard_D2_v4"), ("workerpool", "Standard_D8s_v5")): + members = [node for node in nodes["items"] + if node["metadata"]["labels"].get("kubernetes.azure.com/agentpool") == pool] + if len(members) != 3 or any( + node["metadata"]["labels"].get("node.kubernetes.io/instance-type") != sku + or not any(c["type"] == "Ready" and c["status"] == "True" + for c in node["status"]["conditions"]) + for node in members + ): + raise ValueError(f"Expected three Ready {sku} nodes in {pool}") + write_json(args.artifacts / "nodes-before.json", nodes) + scheduler_pods = json.loads(kubectl("get", "pods", "-A", "-o", "json")) + for pod in scheduler_pods["items"]: + for container in pod["spec"].get("containers", []): + command = container.get("command", []) + container.get("args", []) + if any("kperf-admission-only" in part for part in command): + raise ValueError("An existing container references the benchmark scheduler") + write_json(args.artifacts / "platform-pods-before.json", scheduler_pods) + template = yaml.safe_load((ROOT / "load-profile.yaml").read_text()) + manifests = list(yaml.safe_load_all((ROOT / "workload.yaml").read_text())) + for phase in PHASES: + profile = profile_for_phase(template, args.run_id, phase) + profile_text = yaml.safe_dump(profile, sort_keys=False) + (args.artifacts / f"{phase}-load-profile.yaml").write_text(profile_text) + name = f"kperf-{phase}" + rendered = render(manifests, { + "RUN_NAMESPACE": args.run_id, "RUNNER_NAMESPACE": args.run_id + "-runner", + "RUN_ID": args.run_id, "CLIENT_ID": args.client_id, + "JOB_NAME": name, "RUNNER_IMAGE": args.image, + }) + prerequisites = [doc for doc in rendered if doc["kind"] != "Job"] + job = next(doc for doc in rendered if doc["kind"] == "Job") + if phase != "measure": + job["spec"]["activeDeadlineSeconds"] = 180 + config_map = { + "apiVersion": "v1", "kind": "ConfigMap", + "metadata": {"name": name, "namespace": args.run_id + "-runner"}, + "data": {"load-profile.yaml": profile_text}, + } + write_json(args.artifacts / f"{phase}-job.json", job) + kubectl("apply", "-f", "-", stdin=yaml.safe_dump_all(prerequisites + [config_map])) + write_json(args.artifacts / "inputs.json", { + "run_id": args.run_id, "image": args.image, "client_id": args.client_id, + "profile": profile_for_phase(template, args.run_id, "measure"), + "webhook_resources": "unchanged; managed control-plane visibility requires ASI telemetry", + }) + + +def pod_snapshot(args, phase): + count, samples, continuation = 0, [], "" + deadline = time.monotonic() + 900 + while True: + query = urlencode({ + "labelSelector": f"benchmark-run={args.run_id},benchmark-phase={phase}", + "limit": 500, "continue": continuation, + }) + page = json.loads(kubectl( + "get", "--raw", f"/api/v1/namespaces/{args.run_id}/pods?{query}", + )) + count += len(page["items"]) + samples.extend(page["items"][:max(0, 3 - len(samples))]) + continuation = page["metadata"].get("continue", "") + if not continuation: + break + if time.monotonic() >= deadline: + raise TimeoutError("Retained Pod snapshot exceeded its 900-second budget") + write_json(args.artifacts / f"{phase}-pods.json", { + "retained_pod_count": count, + "sample_admitted_json_bytes": [len(json.dumps(pod, separators=(",", ":")).encode()) + for pod in samples], + "samples": samples, + }) + if count == 0 or (phase == "smoke" and count != 3): + raise ValueError(f"Unexpected retained Pod count for {phase}: {count}") + for pod in samples: + verify_pod(pod, args.run_id, phase, args.client_id) + return count + + +def run_phase(args): + phase = args.phase + namespace, name = args.run_id + "-runner", f"kperf-{phase}" + timing = {"orchestration_start": timestamp()} + try: + kubectl("create", "-f", str(args.artifacts / f"{phase}-job.json")) + deadline = time.monotonic() + (960 if phase == "measure" else 240) + while True: + job = json.loads(kubectl("get", "job", name, "-n", namespace, "-o", "json")) + write_json(args.artifacts / f"{phase}-job-status.json", job) + conditions = {c["type"]: c for c in job.get("status", {}).get("conditions", []) + if c["status"] == "True"} + if "Failed" in conditions: + raise RuntimeError(f"Job failed: {conditions['Failed']}") + if "Complete" in conditions: + break + if time.monotonic() >= deadline: + raise TimeoutError(f"{name} exceeded its observation deadline") + time.sleep(5) + log = kubectl("logs", f"job/{name}", "-n", namespace, "-c", "kperf") + (args.artifacts / f"{phase}.log").write_text(log) + result = extract_result(log) + write_json(args.artifacts / f"{phase}-result.json", result) + summary = evaluate_result(result, {"smoke": 0, "warmup": 30, "measure": 600}[phase]) + summary["retained_pod_count"] = pod_snapshot(args, phase) + write_json(args.artifacts / f"{phase}-summary.json", summary) + finally: + timing["orchestration_end"] = timestamp() + write_json(args.artifacts / f"{phase}-timestamps.json", timing) + + +def collect(args): + failures = [] + + def capture(name, *command): + try: + output = kubectl(*command) + except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: + message = f"{name}: {error}; {getattr(error, 'stderr', '')}" + print(message, file=sys.stderr) + failures.append(message) + (args.artifacts / f"{name}.error.txt").write_text(message) + return None + (args.artifacts / name).write_text(output) + return output + + capture("nodes-after.json", "get", "nodes", "-o", "json") + capture("admission-webhooks.json", "get", "mutatingwebhookconfigurations", "-o", "json") + capture("platform-pods-after.json", "get", "pods", "-n", "kube-system", "-o", "json") + namespace = args.run_id + "-runner" + jobs = capture("jobs-final.json", "get", "jobs", "-n", namespace, "-o", "json") + capture("runner-pods.json", "get", "pods", "-n", namespace, "-o", "json") + capture("runner-events.json", "get", "events", "-n", namespace, "-o", "json") + if jobs is not None: + for job in json.loads(jobs)["items"]: + if job["metadata"].get("labels", {}).get("benchmark-run") != args.run_id: + continue + name = job["metadata"]["name"] + capture(f"{name}-final.log", "logs", f"job/{name}", "-n", namespace, "-c", "kperf") + conditions = job.get("status", {}).get("conditions", []) + terminal = any(c["type"] in ("Complete", "Failed") and c["status"] == "True" + for c in conditions) + if not terminal: + capture(f"{name}-stop.json", "patch", "job", name, "-n", namespace, + "--type=merge", "-p", '{"spec":{"suspend":true}}', "-o", "json") + write_json(args.artifacts / "collection.json", {"failures": failures}) + if failures: + raise RuntimeError("Artifact collection incomplete; see collection.json") + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("action", choices=("prepare", "run", "collect")) + parser.add_argument("--run-id", required=True) + parser.add_argument("--artifacts", required=True, type=Path) + parser.add_argument("--client-id") + parser.add_argument("--image") + parser.add_argument("--phase", choices=PHASES) + args = parser.parse_args() + if not re.fullmatch(r"wi-[0-9]+-[0-9]+", args.run_id): + parser.error("run-id must be wi--") + if args.action != "collect": + if not args.client_id: + parser.error("--client-id is required") + uuid.UUID(args.client_id) + if args.action == "prepare" and not args.image: + parser.error("--image is required for prepare") + if args.action == "run" and not args.phase: + parser.error("--phase is required for run") + args.artifacts.mkdir(parents=True, exist_ok=True) + + def interrupted(signum, _frame): + raise InterruptedError(f"Benchmark orchestration interrupted by signal {signum}") + + signal.signal(signal.SIGTERM, interrupted) + try: + {"prepare": prepare, "run": run_phase, "collect": collect}[args.action](args) + except (ValueError, KeyError, TypeError, OSError, RuntimeError, + subprocess.SubprocessError) as error: + message = f"{error}\n{getattr(error, 'stderr', '')}" + print(f"WI BENCHMARK FAILED: {message}", file=sys.stderr) + write_json(args.artifacts / f"{args.action}-{args.phase or 'all'}-failure.json", + {"error": message, "timestamp": timestamp()}) + return 1 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/kcl/workload_identity_webhook/load-profile.yaml b/kcl/workload_identity_webhook/load-profile.yaml new file mode 100644 index 0000000000..18da7f6c77 --- /dev/null +++ b/kcl/workload_identity_webhook/load-profile.yaml @@ -0,0 +1,27 @@ +version: 1 +description: WI Pod CREATE exploratory benchmark - 600 creates/sec for 10 minutes +specs: + - rate: 600 + duration: 600 + total: 0 + client: 600 + conns: 20 + contentType: json + maxRetries: 0 + requests: + - shares: 1 + postDel: + group: "" + version: v1 + resource: pods + namespace: "__RUN_NAMESPACE__" + deleteRatio: 0 + # PAYLOAD environment padding, not the complete submitted JSON size. + payloadSize: 3650 + pod: + labels: + azure.workload.identity/use: "true" + benchmark: workload-identity-webhook + benchmark-run: "__RUN_ID__" + serviceAccountName: pod-benchmark + schedulerName: kperf-admission-only diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k new file mode 100644 index 0000000000..7c49762232 --- /dev/null +++ b/kcl/workload_identity_webhook/pipeline.k @@ -0,0 +1,356 @@ +import azure_pipelines.ap +import azure_pipelines.ap.jobs.job +import azure_pipelines.ap.steps +import lib.const +import lib.steps.azure +import lib.steps.common + +SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" +LOCATION = "westus2" +SCENARIO = "$(Build.SourcesDirectory)/kcl/workload_identity_webhook" +ARTIFACTS = "$(Build.ArtifactStagingDirectory)/wi-webhook" +# TODO: Replace the user-selected PR image with a published upstream release. +RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4" + +output = ap.Pipeline { + name = "Workload Identity Webhook Benchmark" + trigger = "none" + pr = "none" + pool = const.DEFAULT_POOL + parameters = [ + ap.Parameter { + name = "keep_cluster" + displayName = "Keep cluster and benchmark Pods after benchmark" + type = "boolean" + default = False + }, + ] + jobs = [ + job.Job { + job = "setup" + displayName = "Provision H2 cluster and worker pool" + timeoutInMinutes = 180 + cancelTimeoutInMinutes = 10 + steps = [ + steps.Bash { + bash = """ +set -euo pipefail +mkdir -p "${ARTIFACTS}" +echo "##vso[task.setvariable variable=RUN_ID;isOutput=true]wi-$(Build.BuildId)-$(System.JobAttempt)" +""" + name = "resolve" + displayName = "Resolve run-owned resource group" + }, + azure.Login( + const.DEFAULT_SERVICE_CONNECTION, + SUBSCRIPTION_ID, + LOCATION), + azure.AzCli( + const.DEFAULT_SERVICE_CONNECTION, + "Check AKS version, VM eligibility, and quota", + """ +az extension add --name aks-preview --version 20.0.0b6 --allow-preview true --yes +az aks get-versions \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --location "${LOCATION}" \\ + --output json > "${ARTIFACTS}/kubernetes-versions.json" +jq -e '.values | any(.version | startswith("1.36."))' \\ + "${ARTIFACTS}/kubernetes-versions.json" +az vm list-skus \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --location "${LOCATION}" \\ + --resource-type virtualMachines \\ + --all \\ + --output json > "${ARTIFACTS}/vm-skus.json" +az vm list-usage \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --location "${LOCATION}" \\ + --output json > "${ARTIFACTS}/vm-usage.json" +python3 "${SCENARIO}/preflight.py" "${ARTIFACTS}" +exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$(resolve.RUN_ID)") +if [ "$exists" != "false" ]; then + echo "Refusing to reuse an existing or unverified resource group: $(resolve.RUN_ID)" >&2 + exit 1 +fi +"""), + azure.CreateResourceGroup( + const.DEFAULT_SERVICE_CONNECTION, + "$(resolve.RUN_ID)", + LOCATION, + SUBSCRIPTION_ID, + tags="benchmark=wi-webhook run_id=$(resolve.RUN_ID) definition_id=$(System.DefinitionId)"), + azure.AzCli( + const.DEFAULT_SERVICE_CONNECTION, + "Create H2 cluster with OIDC and workload identity", + """ +az aks create \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --resource-group "$(resolve.RUN_ID)" \\ + --name "wi-webhook" \\ + --location "${LOCATION}" \\ + --kubernetes-version "1.36" \\ + --dns-name-prefix "$(resolve.RUN_ID)" \\ + --tier standard \\ + --control-plane-scaling-size H2 \\ + --enable-managed-identity \\ + --enable-oidc-issuer \\ + --enable-workload-identity \\ + --generate-ssh-keys \\ + --nodepool-name systempool \\ + --node-count 3 \\ + --node-vm-size Standard_D2_v4 \\ + --max-pods 50 \\ + --network-plugin azure \\ + --network-plugin-mode overlay \\ + --pod-cidr 10.64.0.0/10 \\ + --service-cidr 10.0.0.0/16 \\ + --dns-service-ip 10.0.0.10 \\ + --outbound-type managedNATGateway \\ + --nat-gateway-managed-outbound-ip-count 10 \\ + --tags SkipAKSCluster=true \\ + --yes +"""), + azure.WaitForClusterSucceeded( + const.DEFAULT_SERVICE_CONNECTION, + "wi-webhook", + "$(resolve.RUN_ID)", + SUBSCRIPTION_ID), + azure.CreateNodePool( + const.DEFAULT_SERVICE_CONNECTION, + "wi-webhook", + "$(resolve.RUN_ID)", + SUBSCRIPTION_ID, + azure.NodePool { + name = "workerpool" + sku = "Standard_D8s_v5" + count = 3 + maxPods = 50 + }), + azure.WaitForNodePoolSucceeded( + const.DEFAULT_SERVICE_CONNECTION, + "wi-webhook", + "$(resolve.RUN_ID)", + SUBSCRIPTION_ID, + "workerpool"), + azure.AzCli( + const.DEFAULT_SERVICE_CONNECTION, + "Capture cluster configuration and create benchmark identity", + """ +az aks show \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --resource-group "$(resolve.RUN_ID)" \\ + --name wi-webhook \\ + --output json > "${ARTIFACTS}/cluster-before.json" +jq -e ' + .location == "westus2" and .sku.tier == "Standard" + and .controlPlaneScalingProfile.scalingSize == "H2" + and .oidcIssuerProfile.enabled == true + and .securityProfile.workloadIdentity.enabled == true + and (.agentPoolProfiles | length == 2) + and (.agentPoolProfiles | any(.name == "systempool" and .count == 3 and .vmSize == "Standard_D2_v4")) + and (.agentPoolProfiles | any(.name == "workerpool" and .count == 3 and .vmSize == "Standard_D8s_v5")) +' "${ARTIFACTS}/cluster-before.json" +az identity create \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --resource-group "$(resolve.RUN_ID)" \\ + --location "${LOCATION}" \\ + --name wi-benchmark \\ + --output json > "${ARTIFACTS}/identity.json" +client_id=$(jq -er '.clientId | select(type == "string" and length > 0)' "${ARTIFACTS}/identity.json") +echo "##vso[task.setvariable variable=CLIENT_ID;isOutput=true]$client_id" +""", + stepName="identity"), + steps.Task { + task = "PublishPipelineArtifact@1" + displayName = "Publish setup evidence" + condition = "always()" + inputs = { + targetPath = ARTIFACTS + artifact = "wi-setup-$(System.JobAttempt)" + } + }, + ] + }, + job.Job { + job = "storage_preflight" + displayName = "Approve current H2 storage headroom before load" + dependsOn = "setup" + pool = "server" + timeoutInMinutes = 65 + variables = { + RUN_ID = "$[ dependencies.setup.outputs['resolve.RUN_ID'] ]" + } + steps = [ + steps.Task { + task = "ManualValidation@0" + timeoutInMinutes = 60 + inputs = { + notifyUsers = "$(Build.RequestedForEmail)" + instructions = """ +Before resuming, inspect current H2 control-plane/storage telemetry for: +subscription ${SUBSCRIPTION_ID}, region ${LOCATION}, +resource group $(RUN_ID), cluster wi-webhook. +Record the telemetry source, observation time, available storage, and approved +safety margin in the approval comments. Allow for 360,000 retained Pods plus +warm-up and drain. Submitted JSON alone is about 1.37 GiB; WI/defaulting, +revision history, events, and storage overhead require additional headroom. +Confirm no scheduler handles kperf-admission-only and capture the actual +managed WI webhook resource/replica baseline if available. +Reject if storage visibility or an approved margin is missing. This is NOT a +claim that a fixed number of Pods is safe for H2. No load has started yet. +""" + onTimeout = "reject" + } + }, + ] + }, + job.Job { + job = "benchmark" + displayName = "Smoke, warm up, and run custom 600/sec profile" + dependsOn = ["setup", "storage_preflight"] + timeoutInMinutes = 60 + cancelTimeoutInMinutes = 10 + variables = { + RUN_ID = "$[ dependencies.setup.outputs['resolve.RUN_ID'] ]" + CLIENT_ID = "$[ dependencies.setup.outputs['identity.CLIENT_ID'] ]" + KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" + } + steps = [ + steps.Bash { + bash = "mkdir -p \"${ARTIFACTS}\"" + displayName = "Create artifact directory" + }, + common.InstallPythonDependencies(), + azure.GetCredentials( + const.DEFAULT_SERVICE_CONNECTION, + "wi-webhook", + "$(RUN_ID)", + SUBSCRIPTION_ID, + file="$(KUBECONFIG)"), + steps.Bash { + bash = """ +set -euo pipefail +kubectl wait nodes --all --for=condition=Ready --timeout=300s +kubectl get mutatingwebhookconfigurations -o json > "${ARTIFACTS}/admission-webhooks-before.json" +python3 "${SCENARIO}/benchmark.py" prepare \\ + --run-id "$(RUN_ID)" \\ + --client-id "$(CLIENT_ID)" \\ + --image "${RUNNER_IMAGE}" \\ + --artifacts "${ARTIFACTS}" +""" + displayName = "Prepare isolated runner and custom load profiles" + }, + *[ + steps.Bash { + bash = """ +set -euo pipefail +python3 "${SCENARIO}/benchmark.py" run \\ + --phase "${phase}" \\ + --run-id "$(RUN_ID)" \\ + --client-id "$(CLIENT_ID)" \\ + --artifacts "${ARTIFACTS}" +""" + displayName = "Run ${phase} profile" + } for phase in ["smoke", "warmup", "measure"] + ], + steps.Bash { + bash = """ +set -euo pipefail +python3 "${SCENARIO}/benchmark.py" collect \\ + --run-id "$(RUN_ID)" \\ + --artifacts "${ARTIFACTS}" +""" + displayName = "Collect diagnostics and stop any active runner" + condition = "always()" + }, + steps.Task { + task = "PublishPipelineArtifact@1" + displayName = "Publish benchmark results and diagnostics" + condition = "always()" + inputs = { + targetPath = ARTIFACTS + artifact = "wi-benchmark-$(System.JobAttempt)" + } + }, + steps.Bash { + bash = "rm -f -- \"$(KUBECONFIG)\"" + displayName = "Remove run-specific agent kubeconfig" + condition = "always()" + }, + ] + }, + job.Job { + job = "finalize" + displayName = "Retain or delete run-owned resources" + dependsOn = ["setup", "storage_preflight", "benchmark"] + condition = "always()" + timeoutInMinutes = 90 + cancelTimeoutInMinutes = 10 + variables = { + RUN_ID = "$[ dependencies.setup.outputs['resolve.RUN_ID'] ]" + } + steps = [ + steps.Bash { + bash = "mkdir -p \"${ARTIFACTS}\"" + displayName = "Create finalization artifact directory" + condition = "always()" + }, + azure.AzCli( + const.DEFAULT_SERVICE_CONNECTION, + "Verify resource ownership and record retention decision", + """ +run_id="$(RUN_ID)" +if ! [[ "$run_id" =~ ^wi-[0-9]+-[0-9]+$ ]]; then + echo "Missing or invalid setup output; no resources will be deleted." >&2 + exit 1 +fi +exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$run_id") +if [ "$exists" = "false" ]; then + echo "Run resource group does not exist; no cleanup needed." | tee "${ARTIFACTS}/cleanup.txt" + exit 0 +fi +az group show \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --name "$run_id" \\ + --output json > "${ARTIFACTS}/resource-group.json" +jq -e --arg run "$run_id" --arg definition "$(System.DefinitionId)" \\ + '.tags.benchmark == "wi-webhook" and .tags.run_id == $run and .tags.definition_id == $definition' \\ + "${ARTIFACTS}/resource-group.json" +echo "##vso[task.setvariable variable=OWNED_RESOURCE_GROUP]true" +az aks list \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --resource-group "$run_id" \\ + --output json > "${ARTIFACTS}/clusters-final.json" +echo "keep_cluster=\${{ parameters.keep_cluster }}; resource_group=$run_id; cluster=wi-webhook" \\ + | tee "${ARTIFACTS}/retention.txt" +echo "Manual cleanup: az group delete --subscription ${SUBSCRIPTION_ID} --name $run_id --yes" \\ + | tee -a "${ARTIFACTS}/retention.txt" +""", + condition="always()"), + azure.DeleteResourceGroup( + const.DEFAULT_SERVICE_CONNECTION, + "$(RUN_ID)", + SUBSCRIPTION_ID, + condition="and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not(\${{ parameters.keep_cluster }}))"), + azure.AzCli( + const.DEFAULT_SERVICE_CONNECTION, + "Verify deletion completed", + """ +exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$(RUN_ID)") +echo "resource_group_exists=$exists" | tee "${ARTIFACTS}/cleanup.txt" +test "$exists" = "false" +""", + condition="and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not(\${{ parameters.keep_cluster }}))"), + steps.Task { + task = "PublishPipelineArtifact@1" + displayName = "Publish retention and cleanup outcome" + condition = "always()" + inputs = { + targetPath = ARTIFACTS + artifact = "wi-finalize-$(System.JobAttempt)" + } + }, + ] + }, + ] +} diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml new file mode 100755 index 0000000000..cdeff29320 --- /dev/null +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -0,0 +1,456 @@ +name: Workload Identity Webhook Benchmark +pool: AKS-Telescope-Airlock +trigger: none +parameters: +- name: keep_cluster + displayName: Keep cluster and benchmark Pods after benchmark + type: boolean + default: false +pr: none +jobs: +- job: setup + displayName: Provision H2 cluster and worker pool + timeoutInMinutes: 180 + cancelTimeoutInMinutes: 10 + steps: + - bash: |2 + + set -euo pipefail + mkdir -p "$(Build.ArtifactStagingDirectory)/wi-webhook" + echo "##vso[task.setvariable variable=RUN_ID;isOutput=true]wi-$(Build.BuildId)-$(System.JobAttempt)" + displayName: Resolve run-owned resource group + name: resolve + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + az account set --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" + az config set defaults.location="westus2" + az account show + displayName: Login to Azure + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + az extension add --name aks-preview --version 20.0.0b6 --allow-preview true --yes + az aks get-versions \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --location "westus2" \ + --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/kubernetes-versions.json" + jq -e '.values | any(.version | startswith("1.36."))' \ + "$(Build.ArtifactStagingDirectory)/wi-webhook/kubernetes-versions.json" + az vm list-skus \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --location "westus2" \ + --resource-type virtualMachines \ + --all \ + --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/vm-skus.json" + az vm list-usage \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --location "westus2" \ + --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/vm-usage.json" + python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/preflight.py" "$(Build.ArtifactStagingDirectory)/wi-webhook" + exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$(resolve.RUN_ID)") + if [ "$exists" != "false" ]; then + echo "Refusing to reuse an existing or unverified resource group: $(resolve.RUN_ID)" >&2 + exit 1 + fi + displayName: Check AKS version, VM eligibility, and quota + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + az group create \ + --name "$(resolve.RUN_ID)" \ + --location "westus2" \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --tags benchmark=wi-webhook run_id=$(resolve.RUN_ID) definition_id=$(System.DefinitionId) + displayName: Create resource group in westus2 (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + az aks create \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --resource-group "$(resolve.RUN_ID)" \ + --name "wi-webhook" \ + --location "westus2" \ + --kubernetes-version "1.36" \ + --dns-name-prefix "$(resolve.RUN_ID)" \ + --tier standard \ + --control-plane-scaling-size H2 \ + --enable-managed-identity \ + --enable-oidc-issuer \ + --enable-workload-identity \ + --generate-ssh-keys \ + --nodepool-name systempool \ + --node-count 3 \ + --node-vm-size Standard_D2_v4 \ + --max-pods 50 \ + --network-plugin azure \ + --network-plugin-mode overlay \ + --pod-cidr 10.64.0.0/10 \ + --service-cidr 10.0.0.0/16 \ + --dns-service-ip 10.0.0.10 \ + --outbound-type managedNATGateway \ + --nat-gateway-managed-outbound-ip-count 10 \ + --tags SkipAKSCluster=true \ + --yes + displayName: Create H2 cluster with OIDC and workload identity + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + while true; do + STATE=$(az aks show \ + --name "wi-webhook" \ + --resource-group "$(resolve.RUN_ID)" \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --query "provisioningState" \ + --output tsv) + echo "Cluster provisioning state: $STATE" + if [ "$STATE" = "Succeeded" ]; then + echo "Cluster is ready." + break + elif [ "$STATE" = "Failed" ] || [ "$STATE" = "Canceled" ]; then + echo "Cluster failed with state: $STATE." + exit 1 + else + echo "Provisioning state: $STATE. Retry in 30 seconds" + fi + sleep 30 + done + displayName: Wait for cluster to succeed + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + + create_node_pool() { + local deadline sleep_between=30 attempt=0 output rc now remaining_retry_seconds + deadline=$(($(date +%s) + 600)) + while :; do + attempt=$((attempt + 1)) + if output=$(az aks nodepool add "$@" 2>&1); then + rc=0 + else + rc=$? + fi + echo "$output" + if [ "$rc" -eq 0 ]; then + return 0 + fi + if echo "$output" | grep -qiE "OperationNotAllowed"; then + now=$(date +%s) + if [ "$now" -ge "$deadline" ]; then + echo "Retriable error persisted past 600s retry window ($attempt attempts); giving up." + return "$rc" + fi + remaining_retry_seconds=$((deadline - now)) + echo "Attempt $attempt matched retriable pattern; retrying in $sleep_between seconds ($remaining_retry_seconds seconds remain in retry window)." + sleep "$sleep_between" + else + echo "Non-retriable error (rc=$rc); giving up after attempt $attempt." + return "$rc" + fi + done + } + + + create_node_pool \ + --cluster-name "wi-webhook" \ + --resource-group "$(resolve.RUN_ID)" \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --name "workerpool" \ + --node-count 3 \ + --node-vm-size "Standard_D8s_v5" \ + --mode User \ + --max-pods 50 + displayName: Create node pool workerpool + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + while true; do + STATE=$(az aks nodepool show \ + --cluster-name "wi-webhook" \ + --resource-group "$(resolve.RUN_ID)" \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --name "workerpool" \ + --query "provisioningState" \ + --output tsv) + echo "Node pool workerpool provisioning state: $STATE" + if [ "$STATE" = "Succeeded" ]; then + echo "Node pool workerpool is ready." + break + elif [ "$STATE" = "Failed" ] || [ "$STATE" = "Canceled" ]; then + echo "Node pool workerpool failed with state: $STATE." + exit 1 + else + echo "Node pool workerpool provisioning state: $STATE. Retry in 30 seconds" + fi + sleep 30 + done + displayName: Wait for node pool workerpool to succeed + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + az aks show \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --resource-group "$(resolve.RUN_ID)" \ + --name wi-webhook \ + --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/cluster-before.json" + jq -e ' + .location == "westus2" and .sku.tier == "Standard" + and .controlPlaneScalingProfile.scalingSize == "H2" + and .oidcIssuerProfile.enabled == true + and .securityProfile.workloadIdentity.enabled == true + and (.agentPoolProfiles | length == 2) + and (.agentPoolProfiles | any(.name == "systempool" and .count == 3 and .vmSize == "Standard_D2_v4")) + and (.agentPoolProfiles | any(.name == "workerpool" and .count == 3 and .vmSize == "Standard_D8s_v5")) + ' "$(Build.ArtifactStagingDirectory)/wi-webhook/cluster-before.json" + az identity create \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --resource-group "$(resolve.RUN_ID)" \ + --location "westus2" \ + --name wi-benchmark \ + --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/identity.json" + client_id=$(jq -er '.clientId | select(type == "string" and length > 0)' "$(Build.ArtifactStagingDirectory)/wi-webhook/identity.json") + echo "##vso[task.setvariable variable=CLIENT_ID;isOutput=true]$client_id" + displayName: Capture cluster configuration and create benchmark identity + name: identity + - task: PublishPipelineArtifact@1 + inputs: + targetPath: $(Build.ArtifactStagingDirectory)/wi-webhook + artifact: wi-setup-$(System.JobAttempt) + condition: always() + displayName: Publish setup evidence +- job: storage_preflight + displayName: Approve current H2 storage headroom before load + dependsOn: setup + timeoutInMinutes: 65 + variables: + RUN_ID: $[ dependencies.setup.outputs['resolve.RUN_ID'] ] + pool: server + steps: + - task: ManualValidation@0 + inputs: + notifyUsers: $(Build.RequestedForEmail) + instructions: |2 + + Before resuming, inspect current H2 control-plane/storage telemetry for: + subscription b8ceb4e5-f05b-4562-a9f5-14acb1f24219, region westus2, + resource group $(RUN_ID), cluster wi-webhook. + Record the telemetry source, observation time, available storage, and approved + safety margin in the approval comments. Allow for 360,000 retained Pods plus + warm-up and drain. Submitted JSON alone is about 1.37 GiB; WI/defaulting, + revision history, events, and storage overhead require additional headroom. + Confirm no scheduler handles kperf-admission-only and capture the actual + managed WI webhook resource/replica baseline if available. + Reject if storage visibility or an approved margin is missing. This is NOT a + claim that a fixed number of Pods is safe for H2. No load has started yet. + onTimeout: reject + timeoutInMinutes: 60 +- job: benchmark + displayName: Smoke, warm up, and run custom 600/sec profile + dependsOn: + - setup + - storage_preflight + timeoutInMinutes: 60 + cancelTimeoutInMinutes: 10 + variables: + RUN_ID: $[ dependencies.setup.outputs['resolve.RUN_ID'] ] + CLIENT_ID: $[ dependencies.setup.outputs['identity.CLIENT_ID'] ] + KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig + steps: + - bash: mkdir -p "$(Build.ArtifactStagingDirectory)/wi-webhook" + displayName: Create artifact directory + - bash: |- + set -exo pipefail + pip3 install --upgrade "pip<24" + pip3 install -r $(Pipeline.Workspace)/s/modules/python/requirements.txt + displayName: Install Python dependencies + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + az aks get-credentials \ + --name "wi-webhook" \ + --resource-group "$(RUN_ID)" \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --overwrite-existing \ + -f $(KUBECONFIG) + displayName: Get credentials for wi-webhook + - bash: |2 + + set -euo pipefail + kubectl wait nodes --all --for=condition=Ready --timeout=300s + kubectl get mutatingwebhookconfigurations -o json > "$(Build.ArtifactStagingDirectory)/wi-webhook/admission-webhooks-before.json" + python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" prepare \ + --run-id "$(RUN_ID)" \ + --client-id "$(CLIENT_ID)" \ + --image "ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4" \ + --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" + displayName: Prepare isolated runner and custom load profiles + - bash: |2 + + set -euo pipefail + python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" run \ + --phase "smoke" \ + --run-id "$(RUN_ID)" \ + --client-id "$(CLIENT_ID)" \ + --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" + displayName: Run smoke profile + - bash: |2 + + set -euo pipefail + python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" run \ + --phase "warmup" \ + --run-id "$(RUN_ID)" \ + --client-id "$(CLIENT_ID)" \ + --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" + displayName: Run warmup profile + - bash: |2 + + set -euo pipefail + python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" run \ + --phase "measure" \ + --run-id "$(RUN_ID)" \ + --client-id "$(CLIENT_ID)" \ + --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" + displayName: Run measure profile + - bash: |2 + + set -euo pipefail + python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" collect \ + --run-id "$(RUN_ID)" \ + --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" + condition: always() + displayName: Collect diagnostics and stop any active runner + - task: PublishPipelineArtifact@1 + inputs: + targetPath: $(Build.ArtifactStagingDirectory)/wi-webhook + artifact: wi-benchmark-$(System.JobAttempt) + condition: always() + displayName: Publish benchmark results and diagnostics + - bash: rm -f -- "$(KUBECONFIG)" + condition: always() + displayName: Remove run-specific agent kubeconfig +- job: finalize + displayName: Retain or delete run-owned resources + dependsOn: + - setup + - storage_preflight + - benchmark + condition: always() + timeoutInMinutes: 90 + cancelTimeoutInMinutes: 10 + variables: + RUN_ID: $[ dependencies.setup.outputs['resolve.RUN_ID'] ] + steps: + - bash: mkdir -p "$(Build.ArtifactStagingDirectory)/wi-webhook" + condition: always() + displayName: Create finalization artifact directory + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + run_id="$(RUN_ID)" + if ! [[ "$run_id" =~ ^wi-[0-9]+-[0-9]+$ ]]; then + echo "Missing or invalid setup output; no resources will be deleted." >&2 + exit 1 + fi + exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$run_id") + if [ "$exists" = "false" ]; then + echo "Run resource group does not exist; no cleanup needed." | tee "$(Build.ArtifactStagingDirectory)/wi-webhook/cleanup.txt" + exit 0 + fi + az group show \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --name "$run_id" \ + --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/resource-group.json" + jq -e --arg run "$run_id" --arg definition "$(System.DefinitionId)" \ + '.tags.benchmark == "wi-webhook" and .tags.run_id == $run and .tags.definition_id == $definition' \ + "$(Build.ArtifactStagingDirectory)/wi-webhook/resource-group.json" + echo "##vso[task.setvariable variable=OWNED_RESOURCE_GROUP]true" + az aks list \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --resource-group "$run_id" \ + --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/clusters-final.json" + echo "keep_cluster=${{ parameters.keep_cluster }}; resource_group=$run_id; cluster=wi-webhook" \ + | tee "$(Build.ArtifactStagingDirectory)/wi-webhook/retention.txt" + echo "Manual cleanup: az group delete --subscription b8ceb4e5-f05b-4562-a9f5-14acb1f24219 --name $run_id --yes" \ + | tee -a "$(Build.ArtifactStagingDirectory)/wi-webhook/retention.txt" + condition: always() + displayName: Verify resource ownership and record retention decision + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + az group delete --name "$(RUN_ID)" --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --yes + condition: and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not(${{ parameters.keep_cluster }})) + displayName: Delete resource group (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + + exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$(RUN_ID)") + echo "resource_group_exists=$exists" | tee "$(Build.ArtifactStagingDirectory)/wi-webhook/cleanup.txt" + test "$exists" = "false" + condition: and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not(${{ parameters.keep_cluster }})) + displayName: Verify deletion completed + - task: PublishPipelineArtifact@1 + inputs: + targetPath: $(Build.ArtifactStagingDirectory)/wi-webhook + artifact: wi-finalize-$(System.JobAttempt) + condition: always() + displayName: Publish retention and cleanup outcome diff --git a/kcl/workload_identity_webhook/preflight.py b/kcl/workload_identity_webhook/preflight.py new file mode 100644 index 0000000000..79053417c8 --- /dev/null +++ b/kcl/workload_identity_webhook/preflight.py @@ -0,0 +1,35 @@ +"""Verify regional VM eligibility and available vCPU quota before provisioning.""" + +import json +import sys +from pathlib import Path + + +def verify(skus, usage): + required = {"cores": 30} + for name, cpus in (("Standard_D2_v4", 6), ("Standard_D8s_v5", 24)): + matches = [sku for sku in skus if sku["name"] == name] + if len(matches) != 1: + raise ValueError(f"Expected exactly one regional SKU record for {name}") + sku = matches[0] + if any(restriction["type"] == "Location" for restriction in sku["restrictions"]): + raise ValueError(f"SKU {name} has a location restriction: {sku['restrictions']}") + family = sku["family"].lower() + required[family] = required.get(family, 0) + cpus + quotas = {entry["name"]["value"].lower(): entry for entry in usage} + for name, count in required.items(): + if name not in quotas: + raise ValueError(f"Missing quota information: {name}") + quota = quotas[name] + available = quota["limit"] - quota["currentValue"] + if available < count: + raise ValueError(f"Insufficient {name} quota: need {count}, available {available}") + + +if __name__ == "__main__": + directory = Path(sys.argv[1]) + verify( + json.loads((directory / "vm-skus.json").read_text()), + json.loads((directory / "vm-usage.json").read_text()), + ) + print("Regional VM eligibility and vCPU quota checks passed.") diff --git a/kcl/workload_identity_webhook/test_benchmark.py b/kcl/workload_identity_webhook/test_benchmark.py new file mode 100644 index 0000000000..5e657b3e27 --- /dev/null +++ b/kcl/workload_identity_webhook/test_benchmark.py @@ -0,0 +1,367 @@ +import argparse +import copy +import json +import subprocess +import tempfile +import unittest +from pathlib import Path +from unittest.mock import patch + +import yaml + +import benchmark +import preflight + + +RUN_ID = "wi-123-1" +CLIENT_ID = "00000000-0000-0000-0000-000000000001" + + +def report(): + item = { + "total": 0, "duration": "10m1.5s", "totalReceivedBytes": 100, + "percentileLatencies": [[0.5, 0.1], [0.95, 0.2], [0.99, 0.3]], + } + return {"perSpecResults": [copy.deepcopy(item)], "aggregated": item} + + +def pod(phase="smoke"): + return { + "metadata": {"labels": { + "azure.workload.identity/use": "true", + "benchmark": "workload-identity-webhook", + "benchmark-run": RUN_ID, "benchmark-phase": phase, + }}, + "spec": { + "serviceAccountName": "pod-benchmark", + "schedulerName": "kperf-admission-only", + "containers": [{ + "env": [ + {"name": "AZURE_CLIENT_ID", "value": CLIENT_ID}, + {"name": "AZURE_TENANT_ID", "value": "tenant"}, + {"name": "AZURE_AUTHORITY_HOST", "value": "https://login.microsoftonline.com/"}, + {"name": "AZURE_FEDERATED_TOKEN_FILE", "value": "/tokens/azure-token"}, + ], + "volumeMounts": [{"name": "azure-token", "mountPath": "/tokens", "readOnly": True}], + }], + "volumes": [{"name": "azure-token", "projected": {"sources": [{ + "serviceAccountToken": {"audience": "api://AzureADTokenExchange", "path": "azure-token"}, + }]}}], + }, + } + + +class ProfileTests(unittest.TestCase): + def setUp(self): + self.template = yaml.safe_load((benchmark.ROOT / "load-profile.yaml").read_text()) + + def test_measurement_profile_exact_values(self): + profile = benchmark.profile_for_phase(self.template, RUN_ID, "measure") + self.assertEqual(profile["version"], 1) + self.assertEqual(len(profile["specs"]), 1) + spec = profile["specs"][0] + self.assertEqual({key: spec[key] for key in ( + "rate", "duration", "total", "client", "conns", "contentType", "maxRetries", + )}, {"rate": 600, "duration": 600, "total": 0, "client": 600, "conns": 20, + "contentType": "json", "maxRetries": 0}) + self.assertEqual(spec["requests"], [{ + "shares": 1, "postDel": { + "group": "", "version": "v1", "resource": "pods", "namespace": RUN_ID, + "deleteRatio": 0, "payloadSize": 3650, + "pod": { + "labels": { + "azure.workload.identity/use": "true", + "benchmark": "workload-identity-webhook", + "benchmark-run": RUN_ID, "benchmark-phase": "measure", + }, + "serviceAccountName": "pod-benchmark", + "schedulerName": "kperf-admission-only", + }, + }, + }]) + + def test_smoke_and_warmup_do_not_modify_measurement(self): + original = copy.deepcopy(self.template) + for phase, rate, total, duration in (("smoke", 1, 3, 0), ("warmup", 5, 0, 30)): + spec = benchmark.profile_for_phase(self.template, RUN_ID, phase)["specs"][0] + self.assertEqual((spec["rate"], spec["total"], spec["duration"]), (rate, total, duration)) + self.assertEqual(self.template, original) + self.assertEqual(benchmark.profile_for_phase(self.template, RUN_ID, "measure")["specs"][0]["rate"], 600) + + def test_invalid_phase_and_unresolved_placeholder(self): + with self.assertRaises(ValueError): + benchmark.profile_for_phase(self.template, RUN_ID, "invalid") + with self.assertRaises(ValueError): + benchmark.render({"name": "__UNKNOWN__"}, {}) + + def test_job_profile_wiring_and_namespace_permissions(self): + documents = list(yaml.safe_load_all((benchmark.ROOT / "workload.yaml").read_text())) + documents = benchmark.render(documents, { + "RUN_NAMESPACE": RUN_ID, "RUNNER_NAMESPACE": RUN_ID + "-runner", + "RUN_ID": RUN_ID, "CLIENT_ID": CLIENT_ID, + "RUNNER_IMAGE": "image@sha256:test", "JOB_NAME": "kperf-measure", + }) + job = next(item for item in documents if item["kind"] == "Job") + self.assertEqual(job["spec"]["activeDeadlineSeconds"], 900) + self.assertEqual(job["spec"]["backoffLimit"], 0) + spec = job["spec"]["template"]["spec"] + self.assertEqual(spec["restartPolicy"], "Never") + self.assertEqual(spec["nodeSelector"], {"kubernetes.azure.com/agentpool": "workerpool"}) + self.assertEqual(spec["serviceAccountName"], "generator") + self.assertEqual(spec["volumes"][0]["configMap"]["name"], "kperf-measure") + container = spec["containers"][0] + self.assertEqual(container["volumeMounts"], [ + {"name": "profile", "mountPath": "/etc/kperf", "readOnly": True}, + ]) + script = container["args"][0] + self.assertIn("--config /etc/kperf/load-profile.yaml", script) + self.assertIn('--kubeconfig=""', script) + self.assertIn('exit "$status"', script) + for option in ("--rate", "--duration", "--total", "--client", "--conns"): + self.assertNotIn(option, script) + self.assertNotIn("azure.workload.identity/use", job["spec"]["template"]["metadata"]["labels"]) + role = next(item for item in documents if item["kind"] == "Role") + self.assertEqual(role["rules"], [{"apiGroups": [""], "resources": ["pods"], "verbs": ["create"]}]) + self.assertFalse(any(item["kind"] == "ResourceQuota" for item in documents)) + + +class ResultTests(unittest.TestCase): + def test_result_extraction_with_diagnostics(self): + data = report() + self.assertEqual(benchmark.extract_result( + "warning\n" + benchmark.BEGIN + "\n" + json.dumps(data) + "\n" + benchmark.END + "\n" + ), data) + + def test_missing_repeated_or_malformed_result(self): + for text in ("", "{}", benchmark.BEGIN + benchmark.END, + benchmark.BEGIN * 2 + "{}" + benchmark.END, + benchmark.END + "{}" + benchmark.BEGIN): + with self.subTest(text=text), self.assertRaises(ValueError): + benchmark.extract_result(text) + + def test_duration_total_zero_is_not_success_count(self): + summary = benchmark.evaluate_result(report(), 600) + self.assertEqual(summary["runner_reported_total"], 0) + self.assertNotIn("successful_requests", summary) + self.assertEqual(summary["sustained_rate_acceptance"], "not-evaluated") + self.assertEqual(summary["configured_rate_per_second"], 600) + + def test_failures_missing_fields_empty_observations_and_short_duration(self): + changes = [ + ("errorStats", {"429": 1}), ("duration", "9m59s"), + ("duration", "invalid"), ("percentileLatencies", []), + ("errorStats", {"429": -1}), ("errorStats", {"429": "1"}), + ("total", "0"), ("totalReceivedBytes", -1), + ("percentileLatencies", "invalid"), ("percentileLatencies", [[0.5, float("nan")]]), + ("percentileLatencies", [[50, 0.1]]), + ] + for key, value in changes: + data = report() + data["aggregated"][key] = value + with self.subTest(key=key, value=value), self.assertRaises(ValueError): + benchmark.evaluate_result(data, 600) + data = report() + del data["aggregated"]["duration"] + with self.assertRaises(ValueError): + benchmark.evaluate_result(data, 600) + with self.assertRaises(ValueError): + benchmark.evaluate_result({"aggregated": {}}, 600) + + def test_all_requests_failed_reports_errors_without_latency_field(self): + data = report() + for item in (data["perSpecResults"][0], data["aggregated"]): + item.pop("percentileLatencies") + item["errorStats"] = {"forbidden": 3} + with self.assertRaisesRegex(ValueError, "request failures"): + benchmark.evaluate_result(data, 600) + + def test_go_duration_units(self): + self.assertEqual(benchmark.parse_duration("10m1.5s"), 601.5) + self.assertAlmostEqual(benchmark.parse_duration("1ms2us3ns"), 0.001002003) + for value in ("", "-1s", "600", None): + with self.subTest(value=value), self.assertRaises(ValueError): + benchmark.parse_duration(value) + + +class MutationTests(unittest.TestCase): + def test_wi_mutation(self): + benchmark.verify_pod(pod(), RUN_ID, "smoke", CLIENT_ID) + + def test_reject_bound_wrong_scheduler_missing_mutation_and_wrong_ownership(self): + cases = [] + item = pod() + item["spec"]["nodeName"] = "node" + cases.append(item) + item = pod() + item["spec"]["schedulerName"] = "default-scheduler" + cases.append(item) + item = pod() + item["spec"]["containers"][0]["env"] = [] + cases.append(item) + item = pod() + item["spec"]["volumes"] = [] + cases.append(item) + item = pod() + item["metadata"]["labels"]["benchmark-run"] = "other" + cases.append(item) + for item in cases: + with self.subTest(pod=item), self.assertRaises(ValueError): + benchmark.verify_pod(item, RUN_ID, "smoke", CLIENT_ID) + + +class OrchestrationTests(unittest.TestCase): + def setUp(self): + self.directory = tempfile.TemporaryDirectory() + self.addCleanup(self.directory.cleanup) + self.args = argparse.Namespace( + run_id=RUN_ID, artifacts=Path(self.directory.name), phase="smoke", + client_id=CLIENT_ID, image="image@sha256:test", + ) + + @patch("benchmark.subprocess.run") + def test_failed_job_preserves_timestamps(self, run): + run.side_effect = [ + subprocess.CompletedProcess([], 0, stdout="created"), + subprocess.CompletedProcess([], 0, stdout=json.dumps({ + "status": {"conditions": [{"type": "Failed", "status": "True", "reason": "DeadlineExceeded"}]}, + })), + ] + with self.assertRaisesRegex(RuntimeError, "DeadlineExceeded"): + benchmark.run_phase(self.args) + timing = json.loads((self.args.artifacts / "smoke-timestamps.json").read_text()) + self.assertIn("orchestration_start", timing) + self.assertIn("orchestration_end", timing) + + @patch("benchmark.time.monotonic", side_effect=[0, 241]) + @patch("benchmark.subprocess.run") + def test_observation_deadline(self, run, _clock): + run.return_value = subprocess.CompletedProcess([], 0, stdout='{"status":{}}') + with self.assertRaises(TimeoutError): + benchmark.run_phase(self.args) + + @patch("benchmark.subprocess.run") + def test_successful_smoke_and_paginated_snapshot(self, run): + data = report() + data["aggregated"]["total"] = 3 + data["perSpecResults"][0]["total"] = 3 + run.side_effect = [ + subprocess.CompletedProcess([], 0, stdout="created"), + subprocess.CompletedProcess([], 0, stdout=json.dumps({ + "status": {"conditions": [{"type": "Complete", "status": "True"}]}, + })), + subprocess.CompletedProcess([], 0, stdout=benchmark.BEGIN + json.dumps(data) + benchmark.END), + subprocess.CompletedProcess([], 0, stdout=json.dumps({ + "items": [pod()], "metadata": {"continue": "page2"}, + })), + subprocess.CompletedProcess([], 0, stdout=json.dumps({ + "items": [pod(), pod()], "metadata": {}, + })), + ] + benchmark.run_phase(self.args) + summary = json.loads((self.args.artifacts / "smoke-summary.json").read_text()) + self.assertEqual(summary["retained_pod_count"], 3) + self.assertIn("continue=page2", run.call_args.args[0][-1]) + + @patch("benchmark.subprocess.run") + def test_collection_surfaces_errors_and_stops_active_owned_jobs(self, run): + def execute(command, **_kwargs): + if "nodes" in command: + raise subprocess.CalledProcessError(1, command, stderr="forbidden") + value = "{}" + if "jobs" in command: + value = json.dumps({"items": [{ + "metadata": {"name": "kperf-measure", "labels": {"benchmark-run": RUN_ID}}, + "status": {"active": 1}, + }]}) + return subprocess.CompletedProcess(command, 0, stdout=value) + run.side_effect = execute + with self.assertRaisesRegex(RuntimeError, "collection incomplete"): + benchmark.collect(self.args) + self.assertTrue(any("patch" in call.args[0] for call in run.call_args_list)) + failures = json.loads((self.args.artifacts / "collection.json").read_text())["failures"] + self.assertEqual(len(failures), 1) + self.assertIn("forbidden", failures[0]) + + +class PreflightTests(unittest.TestCase): + def setUp(self): + self.skus = [ + {"name": "Standard_D2_v4", "family": "Dv4", "restrictions": []}, + {"name": "Standard_D8s_v5", "family": "DSv5", "restrictions": []}, + ] + self.usage = [ + {"name": {"value": family}, "limit": count + 1, "currentValue": 1} + for family, count in (("cores", 30), ("Dv4", 6), ("DSv5", 24)) + ] + + def test_exact_available_quota_passes(self): + preflight.verify(self.skus, self.usage) + + def test_missing_sku_missing_quota_or_insufficient_quota_fails(self): + for skus, usage in ((self.skus[:1], self.usage), (self.skus, self.usage[:1])): + with self.assertRaises(ValueError): + preflight.verify(skus, usage) + self.usage[2]["limit"] -= 1 + with self.assertRaises(ValueError): + preflight.verify(self.skus, self.usage) + + def test_location_restriction_fails(self): + self.skus[1]["restrictions"] = [{"type": "Location"}] + with self.assertRaises(ValueError): + preflight.verify(self.skus, self.usage) + + +class PipelineTests(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.pipeline = yaml.safe_load((benchmark.ROOT / "pipeline.yaml").read_text()) + cls.jobs = {job["job"]: job for job in cls.pipeline["jobs"]} + + def test_manual_only_and_storage_approval(self): + self.assertEqual(self.pipeline["trigger"], "none") + self.assertEqual(self.pipeline["pr"], "none") + self.assertEqual(self.pipeline["parameters"], [{ + "name": "keep_cluster", + "displayName": "Keep cluster and benchmark Pods after benchmark", + "type": "boolean", "default": False, + }]) + approval = self.jobs["storage_preflight"] + self.assertEqual(approval["pool"], "server") + self.assertEqual(approval["steps"][0]["inputs"]["onTimeout"], "reject") + self.assertEqual(self.jobs["benchmark"]["dependsOn"], ["setup", "storage_preflight"]) + self.assertEqual(self.jobs["benchmark"]["variables"]["KUBECONFIG"], + "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig") + + def test_cleanup_is_always_but_deletion_is_ownership_and_retention_gated(self): + finalize = self.jobs["finalize"] + self.assertEqual(finalize["condition"], "always()") + deletion = next(step for step in finalize["steps"] + if step.get("displayName", "").startswith("Delete resource group")) + for keep in (True, False): + with self.subTest(keep_cluster=keep): + condition = deletion["condition"].replace("${{ parameters.keep_cluster }}", str(keep)) + self.assertEqual(condition, + f"and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not({keep}))") + benchmark_steps = self.jobs["benchmark"]["steps"] + for name in ("Collect diagnostics and stop any active runner", + "Publish benchmark results and diagnostics"): + step = next(step for step in benchmark_steps if step.get("displayName") == name) + self.assertEqual(step["condition"], "always()") + + def test_generated_shell_syntax(self): + scripts = [] + for job in self.jobs.values(): + for step in job["steps"]: + script = step.get("bash", step.get("inputs", {}).get("inlineScript")) + if script: + scripts.append(script) + documents = list(yaml.safe_load_all((benchmark.ROOT / "workload.yaml").read_text())) + job = next(item for item in documents if item["kind"] == "Job") + scripts.append(job["spec"]["template"]["spec"]["containers"][0]["args"][0]) + for script in scripts: + with self.subTest(script=script[:80]): + subprocess.run(["bash", "-n"], input=script, text=True, check=True, capture_output=True) + + +if __name__ == "__main__": + unittest.main() diff --git a/kcl/workload_identity_webhook/workload.yaml b/kcl/workload_identity_webhook/workload.yaml new file mode 100644 index 0000000000..88e147f922 --- /dev/null +++ b/kcl/workload_identity_webhook/workload.yaml @@ -0,0 +1,107 @@ +apiVersion: v1 +kind: Namespace +metadata: + name: "__RUN_NAMESPACE__" + labels: + benchmark-run: "__RUN_ID__" +--- +apiVersion: v1 +kind: Namespace +metadata: + name: "__RUNNER_NAMESPACE__" + labels: + benchmark-run: "__RUN_ID__" +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: pod-benchmark + namespace: "__RUN_NAMESPACE__" + annotations: + azure.workload.identity/client-id: "__CLIENT_ID__" +--- +apiVersion: v1 +kind: ServiceAccount +metadata: + name: generator + namespace: "__RUNNER_NAMESPACE__" +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: Role +metadata: + name: pod-create + namespace: "__RUN_NAMESPACE__" +rules: + - apiGroups: [""] + resources: ["pods"] + verbs: ["create"] +--- +apiVersion: rbac.authorization.k8s.io/v1 +kind: RoleBinding +metadata: + name: generator + namespace: "__RUN_NAMESPACE__" +roleRef: + apiGroup: rbac.authorization.k8s.io + kind: Role + name: pod-create +subjects: + - kind: ServiceAccount + name: generator + namespace: "__RUNNER_NAMESPACE__" +--- +apiVersion: batch/v1 +kind: Job +metadata: + name: "__JOB_NAME__" + namespace: "__RUNNER_NAMESPACE__" + labels: + benchmark-run: "__RUN_ID__" +spec: + backoffLimit: 0 + # Outer bound includes scheduling/image pull, the 600-second profile, and drain. + activeDeadlineSeconds: 900 + template: + metadata: + labels: + benchmark-run: "__RUN_ID__" + spec: + serviceAccountName: generator + restartPolicy: Never + nodeSelector: + kubernetes.azure.com/agentpool: workerpool + containers: + - name: kperf + image: "__RUNNER_IMAGE__" + imagePullPolicy: IfNotPresent + resources: + # Leave headroom on an 8-vCPU, 32-GiB worker; do not share system nodes. + requests: + cpu: "4" + memory: 4Gi + limits: + cpu: "6" + memory: 8Gi + command: ["/bin/bash", "-c"] + args: + - | + set -uo pipefail + /kperf runner run \ + --kubeconfig="" \ + --config /etc/kperf/load-profile.yaml \ + --result /tmp/result.json + status=$? + if [ -s /tmp/result.json ]; then + printf '\nKPERF_RESULT_BEGIN\n' + cat /tmp/result.json + printf '\nKPERF_RESULT_END\n' + fi + exit "$status" + volumeMounts: + - name: profile + mountPath: /etc/kperf + readOnly: true + volumes: + - name: profile + configMap: + name: "__JOB_NAME__" From fc3ba510bb9e049378eb94b8f700d1999c555e24 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Thu, 29 Oct 2026 12:32:44 +1000 Subject: [PATCH 02/24] Simplify WI webhook benchmark and add shared kperf runner Run one custom load profile directly from the ADO agent, reuse Telescope utilities, and regenerate pipeline YAML with KCL 0.13. Remove obsolete orchestration and preflight checks. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/lib/steps/kperf/kperf_runner.k | 54 +++ kcl/lib/steps/kperf/kperf_runner_test.k | 14 + kcl/workload_identity_webhook/README.md | 213 +++++---- kcl/workload_identity_webhook/benchmark.py | 368 ---------------- kcl/workload_identity_webhook/pipeline.k | 312 +++----------- kcl/workload_identity_webhook/pipeline.yaml | 405 +++++------------- kcl/workload_identity_webhook/preflight.py | 35 -- .../test_benchmark.py | 367 ---------------- kcl/workload_identity_webhook/workload.yaml | 107 ----- 9 files changed, 321 insertions(+), 1554 deletions(-) create mode 100644 kcl/lib/steps/kperf/kperf_runner.k create mode 100644 kcl/lib/steps/kperf/kperf_runner_test.k delete mode 100644 kcl/workload_identity_webhook/benchmark.py delete mode 100644 kcl/workload_identity_webhook/preflight.py delete mode 100644 kcl/workload_identity_webhook/test_benchmark.py delete mode 100644 kcl/workload_identity_webhook/workload.yaml diff --git a/kcl/lib/steps/kperf/kperf_runner.k b/kcl/lib/steps/kperf/kperf_runner.k new file mode 100644 index 0000000000..45f1d2f32c --- /dev/null +++ b/kcl/lib/steps/kperf/kperf_runner.k @@ -0,0 +1,54 @@ +import azure_pipelines.ap.steps + +# The caller installs kperf and owns the profile, kubeconfig, and result files. +RunKperfRunner = lambda profilePath: str, kubeconfig: str, resultPath: str, timeoutSeconds: int = 900 -> steps.Script { + assert profilePath != "", "profilePath must not be empty" + assert kubeconfig != "", "kubeconfig must not be empty" + assert resultPath != "", "resultPath must not be empty" + assert resultPath not in [profilePath, kubeconfig], "resultPath must not overwrite an input file" + assert timeoutSeconds > 0, "timeoutSeconds must be positive" + steps.Script { + script = """ +set -euo pipefail +if [ ! -r "${profilePath}" ] || [ ! -r "${kubeconfig}" ]; then + echo "kperf requires a readable load profile and kubeconfig" >&2 + exit 1 +fi +cat "${profilePath}" +rm -f -- "${resultPath}" +echo "Driver start: $(date -u +%Y-%m-%dT%H:%M:%SZ)" +driver_status=0 +timeout --signal=TERM --kill-after=30s ${timeoutSeconds}s \\ + kperf runner run \\ + --kubeconfig "${kubeconfig}" \\ + --config "${profilePath}" \\ + --result "${resultPath}" || driver_status=$? +echo "Driver end: $(date -u +%Y-%m-%dT%H:%M:%SZ); exit status: $driver_status" + +report_status=0 +if [ -s "${resultPath}" ]; then + cat "${resultPath}" + # Native total is configured total (zero for duration mode), not successes. + jq -e ' + (.perSpecResults | type == "array" and length > 0) + and (.aggregated | type == "object") + and ([.perSpecResults[], .aggregated] | all(.[]; + (.total | type == "number" and . >= 0) + and (.duration | type == "string" and length > 0) + and (.percentileLatencies | type == "array" and length > 0) + and (.errorStats // {} | type == "object" and all(.[]; type == "number" and . == 0)) + )) + ' "${resultPath}" || report_status=$? +else + echo "kperf did not produce a nonempty result file" >&2 + report_status=1 +fi +if [ "$report_status" -ne 0 ]; then + echo "kperf result is invalid or contains request failures" >&2 +fi +if [ "$driver_status" -ne 0 ]; then exit "$driver_status"; fi +exit "$report_status" +""" + displayName = "Run kperf runner" + } +} diff --git a/kcl/lib/steps/kperf/kperf_runner_test.k b/kcl/lib/steps/kperf/kperf_runner_test.k new file mode 100644 index 0000000000..d2146d2533 --- /dev/null +++ b/kcl/lib/steps/kperf/kperf_runner_test.k @@ -0,0 +1,14 @@ +test_runner_paths_and_default_timeout = lambda { + step = RunKperfRunner("/tmp/load profile.yaml", "/tmp/kubeconfig", "/tmp/result.json") + assert step.displayName == "Run kperf runner" + assert '--config "/tmp/load profile.yaml"' in step.script + assert '--kubeconfig "/tmp/kubeconfig"' in step.script + assert '--result "/tmp/result.json"' in step.script + assert "timeout --signal=TERM --kill-after=30s 900s" in step.script +} + +test_runner_custom_timeout = lambda { + step = RunKperfRunner("/tmp/profile.yaml", "/tmp/kubeconfig", "/tmp/result.json", timeoutSeconds=1200) + assert "timeout --signal=TERM --kill-after=30s 1200s" in step.script + assert "900s" not in step.script +} diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index 29be722490..e40036bac3 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -1,137 +1,118 @@ # Workload Identity webhook benchmark -A manual, exploratory benchmark on a dedicated AKS Standard H2 cluster in -`westus2`, subscription `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`. +One manual ADO job provisions a dedicated AKS Standard H2 cluster, prepares +workload identity, and runs kperf **once, directly on the ADO agent**. -The cluster has three `Standard_D2_v4` system nodes and three -`Standard_D8s_v5` worker nodes. One generator Job runs on the worker pool. -Benchmark Pods remain unscheduled and do not need worker Pod slots. -Webhook replicas and resources are not tuned by this pipeline. +## Configuration -## Custom load profile +- Subscription: `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`; region: `westus2`. +- System pool: three `Standard_D2_v4` nodes. +- Worker pool: three `Standard_D2s_v5` nodes, retained as requested but not used + to host the traffic driver. +- OIDC and workload identity enabled; webhook resources/replicas are not tuned. +- User-assigned managed identity and an annotated benchmark ServiceAccount. + No federated credential or Azure role assignment is needed for admission-only + testing; the workload does not perform token exchange. -[load-profile.yaml](./load-profile.yaml) is the source of truth: +[load-profile.yaml](./load-profile.yaml) is the traffic configuration: - 600 Pod CREATEs/sec ceiling, 600-second generation window. - `total: 0`, `deleteRatio: 0`, `maxRetries: 0`. -- 600 synchronous request workers and 20 transports, not 600/sec per worker. -- WI opt-in, a dedicated annotated ServiceAccount, run/phase labels, and - `schedulerName: kperf-admission-only`. -- `payloadSize: 3650` pads an environment variable; it is **not** submitted - JSON size. Metadata, defaulting, and WI mutation change object size. +- 600 request workers, 20 transports; the rate is shared across workers. +- WI opt-in, run labels, and `schedulerName: kperf-admission-only`. +- `payloadSize: 3650` pads an environment variable, not the complete submitted + JSON. The resulting single-container Pod is approximately 4 KiB before + server-side mutation/defaulting. -The pipeline renders run identifiers, mounts the profile through a ConfigMap, -and invokes `/kperf runner run --config /etc/kperf/load-profile.yaml` without -CLI traffic overrides. Separate smoke and warm-up profiles reuse the same -Pod configuration without changing the measurement profile. - -The pinned custom image is: +The existing installer extracts kperf from this pinned custom image: ```text ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 ``` -This is the public Linux amd64 image published as `sha-8e8e961`, corresponding -to [Azure/kperf#260](https://github.com/Azure/kperf/pull/260) source commit -`8e8e9617073fa7f0a9a51789923afa96d4d90121`. It is an intentional custom-image -exception; replace it with an upstream release when available. - -## Workflow and safety - -1. Check Kubernetes 1.36 availability, SKU eligibility and regional/family - vCPU quota. Provision the H2 cluster, worker pool, and user-assigned identity. -2. **Manual storage preflight:** before any load, inspect current H2 telemetry. - Record the telemetry source, observation time, available storage, and - approved safety margin in the ADO validation comments. Reject if unavailable. - Confirm no installed scheduler handles `kperf-admission-only`. -3. Check six Ready nodes and expected SKUs. Create isolated runner credentials - with namespace-scoped Pod-create permission. No administrator kubeconfig is - mounted into the runner. The benchmark identity needs neither Azure role - assignments nor a federated credential because no token exchange is tested. -4. Smoke-test three Pods; verify WI environment/projected token mutation, - ownership, and unscheduled state. Warm up at 5/sec for 30 seconds. -5. Execute one measurement Job. `backoffLimit: 0` prevents retries, and a - 900-second outer deadline bounds startup, generation, and drain. -6. Collect results and diagnostics, then finalize according to `keep_cluster`. - -There is **no ResourceQuota** and no claimed 400,000-Pod H2 limit. At the target, -measurement alone retains approximately 360,000 Pods: about 1.37 GiB of -submitted JSON at 4 KiB each, before mutation, history, events, and storage -overhead. Warm-up and outstanding requests add more. Available vCPU quota is -not proof of physical regional capacity or control-plane storage headroom. - -The storage preflight is an agentless ADO manual-validation job, with timeout -set to reject. It is not an automated storage-byte monitor. This first version -has bounded execution, not the original design's full continuous telemetry -and safety-stop implementation. Managed webhook configuration and storage -signals may require ASI/control-plane access beyond `kubectl`; do not infer -their values from worker nodes or substitute defaults. - -### Retention - -`keep_cluster` defaults to **false**: - -- **false:** collect/publish artifacts, then delete only the resource group - whose run and pipeline-definition ownership tags match. -- **true:** retain the cluster, managed identity, namespaces, completed Jobs, - and benchmark Pods for inspection. Attempt to suspend unfinished generators; - Job deadlines remain the fallback if the agent/API is unavailable. - -Retained resources incur charges. The finalization artifact prints their IDs -and an explicit `az group delete` command. Failed or canceled runs attempt -collection/finalization using `always()`; a hard agent interruption can still -prevent these steps. Check the pipeline and Azure before assuming cleanup -completed. A setup failure before resource-group creation needs no deletion; -ownership-check failures deliberately block deletion. - -## Results and limitations - -ADO publishes setup, benchmark, and finalization artifacts containing: - -- Resolved profiles, pinned image, identity client ID (not credentials), cluster - configuration, and before/after platform and admission configuration. -- Per-phase orchestration timestamps, Job status, logs, original kperf JSON, - latency percentiles in seconds, and request error counts. -- Post-run retained-Pod counts and a small set of admitted Pod samples/sizes. - Enumeration is paginated outside measurement; full 360,000-Pod bodies are - neither accumulated in memory nor uploaded. -- Collection failures, retention decisions, and deletion verification. - -The pinned runner's `aggregated.total` and per-spec `total` mirror the configured -total; duration-based runs report **0** there. They are **not successful-request -counts**. Preserve them as `runner_reported_total`; separately report observed -retained Pods. A timeout/error response can still have created a Pod, so these -counts are not interchangeable. - -The runner reports duration including drain. It does not expose per-10-second -dispatch rates, inflight backlog, actual WI invocation rates, exact generation/ -drain boundaries, or submitted-body sizes. Successful exploratory execution -does **not** prove sustained offered load of 600/sec. Reported request errors, -missing/invalid results, smoke failures, and deadlines fail the pipeline rather -than being retried or silently accepted. - -## Development and registration - -The scenario's Python scripts use the repository's existing PyYAML dependency. -Run focused checks after regenerating: +This is tag `sha-8e8e961`, source commit +`8e8e9617073fa7f0a9a51789923afa96d4d90121` from +[Azure/kperf#260](https://github.com/Azure/kperf/pull/260). Replace the custom +image with an upstream release when available. + +## Execution and results + +The job creates the cluster and worker pool, installs the pinned binaries, +fetches credentials into a temporary kubeconfig, creates the identity, +namespace and ServiceAccount, and renders run identifiers into a temporary +profile. It invokes: + +```sh +kperf runner run --kubeconfig "$kubeconfig" --config "$profile" --result "$result" +``` + +Execution uses the shared +[`kperf.RunKperfRunner`](../lib/steps/kperf/kperf_runner.k) step: + +```kcl +kperf.RunKperfRunner( + profilePath="$(KPERF_PROFILE)", + kubeconfig="$(KUBECONFIG)", + resultPath="$(KPERF_RESULT)") +``` + +The helper accepts an optional `timeoutSeconds` (default 900), supports native +single- and multi-spec reports, and leaves input/result file ownership to the +caller. It does not install kperf or provision workload resources. + +There are no CLI traffic overrides, Kubernetes generator Jobs, smoke/warm-up +phases, manual-validation jobs, diagnostic collectors, or artifact uploads. +The profile and native result JSON appear in normal ADO logs. Files live in +[`Agent.TempDirectory`](https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops#agent-variables-devops-services), +which ADO cleans after each job; the shared runner does not delete caller inputs. + +A 900-second outer process timeout bounds generation and drain, with forced +termination after a further 30 seconds if needed. Driver failures, missing or +malformed reports, and reported request errors fail the step; no run is retried. + +The pinned runner's `total` is the configured request total, **not an observed +success count**; it remains zero for this duration-based run. Native duration +includes drain. Per-interval dispatch rates, actual WI invocation rates, and +inflight backlog are unavailable. This is exploratory traffic generation, +not proof that the webhook sustained 600/sec. Agent-to-API-server networking +also differs from an in-cluster driver. + +## Prerequisites and cleanup + +Operators ensure version/SKU availability, quota, and control-plane storage +headroom before queueing. Confirm no scheduler handles `kperf-admission-only`; +the benchmark Pods should remain unscheduled. + +At the target, approximately 360,000 Pods could accumulate: about 1.37 GiB of +submitted JSON at 4 KiB each, before WI/defaulting, revision history, and other +storage overhead. There is no ResourceQuota, continuous storage monitor, or +manual storage gate. The timeout is not a storage-capacity guarantee. + +`keep_cluster` defaults to **false**. The last step deletes the run's resource +group, including the cluster and identity, even after a benchmark failure where +ADO permits cleanup. Deletion is gated on successful resource-group creation +in this job; an existing-group collision never authorizes deletion. + +With **true**, retain the cluster, identity, and benchmark Pods for inspection. +Retained resources incur charges. Use the run's resource-group name from the +ADO logs for manual deletion when finished. There are no separate finalization +reports or deletion-verification steps. A hard agent interruption can prevent +cleanup; check Azure before assuming deletion completed. + +## Development ```sh kcl run kcl/workload_identity_webhook/pipeline.k -S output \ -o kcl/workload_identity_webhook/pipeline.yaml -PYTHONDONTWRITEBYTECODE=1 python3 -m unittest discover \ - -s kcl/workload_identity_webhook -p 'test_*.py' -v +(cd kcl && kcl test lib/steps/kperf) ``` -Registration target: - -- Organization/project: `https://dev.azure.com/akstelescope` / `telescope`. -- Folder: `\AKS\Telescope\v2`. -- Definition name: `Workload Identitiy Webhook Benchmark` (requested spelling). -- Source: `Azure/telescope`, branch `wi-web-bench`. -- YAML: [pipeline.yaml](./pipeline.yaml). -- Existing GitHub connection: `telescope (1)`. -- Azure connection: `Azure-for-Telescope-internal`. -- Agent pool: `AKS-Telescope-Airlock`. +The shared runner has KCL tests. The pipeline does not install a Python +dependency bundle or use a custom Python orchestrator. -Keep CI/PR triggers disabled and register with `--skip-first-run true`. -Registration does not queue a benchmark or create Azure resources. +[ADO pipeline 94](https://dev.azure.com/akstelescope/telescope/_build?definitionId=94) +is registered as `Workload Identitiy Webhook Benchmark` under +`\AKS\Telescope\v2`, using `Azure/telescope:wi-web-bench` and +[pipeline.yaml](./pipeline.yaml). CI/PR triggers remain disabled. +Local changes do not affect that definition until pushed; do not queue a run +as part of local validation. diff --git a/kcl/workload_identity_webhook/benchmark.py b/kcl/workload_identity_webhook/benchmark.py deleted file mode 100644 index 53b5f7f75e..0000000000 --- a/kcl/workload_identity_webhook/benchmark.py +++ /dev/null @@ -1,368 +0,0 @@ -"""Prepare and observe the scenario without changing kperf's traffic contract.""" - -import argparse -import copy -import json -import math -import re -import signal -import subprocess -import sys -import time -import uuid -from datetime import datetime, timezone -from pathlib import Path -from urllib.parse import urlencode - -import yaml - - -ROOT = Path(__file__).parent -BEGIN = "KPERF_RESULT_BEGIN" -END = "KPERF_RESULT_END" -PHASES = ("smoke", "warmup", "measure") - - -def kubectl(*args, stdin=None): - return subprocess.run( - ["kubectl", "--request-timeout=30s", *args], - input=stdin, text=True, capture_output=True, check=True, timeout=90, - ).stdout - - -def write_json(path, value): - path.write_text(json.dumps(value, indent=2) + "\n") - - -def timestamp(): - return datetime.now(timezone.utc).isoformat() - - -def render(value, replacements): - if isinstance(value, dict): - return {key: render(item, replacements) for key, item in value.items()} - if isinstance(value, list): - return [render(item, replacements) for item in value] - if isinstance(value, str): - for key, replacement in replacements.items(): - value = value.replace(f"__{key}__", replacement) - if re.search(r"__[A-Z_]+__", value): - raise ValueError(f"Unresolved placeholder: {value}") - return value - - -def profile_for_phase(template, run_id, phase): - profile = render(copy.deepcopy(template), { - "RUN_NAMESPACE": run_id, "RUN_ID": run_id, - }) - spec = profile["specs"][0] - spec["requests"][0]["postDel"]["pod"]["labels"]["benchmark-phase"] = phase - if phase == "smoke": - spec.update(rate=1, total=3, duration=0, client=1, conns=1) - elif phase == "warmup": - spec.update(rate=5, total=0, duration=30, client=5, conns=1) - elif phase != "measure": - raise ValueError(f"Unknown phase: {phase}") - return profile - - -def extract_result(log): - if log.count(BEGIN) != 1 or log.count(END) != 1: - raise ValueError("Missing or repeated kperf result delimiters") - start = log.index(BEGIN) + len(BEGIN) - stop = log.index(END) - if stop <= start: - raise ValueError("Invalid kperf result delimiter order") - result = json.loads(log[start:stop]) - if not isinstance(result, dict): - raise ValueError("kperf result must be an object") - return result - - -def evaluate_result(result, duration): - specs = result.get("perSpecResults") - aggregate = result.get("aggregated") - if not isinstance(specs, list) or len(specs) != 1 or not isinstance(aggregate, dict): - raise ValueError("Expected one perSpecResults entry and an aggregated report") - for report in [specs[0], aggregate]: - if not isinstance(report, dict): - raise ValueError("Invalid report object") - for field in ("total", "duration", "totalReceivedBytes"): - if field not in report: - raise ValueError(f"Missing report field: {field}") - if any(type(report[field]) is not int or report[field] < 0 - for field in ("total", "totalReceivedBytes")): - raise ValueError("Invalid report total or received bytes") - errors = report.get("errorStats", {}) - if not isinstance(errors, dict) or any( - type(count) is not int or count < 0 for count in errors.values() - ): - raise ValueError("Invalid errorStats") - if sum(errors.values()): - raise ValueError(f"kperf reported request failures: {errors}") - latencies = report.get("percentileLatencies") - if not isinstance(latencies, list) or not latencies: - raise ValueError("No successful-request latency observations") - if any(not isinstance(pair, list) or len(pair) != 2 or any( - type(value) not in (int, float) or not math.isfinite(value) or value < 0 - for value in pair - ) or pair[0] > 1 for pair in latencies): - raise ValueError("Invalid latency percentile pairs") - elapsed = parse_duration(report["duration"]) - if elapsed < duration: - raise ValueError(f"Runner duration {elapsed}s is shorter than {duration}s") - if specs[0] != aggregate: - raise ValueError("Single-spec and aggregate reports disagree") - return { - "classification": "exploratory-completed", - "sustained_rate_acceptance": "not-evaluated", - "configured_rate_per_second": 600 if duration == 600 else None, - "runner_reported_total": aggregate["total"], - "runner_total_semantics": "configured total, NOT observed successful requests", - "runner_duration_including_drain": aggregate["duration"], - "error_stats": aggregate.get("errorStats", {}), - "percentile_latencies_seconds": aggregate["percentileLatencies"], - "limitations": [ - "No per-interval dispatch rate, inflight backlog, or WI invocation count.", - "Retained Pod count is an observation, not successful-response accounting.", - "Submitted body size and exact generation/drain boundaries are unavailable.", - ], - } - - -def parse_duration(value): - if not isinstance(value, str): - raise ValueError("Runner duration must be a Go duration string") - parts = re.findall(r"(\d+(?:\.\d+)?)(ns|us|\u00b5s|ms|s|m|h)", value) - if not parts or "".join(number + unit for number, unit in parts) != value: - raise ValueError(f"Invalid runner duration: {value}") - scales = {"ns": 1e-9, "us": 1e-6, "\u00b5s": 1e-6, "ms": 1e-3, - "s": 1, "m": 60, "h": 3600} - return sum(float(number) * scales[unit] for number, unit in parts) - - -def verify_pod(pod, run_id, phase, client_id): - metadata, spec = pod["metadata"], pod["spec"] - expected = { - "azure.workload.identity/use": "true", - "benchmark": "workload-identity-webhook", - "benchmark-run": run_id, - "benchmark-phase": phase, - } - if any(metadata.get("labels", {}).get(key) != value for key, value in expected.items()): - raise ValueError("Generated Pod labels do not match the benchmark") - if spec.get("schedulerName") != "kperf-admission-only" or spec.get("nodeName"): - raise ValueError("Benchmark Pod is bound or uses the wrong scheduler") - if spec.get("serviceAccountName") != "pod-benchmark" or len(spec["containers"]) != 1: - raise ValueError("Unexpected ServiceAccount or container count") - if spec.get("initContainers"): - raise ValueError("Unexpected init containers") - container = spec["containers"][0] - env = {item["name"]: item.get("value") for item in container.get("env", [])} - if env.get("AZURE_CLIENT_ID") != client_id or not all(env.get(key) for key in ( - "AZURE_TENANT_ID", "AZURE_AUTHORITY_HOST", "AZURE_FEDERATED_TOKEN_FILE", - )): - raise ValueError("Missing or incorrect WI environment mutation") - token_file = env["AZURE_FEDERATED_TOKEN_FILE"] - for volume in spec.get("volumes", []): - for source in volume.get("projected", {}).get("sources", []): - token = source.get("serviceAccountToken", {}) - if token.get("audience") != "api://AzureADTokenExchange": - continue - for mount in container.get("volumeMounts", []): - if (mount["name"] == volume["name"] and mount.get("readOnly") - and token_file == mount["mountPath"].rstrip("/") + "/" + token["path"]): - return - raise ValueError("Missing WI projected token volume/mount") - - -def prepare(args): - nodes = json.loads(kubectl("get", "nodes", "-o", "json")) - for pool, sku in (("systempool", "Standard_D2_v4"), ("workerpool", "Standard_D8s_v5")): - members = [node for node in nodes["items"] - if node["metadata"]["labels"].get("kubernetes.azure.com/agentpool") == pool] - if len(members) != 3 or any( - node["metadata"]["labels"].get("node.kubernetes.io/instance-type") != sku - or not any(c["type"] == "Ready" and c["status"] == "True" - for c in node["status"]["conditions"]) - for node in members - ): - raise ValueError(f"Expected three Ready {sku} nodes in {pool}") - write_json(args.artifacts / "nodes-before.json", nodes) - scheduler_pods = json.loads(kubectl("get", "pods", "-A", "-o", "json")) - for pod in scheduler_pods["items"]: - for container in pod["spec"].get("containers", []): - command = container.get("command", []) + container.get("args", []) - if any("kperf-admission-only" in part for part in command): - raise ValueError("An existing container references the benchmark scheduler") - write_json(args.artifacts / "platform-pods-before.json", scheduler_pods) - template = yaml.safe_load((ROOT / "load-profile.yaml").read_text()) - manifests = list(yaml.safe_load_all((ROOT / "workload.yaml").read_text())) - for phase in PHASES: - profile = profile_for_phase(template, args.run_id, phase) - profile_text = yaml.safe_dump(profile, sort_keys=False) - (args.artifacts / f"{phase}-load-profile.yaml").write_text(profile_text) - name = f"kperf-{phase}" - rendered = render(manifests, { - "RUN_NAMESPACE": args.run_id, "RUNNER_NAMESPACE": args.run_id + "-runner", - "RUN_ID": args.run_id, "CLIENT_ID": args.client_id, - "JOB_NAME": name, "RUNNER_IMAGE": args.image, - }) - prerequisites = [doc for doc in rendered if doc["kind"] != "Job"] - job = next(doc for doc in rendered if doc["kind"] == "Job") - if phase != "measure": - job["spec"]["activeDeadlineSeconds"] = 180 - config_map = { - "apiVersion": "v1", "kind": "ConfigMap", - "metadata": {"name": name, "namespace": args.run_id + "-runner"}, - "data": {"load-profile.yaml": profile_text}, - } - write_json(args.artifacts / f"{phase}-job.json", job) - kubectl("apply", "-f", "-", stdin=yaml.safe_dump_all(prerequisites + [config_map])) - write_json(args.artifacts / "inputs.json", { - "run_id": args.run_id, "image": args.image, "client_id": args.client_id, - "profile": profile_for_phase(template, args.run_id, "measure"), - "webhook_resources": "unchanged; managed control-plane visibility requires ASI telemetry", - }) - - -def pod_snapshot(args, phase): - count, samples, continuation = 0, [], "" - deadline = time.monotonic() + 900 - while True: - query = urlencode({ - "labelSelector": f"benchmark-run={args.run_id},benchmark-phase={phase}", - "limit": 500, "continue": continuation, - }) - page = json.loads(kubectl( - "get", "--raw", f"/api/v1/namespaces/{args.run_id}/pods?{query}", - )) - count += len(page["items"]) - samples.extend(page["items"][:max(0, 3 - len(samples))]) - continuation = page["metadata"].get("continue", "") - if not continuation: - break - if time.monotonic() >= deadline: - raise TimeoutError("Retained Pod snapshot exceeded its 900-second budget") - write_json(args.artifacts / f"{phase}-pods.json", { - "retained_pod_count": count, - "sample_admitted_json_bytes": [len(json.dumps(pod, separators=(",", ":")).encode()) - for pod in samples], - "samples": samples, - }) - if count == 0 or (phase == "smoke" and count != 3): - raise ValueError(f"Unexpected retained Pod count for {phase}: {count}") - for pod in samples: - verify_pod(pod, args.run_id, phase, args.client_id) - return count - - -def run_phase(args): - phase = args.phase - namespace, name = args.run_id + "-runner", f"kperf-{phase}" - timing = {"orchestration_start": timestamp()} - try: - kubectl("create", "-f", str(args.artifacts / f"{phase}-job.json")) - deadline = time.monotonic() + (960 if phase == "measure" else 240) - while True: - job = json.loads(kubectl("get", "job", name, "-n", namespace, "-o", "json")) - write_json(args.artifacts / f"{phase}-job-status.json", job) - conditions = {c["type"]: c for c in job.get("status", {}).get("conditions", []) - if c["status"] == "True"} - if "Failed" in conditions: - raise RuntimeError(f"Job failed: {conditions['Failed']}") - if "Complete" in conditions: - break - if time.monotonic() >= deadline: - raise TimeoutError(f"{name} exceeded its observation deadline") - time.sleep(5) - log = kubectl("logs", f"job/{name}", "-n", namespace, "-c", "kperf") - (args.artifacts / f"{phase}.log").write_text(log) - result = extract_result(log) - write_json(args.artifacts / f"{phase}-result.json", result) - summary = evaluate_result(result, {"smoke": 0, "warmup": 30, "measure": 600}[phase]) - summary["retained_pod_count"] = pod_snapshot(args, phase) - write_json(args.artifacts / f"{phase}-summary.json", summary) - finally: - timing["orchestration_end"] = timestamp() - write_json(args.artifacts / f"{phase}-timestamps.json", timing) - - -def collect(args): - failures = [] - - def capture(name, *command): - try: - output = kubectl(*command) - except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as error: - message = f"{name}: {error}; {getattr(error, 'stderr', '')}" - print(message, file=sys.stderr) - failures.append(message) - (args.artifacts / f"{name}.error.txt").write_text(message) - return None - (args.artifacts / name).write_text(output) - return output - - capture("nodes-after.json", "get", "nodes", "-o", "json") - capture("admission-webhooks.json", "get", "mutatingwebhookconfigurations", "-o", "json") - capture("platform-pods-after.json", "get", "pods", "-n", "kube-system", "-o", "json") - namespace = args.run_id + "-runner" - jobs = capture("jobs-final.json", "get", "jobs", "-n", namespace, "-o", "json") - capture("runner-pods.json", "get", "pods", "-n", namespace, "-o", "json") - capture("runner-events.json", "get", "events", "-n", namespace, "-o", "json") - if jobs is not None: - for job in json.loads(jobs)["items"]: - if job["metadata"].get("labels", {}).get("benchmark-run") != args.run_id: - continue - name = job["metadata"]["name"] - capture(f"{name}-final.log", "logs", f"job/{name}", "-n", namespace, "-c", "kperf") - conditions = job.get("status", {}).get("conditions", []) - terminal = any(c["type"] in ("Complete", "Failed") and c["status"] == "True" - for c in conditions) - if not terminal: - capture(f"{name}-stop.json", "patch", "job", name, "-n", namespace, - "--type=merge", "-p", '{"spec":{"suspend":true}}', "-o", "json") - write_json(args.artifacts / "collection.json", {"failures": failures}) - if failures: - raise RuntimeError("Artifact collection incomplete; see collection.json") - - -def main(): - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("action", choices=("prepare", "run", "collect")) - parser.add_argument("--run-id", required=True) - parser.add_argument("--artifacts", required=True, type=Path) - parser.add_argument("--client-id") - parser.add_argument("--image") - parser.add_argument("--phase", choices=PHASES) - args = parser.parse_args() - if not re.fullmatch(r"wi-[0-9]+-[0-9]+", args.run_id): - parser.error("run-id must be wi--") - if args.action != "collect": - if not args.client_id: - parser.error("--client-id is required") - uuid.UUID(args.client_id) - if args.action == "prepare" and not args.image: - parser.error("--image is required for prepare") - if args.action == "run" and not args.phase: - parser.error("--phase is required for run") - args.artifacts.mkdir(parents=True, exist_ok=True) - - def interrupted(signum, _frame): - raise InterruptedError(f"Benchmark orchestration interrupted by signal {signum}") - - signal.signal(signal.SIGTERM, interrupted) - try: - {"prepare": prepare, "run": run_phase, "collect": collect}[args.action](args) - except (ValueError, KeyError, TypeError, OSError, RuntimeError, - subprocess.SubprocessError) as error: - message = f"{error}\n{getattr(error, 'stderr', '')}" - print(f"WI BENCHMARK FAILED: {message}", file=sys.stderr) - write_json(args.artifacts / f"{args.action}-{args.phase or 'all'}-failure.json", - {"error": message, "timestamp": timestamp()}) - return 1 - return 0 - - -if __name__ == "__main__": - sys.exit(main()) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 7c49762232..357a1f0c28 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -1,14 +1,11 @@ import azure_pipelines.ap import azure_pipelines.ap.jobs.job -import azure_pipelines.ap.steps import lib.const import lib.steps.azure -import lib.steps.common +import lib.steps.kperf SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" LOCATION = "westus2" -SCENARIO = "$(Build.SourcesDirectory)/kcl/workload_identity_webhook" -ARTIFACTS = "$(Build.ArtifactStagingDirectory)/wi-webhook" # TODO: Replace the user-selected PR image with a published upstream release. RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4" @@ -27,69 +24,49 @@ output = ap.Pipeline { ] jobs = [ job.Job { - job = "setup" - displayName = "Provision H2 cluster and worker pool" - timeoutInMinutes = 180 + job = "benchmark" + displayName = "Create H2 cluster and run WI webhook traffic" + timeoutInMinutes = 240 cancelTimeoutInMinutes = 10 + variables = { + RUN_ID = "wi-$(Build.BuildId)-$(System.JobAttempt)" + RESOURCE_GROUP_CREATED = "false" + KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" + KPERF_PROFILE = "$(Agent.TempDirectory)/$(RUN_ID)-load-profile.yaml" + KPERF_RESULT = "$(Agent.TempDirectory)/$(RUN_ID)-result.json" + } steps = [ - steps.Bash { - bash = """ -set -euo pipefail -mkdir -p "${ARTIFACTS}" -echo "##vso[task.setvariable variable=RUN_ID;isOutput=true]wi-$(Build.BuildId)-$(System.JobAttempt)" -""" - name = "resolve" - displayName = "Resolve run-owned resource group" - }, azure.Login( const.DEFAULT_SERVICE_CONNECTION, SUBSCRIPTION_ID, LOCATION), azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, - "Check AKS version, VM eligibility, and quota", + "Verify resource group does not already exist", """ -az extension add --name aks-preview --version 20.0.0b6 --allow-preview true --yes -az aks get-versions \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --location "${LOCATION}" \\ - --output json > "${ARTIFACTS}/kubernetes-versions.json" -jq -e '.values | any(.version | startswith("1.36."))' \\ - "${ARTIFACTS}/kubernetes-versions.json" -az vm list-skus \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --location "${LOCATION}" \\ - --resource-type virtualMachines \\ - --all \\ - --output json > "${ARTIFACTS}/vm-skus.json" -az vm list-usage \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --location "${LOCATION}" \\ - --output json > "${ARTIFACTS}/vm-usage.json" -python3 "${SCENARIO}/preflight.py" "${ARTIFACTS}" -exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$(resolve.RUN_ID)") +exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$(RUN_ID)") if [ "$exists" != "false" ]; then - echo "Refusing to reuse an existing or unverified resource group: $(resolve.RUN_ID)" >&2 + echo "Refusing to reuse an existing or unverified resource group: $(RUN_ID)" >&2 exit 1 fi """), azure.CreateResourceGroup( const.DEFAULT_SERVICE_CONNECTION, - "$(resolve.RUN_ID)", + "$(RUN_ID)", LOCATION, - SUBSCRIPTION_ID, - tags="benchmark=wi-webhook run_id=$(resolve.RUN_ID) definition_id=$(System.DefinitionId)"), + SUBSCRIPTION_ID), azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, "Create H2 cluster with OIDC and workload identity", """ +echo "##vso[task.setvariable variable=RESOURCE_GROUP_CREATED]true" az aks create \\ --subscription "${SUBSCRIPTION_ID}" \\ - --resource-group "$(resolve.RUN_ID)" \\ - --name "wi-webhook" \\ + --resource-group "$(RUN_ID)" \\ + --name wi-webhook \\ --location "${LOCATION}" \\ --kubernetes-version "1.36" \\ - --dns-name-prefix "$(resolve.RUN_ID)" \\ + --dns-name-prefix "$(RUN_ID)" \\ --tier standard \\ --control-plane-scaling-size H2 \\ --enable-managed-identity \\ @@ -110,246 +87,65 @@ az aks create \\ --tags SkipAKSCluster=true \\ --yes """), - azure.WaitForClusterSucceeded( - const.DEFAULT_SERVICE_CONNECTION, - "wi-webhook", - "$(resolve.RUN_ID)", - SUBSCRIPTION_ID), azure.CreateNodePool( const.DEFAULT_SERVICE_CONNECTION, "wi-webhook", - "$(resolve.RUN_ID)", + "$(RUN_ID)", SUBSCRIPTION_ID, azure.NodePool { name = "workerpool" - sku = "Standard_D8s_v5" + sku = "Standard_D2s_v5" count = 3 maxPods = 50 }), - azure.WaitForNodePoolSucceeded( - const.DEFAULT_SERVICE_CONNECTION, - "wi-webhook", - "$(resolve.RUN_ID)", - SUBSCRIPTION_ID, - "workerpool"), - azure.AzCli( - const.DEFAULT_SERVICE_CONNECTION, - "Capture cluster configuration and create benchmark identity", - """ -az aks show \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --resource-group "$(resolve.RUN_ID)" \\ - --name wi-webhook \\ - --output json > "${ARTIFACTS}/cluster-before.json" -jq -e ' - .location == "westus2" and .sku.tier == "Standard" - and .controlPlaneScalingProfile.scalingSize == "H2" - and .oidcIssuerProfile.enabled == true - and .securityProfile.workloadIdentity.enabled == true - and (.agentPoolProfiles | length == 2) - and (.agentPoolProfiles | any(.name == "systempool" and .count == 3 and .vmSize == "Standard_D2_v4")) - and (.agentPoolProfiles | any(.name == "workerpool" and .count == 3 and .vmSize == "Standard_D8s_v5")) -' "${ARTIFACTS}/cluster-before.json" -az identity create \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --resource-group "$(resolve.RUN_ID)" \\ - --location "${LOCATION}" \\ - --name wi-benchmark \\ - --output json > "${ARTIFACTS}/identity.json" -client_id=$(jq -er '.clientId | select(type == "string" and length > 0)' "${ARTIFACTS}/identity.json") -echo "##vso[task.setvariable variable=CLIENT_ID;isOutput=true]$client_id" -""", - stepName="identity"), - steps.Task { - task = "PublishPipelineArtifact@1" - displayName = "Publish setup evidence" - condition = "always()" - inputs = { - targetPath = ARTIFACTS - artifact = "wi-setup-$(System.JobAttempt)" - } - }, - ] - }, - job.Job { - job = "storage_preflight" - displayName = "Approve current H2 storage headroom before load" - dependsOn = "setup" - pool = "server" - timeoutInMinutes = 65 - variables = { - RUN_ID = "$[ dependencies.setup.outputs['resolve.RUN_ID'] ]" - } - steps = [ - steps.Task { - task = "ManualValidation@0" - timeoutInMinutes = 60 - inputs = { - notifyUsers = "$(Build.RequestedForEmail)" - instructions = """ -Before resuming, inspect current H2 control-plane/storage telemetry for: -subscription ${SUBSCRIPTION_ID}, region ${LOCATION}, -resource group $(RUN_ID), cluster wi-webhook. -Record the telemetry source, observation time, available storage, and approved -safety margin in the approval comments. Allow for 360,000 retained Pods plus -warm-up and drain. Submitted JSON alone is about 1.37 GiB; WI/defaulting, -revision history, events, and storage overhead require additional headroom. -Confirm no scheduler handles kperf-admission-only and capture the actual -managed WI webhook resource/replica baseline if available. -Reject if storage visibility or an approved margin is missing. This is NOT a -claim that a fixed number of Pods is safe for H2. No load has started yet. -""" - onTimeout = "reject" - } - }, - ] - }, - job.Job { - job = "benchmark" - displayName = "Smoke, warm up, and run custom 600/sec profile" - dependsOn = ["setup", "storage_preflight"] - timeoutInMinutes = 60 - cancelTimeoutInMinutes = 10 - variables = { - RUN_ID = "$[ dependencies.setup.outputs['resolve.RUN_ID'] ]" - CLIENT_ID = "$[ dependencies.setup.outputs['identity.CLIENT_ID'] ]" - KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" - } - steps = [ - steps.Bash { - bash = "mkdir -p \"${ARTIFACTS}\"" - displayName = "Create artifact directory" - }, - common.InstallPythonDependencies(), + kperf.InstallRunkperf(RUNNER_IMAGE), azure.GetCredentials( const.DEFAULT_SERVICE_CONNECTION, "wi-webhook", "$(RUN_ID)", SUBSCRIPTION_ID, file="$(KUBECONFIG)"), - steps.Bash { - bash = """ -set -euo pipefail -kubectl wait nodes --all --for=condition=Ready --timeout=300s -kubectl get mutatingwebhookconfigurations -o json > "${ARTIFACTS}/admission-webhooks-before.json" -python3 "${SCENARIO}/benchmark.py" prepare \\ - --run-id "$(RUN_ID)" \\ - --client-id "$(CLIENT_ID)" \\ - --image "${RUNNER_IMAGE}" \\ - --artifacts "${ARTIFACTS}" -""" - displayName = "Prepare isolated runner and custom load profiles" - }, - *[ - steps.Bash { - bash = """ -set -euo pipefail -python3 "${SCENARIO}/benchmark.py" run \\ - --phase "${phase}" \\ - --run-id "$(RUN_ID)" \\ - --client-id "$(CLIENT_ID)" \\ - --artifacts "${ARTIFACTS}" -""" - displayName = "Run ${phase} profile" - } for phase in ["smoke", "warmup", "measure"] - ], - steps.Bash { - bash = """ -set -euo pipefail -python3 "${SCENARIO}/benchmark.py" collect \\ - --run-id "$(RUN_ID)" \\ - --artifacts "${ARTIFACTS}" -""" - displayName = "Collect diagnostics and stop any active runner" - condition = "always()" - }, - steps.Task { - task = "PublishPipelineArtifact@1" - displayName = "Publish benchmark results and diagnostics" - condition = "always()" - inputs = { - targetPath = ARTIFACTS - artifact = "wi-benchmark-$(System.JobAttempt)" - } - }, - steps.Bash { - bash = "rm -f -- \"$(KUBECONFIG)\"" - displayName = "Remove run-specific agent kubeconfig" - condition = "always()" - }, - ] - }, - job.Job { - job = "finalize" - displayName = "Retain or delete run-owned resources" - dependsOn = ["setup", "storage_preflight", "benchmark"] - condition = "always()" - timeoutInMinutes = 90 - cancelTimeoutInMinutes = 10 - variables = { - RUN_ID = "$[ dependencies.setup.outputs['resolve.RUN_ID'] ]" - } - steps = [ - steps.Bash { - bash = "mkdir -p \"${ARTIFACTS}\"" - displayName = "Create finalization artifact directory" - condition = "always()" - }, azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, - "Verify resource ownership and record retention decision", + "Prepare WI resources and load profile", """ -run_id="$(RUN_ID)" -if ! [[ "$run_id" =~ ^wi-[0-9]+-[0-9]+$ ]]; then - echo "Missing or invalid setup output; no resources will be deleted." >&2 +set -u +profile="$(KPERF_PROFILE)" +client_id=$(az identity create \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --resource-group "$(RUN_ID)" \\ + --location "${LOCATION}" \\ + --name wi-benchmark \\ + --query clientId \\ + --output tsv) +if ! [[ "$client_id" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then + echo "Managed identity returned an invalid client ID" >&2 exit 1 fi -exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$run_id") -if [ "$exists" = "false" ]; then - echo "Run resource group does not exist; no cleanup needed." | tee "${ARTIFACTS}/cleanup.txt" - exit 0 +kubectl create namespace "$(RUN_ID)" +kubectl create serviceaccount pod-benchmark --namespace "$(RUN_ID)" +kubectl annotate serviceaccount pod-benchmark \\ + --namespace "$(RUN_ID)" \\ + "azure.workload.identity/client-id=$client_id" + +sed \\ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)/g' \\ + -e 's/__RUN_ID__/$(RUN_ID)/g' \\ + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" +if grep -q '__[A-Z_]*__' "$profile"; then + echo "Unresolved load-profile placeholders" >&2 + exit 1 fi -az group show \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --name "$run_id" \\ - --output json > "${ARTIFACTS}/resource-group.json" -jq -e --arg run "$run_id" --arg definition "$(System.DefinitionId)" \\ - '.tags.benchmark == "wi-webhook" and .tags.run_id == $run and .tags.definition_id == $definition' \\ - "${ARTIFACTS}/resource-group.json" -echo "##vso[task.setvariable variable=OWNED_RESOURCE_GROUP]true" -az aks list \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --resource-group "$run_id" \\ - --output json > "${ARTIFACTS}/clusters-final.json" -echo "keep_cluster=\${{ parameters.keep_cluster }}; resource_group=$run_id; cluster=wi-webhook" \\ - | tee "${ARTIFACTS}/retention.txt" -echo "Manual cleanup: az group delete --subscription ${SUBSCRIPTION_ID} --name $run_id --yes" \\ - | tee -a "${ARTIFACTS}/retention.txt" -""", - condition="always()"), +"""), + kperf.RunKperfRunner( + profilePath="$(KPERF_PROFILE)", + kubeconfig="$(KUBECONFIG)", + resultPath="$(KPERF_RESULT)"), azure.DeleteResourceGroup( const.DEFAULT_SERVICE_CONNECTION, "$(RUN_ID)", SUBSCRIPTION_ID, - condition="and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not(\${{ parameters.keep_cluster }}))"), - azure.AzCli( - const.DEFAULT_SERVICE_CONNECTION, - "Verify deletion completed", - """ -exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$(RUN_ID)") -echo "resource_group_exists=$exists" | tee "${ARTIFACTS}/cleanup.txt" -test "$exists" = "false" -""", - condition="and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not(\${{ parameters.keep_cluster }}))"), - steps.Task { - task = "PublishPipelineArtifact@1" - displayName = "Publish retention and cleanup outcome" - condition = "always()" - inputs = { - targetPath = ARTIFACTS - artifact = "wi-finalize-$(System.JobAttempt)" - } - }, + condition="and(always(), eq(variables['RESOURCE_GROUP_CREATED'], 'true'), not(\${{ parameters.keep_cluster }}))"), ] }, ] diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index cdeff29320..8847896b17 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -8,18 +8,17 @@ parameters: default: false pr: none jobs: -- job: setup - displayName: Provision H2 cluster and worker pool - timeoutInMinutes: 180 +- job: benchmark + displayName: Create H2 cluster and run WI webhook traffic + timeoutInMinutes: 240 cancelTimeoutInMinutes: 10 + variables: + RUN_ID: wi-$(Build.BuildId)-$(System.JobAttempt) + RESOURCE_GROUP_CREATED: 'false' + KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig + KPERF_PROFILE: $(Agent.TempDirectory)/$(RUN_ID)-load-profile.yaml + KPERF_RESULT: $(Agent.TempDirectory)/$(RUN_ID)-result.json steps: - - bash: |2 - - set -euo pipefail - mkdir -p "$(Build.ArtifactStagingDirectory)/wi-webhook" - echo "##vso[task.setvariable variable=RUN_ID;isOutput=true]wi-$(Build.BuildId)-$(System.JobAttempt)" - displayName: Resolve run-owned resource group - name: resolve - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -27,7 +26,6 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - az account set --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" az config set defaults.location="westus2" az account show @@ -39,44 +37,24 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - - az extension add --name aks-preview --version 20.0.0b6 --allow-preview true --yes - az aks get-versions \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --location "westus2" \ - --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/kubernetes-versions.json" - jq -e '.values | any(.version | startswith("1.36."))' \ - "$(Build.ArtifactStagingDirectory)/wi-webhook/kubernetes-versions.json" - az vm list-skus \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --location "westus2" \ - --resource-type virtualMachines \ - --all \ - --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/vm-skus.json" - az vm list-usage \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --location "westus2" \ - --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/vm-usage.json" - python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/preflight.py" "$(Build.ArtifactStagingDirectory)/wi-webhook" - exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$(resolve.RUN_ID)") + exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$(RUN_ID)") if [ "$exists" != "false" ]; then - echo "Refusing to reuse an existing or unverified resource group: $(resolve.RUN_ID)" >&2 + echo "Refusing to reuse an existing or unverified resource group: $(RUN_ID)" >&2 exit 1 fi - displayName: Check AKS version, VM eligibility, and quota + displayName: Verify resource group does not already exist - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal scriptType: bash scriptLocation: inlineScript - inlineScript: | + inlineScript: |+ set -exo pipefail - az group create \ - --name "$(resolve.RUN_ID)" \ + --name "$(RUN_ID)" \ --location "westus2" \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --tags benchmark=wi-webhook run_id=$(resolve.RUN_ID) definition_id=$(System.DefinitionId) + displayName: Create resource group in westus2 (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) - task: AzureCLI@2 inputs: @@ -85,14 +63,14 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - + echo "##vso[task.setvariable variable=RESOURCE_GROUP_CREATED]true" az aks create \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --resource-group "$(resolve.RUN_ID)" \ - --name "wi-webhook" \ + --resource-group "$(RUN_ID)" \ + --name wi-webhook \ --location "westus2" \ --kubernetes-version "1.36" \ - --dns-name-prefix "$(resolve.RUN_ID)" \ + --dns-name-prefix "$(RUN_ID)" \ --tier standard \ --control-plane-scaling-size H2 \ --enable-managed-identity \ @@ -120,36 +98,6 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - - while true; do - STATE=$(az aks show \ - --name "wi-webhook" \ - --resource-group "$(resolve.RUN_ID)" \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --query "provisioningState" \ - --output tsv) - echo "Cluster provisioning state: $STATE" - if [ "$STATE" = "Succeeded" ]; then - echo "Cluster is ready." - break - elif [ "$STATE" = "Failed" ] || [ "$STATE" = "Canceled" ]; then - echo "Cluster failed with state: $STATE." - exit 1 - else - echo "Provisioning state: $STATE. Retry in 30 seconds" - fi - sleep 30 - done - displayName: Wait for cluster to succeed - - task: AzureCLI@2 - inputs: - azureSubscription: Azure-for-Telescope-internal - scriptType: bash - scriptLocation: inlineScript - inlineScript: | - set -exo pipefail - - create_node_pool() { local deadline sleep_between=30 attempt=0 output rc now remaining_retry_seconds deadline=$(($(date +%s) + 600)) @@ -183,14 +131,28 @@ jobs: create_node_pool \ --cluster-name "wi-webhook" \ - --resource-group "$(resolve.RUN_ID)" \ + --resource-group "$(RUN_ID)" \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ --name "workerpool" \ --node-count 3 \ - --node-vm-size "Standard_D8s_v5" \ + --node-vm-size "Standard_D2s_v5" \ --mode User \ --max-pods 50 displayName: Create node pool workerpool + - script: | + set -euo pipefail + set -x + + temp_dir=$(mktemp -p /tmp -d kperfinstall.XXXX) + docker rmi ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 2>/dev/null || true + docker pull ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 + docker run --rm -v $temp_dir:/install-dir \ + ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 bash -c "set -x; install /kperf /runkperf /install-dir" + + sudo install $temp_dir/kperf $temp_dir/runkperf /usr/local/bin + rm -rf $temp_dir + docker rmi ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 2>/dev/null || true + displayName: Install runkperf binary - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -198,119 +160,6 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - - while true; do - STATE=$(az aks nodepool show \ - --cluster-name "wi-webhook" \ - --resource-group "$(resolve.RUN_ID)" \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --name "workerpool" \ - --query "provisioningState" \ - --output tsv) - echo "Node pool workerpool provisioning state: $STATE" - if [ "$STATE" = "Succeeded" ]; then - echo "Node pool workerpool is ready." - break - elif [ "$STATE" = "Failed" ] || [ "$STATE" = "Canceled" ]; then - echo "Node pool workerpool failed with state: $STATE." - exit 1 - else - echo "Node pool workerpool provisioning state: $STATE. Retry in 30 seconds" - fi - sleep 30 - done - displayName: Wait for node pool workerpool to succeed - - task: AzureCLI@2 - inputs: - azureSubscription: Azure-for-Telescope-internal - scriptType: bash - scriptLocation: inlineScript - inlineScript: | - set -exo pipefail - - az aks show \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --resource-group "$(resolve.RUN_ID)" \ - --name wi-webhook \ - --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/cluster-before.json" - jq -e ' - .location == "westus2" and .sku.tier == "Standard" - and .controlPlaneScalingProfile.scalingSize == "H2" - and .oidcIssuerProfile.enabled == true - and .securityProfile.workloadIdentity.enabled == true - and (.agentPoolProfiles | length == 2) - and (.agentPoolProfiles | any(.name == "systempool" and .count == 3 and .vmSize == "Standard_D2_v4")) - and (.agentPoolProfiles | any(.name == "workerpool" and .count == 3 and .vmSize == "Standard_D8s_v5")) - ' "$(Build.ArtifactStagingDirectory)/wi-webhook/cluster-before.json" - az identity create \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --resource-group "$(resolve.RUN_ID)" \ - --location "westus2" \ - --name wi-benchmark \ - --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/identity.json" - client_id=$(jq -er '.clientId | select(type == "string" and length > 0)' "$(Build.ArtifactStagingDirectory)/wi-webhook/identity.json") - echo "##vso[task.setvariable variable=CLIENT_ID;isOutput=true]$client_id" - displayName: Capture cluster configuration and create benchmark identity - name: identity - - task: PublishPipelineArtifact@1 - inputs: - targetPath: $(Build.ArtifactStagingDirectory)/wi-webhook - artifact: wi-setup-$(System.JobAttempt) - condition: always() - displayName: Publish setup evidence -- job: storage_preflight - displayName: Approve current H2 storage headroom before load - dependsOn: setup - timeoutInMinutes: 65 - variables: - RUN_ID: $[ dependencies.setup.outputs['resolve.RUN_ID'] ] - pool: server - steps: - - task: ManualValidation@0 - inputs: - notifyUsers: $(Build.RequestedForEmail) - instructions: |2 - - Before resuming, inspect current H2 control-plane/storage telemetry for: - subscription b8ceb4e5-f05b-4562-a9f5-14acb1f24219, region westus2, - resource group $(RUN_ID), cluster wi-webhook. - Record the telemetry source, observation time, available storage, and approved - safety margin in the approval comments. Allow for 360,000 retained Pods plus - warm-up and drain. Submitted JSON alone is about 1.37 GiB; WI/defaulting, - revision history, events, and storage overhead require additional headroom. - Confirm no scheduler handles kperf-admission-only and capture the actual - managed WI webhook resource/replica baseline if available. - Reject if storage visibility or an approved margin is missing. This is NOT a - claim that a fixed number of Pods is safe for H2. No load has started yet. - onTimeout: reject - timeoutInMinutes: 60 -- job: benchmark - displayName: Smoke, warm up, and run custom 600/sec profile - dependsOn: - - setup - - storage_preflight - timeoutInMinutes: 60 - cancelTimeoutInMinutes: 10 - variables: - RUN_ID: $[ dependencies.setup.outputs['resolve.RUN_ID'] ] - CLIENT_ID: $[ dependencies.setup.outputs['identity.CLIENT_ID'] ] - KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig - steps: - - bash: mkdir -p "$(Build.ArtifactStagingDirectory)/wi-webhook" - displayName: Create artifact directory - - bash: |- - set -exo pipefail - pip3 install --upgrade "pip<24" - pip3 install -r $(Pipeline.Workspace)/s/modules/python/requirements.txt - displayName: Install Python dependencies - - task: AzureCLI@2 - inputs: - azureSubscription: Azure-for-Telescope-internal - scriptType: bash - scriptLocation: inlineScript - inlineScript: | - set -exo pipefail - az aks get-credentials \ --name "wi-webhook" \ --resource-group "$(RUN_ID)" \ @@ -318,76 +167,6 @@ jobs: --overwrite-existing \ -f $(KUBECONFIG) displayName: Get credentials for wi-webhook - - bash: |2 - - set -euo pipefail - kubectl wait nodes --all --for=condition=Ready --timeout=300s - kubectl get mutatingwebhookconfigurations -o json > "$(Build.ArtifactStagingDirectory)/wi-webhook/admission-webhooks-before.json" - python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" prepare \ - --run-id "$(RUN_ID)" \ - --client-id "$(CLIENT_ID)" \ - --image "ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4" \ - --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" - displayName: Prepare isolated runner and custom load profiles - - bash: |2 - - set -euo pipefail - python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" run \ - --phase "smoke" \ - --run-id "$(RUN_ID)" \ - --client-id "$(CLIENT_ID)" \ - --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" - displayName: Run smoke profile - - bash: |2 - - set -euo pipefail - python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" run \ - --phase "warmup" \ - --run-id "$(RUN_ID)" \ - --client-id "$(CLIENT_ID)" \ - --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" - displayName: Run warmup profile - - bash: |2 - - set -euo pipefail - python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" run \ - --phase "measure" \ - --run-id "$(RUN_ID)" \ - --client-id "$(CLIENT_ID)" \ - --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" - displayName: Run measure profile - - bash: |2 - - set -euo pipefail - python3 "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/benchmark.py" collect \ - --run-id "$(RUN_ID)" \ - --artifacts "$(Build.ArtifactStagingDirectory)/wi-webhook" - condition: always() - displayName: Collect diagnostics and stop any active runner - - task: PublishPipelineArtifact@1 - inputs: - targetPath: $(Build.ArtifactStagingDirectory)/wi-webhook - artifact: wi-benchmark-$(System.JobAttempt) - condition: always() - displayName: Publish benchmark results and diagnostics - - bash: rm -f -- "$(KUBECONFIG)" - condition: always() - displayName: Remove run-specific agent kubeconfig -- job: finalize - displayName: Retain or delete run-owned resources - dependsOn: - - setup - - storage_preflight - - benchmark - condition: always() - timeoutInMinutes: 90 - cancelTimeoutInMinutes: 10 - variables: - RUN_ID: $[ dependencies.setup.outputs['resolve.RUN_ID'] ] - steps: - - bash: mkdir -p "$(Build.ArtifactStagingDirectory)/wi-webhook" - condition: always() - displayName: Create finalization artifact directory - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -395,35 +174,75 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - - run_id="$(RUN_ID)" - if ! [[ "$run_id" =~ ^wi-[0-9]+-[0-9]+$ ]]; then - echo "Missing or invalid setup output; no resources will be deleted." >&2 + set -u + profile="$(KPERF_PROFILE)" + client_id=$(az identity create \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --resource-group "$(RUN_ID)" \ + --location "westus2" \ + --name wi-benchmark \ + --query clientId \ + --output tsv) + if ! [[ "$client_id" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then + echo "Managed identity returned an invalid client ID" >&2 exit 1 fi - exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$run_id") - if [ "$exists" = "false" ]; then - echo "Run resource group does not exist; no cleanup needed." | tee "$(Build.ArtifactStagingDirectory)/wi-webhook/cleanup.txt" - exit 0 + kubectl create namespace "$(RUN_ID)" + kubectl create serviceaccount pod-benchmark --namespace "$(RUN_ID)" + kubectl annotate serviceaccount pod-benchmark \ + --namespace "$(RUN_ID)" \ + "azure.workload.identity/client-id=$client_id" + + sed \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)/g' \ + -e 's/__RUN_ID__/$(RUN_ID)/g' \ + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + if grep -q '__[A-Z_]*__' "$profile"; then + echo "Unresolved load-profile placeholders" >&2 + exit 1 fi - az group show \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --name "$run_id" \ - --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/resource-group.json" - jq -e --arg run "$run_id" --arg definition "$(System.DefinitionId)" \ - '.tags.benchmark == "wi-webhook" and .tags.run_id == $run and .tags.definition_id == $definition' \ - "$(Build.ArtifactStagingDirectory)/wi-webhook/resource-group.json" - echo "##vso[task.setvariable variable=OWNED_RESOURCE_GROUP]true" - az aks list \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --resource-group "$run_id" \ - --output json > "$(Build.ArtifactStagingDirectory)/wi-webhook/clusters-final.json" - echo "keep_cluster=${{ parameters.keep_cluster }}; resource_group=$run_id; cluster=wi-webhook" \ - | tee "$(Build.ArtifactStagingDirectory)/wi-webhook/retention.txt" - echo "Manual cleanup: az group delete --subscription b8ceb4e5-f05b-4562-a9f5-14acb1f24219 --name $run_id --yes" \ - | tee -a "$(Build.ArtifactStagingDirectory)/wi-webhook/retention.txt" - condition: always() - displayName: Verify resource ownership and record retention decision + displayName: Prepare WI resources and load profile + - script: | + set -euo pipefail + if [ ! -r "$(KPERF_PROFILE)" ] || [ ! -r "$(KUBECONFIG)" ]; then + echo "kperf requires a readable load profile and kubeconfig" >&2 + exit 1 + fi + cat "$(KPERF_PROFILE)" + rm -f -- "$(KPERF_RESULT)" + echo "Driver start: $(date -u +%Y-%m-%dT%H:%M:%SZ)" + driver_status=0 + timeout --signal=TERM --kill-after=30s 900s \ + kperf runner run \ + --kubeconfig "$(KUBECONFIG)" \ + --config "$(KPERF_PROFILE)" \ + --result "$(KPERF_RESULT)" || driver_status=$? + echo "Driver end: $(date -u +%Y-%m-%dT%H:%M:%SZ); exit status: $driver_status" + + report_status=0 + if [ -s "$(KPERF_RESULT)" ]; then + cat "$(KPERF_RESULT)" + # Native total is configured total (zero for duration mode), not successes. + jq -e ' + (.perSpecResults | type == "array" and length > 0) + and (.aggregated | type == "object") + and ([.perSpecResults[], .aggregated] | all(.[]; + (.total | type == "number" and . >= 0) + and (.duration | type == "string" and length > 0) + and (.percentileLatencies | type == "array" and length > 0) + and (.errorStats // {} | type == "object" and all(.[]; type == "number" and . == 0)) + )) + ' "$(KPERF_RESULT)" || report_status=$? + else + echo "kperf did not produce a nonempty result file" >&2 + report_status=1 + fi + if [ "$report_status" -ne 0 ]; then + echo "kperf result is invalid or contains request failures" >&2 + fi + if [ "$driver_status" -ne 0 ]; then exit "$driver_status"; fi + exit "$report_status" + displayName: Run kperf runner - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -431,26 +250,6 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - az group delete --name "$(RUN_ID)" --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --yes - condition: and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not(${{ parameters.keep_cluster }})) + condition: and(always(), eq(variables['RESOURCE_GROUP_CREATED'], 'true'), not(${{ parameters.keep_cluster }})) displayName: Delete resource group (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) - - task: AzureCLI@2 - inputs: - azureSubscription: Azure-for-Telescope-internal - scriptType: bash - scriptLocation: inlineScript - inlineScript: | - set -exo pipefail - - exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$(RUN_ID)") - echo "resource_group_exists=$exists" | tee "$(Build.ArtifactStagingDirectory)/wi-webhook/cleanup.txt" - test "$exists" = "false" - condition: and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not(${{ parameters.keep_cluster }})) - displayName: Verify deletion completed - - task: PublishPipelineArtifact@1 - inputs: - targetPath: $(Build.ArtifactStagingDirectory)/wi-webhook - artifact: wi-finalize-$(System.JobAttempt) - condition: always() - displayName: Publish retention and cleanup outcome diff --git a/kcl/workload_identity_webhook/preflight.py b/kcl/workload_identity_webhook/preflight.py deleted file mode 100644 index 79053417c8..0000000000 --- a/kcl/workload_identity_webhook/preflight.py +++ /dev/null @@ -1,35 +0,0 @@ -"""Verify regional VM eligibility and available vCPU quota before provisioning.""" - -import json -import sys -from pathlib import Path - - -def verify(skus, usage): - required = {"cores": 30} - for name, cpus in (("Standard_D2_v4", 6), ("Standard_D8s_v5", 24)): - matches = [sku for sku in skus if sku["name"] == name] - if len(matches) != 1: - raise ValueError(f"Expected exactly one regional SKU record for {name}") - sku = matches[0] - if any(restriction["type"] == "Location" for restriction in sku["restrictions"]): - raise ValueError(f"SKU {name} has a location restriction: {sku['restrictions']}") - family = sku["family"].lower() - required[family] = required.get(family, 0) + cpus - quotas = {entry["name"]["value"].lower(): entry for entry in usage} - for name, count in required.items(): - if name not in quotas: - raise ValueError(f"Missing quota information: {name}") - quota = quotas[name] - available = quota["limit"] - quota["currentValue"] - if available < count: - raise ValueError(f"Insufficient {name} quota: need {count}, available {available}") - - -if __name__ == "__main__": - directory = Path(sys.argv[1]) - verify( - json.loads((directory / "vm-skus.json").read_text()), - json.loads((directory / "vm-usage.json").read_text()), - ) - print("Regional VM eligibility and vCPU quota checks passed.") diff --git a/kcl/workload_identity_webhook/test_benchmark.py b/kcl/workload_identity_webhook/test_benchmark.py deleted file mode 100644 index 5e657b3e27..0000000000 --- a/kcl/workload_identity_webhook/test_benchmark.py +++ /dev/null @@ -1,367 +0,0 @@ -import argparse -import copy -import json -import subprocess -import tempfile -import unittest -from pathlib import Path -from unittest.mock import patch - -import yaml - -import benchmark -import preflight - - -RUN_ID = "wi-123-1" -CLIENT_ID = "00000000-0000-0000-0000-000000000001" - - -def report(): - item = { - "total": 0, "duration": "10m1.5s", "totalReceivedBytes": 100, - "percentileLatencies": [[0.5, 0.1], [0.95, 0.2], [0.99, 0.3]], - } - return {"perSpecResults": [copy.deepcopy(item)], "aggregated": item} - - -def pod(phase="smoke"): - return { - "metadata": {"labels": { - "azure.workload.identity/use": "true", - "benchmark": "workload-identity-webhook", - "benchmark-run": RUN_ID, "benchmark-phase": phase, - }}, - "spec": { - "serviceAccountName": "pod-benchmark", - "schedulerName": "kperf-admission-only", - "containers": [{ - "env": [ - {"name": "AZURE_CLIENT_ID", "value": CLIENT_ID}, - {"name": "AZURE_TENANT_ID", "value": "tenant"}, - {"name": "AZURE_AUTHORITY_HOST", "value": "https://login.microsoftonline.com/"}, - {"name": "AZURE_FEDERATED_TOKEN_FILE", "value": "/tokens/azure-token"}, - ], - "volumeMounts": [{"name": "azure-token", "mountPath": "/tokens", "readOnly": True}], - }], - "volumes": [{"name": "azure-token", "projected": {"sources": [{ - "serviceAccountToken": {"audience": "api://AzureADTokenExchange", "path": "azure-token"}, - }]}}], - }, - } - - -class ProfileTests(unittest.TestCase): - def setUp(self): - self.template = yaml.safe_load((benchmark.ROOT / "load-profile.yaml").read_text()) - - def test_measurement_profile_exact_values(self): - profile = benchmark.profile_for_phase(self.template, RUN_ID, "measure") - self.assertEqual(profile["version"], 1) - self.assertEqual(len(profile["specs"]), 1) - spec = profile["specs"][0] - self.assertEqual({key: spec[key] for key in ( - "rate", "duration", "total", "client", "conns", "contentType", "maxRetries", - )}, {"rate": 600, "duration": 600, "total": 0, "client": 600, "conns": 20, - "contentType": "json", "maxRetries": 0}) - self.assertEqual(spec["requests"], [{ - "shares": 1, "postDel": { - "group": "", "version": "v1", "resource": "pods", "namespace": RUN_ID, - "deleteRatio": 0, "payloadSize": 3650, - "pod": { - "labels": { - "azure.workload.identity/use": "true", - "benchmark": "workload-identity-webhook", - "benchmark-run": RUN_ID, "benchmark-phase": "measure", - }, - "serviceAccountName": "pod-benchmark", - "schedulerName": "kperf-admission-only", - }, - }, - }]) - - def test_smoke_and_warmup_do_not_modify_measurement(self): - original = copy.deepcopy(self.template) - for phase, rate, total, duration in (("smoke", 1, 3, 0), ("warmup", 5, 0, 30)): - spec = benchmark.profile_for_phase(self.template, RUN_ID, phase)["specs"][0] - self.assertEqual((spec["rate"], spec["total"], spec["duration"]), (rate, total, duration)) - self.assertEqual(self.template, original) - self.assertEqual(benchmark.profile_for_phase(self.template, RUN_ID, "measure")["specs"][0]["rate"], 600) - - def test_invalid_phase_and_unresolved_placeholder(self): - with self.assertRaises(ValueError): - benchmark.profile_for_phase(self.template, RUN_ID, "invalid") - with self.assertRaises(ValueError): - benchmark.render({"name": "__UNKNOWN__"}, {}) - - def test_job_profile_wiring_and_namespace_permissions(self): - documents = list(yaml.safe_load_all((benchmark.ROOT / "workload.yaml").read_text())) - documents = benchmark.render(documents, { - "RUN_NAMESPACE": RUN_ID, "RUNNER_NAMESPACE": RUN_ID + "-runner", - "RUN_ID": RUN_ID, "CLIENT_ID": CLIENT_ID, - "RUNNER_IMAGE": "image@sha256:test", "JOB_NAME": "kperf-measure", - }) - job = next(item for item in documents if item["kind"] == "Job") - self.assertEqual(job["spec"]["activeDeadlineSeconds"], 900) - self.assertEqual(job["spec"]["backoffLimit"], 0) - spec = job["spec"]["template"]["spec"] - self.assertEqual(spec["restartPolicy"], "Never") - self.assertEqual(spec["nodeSelector"], {"kubernetes.azure.com/agentpool": "workerpool"}) - self.assertEqual(spec["serviceAccountName"], "generator") - self.assertEqual(spec["volumes"][0]["configMap"]["name"], "kperf-measure") - container = spec["containers"][0] - self.assertEqual(container["volumeMounts"], [ - {"name": "profile", "mountPath": "/etc/kperf", "readOnly": True}, - ]) - script = container["args"][0] - self.assertIn("--config /etc/kperf/load-profile.yaml", script) - self.assertIn('--kubeconfig=""', script) - self.assertIn('exit "$status"', script) - for option in ("--rate", "--duration", "--total", "--client", "--conns"): - self.assertNotIn(option, script) - self.assertNotIn("azure.workload.identity/use", job["spec"]["template"]["metadata"]["labels"]) - role = next(item for item in documents if item["kind"] == "Role") - self.assertEqual(role["rules"], [{"apiGroups": [""], "resources": ["pods"], "verbs": ["create"]}]) - self.assertFalse(any(item["kind"] == "ResourceQuota" for item in documents)) - - -class ResultTests(unittest.TestCase): - def test_result_extraction_with_diagnostics(self): - data = report() - self.assertEqual(benchmark.extract_result( - "warning\n" + benchmark.BEGIN + "\n" + json.dumps(data) + "\n" + benchmark.END + "\n" - ), data) - - def test_missing_repeated_or_malformed_result(self): - for text in ("", "{}", benchmark.BEGIN + benchmark.END, - benchmark.BEGIN * 2 + "{}" + benchmark.END, - benchmark.END + "{}" + benchmark.BEGIN): - with self.subTest(text=text), self.assertRaises(ValueError): - benchmark.extract_result(text) - - def test_duration_total_zero_is_not_success_count(self): - summary = benchmark.evaluate_result(report(), 600) - self.assertEqual(summary["runner_reported_total"], 0) - self.assertNotIn("successful_requests", summary) - self.assertEqual(summary["sustained_rate_acceptance"], "not-evaluated") - self.assertEqual(summary["configured_rate_per_second"], 600) - - def test_failures_missing_fields_empty_observations_and_short_duration(self): - changes = [ - ("errorStats", {"429": 1}), ("duration", "9m59s"), - ("duration", "invalid"), ("percentileLatencies", []), - ("errorStats", {"429": -1}), ("errorStats", {"429": "1"}), - ("total", "0"), ("totalReceivedBytes", -1), - ("percentileLatencies", "invalid"), ("percentileLatencies", [[0.5, float("nan")]]), - ("percentileLatencies", [[50, 0.1]]), - ] - for key, value in changes: - data = report() - data["aggregated"][key] = value - with self.subTest(key=key, value=value), self.assertRaises(ValueError): - benchmark.evaluate_result(data, 600) - data = report() - del data["aggregated"]["duration"] - with self.assertRaises(ValueError): - benchmark.evaluate_result(data, 600) - with self.assertRaises(ValueError): - benchmark.evaluate_result({"aggregated": {}}, 600) - - def test_all_requests_failed_reports_errors_without_latency_field(self): - data = report() - for item in (data["perSpecResults"][0], data["aggregated"]): - item.pop("percentileLatencies") - item["errorStats"] = {"forbidden": 3} - with self.assertRaisesRegex(ValueError, "request failures"): - benchmark.evaluate_result(data, 600) - - def test_go_duration_units(self): - self.assertEqual(benchmark.parse_duration("10m1.5s"), 601.5) - self.assertAlmostEqual(benchmark.parse_duration("1ms2us3ns"), 0.001002003) - for value in ("", "-1s", "600", None): - with self.subTest(value=value), self.assertRaises(ValueError): - benchmark.parse_duration(value) - - -class MutationTests(unittest.TestCase): - def test_wi_mutation(self): - benchmark.verify_pod(pod(), RUN_ID, "smoke", CLIENT_ID) - - def test_reject_bound_wrong_scheduler_missing_mutation_and_wrong_ownership(self): - cases = [] - item = pod() - item["spec"]["nodeName"] = "node" - cases.append(item) - item = pod() - item["spec"]["schedulerName"] = "default-scheduler" - cases.append(item) - item = pod() - item["spec"]["containers"][0]["env"] = [] - cases.append(item) - item = pod() - item["spec"]["volumes"] = [] - cases.append(item) - item = pod() - item["metadata"]["labels"]["benchmark-run"] = "other" - cases.append(item) - for item in cases: - with self.subTest(pod=item), self.assertRaises(ValueError): - benchmark.verify_pod(item, RUN_ID, "smoke", CLIENT_ID) - - -class OrchestrationTests(unittest.TestCase): - def setUp(self): - self.directory = tempfile.TemporaryDirectory() - self.addCleanup(self.directory.cleanup) - self.args = argparse.Namespace( - run_id=RUN_ID, artifacts=Path(self.directory.name), phase="smoke", - client_id=CLIENT_ID, image="image@sha256:test", - ) - - @patch("benchmark.subprocess.run") - def test_failed_job_preserves_timestamps(self, run): - run.side_effect = [ - subprocess.CompletedProcess([], 0, stdout="created"), - subprocess.CompletedProcess([], 0, stdout=json.dumps({ - "status": {"conditions": [{"type": "Failed", "status": "True", "reason": "DeadlineExceeded"}]}, - })), - ] - with self.assertRaisesRegex(RuntimeError, "DeadlineExceeded"): - benchmark.run_phase(self.args) - timing = json.loads((self.args.artifacts / "smoke-timestamps.json").read_text()) - self.assertIn("orchestration_start", timing) - self.assertIn("orchestration_end", timing) - - @patch("benchmark.time.monotonic", side_effect=[0, 241]) - @patch("benchmark.subprocess.run") - def test_observation_deadline(self, run, _clock): - run.return_value = subprocess.CompletedProcess([], 0, stdout='{"status":{}}') - with self.assertRaises(TimeoutError): - benchmark.run_phase(self.args) - - @patch("benchmark.subprocess.run") - def test_successful_smoke_and_paginated_snapshot(self, run): - data = report() - data["aggregated"]["total"] = 3 - data["perSpecResults"][0]["total"] = 3 - run.side_effect = [ - subprocess.CompletedProcess([], 0, stdout="created"), - subprocess.CompletedProcess([], 0, stdout=json.dumps({ - "status": {"conditions": [{"type": "Complete", "status": "True"}]}, - })), - subprocess.CompletedProcess([], 0, stdout=benchmark.BEGIN + json.dumps(data) + benchmark.END), - subprocess.CompletedProcess([], 0, stdout=json.dumps({ - "items": [pod()], "metadata": {"continue": "page2"}, - })), - subprocess.CompletedProcess([], 0, stdout=json.dumps({ - "items": [pod(), pod()], "metadata": {}, - })), - ] - benchmark.run_phase(self.args) - summary = json.loads((self.args.artifacts / "smoke-summary.json").read_text()) - self.assertEqual(summary["retained_pod_count"], 3) - self.assertIn("continue=page2", run.call_args.args[0][-1]) - - @patch("benchmark.subprocess.run") - def test_collection_surfaces_errors_and_stops_active_owned_jobs(self, run): - def execute(command, **_kwargs): - if "nodes" in command: - raise subprocess.CalledProcessError(1, command, stderr="forbidden") - value = "{}" - if "jobs" in command: - value = json.dumps({"items": [{ - "metadata": {"name": "kperf-measure", "labels": {"benchmark-run": RUN_ID}}, - "status": {"active": 1}, - }]}) - return subprocess.CompletedProcess(command, 0, stdout=value) - run.side_effect = execute - with self.assertRaisesRegex(RuntimeError, "collection incomplete"): - benchmark.collect(self.args) - self.assertTrue(any("patch" in call.args[0] for call in run.call_args_list)) - failures = json.loads((self.args.artifacts / "collection.json").read_text())["failures"] - self.assertEqual(len(failures), 1) - self.assertIn("forbidden", failures[0]) - - -class PreflightTests(unittest.TestCase): - def setUp(self): - self.skus = [ - {"name": "Standard_D2_v4", "family": "Dv4", "restrictions": []}, - {"name": "Standard_D8s_v5", "family": "DSv5", "restrictions": []}, - ] - self.usage = [ - {"name": {"value": family}, "limit": count + 1, "currentValue": 1} - for family, count in (("cores", 30), ("Dv4", 6), ("DSv5", 24)) - ] - - def test_exact_available_quota_passes(self): - preflight.verify(self.skus, self.usage) - - def test_missing_sku_missing_quota_or_insufficient_quota_fails(self): - for skus, usage in ((self.skus[:1], self.usage), (self.skus, self.usage[:1])): - with self.assertRaises(ValueError): - preflight.verify(skus, usage) - self.usage[2]["limit"] -= 1 - with self.assertRaises(ValueError): - preflight.verify(self.skus, self.usage) - - def test_location_restriction_fails(self): - self.skus[1]["restrictions"] = [{"type": "Location"}] - with self.assertRaises(ValueError): - preflight.verify(self.skus, self.usage) - - -class PipelineTests(unittest.TestCase): - @classmethod - def setUpClass(cls): - cls.pipeline = yaml.safe_load((benchmark.ROOT / "pipeline.yaml").read_text()) - cls.jobs = {job["job"]: job for job in cls.pipeline["jobs"]} - - def test_manual_only_and_storage_approval(self): - self.assertEqual(self.pipeline["trigger"], "none") - self.assertEqual(self.pipeline["pr"], "none") - self.assertEqual(self.pipeline["parameters"], [{ - "name": "keep_cluster", - "displayName": "Keep cluster and benchmark Pods after benchmark", - "type": "boolean", "default": False, - }]) - approval = self.jobs["storage_preflight"] - self.assertEqual(approval["pool"], "server") - self.assertEqual(approval["steps"][0]["inputs"]["onTimeout"], "reject") - self.assertEqual(self.jobs["benchmark"]["dependsOn"], ["setup", "storage_preflight"]) - self.assertEqual(self.jobs["benchmark"]["variables"]["KUBECONFIG"], - "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig") - - def test_cleanup_is_always_but_deletion_is_ownership_and_retention_gated(self): - finalize = self.jobs["finalize"] - self.assertEqual(finalize["condition"], "always()") - deletion = next(step for step in finalize["steps"] - if step.get("displayName", "").startswith("Delete resource group")) - for keep in (True, False): - with self.subTest(keep_cluster=keep): - condition = deletion["condition"].replace("${{ parameters.keep_cluster }}", str(keep)) - self.assertEqual(condition, - f"and(always(), eq(variables['OWNED_RESOURCE_GROUP'], 'true'), not({keep}))") - benchmark_steps = self.jobs["benchmark"]["steps"] - for name in ("Collect diagnostics and stop any active runner", - "Publish benchmark results and diagnostics"): - step = next(step for step in benchmark_steps if step.get("displayName") == name) - self.assertEqual(step["condition"], "always()") - - def test_generated_shell_syntax(self): - scripts = [] - for job in self.jobs.values(): - for step in job["steps"]: - script = step.get("bash", step.get("inputs", {}).get("inlineScript")) - if script: - scripts.append(script) - documents = list(yaml.safe_load_all((benchmark.ROOT / "workload.yaml").read_text())) - job = next(item for item in documents if item["kind"] == "Job") - scripts.append(job["spec"]["template"]["spec"]["containers"][0]["args"][0]) - for script in scripts: - with self.subTest(script=script[:80]): - subprocess.run(["bash", "-n"], input=script, text=True, check=True, capture_output=True) - - -if __name__ == "__main__": - unittest.main() diff --git a/kcl/workload_identity_webhook/workload.yaml b/kcl/workload_identity_webhook/workload.yaml deleted file mode 100644 index 88e147f922..0000000000 --- a/kcl/workload_identity_webhook/workload.yaml +++ /dev/null @@ -1,107 +0,0 @@ -apiVersion: v1 -kind: Namespace -metadata: - name: "__RUN_NAMESPACE__" - labels: - benchmark-run: "__RUN_ID__" ---- -apiVersion: v1 -kind: Namespace -metadata: - name: "__RUNNER_NAMESPACE__" - labels: - benchmark-run: "__RUN_ID__" ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: pod-benchmark - namespace: "__RUN_NAMESPACE__" - annotations: - azure.workload.identity/client-id: "__CLIENT_ID__" ---- -apiVersion: v1 -kind: ServiceAccount -metadata: - name: generator - namespace: "__RUNNER_NAMESPACE__" ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: Role -metadata: - name: pod-create - namespace: "__RUN_NAMESPACE__" -rules: - - apiGroups: [""] - resources: ["pods"] - verbs: ["create"] ---- -apiVersion: rbac.authorization.k8s.io/v1 -kind: RoleBinding -metadata: - name: generator - namespace: "__RUN_NAMESPACE__" -roleRef: - apiGroup: rbac.authorization.k8s.io - kind: Role - name: pod-create -subjects: - - kind: ServiceAccount - name: generator - namespace: "__RUNNER_NAMESPACE__" ---- -apiVersion: batch/v1 -kind: Job -metadata: - name: "__JOB_NAME__" - namespace: "__RUNNER_NAMESPACE__" - labels: - benchmark-run: "__RUN_ID__" -spec: - backoffLimit: 0 - # Outer bound includes scheduling/image pull, the 600-second profile, and drain. - activeDeadlineSeconds: 900 - template: - metadata: - labels: - benchmark-run: "__RUN_ID__" - spec: - serviceAccountName: generator - restartPolicy: Never - nodeSelector: - kubernetes.azure.com/agentpool: workerpool - containers: - - name: kperf - image: "__RUNNER_IMAGE__" - imagePullPolicy: IfNotPresent - resources: - # Leave headroom on an 8-vCPU, 32-GiB worker; do not share system nodes. - requests: - cpu: "4" - memory: 4Gi - limits: - cpu: "6" - memory: 8Gi - command: ["/bin/bash", "-c"] - args: - - | - set -uo pipefail - /kperf runner run \ - --kubeconfig="" \ - --config /etc/kperf/load-profile.yaml \ - --result /tmp/result.json - status=$? - if [ -s /tmp/result.json ]; then - printf '\nKPERF_RESULT_BEGIN\n' - cat /tmp/result.json - printf '\nKPERF_RESULT_END\n' - fi - exit "$status" - volumeMounts: - - name: profile - mountPath: /etc/kperf - readOnly: true - volumes: - - name: profile - configMap: - name: "__JOB_NAME__" From df484600453aebfd62c27ec19c8aafa4191f76f6 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Thu, 29 Oct 2026 12:45:09 +1000 Subject: [PATCH 03/24] Restore aks-preview before H2 cluster creation Install pinned aks-preview 20.0.0b6 in the cluster-creation task to support the H2 scaling argument. Regenerate YAML with KCL 0.13. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 4 ++++ kcl/workload_identity_webhook/pipeline.k | 5 +++++ kcl/workload_identity_webhook/pipeline.yaml | 5 +++++ 3 files changed, 14 insertions(+) diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index e40036bac3..6f1ad7b4be 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -37,6 +37,10 @@ image with an upstream release when available. ## Execution and results +The cluster-creation task installs `aks-preview` version `20.0.0b6` immediately +before `az aks create`. The extension provides `--control-plane-scaling-size H2`, +which the agent's base Azure CLI does not support. + The job creates the cluster and worker pool, installs the pinned binaries, fetches credentials into a temporary kubeconfig, creates the identity, namespace and ServiceAccount, and renders run identifiers into a temporary diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 357a1f0c28..9161fcf31e 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -60,6 +60,11 @@ fi "Create H2 cluster with OIDC and workload identity", """ echo "##vso[task.setvariable variable=RESOURCE_GROUP_CREATED]true" +az extension add \\ + --name aks-preview \\ + --version 20.0.0b6 \\ + --allow-preview true \\ + --yes az aks create \\ --subscription "${SUBSCRIPTION_ID}" \\ --resource-group "$(RUN_ID)" \\ diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 8847896b17..5c627b7d3a 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -64,6 +64,11 @@ jobs: inlineScript: | set -exo pipefail echo "##vso[task.setvariable variable=RESOURCE_GROUP_CREATED]true" + az extension add \ + --name aks-preview \ + --version 20.0.0b6 \ + --allow-preview true \ + --yes az aks create \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ --resource-group "$(RUN_ID)" \ From 325191b1e0f6c5cc8f28224751fded43e3644ffe Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Fri, 30 Oct 2026 12:21:10 +1000 Subject: [PATCH 04/24] Simplify kperf runner and reduce WI benchmark traffic Move the thin runner wrapper into run_benchmark.k, print native results, and use a caller-owned ADO timeout. Reduce traffic to 400 creates per second and remove redundant benchmark labels. Regenerate YAML with KCL 0.13. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/lib/steps/kperf/kperf_runner.k | 54 ------------------- kcl/lib/steps/kperf/kperf_runner_test.k | 14 ----- kcl/lib/steps/kperf/run_benchmark.k | 21 ++++++++ kcl/workload_identity_webhook/README.md | 44 ++++++++------- .../load-profile.yaml | 6 +-- kcl/workload_identity_webhook/pipeline.k | 5 +- kcl/workload_identity_webhook/pipeline.yaml | 44 ++------------- 7 files changed, 55 insertions(+), 133 deletions(-) delete mode 100644 kcl/lib/steps/kperf/kperf_runner.k delete mode 100644 kcl/lib/steps/kperf/kperf_runner_test.k diff --git a/kcl/lib/steps/kperf/kperf_runner.k b/kcl/lib/steps/kperf/kperf_runner.k deleted file mode 100644 index 45f1d2f32c..0000000000 --- a/kcl/lib/steps/kperf/kperf_runner.k +++ /dev/null @@ -1,54 +0,0 @@ -import azure_pipelines.ap.steps - -# The caller installs kperf and owns the profile, kubeconfig, and result files. -RunKperfRunner = lambda profilePath: str, kubeconfig: str, resultPath: str, timeoutSeconds: int = 900 -> steps.Script { - assert profilePath != "", "profilePath must not be empty" - assert kubeconfig != "", "kubeconfig must not be empty" - assert resultPath != "", "resultPath must not be empty" - assert resultPath not in [profilePath, kubeconfig], "resultPath must not overwrite an input file" - assert timeoutSeconds > 0, "timeoutSeconds must be positive" - steps.Script { - script = """ -set -euo pipefail -if [ ! -r "${profilePath}" ] || [ ! -r "${kubeconfig}" ]; then - echo "kperf requires a readable load profile and kubeconfig" >&2 - exit 1 -fi -cat "${profilePath}" -rm -f -- "${resultPath}" -echo "Driver start: $(date -u +%Y-%m-%dT%H:%M:%SZ)" -driver_status=0 -timeout --signal=TERM --kill-after=30s ${timeoutSeconds}s \\ - kperf runner run \\ - --kubeconfig "${kubeconfig}" \\ - --config "${profilePath}" \\ - --result "${resultPath}" || driver_status=$? -echo "Driver end: $(date -u +%Y-%m-%dT%H:%M:%SZ); exit status: $driver_status" - -report_status=0 -if [ -s "${resultPath}" ]; then - cat "${resultPath}" - # Native total is configured total (zero for duration mode), not successes. - jq -e ' - (.perSpecResults | type == "array" and length > 0) - and (.aggregated | type == "object") - and ([.perSpecResults[], .aggregated] | all(.[]; - (.total | type == "number" and . >= 0) - and (.duration | type == "string" and length > 0) - and (.percentileLatencies | type == "array" and length > 0) - and (.errorStats // {} | type == "object" and all(.[]; type == "number" and . == 0)) - )) - ' "${resultPath}" || report_status=$? -else - echo "kperf did not produce a nonempty result file" >&2 - report_status=1 -fi -if [ "$report_status" -ne 0 ]; then - echo "kperf result is invalid or contains request failures" >&2 -fi -if [ "$driver_status" -ne 0 ]; then exit "$driver_status"; fi -exit "$report_status" -""" - displayName = "Run kperf runner" - } -} diff --git a/kcl/lib/steps/kperf/kperf_runner_test.k b/kcl/lib/steps/kperf/kperf_runner_test.k deleted file mode 100644 index d2146d2533..0000000000 --- a/kcl/lib/steps/kperf/kperf_runner_test.k +++ /dev/null @@ -1,14 +0,0 @@ -test_runner_paths_and_default_timeout = lambda { - step = RunKperfRunner("/tmp/load profile.yaml", "/tmp/kubeconfig", "/tmp/result.json") - assert step.displayName == "Run kperf runner" - assert '--config "/tmp/load profile.yaml"' in step.script - assert '--kubeconfig "/tmp/kubeconfig"' in step.script - assert '--result "/tmp/result.json"' in step.script - assert "timeout --signal=TERM --kill-after=30s 900s" in step.script -} - -test_runner_custom_timeout = lambda { - step = RunKperfRunner("/tmp/profile.yaml", "/tmp/kubeconfig", "/tmp/result.json", timeoutSeconds=1200) - assert "timeout --signal=TERM --kill-after=30s 1200s" in step.script - assert "900s" not in step.script -} diff --git a/kcl/lib/steps/kperf/run_benchmark.k b/kcl/lib/steps/kperf/run_benchmark.k index d98d854e04..c19fdf63ad 100644 --- a/kcl/lib/steps/kperf/run_benchmark.k +++ b/kcl/lib/steps/kperf/run_benchmark.k @@ -1,5 +1,26 @@ import azure_pipelines.ap.steps +# Runs a custom profile in pipeline; kperf owns output formatting and exit status. +RunKperfRunner = lambda profilePath: str, kubeconfig: str = "", resultPath: str = "" -> steps.Script { + assert profilePath != "", "profilePath must not be empty" + args = [ + '--config "${profilePath}"', + '--kubeconfig "${kubeconfig}"' if kubeconfig else "", + '--result "${resultPath}"' if resultPath else "", + ] + flags = " \\\n ".join([arg for arg in args if arg]) + steps.Script { + script = """ +set -euo pipefail +set -x + +kperf runner run \\ + ${flags} +""" + displayName = "Run kperf runner" + } +} + # RunKperfBenchmark runs runkperf bench with the given subcommand and flow control settings. # Results are written to resultPath (default /tmp/tmp_results.json) for collection by CollectKperfResult. RunKperfBenchmark = lambda benchmarkSubcmd: str, benchmarkSubcmdArgs: str, flowcontrol: str, kubeconfig: str, runnerImage: str, target: str = Undefined, resultPath: str = "/tmp/tmp_results.json" -> steps.Step { diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index 6f1ad7b4be..5d6a4223fd 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -16,10 +16,10 @@ workload identity, and runs kperf **once, directly on the ADO agent**. [load-profile.yaml](./load-profile.yaml) is the traffic configuration: -- 600 Pod CREATEs/sec ceiling, 600-second generation window. +- 400 Pod CREATEs/sec ceiling, 600-second generation window. - `total: 0`, `deleteRatio: 0`, `maxRetries: 0`. - 600 request workers, 20 transports; the rate is shared across workers. -- WI opt-in, run labels, and `schedulerName: kperf-admission-only`. +- WI opt-in and `schedulerName: kperf-admission-only`; the dedicated namespace identifies the run. - `payloadSize: 3650` pads an environment variable, not the complete submitted JSON. The resulting single-container Pod is approximately 4 KiB before server-side mutation/defaulting. @@ -43,42 +43,51 @@ which the agent's base Azure CLI does not support. The job creates the cluster and worker pool, installs the pinned binaries, fetches credentials into a temporary kubeconfig, creates the identity, -namespace and ServiceAccount, and renders run identifiers into a temporary +namespace and ServiceAccount, and renders the run namespace into a temporary profile. It invokes: ```sh -kperf runner run --kubeconfig "$kubeconfig" --config "$profile" --result "$result" +kperf runner run --config "$profile" --kubeconfig "$kubeconfig" ``` Execution uses the shared -[`kperf.RunKperfRunner`](../lib/steps/kperf/kperf_runner.k) step: +[`kperf.RunKperfRunner`](../lib/steps/kperf/run_benchmark.k) step: ```kcl kperf.RunKperfRunner( profilePath="$(KPERF_PROFILE)", - kubeconfig="$(KUBECONFIG)", - resultPath="$(KPERF_RESULT)") + kubeconfig="$(KUBECONFIG)") | {timeoutInMinutes = 15} ``` -The helper accepts an optional `timeoutSeconds` (default 900), supports native -single- and multi-spec reports, and leaves input/result file ownership to the -caller. It does not install kperf or provision workload resources. +Only `profilePath` is required. Optional arguments: + +- `kubeconfig`: omitted by default, letting kperf select its default kubeconfig + (`$HOME/.kube/config` outside Kubernetes, or in-cluster configuration when detected). + This pipeline still supplies its isolated kubeconfig explicitly. +- `resultPath`: omitted by default, so kperf prints its native JSON directly to + stdout. If supplied, kperf writes to that file instead; the caller owns the file. + +The helper only runs the command and propagates its exit code. It does not install +kperf, provision workload resources, parse results, capture output, or delete files. There are no CLI traffic overrides, Kubernetes generator Jobs, smoke/warm-up phases, manual-validation jobs, diagnostic collectors, or artifact uploads. -The profile and native result JSON appear in normal ADO logs. Files live in +The native result JSON appears in normal ADO logs without result validation. +The resolved profile and kubeconfig live in [`Agent.TempDirectory`](https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops#agent-variables-devops-services), which ADO cleans after each job; the shared runner does not delete caller inputs. -A 900-second outer process timeout bounds generation and drain, with forced -termination after a further 30 seconds if needed. Driver failures, missing or -malformed reports, and reported request errors fail the step; no run is retried. +The caller sets a 15-minute ADO step timeout; the helper has no process-timeout +parameter or external timeout command. ADO cancellation governs timeout handling. +Nonzero kperf process exits fail the step; no run is retried. HTTP errors in the +report do not independently fail it: kperf can exit zero despite failed requests, +as observed in build 84716. Missing or malformed reports are not checked. The pinned runner's `total` is the configured request total, **not an observed success count**; it remains zero for this duration-based run. Native duration includes drain. Per-interval dispatch rates, actual WI invocation rates, and inflight backlog are unavailable. This is exploratory traffic generation, -not proof that the webhook sustained 600/sec. Agent-to-API-server networking +not proof that the webhook sustained 400/sec. Agent-to-API-server networking also differs from an in-cluster driver. ## Prerequisites and cleanup @@ -87,7 +96,7 @@ Operators ensure version/SKU availability, quota, and control-plane storage headroom before queueing. Confirm no scheduler handles `kperf-admission-only`; the benchmark Pods should remain unscheduled. -At the target, approximately 360,000 Pods could accumulate: about 1.37 GiB of +At the target, approximately 240,000 Pods could accumulate: about 0.916 GiB of submitted JSON at 4 KiB each, before WI/defaulting, revision history, and other storage overhead. There is no ResourceQuota, continuous storage monitor, or manual storage gate. The timeout is not a storage-capacity guarantee. @@ -108,10 +117,9 @@ cleanup; check Azure before assuming deletion completed. ```sh kcl run kcl/workload_identity_webhook/pipeline.k -S output \ -o kcl/workload_identity_webhook/pipeline.yaml -(cd kcl && kcl test lib/steps/kperf) ``` -The shared runner has KCL tests. The pipeline does not install a Python +The pipeline does not install a Python dependency bundle or use a custom Python orchestrator. [ADO pipeline 94](https://dev.azure.com/akstelescope/telescope/_build?definitionId=94) diff --git a/kcl/workload_identity_webhook/load-profile.yaml b/kcl/workload_identity_webhook/load-profile.yaml index 18da7f6c77..ea5804368b 100644 --- a/kcl/workload_identity_webhook/load-profile.yaml +++ b/kcl/workload_identity_webhook/load-profile.yaml @@ -1,7 +1,7 @@ version: 1 -description: WI Pod CREATE exploratory benchmark - 600 creates/sec for 10 minutes +description: WI Pod CREATE exploratory benchmark - 400 creates/sec for 10 minutes specs: - - rate: 600 + - rate: 400 duration: 600 total: 0 client: 600 @@ -21,7 +21,5 @@ specs: pod: labels: azure.workload.identity/use: "true" - benchmark: workload-identity-webhook - benchmark-run: "__RUN_ID__" serviceAccountName: pod-benchmark schedulerName: kperf-admission-only diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 9161fcf31e..c62d6d9930 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -33,7 +33,6 @@ output = ap.Pipeline { RESOURCE_GROUP_CREATED = "false" KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" KPERF_PROFILE = "$(Agent.TempDirectory)/$(RUN_ID)-load-profile.yaml" - KPERF_RESULT = "$(Agent.TempDirectory)/$(RUN_ID)-result.json" } steps = [ azure.Login( @@ -135,7 +134,6 @@ kubectl annotate serviceaccount pod-benchmark \\ sed \\ -e 's/__RUN_NAMESPACE__/$(RUN_ID)/g' \\ - -e 's/__RUN_ID__/$(RUN_ID)/g' \\ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved load-profile placeholders" >&2 @@ -144,8 +142,7 @@ fi """), kperf.RunKperfRunner( profilePath="$(KPERF_PROFILE)", - kubeconfig="$(KUBECONFIG)", - resultPath="$(KPERF_RESULT)"), + kubeconfig="$(KUBECONFIG)") | {timeoutInMinutes = 15}, azure.DeleteResourceGroup( const.DEFAULT_SERVICE_CONNECTION, "$(RUN_ID)", diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 5c627b7d3a..f5651ba470 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -17,7 +17,6 @@ jobs: RESOURCE_GROUP_CREATED: 'false' KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig KPERF_PROFILE: $(Agent.TempDirectory)/$(RUN_ID)-load-profile.yaml - KPERF_RESULT: $(Agent.TempDirectory)/$(RUN_ID)-result.json steps: - task: AzureCLI@2 inputs: @@ -200,7 +199,6 @@ jobs: sed \ -e 's/__RUN_NAMESPACE__/$(RUN_ID)/g' \ - -e 's/__RUN_ID__/$(RUN_ID)/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved load-profile placeholders" >&2 @@ -209,45 +207,13 @@ jobs: displayName: Prepare WI resources and load profile - script: | set -euo pipefail - if [ ! -r "$(KPERF_PROFILE)" ] || [ ! -r "$(KUBECONFIG)" ]; then - echo "kperf requires a readable load profile and kubeconfig" >&2 - exit 1 - fi - cat "$(KPERF_PROFILE)" - rm -f -- "$(KPERF_RESULT)" - echo "Driver start: $(date -u +%Y-%m-%dT%H:%M:%SZ)" - driver_status=0 - timeout --signal=TERM --kill-after=30s 900s \ - kperf runner run \ - --kubeconfig "$(KUBECONFIG)" \ - --config "$(KPERF_PROFILE)" \ - --result "$(KPERF_RESULT)" || driver_status=$? - echo "Driver end: $(date -u +%Y-%m-%dT%H:%M:%SZ); exit status: $driver_status" + set -x - report_status=0 - if [ -s "$(KPERF_RESULT)" ]; then - cat "$(KPERF_RESULT)" - # Native total is configured total (zero for duration mode), not successes. - jq -e ' - (.perSpecResults | type == "array" and length > 0) - and (.aggregated | type == "object") - and ([.perSpecResults[], .aggregated] | all(.[]; - (.total | type == "number" and . >= 0) - and (.duration | type == "string" and length > 0) - and (.percentileLatencies | type == "array" and length > 0) - and (.errorStats // {} | type == "object" and all(.[]; type == "number" and . == 0)) - )) - ' "$(KPERF_RESULT)" || report_status=$? - else - echo "kperf did not produce a nonempty result file" >&2 - report_status=1 - fi - if [ "$report_status" -ne 0 ]; then - echo "kperf result is invalid or contains request failures" >&2 - fi - if [ "$driver_status" -ne 0 ]; then exit "$driver_status"; fi - exit "$report_status" + kperf runner run \ + --config "$(KPERF_PROFILE)" \ + --kubeconfig "$(KUBECONFIG)" displayName: Run kperf runner + timeoutInMinutes: 15 - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal From 02eb514f6f94c901ca6ce305755a19ed2f9166f0 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Fri, 30 Oct 2026 15:55:50 +1000 Subject: [PATCH 05/24] Simplify WI identity setup and enlarge system nodes Use a fake client ID for admission-only benchmark Pods, remove the redundant managed-identity flag, and configure three Standard_D4_v4 system nodes. Update documentation and regenerate YAML with KCL 0.13. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 18 ++++++++++-------- kcl/workload_identity_webhook/pipeline.k | 17 +++-------------- kcl/workload_identity_webhook/pipeline.yaml | 17 +++-------------- 3 files changed, 16 insertions(+), 36 deletions(-) diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index 5d6a4223fd..882bb5988a 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -6,13 +6,15 @@ workload identity, and runs kperf **once, directly on the ADO agent**. ## Configuration - Subscription: `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`; region: `westus2`. -- System pool: three `Standard_D2_v4` nodes. +- System pool: three `Standard_D4_v4` nodes. - Worker pool: three `Standard_D2s_v5` nodes, retained as requested but not used to host the traffic driver. - OIDC and workload identity enabled; webhook resources/replicas are not tuned. -- User-assigned managed identity and an annotated benchmark ServiceAccount. - No federated credential or Azure role assignment is needed for admission-only - testing; the workload does not perform token exchange. +- A benchmark ServiceAccount annotated with dummy client ID + `00000000-0000-4000-8000-000000000001`. This preserves `AZURE_CLIENT_ID` + injection without provisioning a workload managed identity. No federated + credential or Azure role assignment is needed: this admission-only workload + does not perform token exchange. Use a real identity for token-exchange tests. [load-profile.yaml](./load-profile.yaml) is the traffic configuration: @@ -42,8 +44,8 @@ before `az aks create`. The extension provides `--control-plane-scaling-size H2` which the agent's base Azure CLI does not support. The job creates the cluster and worker pool, installs the pinned binaries, -fetches credentials into a temporary kubeconfig, creates the identity, -namespace and ServiceAccount, and renders the run namespace into a temporary +fetches credentials into a temporary kubeconfig, creates the namespace and +annotated ServiceAccount, and renders the run namespace into a temporary profile. It invokes: ```sh @@ -102,11 +104,11 @@ storage overhead. There is no ResourceQuota, continuous storage monitor, or manual storage gate. The timeout is not a storage-capacity guarantee. `keep_cluster` defaults to **false**. The last step deletes the run's resource -group, including the cluster and identity, even after a benchmark failure where +group, including the cluster, even after a benchmark failure where ADO permits cleanup. Deletion is gated on successful resource-group creation in this job; an existing-group collision never authorizes deletion. -With **true**, retain the cluster, identity, and benchmark Pods for inspection. +With **true**, retain the cluster and benchmark Pods for inspection. Retained resources incur charges. Use the run's resource-group name from the ADO logs for manual deletion when finished. There are no separate finalization reports or deletion-verification steps. A hard agent interruption can prevent diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index c62d6d9930..a09670b89a 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -73,13 +73,12 @@ az aks create \\ --dns-name-prefix "$(RUN_ID)" \\ --tier standard \\ --control-plane-scaling-size H2 \\ - --enable-managed-identity \\ --enable-oidc-issuer \\ --enable-workload-identity \\ --generate-ssh-keys \\ --nodepool-name systempool \\ --node-count 3 \\ - --node-vm-size Standard_D2_v4 \\ + --node-vm-size Standard_D4_v4 \\ --max-pods 50 \\ --network-plugin azure \\ --network-plugin-mode overlay \\ @@ -115,22 +114,12 @@ az aks create \\ """ set -u profile="$(KPERF_PROFILE)" -client_id=$(az identity create \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --resource-group "$(RUN_ID)" \\ - --location "${LOCATION}" \\ - --name wi-benchmark \\ - --query clientId \\ - --output tsv) -if ! [[ "$client_id" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then - echo "Managed identity returned an invalid client ID" >&2 - exit 1 -fi kubectl create namespace "$(RUN_ID)" kubectl create serviceaccount pod-benchmark --namespace "$(RUN_ID)" +# Use a fake client ID because benchmark Pods do not access Azure resources. kubectl annotate serviceaccount pod-benchmark \\ --namespace "$(RUN_ID)" \\ - "azure.workload.identity/client-id=$client_id" + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" sed \\ -e 's/__RUN_NAMESPACE__/$(RUN_ID)/g' \\ diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index f5651ba470..d87193c888 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -77,13 +77,12 @@ jobs: --dns-name-prefix "$(RUN_ID)" \ --tier standard \ --control-plane-scaling-size H2 \ - --enable-managed-identity \ --enable-oidc-issuer \ --enable-workload-identity \ --generate-ssh-keys \ --nodepool-name systempool \ --node-count 3 \ - --node-vm-size Standard_D2_v4 \ + --node-vm-size Standard_D4_v4 \ --max-pods 50 \ --network-plugin azure \ --network-plugin-mode overlay \ @@ -180,22 +179,12 @@ jobs: set -exo pipefail set -u profile="$(KPERF_PROFILE)" - client_id=$(az identity create \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --resource-group "$(RUN_ID)" \ - --location "westus2" \ - --name wi-benchmark \ - --query clientId \ - --output tsv) - if ! [[ "$client_id" =~ ^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$ ]]; then - echo "Managed identity returned an invalid client ID" >&2 - exit 1 - fi kubectl create namespace "$(RUN_ID)" kubectl create serviceaccount pod-benchmark --namespace "$(RUN_ID)" + # Use a fake client ID because benchmark Pods do not access Azure resources. kubectl annotate serviceaccount pod-benchmark \ --namespace "$(RUN_ID)" \ - "azure.workload.identity/client-id=$client_id" + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" sed \ -e 's/__RUN_NAMESPACE__/$(RUN_ID)/g' \ From 353a6ef5d96436d75be776feb4e373dfbabdbec6 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Fri, 30 Oct 2026 23:19:32 +1000 Subject: [PATCH 06/24] Support existing WI benchmark clusters and enable Prometheus Add paired existing-cluster parameters, idempotent WI preparation, and safe retention of reused resource groups. Enable managed Prometheus during cluster creation, update the pinned kperf image to sha-38567a6, and regenerate YAML with KCL 0.13. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 64 +++++-- kcl/workload_identity_webhook/pipeline.k | 140 ++++++++++++---- kcl/workload_identity_webhook/pipeline.yaml | 175 +++++++++++--------- 3 files changed, 251 insertions(+), 128 deletions(-) diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index 882bb5988a..bc3a9cfeef 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -1,15 +1,50 @@ # Workload Identity webhook benchmark -One manual ADO job provisions a dedicated AKS Standard H2 cluster, prepares -workload identity, and runs kperf **once, directly on the ADO agent**. +One manual ADO job provisions a dedicated AKS Standard H2 cluster or reuses an +existing cluster, and runs kperf **once, directly on the ADO agent**. -## Configuration +## Cluster selection + +| Parameter | Default | Behavior | +|---|---|---| +| `existing_resource_group` | `none` | Existing resource group, also used as the benchmark namespace | +| `existing_cluster` | `none` | Existing AKS cluster name; must be supplied with the resource group | +| `keep_cluster` | `false` | Retain a newly created cluster; existing clusters are always retained | + +Leave both existing-cluster parameters as `none` (or empty) to create a new cluster. +Supplying only one fails before provisioning or traffic. + +For example, reuse the retained benchmark cluster with +`existing_resource_group=wi-84842-1` and `existing_cluster=wi-webhook`. +The cluster must be in subscription `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`. +Its resource-group name must also be a valid Kubernetes namespace name: +a lowercase DNS label of at most 63 characters. + +Reuse skips resource-group/cluster/node-pool creation, aks-preview installation, +and monitoring enablement. Operators must provide an existing WI-enabled cluster. +In both modes, WI preparation idempotently applies the benchmark namespace and +ServiceAccount `pod-benchmark`, then sets `azure.workload.identity/client-id` to +the dummy UUID with `--overwrite`. Any previous client-ID annotation on this +benchmark ServiceAccount is replaced. Use a namespace dedicated to this benchmark. +Other reused cluster settings, including monitoring, remain unchanged. + +Both modes fetch credentials, prepare WI resources, render the load profile, install kperf on the agent, +and run traffic. Temporary filenames still use the current run ID. In reuse mode, +the profile uses the existing resource-group name as its namespace. Repeated runs +retain prior Pods, increasing storage use and potentially affecting comparisons. + +## New-cluster configuration - Subscription: `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`; region: `westus2`. - System pool: three `Standard_D4_v4` nodes. - Worker pool: three `Standard_D2s_v5` nodes, retained as requested but not used to host the traffic driver. - OIDC and workload identity enabled; webhook resources/replicas are not tuned. +- Managed Prometheus enabled during cluster creation, using the existing + `wi-benchmark-prometheus` Azure Monitor workspace in `wi-benchmark-monitoring` + in the same subscription. Metrics survive deletion of the benchmark resource + group. The pipeline identity needs permission to onboard the cluster to this + workspace. This enables metrics, not container stdout/stderr logging. - A benchmark ServiceAccount annotated with dummy client ID `00000000-0000-4000-8000-000000000001`. This preserves `AZURE_CLIENT_ID` injection without provisioning a workload managed identity. No federated @@ -29,24 +64,25 @@ workload identity, and runs kperf **once, directly on the ADO agent**. The existing installer extracts kperf from this pinned custom image: ```text -ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 +ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 ``` -This is tag `sha-8e8e961`, source commit -`8e8e9617073fa7f0a9a51789923afa96d4d90121` from +This is tag `sha-38567a6`, source commit +`38567a6b70337e7efa3d287988ab36cfe47f9d04` from [Azure/kperf#260](https://github.com/Azure/kperf/pull/260). Replace the custom image with an upstream release when available. ## Execution and results -The cluster-creation task installs `aks-preview` version `20.0.0b6` immediately +For new clusters, the cluster-creation task installs `aks-preview` version `20.0.0b6` immediately before `az aks create`. The extension provides `--control-plane-scaling-size H2`, which the agent's base Azure CLI does not support. -The job creates the cluster and worker pool, installs the pinned binaries, -fetches credentials into a temporary kubeconfig, creates the namespace and -annotated ServiceAccount, and renders the run namespace into a temporary -profile. It invokes: +The new-cluster path creates the cluster and worker pool. Both paths fetch +credentials into a temporary kubeconfig, prepare the namespace and annotated +ServiceAccount idempotently, render the selected namespace into a temporary +profile, and install the pinned binaries. +The driver invokes: ```sh kperf runner run --config "$profile" --kubeconfig "$kubeconfig" @@ -103,10 +139,12 @@ submitted JSON at 4 KiB each, before WI/defaulting, revision history, and other storage overhead. There is no ResourceQuota, continuous storage monitor, or manual storage gate. The timeout is not a storage-capacity guarantee. -`keep_cluster` defaults to **false**. The last step deletes the run's resource +`keep_cluster` defaults to **false**. For new clusters, the last step deletes the run's resource group, including the cluster, even after a benchmark failure where ADO permits cleanup. Deletion is gated on successful resource-group creation -in this job; an existing-group collision never authorizes deletion. +in this job and explicitly resolved new-cluster mode; an existing-group collision +never authorizes deletion. Reused resource groups are **never deleted**, even when +`keep_cluster` is false or the benchmark fails. With **true**, retain the cluster and benchmark Pods for inspection. Retained resources incur charges. Use the run's resource-group name from the diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index a09670b89a..f58b5ca07b 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -1,5 +1,6 @@ import azure_pipelines.ap import azure_pipelines.ap.jobs.job +import azure_pipelines.ap.steps import lib.const import lib.steps.azure import lib.steps.kperf @@ -7,7 +8,8 @@ import lib.steps.kperf SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" LOCATION = "westus2" # TODO: Replace the user-selected PR image with a published upstream release. -RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4" +RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" +CREATE_NEW_CLUSTER = "and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false'))" output = ap.Pipeline { name = "Workload Identity Webhook Benchmark" @@ -15,6 +17,18 @@ output = ap.Pipeline { pr = "none" pool = const.DEFAULT_POOL parameters = [ + ap.Parameter { + name = "existing_resource_group" + displayName = "Existing resource group (none creates a cluster)" + type = "string" + default = "none" + }, + ap.Parameter { + name = "existing_cluster" + displayName = "Existing cluster name (provide together with resource group)" + type = "string" + default = "none" + }, ap.Parameter { name = "keep_cluster" displayName = "Keep cluster and benchmark Pods after benchmark" @@ -25,16 +39,59 @@ output = ap.Pipeline { jobs = [ job.Job { job = "benchmark" - displayName = "Create H2 cluster and run WI webhook traffic" + displayName = "Run WI webhook traffic on a new or existing cluster" timeoutInMinutes = 240 cancelTimeoutInMinutes = 10 variables = { RUN_ID = "wi-$(Build.BuildId)-$(System.JobAttempt)" RESOURCE_GROUP_CREATED = "false" + USE_EXISTING_CLUSTER = "unresolved" KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" KPERF_PROFILE = "$(Agent.TempDirectory)/$(RUN_ID)-load-profile.yaml" } steps = [ + steps.Bash { + bash = """ +set -euo pipefail +resource_group="$PARAM_EXISTING_RESOURCE_GROUP" +cluster="$PARAM_EXISTING_CLUSTER" +if [ "$resource_group" = "none" ]; then resource_group=""; fi +if [ "$cluster" = "none" ]; then cluster=""; fi +if { [ -z "$resource_group" ] && [ -n "$cluster" ]; } || + { [ -n "$resource_group" ] && [ -z "$cluster" ]; }; then + echo "existing_resource_group and existing_cluster must be provided together." >&2 + exit 1 +fi +if [ -n "$cluster" ]; then + use_existing=true +else + use_existing=false + resource_group="$RUN_ID" + cluster=wi-webhook +fi +# Reused resource groups also name the existing Kubernetes namespace. +if ! [[ "$resource_group" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]] || + [ "\${#resource_group}" -gt 63 ]; then + echo "The resource group must also be a valid Kubernetes namespace (lowercase DNS label, at most 63 characters)." >&2 + exit 1 +fi +if ! [[ "$cluster" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]] || + [ "\${#cluster}" -gt 63 ]; then + echo "Invalid existing cluster name." >&2 + exit 1 +fi +echo "Benchmark target: cluster=$cluster resource_group=$resource_group namespace=$resource_group existing=$use_existing" +echo "##vso[task.setvariable variable=RESOURCE_GROUP]$resource_group" +echo "##vso[task.setvariable variable=CLUSTER]$cluster" +echo "##vso[task.setvariable variable=BENCHMARK_NAMESPACE]$resource_group" +echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]$use_existing" +""" + displayName = "Resolve benchmark cluster" + env = { + PARAM_EXISTING_RESOURCE_GROUP = "\${{ parameters.existing_resource_group }}" + PARAM_EXISTING_CLUSTER = "\${{ parameters.existing_cluster }}" + } + }, azure.Login( const.DEFAULT_SERVICE_CONNECTION, SUBSCRIPTION_ID, @@ -43,17 +100,19 @@ output = ap.Pipeline { const.DEFAULT_SERVICE_CONNECTION, "Verify resource group does not already exist", """ -exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$(RUN_ID)") +exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$(RESOURCE_GROUP)") if [ "$exists" != "false" ]; then - echo "Refusing to reuse an existing or unverified resource group: $(RUN_ID)" >&2 + echo "Refusing to reuse an existing or unverified resource group: $(RESOURCE_GROUP)" >&2 exit 1 fi -"""), +""", + condition=CREATE_NEW_CLUSTER), azure.CreateResourceGroup( const.DEFAULT_SERVICE_CONNECTION, - "$(RUN_ID)", + "$(RESOURCE_GROUP)", LOCATION, - SUBSCRIPTION_ID), + SUBSCRIPTION_ID, + condition=CREATE_NEW_CLUSTER), azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, "Create H2 cluster with OIDC and workload identity", @@ -66,8 +125,8 @@ az extension add \\ --yes az aks create \\ --subscription "${SUBSCRIPTION_ID}" \\ - --resource-group "$(RUN_ID)" \\ - --name wi-webhook \\ + --resource-group "$(RESOURCE_GROUP)" \\ + --name "$(CLUSTER)" \\ --location "${LOCATION}" \\ --kubernetes-version "1.36" \\ --dns-name-prefix "$(RUN_ID)" \\ @@ -75,6 +134,8 @@ az aks create \\ --control-plane-scaling-size H2 \\ --enable-oidc-issuer \\ --enable-workload-identity \\ + --enable-azure-monitor-metrics \\ + --azure-monitor-workspace-resource-id "/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/wi-benchmark-monitoring/providers/Microsoft.Monitor/accounts/wi-benchmark-prometheus" \\ --generate-ssh-keys \\ --nodepool-name systempool \\ --node-count 3 \\ @@ -89,54 +150,63 @@ az aks create \\ --nat-gateway-managed-outbound-ip-count 10 \\ --tags SkipAKSCluster=true \\ --yes -"""), - azure.CreateNodePool( - const.DEFAULT_SERVICE_CONNECTION, - "wi-webhook", - "$(RUN_ID)", - SUBSCRIPTION_ID, - azure.NodePool { - name = "workerpool" - sku = "Standard_D2s_v5" - count = 3 - maxPods = 50 - }), - kperf.InstallRunkperf(RUNNER_IMAGE), +""", + condition=CREATE_NEW_CLUSTER), + steps.Task { + **azure.CreateNodePool( + const.DEFAULT_SERVICE_CONNECTION, + "$(CLUSTER)", + "$(RESOURCE_GROUP)", + SUBSCRIPTION_ID, + azure.NodePool { + name = "workerpool" + sku = "Standard_D2s_v5" + count = 3 + }) + condition = CREATE_NEW_CLUSTER + }, azure.GetCredentials( const.DEFAULT_SERVICE_CONNECTION, - "wi-webhook", - "$(RUN_ID)", + "$(CLUSTER)", + "$(RESOURCE_GROUP)", SUBSCRIPTION_ID, file="$(KUBECONFIG)"), azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, - "Prepare WI resources and load profile", + "Prepare WI resources", """ set -u -profile="$(KPERF_PROFILE)" -kubectl create namespace "$(RUN_ID)" -kubectl create serviceaccount pod-benchmark --namespace "$(RUN_ID)" +kubectl create namespace "$(BENCHMARK_NAMESPACE)" --dry-run=client -o yaml | kubectl apply -f - +kubectl create serviceaccount pod-benchmark --namespace "$(BENCHMARK_NAMESPACE)" --dry-run=client -o yaml | kubectl apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. kubectl annotate serviceaccount pod-benchmark \\ - --namespace "$(RUN_ID)" \\ - "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" - + --namespace "$(BENCHMARK_NAMESPACE)" \\ + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \\ + --overwrite +"""), + steps.Bash { + bash = """ +set -euo pipefail +profile="$(KPERF_PROFILE)" sed \\ - -e 's/__RUN_NAMESPACE__/$(RUN_ID)/g' \\ + -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \\ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved load-profile placeholders" >&2 exit 1 fi -"""), +""" + displayName = "Prepare load profile" + }, + kperf.InstallRunkperf(RUNNER_IMAGE), kperf.RunKperfRunner( profilePath="$(KPERF_PROFILE)", kubeconfig="$(KUBECONFIG)") | {timeoutInMinutes = 15}, azure.DeleteResourceGroup( const.DEFAULT_SERVICE_CONNECTION, - "$(RUN_ID)", + "$(RESOURCE_GROUP)", SUBSCRIPTION_ID, - condition="and(always(), eq(variables['RESOURCE_GROUP_CREATED'], 'true'), not(\${{ parameters.keep_cluster }}))"), + condition="and(always(), eq(variables['USE_EXISTING_CLUSTER'], 'false'), eq(variables['RESOURCE_GROUP_CREATED'], 'true'), not(\${{ parameters.keep_cluster }}))"), ] }, ] diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index d87193c888..fb8910b81f 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -2,6 +2,14 @@ name: Workload Identity Webhook Benchmark pool: AKS-Telescope-Airlock trigger: none parameters: +- name: existing_resource_group + displayName: Existing resource group (none creates a cluster) + type: string + default: none +- name: existing_cluster + displayName: Existing cluster name (provide together with resource group) + type: string + default: none - name: keep_cluster displayName: Keep cluster and benchmark Pods after benchmark type: boolean @@ -9,15 +17,54 @@ parameters: pr: none jobs: - job: benchmark - displayName: Create H2 cluster and run WI webhook traffic + displayName: Run WI webhook traffic on a new or existing cluster timeoutInMinutes: 240 cancelTimeoutInMinutes: 10 variables: RUN_ID: wi-$(Build.BuildId)-$(System.JobAttempt) RESOURCE_GROUP_CREATED: 'false' + USE_EXISTING_CLUSTER: unresolved KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig KPERF_PROFILE: $(Agent.TempDirectory)/$(RUN_ID)-load-profile.yaml steps: + - bash: | + set -euo pipefail + resource_group="$PARAM_EXISTING_RESOURCE_GROUP" + cluster="$PARAM_EXISTING_CLUSTER" + if [ "$resource_group" = "none" ]; then resource_group=""; fi + if [ "$cluster" = "none" ]; then cluster=""; fi + if { [ -z "$resource_group" ] && [ -n "$cluster" ]; } || + { [ -n "$resource_group" ] && [ -z "$cluster" ]; }; then + echo "existing_resource_group and existing_cluster must be provided together." >&2 + exit 1 + fi + if [ -n "$cluster" ]; then + use_existing=true + else + use_existing=false + resource_group="$RUN_ID" + cluster=wi-webhook + fi + # Reused resource groups also name the existing Kubernetes namespace. + if ! [[ "$resource_group" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]] || + [ "${#resource_group}" -gt 63 ]; then + echo "The resource group must also be a valid Kubernetes namespace (lowercase DNS label, at most 63 characters)." >&2 + exit 1 + fi + if ! [[ "$cluster" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]] || + [ "${#cluster}" -gt 63 ]; then + echo "Invalid existing cluster name." >&2 + exit 1 + fi + echo "Benchmark target: cluster=$cluster resource_group=$resource_group namespace=$resource_group existing=$use_existing" + echo "##vso[task.setvariable variable=RESOURCE_GROUP]$resource_group" + echo "##vso[task.setvariable variable=CLUSTER]$cluster" + echo "##vso[task.setvariable variable=BENCHMARK_NAMESPACE]$resource_group" + echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]$use_existing" + displayName: Resolve benchmark cluster + env: + PARAM_EXISTING_RESOURCE_GROUP: ${{ parameters.existing_resource_group }} + PARAM_EXISTING_CLUSTER: ${{ parameters.existing_cluster }} - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -36,11 +83,12 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$(RUN_ID)") + exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$(RESOURCE_GROUP)") if [ "$exists" != "false" ]; then - echo "Refusing to reuse an existing or unverified resource group: $(RUN_ID)" >&2 + echo "Refusing to reuse an existing or unverified resource group: $(RESOURCE_GROUP)" >&2 exit 1 fi + condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) displayName: Verify resource group does not already exist - task: AzureCLI@2 inputs: @@ -50,10 +98,11 @@ jobs: inlineScript: |+ set -exo pipefail az group create \ - --name "$(RUN_ID)" \ + --name "$(RESOURCE_GROUP)" \ --location "westus2" \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) displayName: Create resource group in westus2 (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) - task: AzureCLI@2 inputs: @@ -70,8 +119,8 @@ jobs: --yes az aks create \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --resource-group "$(RUN_ID)" \ - --name wi-webhook \ + --resource-group "$(RESOURCE_GROUP)" \ + --name "$(CLUSTER)" \ --location "westus2" \ --kubernetes-version "1.36" \ --dns-name-prefix "$(RUN_ID)" \ @@ -79,6 +128,8 @@ jobs: --control-plane-scaling-size H2 \ --enable-oidc-issuer \ --enable-workload-identity \ + --enable-azure-monitor-metrics \ + --azure-monitor-workspace-resource-id "/subscriptions/b8ceb4e5-f05b-4562-a9f5-14acb1f24219/resourceGroups/wi-benchmark-monitoring/providers/Microsoft.Monitor/accounts/wi-benchmark-prometheus" \ --generate-ssh-keys \ --nodepool-name systempool \ --node-count 3 \ @@ -93,69 +144,16 @@ jobs: --nat-gateway-managed-outbound-ip-count 10 \ --tags SkipAKSCluster=true \ --yes + condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) displayName: Create H2 cluster with OIDC and workload identity - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal scriptType: bash scriptLocation: inlineScript - inlineScript: | - set -exo pipefail - create_node_pool() { - local deadline sleep_between=30 attempt=0 output rc now remaining_retry_seconds - deadline=$(($(date +%s) + 600)) - while :; do - attempt=$((attempt + 1)) - if output=$(az aks nodepool add "$@" 2>&1); then - rc=0 - else - rc=$? - fi - echo "$output" - if [ "$rc" -eq 0 ]; then - return 0 - fi - if echo "$output" | grep -qiE "OperationNotAllowed"; then - now=$(date +%s) - if [ "$now" -ge "$deadline" ]; then - echo "Retriable error persisted past 600s retry window ($attempt attempts); giving up." - return "$rc" - fi - remaining_retry_seconds=$((deadline - now)) - echo "Attempt $attempt matched retriable pattern; retrying in $sleep_between seconds ($remaining_retry_seconds seconds remain in retry window)." - sleep "$sleep_between" - else - echo "Non-retriable error (rc=$rc); giving up after attempt $attempt." - return "$rc" - fi - done - } - - - create_node_pool \ - --cluster-name "wi-webhook" \ - --resource-group "$(RUN_ID)" \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --name "workerpool" \ - --node-count 3 \ - --node-vm-size "Standard_D2s_v5" \ - --mode User \ - --max-pods 50 + inlineScript: "set -exo pipefail\ncreate_node_pool() {\n local deadline sleep_between=30 attempt=0 output rc now remaining_retry_seconds\n deadline=$(($(date +%s) + 600))\n while :; do\n attempt=$((attempt + 1))\n if output=$(az aks nodepool add \"$@\" 2>&1); then\n rc=0\n else\n rc=$?\n fi\n echo \"$output\"\n if [ \"$rc\" -eq 0 ]; then\n return 0\n fi\n if echo \"$output\" | grep -qiE \"OperationNotAllowed\"; then\n now=$(date +%s)\n if [ \"$now\" -ge \"$deadline\" ]; then\n echo \"Retriable error persisted past 600s retry window ($attempt attempts); giving up.\"\n return \"$rc\"\n fi\n remaining_retry_seconds=$((deadline - now))\n echo \"Attempt $attempt matched retriable pattern; retrying in $sleep_between seconds ($remaining_retry_seconds seconds remain in retry window).\"\n sleep \"$sleep_between\"\n else\n echo \"Non-retriable error (rc=$rc); giving up after attempt $attempt.\"\n return \"$rc\"\n fi\n done\n}\n\n\ncreate_node_pool \\\n --cluster-name \"$(CLUSTER)\" \\\n --resource-group \"$(RESOURCE_GROUP)\" \\\n --subscription \"b8ceb4e5-f05b-4562-a9f5-14acb1f24219\" \\\n --name \"workerpool\" \\\n --node-count 3 \\\n --node-vm-size \"Standard_D2s_v5\" \\\n --mode User \\\n \n" + condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) displayName: Create node pool workerpool - - script: | - set -euo pipefail - set -x - - temp_dir=$(mktemp -p /tmp -d kperfinstall.XXXX) - docker rmi ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 2>/dev/null || true - docker pull ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 - docker run --rm -v $temp_dir:/install-dir \ - ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 bash -c "set -x; install /kperf /runkperf /install-dir" - - sudo install $temp_dir/kperf $temp_dir/runkperf /usr/local/bin - rm -rf $temp_dir - docker rmi ghcr.io/liyu-ma/kperf@sha256:67e4924b23d2aea35526479721dd83f9afe707685a6efafd60916423017479d4 2>/dev/null || true - displayName: Install runkperf binary - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -164,12 +162,12 @@ jobs: inlineScript: | set -exo pipefail az aks get-credentials \ - --name "wi-webhook" \ - --resource-group "$(RUN_ID)" \ + --name "$(CLUSTER)" \ + --resource-group "$(RESOURCE_GROUP)" \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ --overwrite-existing \ -f $(KUBECONFIG) - displayName: Get credentials for wi-webhook + displayName: Get credentials for $(CLUSTER) - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -178,22 +176,39 @@ jobs: inlineScript: | set -exo pipefail set -u - profile="$(KPERF_PROFILE)" - kubectl create namespace "$(RUN_ID)" - kubectl create serviceaccount pod-benchmark --namespace "$(RUN_ID)" + kubectl create namespace "$(BENCHMARK_NAMESPACE)" --dry-run=client -o yaml | kubectl apply -f - + kubectl create serviceaccount pod-benchmark --namespace "$(BENCHMARK_NAMESPACE)" --dry-run=client -o yaml | kubectl apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. kubectl annotate serviceaccount pod-benchmark \ - --namespace "$(RUN_ID)" \ - "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" + --namespace "$(BENCHMARK_NAMESPACE)" \ + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ + --overwrite + displayName: Prepare WI resources + - bash: | + set -euo pipefail + profile="$(KPERF_PROFILE)" + sed \ + -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \ + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + if grep -q '__[A-Z_]*__' "$profile"; then + echo "Unresolved load-profile placeholders" >&2 + exit 1 + fi + displayName: Prepare load profile + - script: | + set -euo pipefail + set -x - sed \ - -e 's/__RUN_NAMESPACE__/$(RUN_ID)/g' \ - "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" - if grep -q '__[A-Z_]*__' "$profile"; then - echo "Unresolved load-profile placeholders" >&2 - exit 1 - fi - displayName: Prepare WI resources and load profile + temp_dir=$(mktemp -p /tmp -d kperfinstall.XXXX) + docker rmi ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 2>/dev/null || true + docker pull ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 + docker run --rm -v $temp_dir:/install-dir \ + ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 bash -c "set -x; install /kperf /runkperf /install-dir" + + sudo install $temp_dir/kperf $temp_dir/runkperf /usr/local/bin + rm -rf $temp_dir + docker rmi ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 2>/dev/null || true + displayName: Install runkperf binary - script: | set -euo pipefail set -x @@ -210,6 +225,6 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - az group delete --name "$(RUN_ID)" --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --yes - condition: and(always(), eq(variables['RESOURCE_GROUP_CREATED'], 'true'), not(${{ parameters.keep_cluster }})) + az group delete --name "$(RESOURCE_GROUP)" --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --yes + condition: and(always(), eq(variables['USE_EXISTING_CLUSTER'], 'false'), eq(variables['RESOURCE_GROUP_CREATED'], 'true'), not(${{ parameters.keep_cluster }})) displayName: Delete resource group (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) From 76e00891f63ce4501a394cfd0671d1934a6637b9 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Mon, 2 Nov 2026 23:43:48 +1000 Subject: [PATCH 07/24] Run WI benchmark at three sequential traffic rates Run 50, 100, and 200 Pod CREATEs per second for ten minutes each. Clean up phase-owned Pods and pause five minutes after every run, preserving failure propagation and existing-cluster retention. Update documentation and regenerate YAML with KCL 0.13. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 71 ++++++--- .../load-profile.yaml | 5 +- kcl/workload_identity_webhook/pipeline.k | 61 ++++++-- kcl/workload_identity_webhook/pipeline.yaml | 146 ++++++++++++++++-- 4 files changed, 232 insertions(+), 51 deletions(-) diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index bc3a9cfeef..1d3c7a42b0 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -1,7 +1,9 @@ # Workload Identity webhook benchmark One manual ADO job provisions a dedicated AKS Standard H2 cluster or reuses an -existing cluster, and runs kperf **once, directly on the ADO agent**. +existing cluster, and runs kperf **three times sequentially on the ADO agent**: +50, 100, then 200 Pod CREATEs/sec, each for 10 minutes. After each run, delete +its Pods and pause for five minutes, including after the final run. ## Cluster selection @@ -28,10 +30,10 @@ the dummy UUID with `--overwrite`. Any previous client-ID annotation on this benchmark ServiceAccount is replaced. Use a namespace dedicated to this benchmark. Other reused cluster settings, including monitoring, remain unchanged. -Both modes fetch credentials, prepare WI resources, render the load profile, install kperf on the agent, -and run traffic. Temporary filenames still use the current run ID. In reuse mode, -the profile uses the existing resource-group name as its namespace. Repeated runs -retain prior Pods, increasing storage use and potentially affecting comparisons. +Both modes fetch credentials, prepare WI resources, and install kperf once. Each +phase renders a distinct profile using the run ID and rate in its temporary +filename. In reuse mode, the profile uses the existing resource-group name as its +namespace. Phase cleanup leaves any pre-existing Pods untouched. ## New-cluster configuration @@ -51,15 +53,19 @@ retain prior Pods, increasing storage use and potentially affecting comparisons. credential or Azure role assignment is needed: this admission-only workload does not perform token exchange. Use a real identity for token-exchange tests. -[load-profile.yaml](./load-profile.yaml) is the traffic configuration: +[load-profile.yaml](./load-profile.yaml) is a template rendered before each phase: -- 400 Pod CREATEs/sec ceiling, 600-second generation window. +- `__RATE__` becomes 50, 100, or 200 Pod CREATEs/sec; 600-second generation window each. - `total: 0`, `deleteRatio: 0`, `maxRetries: 0`. - 600 request workers, 20 transports; the rate is shared across workers. -- WI opt-in and `schedulerName: kperf-admission-only`; the dedicated namespace identifies the run. +- WI opt-in and `schedulerName: kperf-admission-only`. +- `__RUN_NAMESPACE__` selects the benchmark namespace; `__PHASE_RUN_ID__` + becomes `$(RUN_ID)-r` in the `benchmark-run` label. Cleanup uses that + exact namespace and label, never all Pods in a reused namespace. - `payloadSize: 3650` pads an environment variable, not the complete submitted JSON. The resulting single-container Pod is approximately 4 KiB before - server-side mutation/defaulting. + server-side mutation/defaulting. The phase ownership label adds a small amount + of metadata compared with the earlier unlabelled profile. The existing installer extracts kperf from this pinned custom image: @@ -80,9 +86,16 @@ which the agent's base Azure CLI does not support. The new-cluster path creates the cluster and worker pool. Both paths fetch credentials into a temporary kubeconfig, prepare the namespace and annotated -ServiceAccount idempotently, render the selected namespace into a temporary -profile, and install the pinned binaries. -The driver invokes: +ServiceAccount idempotently and install the pinned binaries. The rate loop +generates explicit ADO preparation, runner, cleanup, and pause steps: + +```text +50/sec for 10m -> delete phase Pods -> pause 5m +100/sec for 10m -> delete phase Pods -> pause 5m +200/sec for 10m -> delete phase Pods -> pause 5m +``` + +Each driver step invokes: ```sh kperf runner run --config "$profile" --kubeconfig "$kubeconfig" @@ -93,7 +106,7 @@ Execution uses the shared ```kcl kperf.RunKperfRunner( - profilePath="$(KPERF_PROFILE)", + profilePath="$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml", kubeconfig="$(KUBECONFIG)") | {timeoutInMinutes = 15} ``` @@ -115,9 +128,12 @@ The resolved profile and kubeconfig live in [`Agent.TempDirectory`](https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops#agent-variables-devops-services), which ADO cleans after each job; the shared runner does not delete caller inputs. -The caller sets a 15-minute ADO step timeout; the helper has no process-timeout +The caller sets a 15-minute ADO step timeout per run; the helper has no process-timeout parameter or external timeout command. ADO cancellation governs timeout handling. -Nonzero kperf process exits fail the step; no run is retried. HTTP errors in the +Nonzero kperf process exits fail the step; no run is retried. The started phase's +cleanup and five-minute pause are attempted even after driver failure, but later +rates are skipped. Cleanup failure also blocks later rates, without skipping +the pause. HTTP errors in the report do not independently fail it: kperf can exit zero despite failed requests, as observed in build 84716. Missing or malformed reports are not checked. @@ -125,7 +141,7 @@ The pinned runner's `total` is the configured request total, **not an observed success count**; it remains zero for this duration-based run. Native duration includes drain. Per-interval dispatch rates, actual WI invocation rates, and inflight backlog are unavailable. This is exploratory traffic generation, -not proof that the webhook sustained 400/sec. Agent-to-API-server networking +not proof that the webhook sustained the configured rate. Agent-to-API-server networking also differs from an in-cluster driver. ## Prerequisites and cleanup @@ -134,10 +150,21 @@ Operators ensure version/SKU availability, quota, and control-plane storage headroom before queueing. Confirm no scheduler handles `kperf-admission-only`; the benchmark Pods should remain unscheduled. -At the target, approximately 240,000 Pods could accumulate: about 0.916 GiB of -submitted JSON at 4 KiB each, before WI/defaulting, revision history, and other -storage overhead. There is no ResourceQuota, continuous storage monitor, or -manual storage gate. The timeout is not a storage-capacity guarantee. +Successful traffic at each target would create approximately 30,000, 60,000, +and 120,000 Pods respectively before that phase's cleanup. The largest phase +is about 0.458 GiB of submitted JSON at 4 KiB each, before WI/defaulting, +revision history, and other storage overhead. There is no ResourceQuota, +continuous storage monitor, or manual storage gate. + +Cleanup uses normal Pod deletion with an exact ownership selector, waits for +completion with a 10-minute deletion budget, and has a 15-minute ADO step limit. +Each 300-second pause has a six-minute step limit. The job allows 25 minutes +of cancellation grace for active cleanup and recovery where ADO permits. +Skipped phases do not perform cleanup or pause. + +Deleting Pods and waiting five minutes is not a full storage/cache reset: +etcd revisions, caches, controller state, and pre-existing objects remain. +Recovery and equivalent fresh-cluster baselines are not guaranteed. `keep_cluster` defaults to **false**. For new clusters, the last step deletes the run's resource group, including the cluster, even after a benchmark failure where @@ -146,7 +173,9 @@ in this job and explicitly resolved new-cluster mode; an existing-group collisio never authorizes deletion. Reused resource groups are **never deleted**, even when `keep_cluster` is false or the benchmark fails. -With **true**, retain the cluster and benchmark Pods for inspection. +With **true**, retain the cluster, benchmark namespace, and ServiceAccount. +This execution's phase Pods are still deleted after each run, regardless of +`keep_cluster`. Failed or interrupted cleanup may leave some Pods behind. Retained resources incur charges. Use the run's resource-group name from the ADO logs for manual deletion when finished. There are no separate finalization reports or deletion-verification steps. A hard agent interruption can prevent diff --git a/kcl/workload_identity_webhook/load-profile.yaml b/kcl/workload_identity_webhook/load-profile.yaml index ea5804368b..4dde6cc861 100644 --- a/kcl/workload_identity_webhook/load-profile.yaml +++ b/kcl/workload_identity_webhook/load-profile.yaml @@ -1,7 +1,7 @@ version: 1 -description: WI Pod CREATE exploratory benchmark - 400 creates/sec for 10 minutes +description: WI Pod CREATE exploratory benchmark - __RATE__ creates/sec for 10 minutes specs: - - rate: 400 + - rate: __RATE__ duration: 600 total: 0 client: 600 @@ -21,5 +21,6 @@ specs: pod: labels: azure.workload.identity/use: "true" + benchmark-run: "__PHASE_RUN_ID__" serviceAccountName: pod-benchmark schedulerName: kperf-admission-only diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index f58b5ca07b..e4bd474703 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -10,6 +10,7 @@ LOCATION = "westus2" # TODO: Replace the user-selected PR image with a published upstream release. RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" CREATE_NEW_CLUSTER = "and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false'))" +RATES = [50, 100, 200] output = ap.Pipeline { name = "Workload Identity Webhook Benchmark" @@ -31,7 +32,7 @@ output = ap.Pipeline { }, ap.Parameter { name = "keep_cluster" - displayName = "Keep cluster and benchmark Pods after benchmark" + displayName = "Keep cluster after benchmark (phase Pods are deleted)" type = "boolean" default = False }, @@ -41,13 +42,14 @@ output = ap.Pipeline { job = "benchmark" displayName = "Run WI webhook traffic on a new or existing cluster" timeoutInMinutes = 240 - cancelTimeoutInMinutes = 10 + # Allow an active phase's bounded cleanup and five-minute recovery pause. + cancelTimeoutInMinutes = 25 variables = { RUN_ID = "wi-$(Build.BuildId)-$(System.JobAttempt)" RESOURCE_GROUP_CREATED = "false" USE_EXISTING_CLUSTER = "unresolved" KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" - KPERF_PROFILE = "$(Agent.TempDirectory)/$(RUN_ID)-load-profile.yaml" + **{"PHASE_${rate}_STARTED" = "false" for rate in RATES} } steps = [ steps.Bash { @@ -184,24 +186,59 @@ kubectl annotate serviceaccount pod-benchmark \\ "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \\ --overwrite """), - steps.Bash { - bash = """ + kperf.InstallRunkperf(RUNNER_IMAGE), + *[step for rate in RATES for step in [ + steps.Bash { + bash = """ set -euo pipefail -profile="$(KPERF_PROFILE)" +profile="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" sed \\ -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \\ + -e 's/__RATE__/${rate}/g' \\ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r${rate}/g' \\ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved load-profile placeholders" >&2 exit 1 fi +echo "Starting ${rate} CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r${rate}" +echo "##vso[task.setvariable variable=PHASE_${rate}_STARTED]true" """ - displayName = "Prepare load profile" - }, - kperf.InstallRunkperf(RUNNER_IMAGE), - kperf.RunKperfRunner( - profilePath="$(KPERF_PROFILE)", - kubeconfig="$(KUBECONFIG)") | {timeoutInMinutes = 15}, + displayName = "Prepare ${rate}/sec load profile" + }, + kperf.RunKperfRunner( + profilePath="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml", + kubeconfig="$(KUBECONFIG)") | { + displayName = "Run kperf at ${rate} CREATEs/sec" + timeoutInMinutes = 15 + }, + steps.Bash { + bash = """ +set -euo pipefail +echo "Cleaning ${rate}/sec phase Pods at $(date -u +%Y-%m-%dT%H:%M:%SZ)" +kubectl --request-timeout=60s delete pods \\ + --namespace "$(BENCHMARK_NAMESPACE)" \\ + --selector "benchmark-run=$(RUN_ID)-r${rate}" \\ + --wait=true \\ + --timeout=10m +echo "Finished ${rate}/sec phase cleanup at $(date -u +%Y-%m-%dT%H:%M:%SZ)" +""" + displayName = "Delete ${rate}/sec phase Pods" + condition = "and(always(), eq(variables['PHASE_${rate}_STARTED'], 'true'))" + timeoutInMinutes = 15 + }, + steps.Bash { + bash = """ +set -euo pipefail +echo "Starting five-minute pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" +sleep 300 +echo "Finished pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" +""" + displayName = "Pause 5 minutes after ${rate}/sec" + condition = "and(always(), eq(variables['PHASE_${rate}_STARTED'], 'true'))" + timeoutInMinutes = 6 + }, + ]], azure.DeleteResourceGroup( const.DEFAULT_SERVICE_CONNECTION, "$(RESOURCE_GROUP)", diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index fb8910b81f..2480ca3bdc 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -11,7 +11,7 @@ parameters: type: string default: none - name: keep_cluster - displayName: Keep cluster and benchmark Pods after benchmark + displayName: Keep cluster after benchmark (phase Pods are deleted) type: boolean default: false pr: none @@ -19,13 +19,15 @@ jobs: - job: benchmark displayName: Run WI webhook traffic on a new or existing cluster timeoutInMinutes: 240 - cancelTimeoutInMinutes: 10 + cancelTimeoutInMinutes: 25 variables: RUN_ID: wi-$(Build.BuildId)-$(System.JobAttempt) RESOURCE_GROUP_CREATED: 'false' USE_EXISTING_CLUSTER: unresolved KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig - KPERF_PROFILE: $(Agent.TempDirectory)/$(RUN_ID)-load-profile.yaml + PHASE_50_STARTED: 'false' + PHASE_100_STARTED: 'false' + PHASE_200_STARTED: 'false' steps: - bash: | set -euo pipefail @@ -184,17 +186,6 @@ jobs: "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ --overwrite displayName: Prepare WI resources - - bash: | - set -euo pipefail - profile="$(KPERF_PROFILE)" - sed \ - -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \ - "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" - if grep -q '__[A-Z_]*__' "$profile"; then - echo "Unresolved load-profile placeholders" >&2 - exit 1 - fi - displayName: Prepare load profile - script: | set -euo pipefail set -x @@ -209,15 +200,138 @@ jobs: rm -rf $temp_dir docker rmi ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 2>/dev/null || true displayName: Install runkperf binary + - bash: | + set -euo pipefail + profile="$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml" + sed \ + -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \ + -e 's/__RATE__/50/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r50/g' \ + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + if grep -q '__[A-Z_]*__' "$profile"; then + echo "Unresolved load-profile placeholders" >&2 + exit 1 + fi + echo "Starting 50 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r50" + echo "##vso[task.setvariable variable=PHASE_50_STARTED]true" + displayName: Prepare 50/sec load profile - script: | set -euo pipefail set -x kperf runner run \ - --config "$(KPERF_PROFILE)" \ + --config "$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml" \ --kubeconfig "$(KUBECONFIG)" - displayName: Run kperf runner + displayName: Run kperf at 50 CREATEs/sec + timeoutInMinutes: 15 + - bash: | + set -euo pipefail + echo "Cleaning 50/sec phase Pods at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + kubectl --request-timeout=60s delete pods \ + --namespace "$(BENCHMARK_NAMESPACE)" \ + --selector "benchmark-run=$(RUN_ID)-r50" \ + --wait=true \ + --timeout=10m + echo "Finished 50/sec phase cleanup at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_50_STARTED'], 'true')) + displayName: Delete 50/sec phase Pods timeoutInMinutes: 15 + - bash: | + set -euo pipefail + echo "Starting five-minute pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + sleep 300 + echo "Finished pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_50_STARTED'], 'true')) + displayName: Pause 5 minutes after 50/sec + timeoutInMinutes: 6 + - bash: | + set -euo pipefail + profile="$(Agent.TempDirectory)/$(RUN_ID)-r100-load-profile.yaml" + sed \ + -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \ + -e 's/__RATE__/100/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r100/g' \ + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + if grep -q '__[A-Z_]*__' "$profile"; then + echo "Unresolved load-profile placeholders" >&2 + exit 1 + fi + echo "Starting 100 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r100" + echo "##vso[task.setvariable variable=PHASE_100_STARTED]true" + displayName: Prepare 100/sec load profile + - script: | + set -euo pipefail + set -x + + kperf runner run \ + --config "$(Agent.TempDirectory)/$(RUN_ID)-r100-load-profile.yaml" \ + --kubeconfig "$(KUBECONFIG)" + displayName: Run kperf at 100 CREATEs/sec + timeoutInMinutes: 15 + - bash: | + set -euo pipefail + echo "Cleaning 100/sec phase Pods at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + kubectl --request-timeout=60s delete pods \ + --namespace "$(BENCHMARK_NAMESPACE)" \ + --selector "benchmark-run=$(RUN_ID)-r100" \ + --wait=true \ + --timeout=10m + echo "Finished 100/sec phase cleanup at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_100_STARTED'], 'true')) + displayName: Delete 100/sec phase Pods + timeoutInMinutes: 15 + - bash: | + set -euo pipefail + echo "Starting five-minute pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + sleep 300 + echo "Finished pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_100_STARTED'], 'true')) + displayName: Pause 5 minutes after 100/sec + timeoutInMinutes: 6 + - bash: | + set -euo pipefail + profile="$(Agent.TempDirectory)/$(RUN_ID)-r200-load-profile.yaml" + sed \ + -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \ + -e 's/__RATE__/200/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r200/g' \ + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + if grep -q '__[A-Z_]*__' "$profile"; then + echo "Unresolved load-profile placeholders" >&2 + exit 1 + fi + echo "Starting 200 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r200" + echo "##vso[task.setvariable variable=PHASE_200_STARTED]true" + displayName: Prepare 200/sec load profile + - script: | + set -euo pipefail + set -x + + kperf runner run \ + --config "$(Agent.TempDirectory)/$(RUN_ID)-r200-load-profile.yaml" \ + --kubeconfig "$(KUBECONFIG)" + displayName: Run kperf at 200 CREATEs/sec + timeoutInMinutes: 15 + - bash: | + set -euo pipefail + echo "Cleaning 200/sec phase Pods at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + kubectl --request-timeout=60s delete pods \ + --namespace "$(BENCHMARK_NAMESPACE)" \ + --selector "benchmark-run=$(RUN_ID)-r200" \ + --wait=true \ + --timeout=10m + echo "Finished 200/sec phase cleanup at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_200_STARTED'], 'true')) + displayName: Delete 200/sec phase Pods + timeoutInMinutes: 15 + - bash: | + set -euo pipefail + echo "Starting five-minute pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + sleep 300 + echo "Finished pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_200_STARTED'], 'true')) + displayName: Pause 5 minutes after 200/sec + timeoutInMinutes: 6 - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal From 46b9c16a8eb39caa5596269390a341035d7d6345 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Tue, 3 Nov 2026 00:34:08 +1000 Subject: [PATCH 08/24] Create Prometheus workspace with benchmark cluster resources Provision the monitoring workspace in the cluster resource group before AKS creation. Skip provisioning for reused clusters and apply the existing keep_cluster cleanup lifecycle to the workspace. Update documentation and regenerate YAML with KCL 0.13. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 25 ++++++++++++--------- kcl/workload_identity_webhook/pipeline.k | 15 +++++++++++-- kcl/workload_identity_webhook/pipeline.yaml | 16 ++++++++++++- 3 files changed, 43 insertions(+), 13 deletions(-) diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index 1d3c7a42b0..071c124fb7 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -11,7 +11,7 @@ its Pods and pause for five minutes, including after the final run. |---|---|---| | `existing_resource_group` | `none` | Existing resource group, also used as the benchmark namespace | | `existing_cluster` | `none` | Existing AKS cluster name; must be supplied with the resource group | -| `keep_cluster` | `false` | Retain a newly created cluster; existing clusters are always retained | +| `keep_cluster` | `false` | Retain a newly created cluster and its Prometheus workspace; existing resource groups are always retained | Leave both existing-cluster parameters as `none` (or empty) to create a new cluster. Supplying only one fails before provisioning or traffic. @@ -22,8 +22,8 @@ The cluster must be in subscription `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`. Its resource-group name must also be a valid Kubernetes namespace name: a lowercase DNS label of at most 63 characters. -Reuse skips resource-group/cluster/node-pool creation, aks-preview installation, -and monitoring enablement. Operators must provide an existing WI-enabled cluster. +Reuse skips resource-group/cluster/node-pool and Prometheus workspace creation, +aks-preview installation, and monitoring enablement. Operators must provide an existing WI-enabled cluster. In both modes, WI preparation idempotently applies the benchmark namespace and ServiceAccount `pod-benchmark`, then sets `azure.workload.identity/client-id` to the dummy UUID with `--overwrite`. Any previous client-ID annotation on this @@ -42,11 +42,12 @@ namespace. Phase cleanup leaves any pre-existing Pods untouched. - Worker pool: three `Standard_D2s_v5` nodes, retained as requested but not used to host the traffic driver. - OIDC and workload identity enabled; webhook resources/replicas are not tuned. -- Managed Prometheus enabled during cluster creation, using the existing - `wi-benchmark-prometheus` Azure Monitor workspace in `wi-benchmark-monitoring` - in the same subscription. Metrics survive deletion of the benchmark resource - group. The pipeline identity needs permission to onboard the cluster to this - workspace. This enables metrics, not container stdout/stderr logging. +- The pipeline creates `wi-benchmark-prometheus`, an Azure Monitor workspace, + in the cluster's resource group before enabling managed Prometheus during + cluster creation. No separate `wi-benchmark-monitoring` group is required. + The pipeline identity needs permission to create the workspace and onboard + the cluster. This enables metrics, not container stdout/stderr logging; + no Log Analytics workspace is provisioned. - A benchmark ServiceAccount annotated with dummy client ID `00000000-0000-4000-8000-000000000001`. This preserves `AZURE_CLIENT_ID` injection without provisioning a workload managed identity. No federated @@ -167,13 +168,17 @@ etcd revisions, caches, controller state, and pre-existing objects remain. Recovery and equivalent fresh-cluster baselines are not guaranteed. `keep_cluster` defaults to **false**. For new clusters, the last step deletes the run's resource -group, including the cluster, even after a benchmark failure where +group, including the cluster and its Prometheus workspace, even after a benchmark failure where ADO permits cleanup. Deletion is gated on successful resource-group creation in this job and explicitly resolved new-cluster mode; an existing-group collision never authorizes deletion. Reused resource groups are **never deleted**, even when `keep_cluster` is false or the benchmark fails. -With **true**, retain the cluster, benchmark namespace, and ServiceAccount. +With **true**, retain the cluster, Prometheus workspace, benchmark namespace, +and ServiceAccount. With **false**, deleting the group also deletes the workspace +and its stored metrics; export required results beforehand if historical +analysis is needed after cleanup. Existing-cluster reuse never deletes or +reconfigures its monitoring workspace. This execution's phase Pods are still deleted after each run, regardless of `keep_cluster`. Failed or interrupted cleanup may leave some Pods behind. Retained resources incur charges. Use the run's resource-group name from the diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index e4bd474703..408a4f912e 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -117,9 +117,20 @@ fi condition=CREATE_NEW_CLUSTER), azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, - "Create H2 cluster with OIDC and workload identity", + "Create benchmark Prometheus workspace", """ echo "##vso[task.setvariable variable=RESOURCE_GROUP_CREATED]true" +az monitor account create \\ + --subscription "${SUBSCRIPTION_ID}" \\ + --resource-group "$(RESOURCE_GROUP)" \\ + --name wi-benchmark-prometheus \\ + --location "${LOCATION}" +""", + condition=CREATE_NEW_CLUSTER), + azure.AzCli( + const.DEFAULT_SERVICE_CONNECTION, + "Create H2 cluster with OIDC and workload identity", + """ az extension add \\ --name aks-preview \\ --version 20.0.0b6 \\ @@ -137,7 +148,7 @@ az aks create \\ --enable-oidc-issuer \\ --enable-workload-identity \\ --enable-azure-monitor-metrics \\ - --azure-monitor-workspace-resource-id "/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/wi-benchmark-monitoring/providers/Microsoft.Monitor/accounts/wi-benchmark-prometheus" \\ + --azure-monitor-workspace-resource-id "/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/$(RESOURCE_GROUP)/providers/Microsoft.Monitor/accounts/wi-benchmark-prometheus" \\ --generate-ssh-keys \\ --nodepool-name systempool \\ --node-count 3 \\ diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 2480ca3bdc..2aa905b2e7 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -114,6 +114,20 @@ jobs: inlineScript: | set -exo pipefail echo "##vso[task.setvariable variable=RESOURCE_GROUP_CREATED]true" + az monitor account create \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --resource-group "$(RESOURCE_GROUP)" \ + --name wi-benchmark-prometheus \ + --location "westus2" + condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) + displayName: Create benchmark Prometheus workspace + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail az extension add \ --name aks-preview \ --version 20.0.0b6 \ @@ -131,7 +145,7 @@ jobs: --enable-oidc-issuer \ --enable-workload-identity \ --enable-azure-monitor-metrics \ - --azure-monitor-workspace-resource-id "/subscriptions/b8ceb4e5-f05b-4562-a9f5-14acb1f24219/resourceGroups/wi-benchmark-monitoring/providers/Microsoft.Monitor/accounts/wi-benchmark-prometheus" \ + --azure-monitor-workspace-resource-id "/subscriptions/b8ceb4e5-f05b-4562-a9f5-14acb1f24219/resourceGroups/$(RESOURCE_GROUP)/providers/Microsoft.Monitor/accounts/wi-benchmark-prometheus" \ --generate-ssh-keys \ --nodepool-name systempool \ --node-count 3 \ From 24bb3a2e05c4a12d6342df32df00a56d81c2ff1c Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Tue, 3 Nov 2026 10:12:13 +1000 Subject: [PATCH 09/24] Use per-rate namespaces for WI benchmark cleanup Prepare namespaces and ServiceAccounts idempotently for each rate on new and reused clusters. Request namespace deletion without waiting, preserve five-minute pauses and failure guards, and regenerate YAML with KCL 0.13. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 70 +++++----- kcl/workload_identity_webhook/pipeline.k | 65 ++++----- kcl/workload_identity_webhook/pipeline.yaml | 145 +++++++++++--------- 3 files changed, 155 insertions(+), 125 deletions(-) diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index 071c124fb7..55b634b817 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -2,14 +2,15 @@ One manual ADO job provisions a dedicated AKS Standard H2 cluster or reuses an existing cluster, and runs kperf **three times sequentially on the ADO agent**: -50, 100, then 200 Pod CREATEs/sec, each for 10 minutes. After each run, delete -its Pods and pause for five minutes, including after the final run. +50, 100, then 200 Pod CREATEs/sec, each for 10 minutes. After each run, request +deletion of its namespace without waiting, then pause for five minutes, +including after the final run. ## Cluster selection | Parameter | Default | Behavior | |---|---|---| -| `existing_resource_group` | `none` | Existing resource group, also used as the benchmark namespace | +| `existing_resource_group` | `none` | Existing Azure resource group containing the cluster | | `existing_cluster` | `none` | Existing AKS cluster name; must be supplied with the resource group | | `keep_cluster` | `false` | Retain a newly created cluster and its Prometheus workspace; existing resource groups are always retained | @@ -19,21 +20,22 @@ Supplying only one fails before provisioning or traffic. For example, reuse the retained benchmark cluster with `existing_resource_group=wi-84842-1` and `existing_cluster=wi-webhook`. The cluster must be in subscription `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`. -Its resource-group name must also be a valid Kubernetes namespace name: -a lowercase DNS label of at most 63 characters. +Azure resource-group names are independent of the benchmark namespaces. Reuse skips resource-group/cluster/node-pool and Prometheus workspace creation, aks-preview installation, and monitoring enablement. Operators must provide an existing WI-enabled cluster. -In both modes, WI preparation idempotently applies the benchmark namespace and +In both modes, each rate's WI preparation idempotently applies its namespace and ServiceAccount `pod-benchmark`, then sets `azure.workload.identity/client-id` to the dummy UUID with `--overwrite`. Any previous client-ID annotation on this -benchmark ServiceAccount is replaced. Use a namespace dedicated to this benchmark. +benchmark ServiceAccount is replaced. Each namespace is dedicated to that phase. Other reused cluster settings, including monitoring, remain unchanged. -Both modes fetch credentials, prepare WI resources, and install kperf once. Each -phase renders a distinct profile using the run ID and rate in its temporary -filename. In reuse mode, the profile uses the existing resource-group name as its -namespace. Phase cleanup leaves any pre-existing Pods untouched. +Both modes fetch credentials and install kperf once. The per-rate steps prepare +WI resources and render a profile using `$(RUN_ID)-r` as both the namespace +and the phase identifier, for example `wi-85212-1-r50`. New builds and job attempts +get distinct names. Repeated preparation works for an existing Active phase +namespace; a Terminating namespace fails explicitly without waiting or removing +finalizers. Namespace cleanup leaves namespaces from previous runs untouched. ## New-cluster configuration @@ -60,9 +62,10 @@ namespace. Phase cleanup leaves any pre-existing Pods untouched. - `total: 0`, `deleteRatio: 0`, `maxRetries: 0`. - 600 request workers, 20 transports; the rate is shared across workers. - WI opt-in and `schedulerName: kperf-admission-only`. -- `__RUN_NAMESPACE__` selects the benchmark namespace; `__PHASE_RUN_ID__` +- `__RUN_NAMESPACE__` selects the run/attempt/rate namespace; `__PHASE_RUN_ID__` becomes `$(RUN_ID)-r` in the `benchmark-run` label. Cleanup uses that - exact namespace and label, never all Pods in a reused namespace. + exact namespace for deletion, including its Pods and ServiceAccount; the label + remains useful for identifying the phase's Pods. - `payloadSize: 3650` pads an environment variable, not the complete submitted JSON. The resulting single-container Pod is approximately 4 KiB before server-side mutation/defaulting. The phase ownership label adds a small amount @@ -86,14 +89,14 @@ before `az aks create`. The extension provides `--control-plane-scaling-size H2` which the agent's base Azure CLI does not support. The new-cluster path creates the cluster and worker pool. Both paths fetch -credentials into a temporary kubeconfig, prepare the namespace and annotated -ServiceAccount idempotently and install the pinned binaries. The rate loop -generates explicit ADO preparation, runner, cleanup, and pause steps: +credentials into a temporary kubeconfig and install the pinned binaries. The +rate loop prepares each namespace and annotated ServiceAccount idempotently, +then generates explicit profile, runner, namespace-deletion, and pause steps: ```text -50/sec for 10m -> delete phase Pods -> pause 5m -100/sec for 10m -> delete phase Pods -> pause 5m -200/sec for 10m -> delete phase Pods -> pause 5m +prepare r50 namespace/ServiceAccount -> 50/sec for 10m -> request namespace deletion -> pause 5m +prepare r100 namespace/ServiceAccount -> 100/sec for 10m -> request namespace deletion -> pause 5m +prepare r200 namespace/ServiceAccount -> 200/sec for 10m -> request namespace deletion -> pause 5m ``` Each driver step invokes: @@ -131,10 +134,12 @@ which ADO cleans after each job; the shared runner does not delete caller inputs The caller sets a 15-minute ADO step timeout per run; the helper has no process-timeout parameter or external timeout command. ADO cancellation governs timeout handling. -Nonzero kperf process exits fail the step; no run is retried. The started phase's -cleanup and five-minute pause are attempted even after driver failure, but later -rates are skipped. Cleanup failure also blocks later rates, without skipping -the pause. HTTP errors in the +Nonzero kperf process exits fail the step; no run is retried. Once a phase namespace +is successfully applied, deletion and the five-minute pause are attempted even +if ServiceAccount setup, profile preparation, or the driver fails; later rates +are skipped. A failed deletion command also blocks later rates, without skipping +the pause. Successfully requesting deletion does not require the namespace to +finish terminating before proceeding. HTTP errors in the report do not independently fail it: kperf can exit zero despite failed requests, as observed in build 84716. Missing or malformed reports are not checked. @@ -157,13 +162,16 @@ is about 0.458 GiB of submitted JSON at 4 KiB each, before WI/defaulting, revision history, and other storage overhead. There is no ResourceQuota, continuous storage monitor, or manual storage gate. -Cleanup uses normal Pod deletion with an exact ownership selector, waits for -completion with a 10-minute deletion budget, and has a 15-minute ADO step limit. +Cleanup issues one namespace deletion request with `--wait=false` and +`--ignore-not-found=true`. It uses a 60-second API request timeout and a +15-minute ADO step limit, but never polls for namespace deletion completion. Each 300-second pause has a six-minute step limit. The job allows 25 minutes of cancellation grace for active cleanup and recovery where ADO permits. -Skipped phases do not perform cleanup or pause. +Skipped phases do not perform cleanup or pause. A failed namespace apply does +not enable cleanup; inspect for partially created resources after such failures. -Deleting Pods and waiting five minutes is not a full storage/cache reset: +Namespace deletion may still be running after the pause and overlap the next +rate's traffic. Requesting deletion and pausing is not a full storage/cache reset: etcd revisions, caches, controller state, and pre-existing objects remain. Recovery and equivalent fresh-cluster baselines are not guaranteed. @@ -174,13 +182,13 @@ in this job and explicitly resolved new-cluster mode; an existing-group collisio never authorizes deletion. Reused resource groups are **never deleted**, even when `keep_cluster` is false or the benchmark fails. -With **true**, retain the cluster, Prometheus workspace, benchmark namespace, -and ServiceAccount. With **false**, deleting the group also deletes the workspace +With **true**, retain the cluster and Prometheus workspace, but still request +deletion of every prepared phase namespace and its ServiceAccount. With **false**, +deleting the group also deletes the workspace and its stored metrics; export required results beforehand if historical analysis is needed after cleanup. Existing-cluster reuse never deletes or reconfigures its monitoring workspace. -This execution's phase Pods are still deleted after each run, regardless of -`keep_cluster`. Failed or interrupted cleanup may leave some Pods behind. +Failed, interrupted, or still-pending namespace cleanup may leave some Pods behind. Retained resources incur charges. Use the run's resource-group name from the ADO logs for manual deletion when finished. There are no separate finalization reports or deletion-verification steps. A hard agent interruption can prevent diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 408a4f912e..d3b5436c0f 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -32,7 +32,7 @@ output = ap.Pipeline { }, ap.Parameter { name = "keep_cluster" - displayName = "Keep cluster after benchmark (phase Pods are deleted)" + displayName = "Keep cluster after benchmark (phase namespaces are deleted)" type = "boolean" default = False }, @@ -49,7 +49,7 @@ output = ap.Pipeline { RESOURCE_GROUP_CREATED = "false" USE_EXISTING_CLUSTER = "unresolved" KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" - **{"PHASE_${rate}_STARTED" = "false" for rate in RATES} + **{"PHASE_${rate}_NAMESPACE_PREPARED" = "false" for rate in RATES} } steps = [ steps.Bash { @@ -71,10 +71,9 @@ else resource_group="$RUN_ID" cluster=wi-webhook fi -# Reused resource groups also name the existing Kubernetes namespace. -if ! [[ "$resource_group" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]] || - [ "\${#resource_group}" -gt 63 ]; then - echo "The resource group must also be a valid Kubernetes namespace (lowercase DNS label, at most 63 characters)." >&2 +if ! [[ "$resource_group" =~ ^[a-zA-Z0-9_.()-]+$ ]] || + [ "\${#resource_group}" -gt 90 ] || [[ "$resource_group" = *. ]]; then + echo "Invalid resource group name: use at most 90 letters, digits, underscores, parentheses, hyphens, or periods; do not end with a period." >&2 exit 1 fi if ! [[ "$cluster" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]] || @@ -82,10 +81,9 @@ if ! [[ "$cluster" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]] || echo "Invalid existing cluster name." >&2 exit 1 fi -echo "Benchmark target: cluster=$cluster resource_group=$resource_group namespace=$resource_group existing=$use_existing" +echo "Benchmark target: cluster=$cluster resource_group=$resource_group existing=$use_existing" echo "##vso[task.setvariable variable=RESOURCE_GROUP]$resource_group" echo "##vso[task.setvariable variable=CLUSTER]$cluster" -echo "##vso[task.setvariable variable=BENCHMARK_NAMESPACE]$resource_group" echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]$use_existing" """ displayName = "Resolve benchmark cluster" @@ -184,27 +182,34 @@ az aks create \\ "$(RESOURCE_GROUP)", SUBSCRIPTION_ID, file="$(KUBECONFIG)"), - azure.AzCli( - const.DEFAULT_SERVICE_CONNECTION, - "Prepare WI resources", - """ -set -u -kubectl create namespace "$(BENCHMARK_NAMESPACE)" --dry-run=client -o yaml | kubectl apply -f - -kubectl create serviceaccount pod-benchmark --namespace "$(BENCHMARK_NAMESPACE)" --dry-run=client -o yaml | kubectl apply -f - + kperf.InstallRunkperf(RUNNER_IMAGE), + *[step for rate in RATES for step in [ + steps.Bash { + bash = """ +set -euo pipefail +namespace="$(RUN_ID)-r${rate}" +deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') +if [ -n "$deleting" ]; then + echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 + exit 1 +fi +kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - +echo "##vso[task.setvariable variable=PHASE_${rate}_NAMESPACE_PREPARED]true" +kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. -kubectl annotate serviceaccount pod-benchmark \\ - --namespace "$(BENCHMARK_NAMESPACE)" \\ +kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \\ + --namespace "$namespace" \\ "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \\ --overwrite -"""), - kperf.InstallRunkperf(RUNNER_IMAGE), - *[step for rate in RATES for step in [ +""" + displayName = "Prepare WI resources for ${rate}/sec" + }, steps.Bash { bash = """ set -euo pipefail profile="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" sed \\ - -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \\ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r${rate}/g' \\ -e 's/__RATE__/${rate}/g' \\ -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r${rate}/g' \\ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" @@ -213,7 +218,6 @@ if grep -q '__[A-Z_]*__' "$profile"; then exit 1 fi echo "Starting ${rate} CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r${rate}" -echo "##vso[task.setvariable variable=PHASE_${rate}_STARTED]true" """ displayName = "Prepare ${rate}/sec load profile" }, @@ -226,16 +230,13 @@ echo "##vso[task.setvariable variable=PHASE_${rate}_STARTED]true" steps.Bash { bash = """ set -euo pipefail -echo "Cleaning ${rate}/sec phase Pods at $(date -u +%Y-%m-%dT%H:%M:%SZ)" -kubectl --request-timeout=60s delete pods \\ - --namespace "$(BENCHMARK_NAMESPACE)" \\ - --selector "benchmark-run=$(RUN_ID)-r${rate}" \\ - --wait=true \\ - --timeout=10m -echo "Finished ${rate}/sec phase cleanup at $(date -u +%Y-%m-%dT%H:%M:%SZ)" +kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r${rate}" \\ + --ignore-not-found=true \\ + --wait=false +echo "Namespace deletion requested for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ - displayName = "Delete ${rate}/sec phase Pods" - condition = "and(always(), eq(variables['PHASE_${rate}_STARTED'], 'true'))" + displayName = "Request ${rate}/sec namespace deletion" + condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" timeoutInMinutes = 15 }, steps.Bash { @@ -246,7 +247,7 @@ sleep 300 echo "Finished pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ displayName = "Pause 5 minutes after ${rate}/sec" - condition = "and(always(), eq(variables['PHASE_${rate}_STARTED'], 'true'))" + condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" timeoutInMinutes = 6 }, ]], diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 2aa905b2e7..21241f1015 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -11,7 +11,7 @@ parameters: type: string default: none - name: keep_cluster - displayName: Keep cluster after benchmark (phase Pods are deleted) + displayName: Keep cluster after benchmark (phase namespaces are deleted) type: boolean default: false pr: none @@ -25,9 +25,9 @@ jobs: RESOURCE_GROUP_CREATED: 'false' USE_EXISTING_CLUSTER: unresolved KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig - PHASE_50_STARTED: 'false' - PHASE_100_STARTED: 'false' - PHASE_200_STARTED: 'false' + PHASE_50_NAMESPACE_PREPARED: 'false' + PHASE_100_NAMESPACE_PREPARED: 'false' + PHASE_200_NAMESPACE_PREPARED: 'false' steps: - bash: | set -euo pipefail @@ -47,10 +47,9 @@ jobs: resource_group="$RUN_ID" cluster=wi-webhook fi - # Reused resource groups also name the existing Kubernetes namespace. - if ! [[ "$resource_group" =~ ^[a-z0-9]([-a-z0-9]*[a-z0-9])?$ ]] || - [ "${#resource_group}" -gt 63 ]; then - echo "The resource group must also be a valid Kubernetes namespace (lowercase DNS label, at most 63 characters)." >&2 + if ! [[ "$resource_group" =~ ^[a-zA-Z0-9_.()-]+$ ]] || + [ "${#resource_group}" -gt 90 ] || [[ "$resource_group" = *. ]]; then + echo "Invalid resource group name: use at most 90 letters, digits, underscores, parentheses, hyphens, or periods; do not end with a period." >&2 exit 1 fi if ! [[ "$cluster" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]] || @@ -58,10 +57,9 @@ jobs: echo "Invalid existing cluster name." >&2 exit 1 fi - echo "Benchmark target: cluster=$cluster resource_group=$resource_group namespace=$resource_group existing=$use_existing" + echo "Benchmark target: cluster=$cluster resource_group=$resource_group existing=$use_existing" echo "##vso[task.setvariable variable=RESOURCE_GROUP]$resource_group" echo "##vso[task.setvariable variable=CLUSTER]$cluster" - echo "##vso[task.setvariable variable=BENCHMARK_NAMESPACE]$resource_group" echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]$use_existing" displayName: Resolve benchmark cluster env: @@ -184,22 +182,6 @@ jobs: --overwrite-existing \ -f $(KUBECONFIG) displayName: Get credentials for $(CLUSTER) - - task: AzureCLI@2 - inputs: - azureSubscription: Azure-for-Telescope-internal - scriptType: bash - scriptLocation: inlineScript - inlineScript: | - set -exo pipefail - set -u - kubectl create namespace "$(BENCHMARK_NAMESPACE)" --dry-run=client -o yaml | kubectl apply -f - - kubectl create serviceaccount pod-benchmark --namespace "$(BENCHMARK_NAMESPACE)" --dry-run=client -o yaml | kubectl apply -f - - # Use a fake client ID because benchmark Pods do not access Azure resources. - kubectl annotate serviceaccount pod-benchmark \ - --namespace "$(BENCHMARK_NAMESPACE)" \ - "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ - --overwrite - displayName: Prepare WI resources - script: | set -euo pipefail set -x @@ -214,11 +196,28 @@ jobs: rm -rf $temp_dir docker rmi ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 2>/dev/null || true displayName: Install runkperf binary + - bash: | + set -euo pipefail + namespace="$(RUN_ID)-r50" + deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') + if [ -n "$deleting" ]; then + echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 + exit 1 + fi + kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - + echo "##vso[task.setvariable variable=PHASE_50_NAMESPACE_PREPARED]true" + kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - + # Use a fake client ID because benchmark Pods do not access Azure resources. + kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \ + --namespace "$namespace" \ + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ + --overwrite + displayName: Prepare WI resources for 50/sec - bash: | set -euo pipefail profile="$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml" sed \ - -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r50/g' \ -e 's/__RATE__/50/g' \ -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r50/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" @@ -227,7 +226,6 @@ jobs: exit 1 fi echo "Starting 50 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r50" - echo "##vso[task.setvariable variable=PHASE_50_STARTED]true" displayName: Prepare 50/sec load profile - script: | set -euo pipefail @@ -240,29 +238,43 @@ jobs: timeoutInMinutes: 15 - bash: | set -euo pipefail - echo "Cleaning 50/sec phase Pods at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - kubectl --request-timeout=60s delete pods \ - --namespace "$(BENCHMARK_NAMESPACE)" \ - --selector "benchmark-run=$(RUN_ID)-r50" \ - --wait=true \ - --timeout=10m - echo "Finished 50/sec phase cleanup at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_50_STARTED'], 'true')) - displayName: Delete 50/sec phase Pods + kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r50" \ + --ignore-not-found=true \ + --wait=false + echo "Namespace deletion requested for 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_50_NAMESPACE_PREPARED'], 'true')) + displayName: Request 50/sec namespace deletion timeoutInMinutes: 15 - bash: | set -euo pipefail echo "Starting five-minute pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_50_STARTED'], 'true')) + condition: and(always(), eq(variables['PHASE_50_NAMESPACE_PREPARED'], 'true')) displayName: Pause 5 minutes after 50/sec timeoutInMinutes: 6 + - bash: | + set -euo pipefail + namespace="$(RUN_ID)-r100" + deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') + if [ -n "$deleting" ]; then + echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 + exit 1 + fi + kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - + echo "##vso[task.setvariable variable=PHASE_100_NAMESPACE_PREPARED]true" + kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - + # Use a fake client ID because benchmark Pods do not access Azure resources. + kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \ + --namespace "$namespace" \ + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ + --overwrite + displayName: Prepare WI resources for 100/sec - bash: | set -euo pipefail profile="$(Agent.TempDirectory)/$(RUN_ID)-r100-load-profile.yaml" sed \ - -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r100/g' \ -e 's/__RATE__/100/g' \ -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r100/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" @@ -271,7 +283,6 @@ jobs: exit 1 fi echo "Starting 100 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r100" - echo "##vso[task.setvariable variable=PHASE_100_STARTED]true" displayName: Prepare 100/sec load profile - script: | set -euo pipefail @@ -284,29 +295,43 @@ jobs: timeoutInMinutes: 15 - bash: | set -euo pipefail - echo "Cleaning 100/sec phase Pods at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - kubectl --request-timeout=60s delete pods \ - --namespace "$(BENCHMARK_NAMESPACE)" \ - --selector "benchmark-run=$(RUN_ID)-r100" \ - --wait=true \ - --timeout=10m - echo "Finished 100/sec phase cleanup at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_100_STARTED'], 'true')) - displayName: Delete 100/sec phase Pods + kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r100" \ + --ignore-not-found=true \ + --wait=false + echo "Namespace deletion requested for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_100_NAMESPACE_PREPARED'], 'true')) + displayName: Request 100/sec namespace deletion timeoutInMinutes: 15 - bash: | set -euo pipefail echo "Starting five-minute pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_100_STARTED'], 'true')) + condition: and(always(), eq(variables['PHASE_100_NAMESPACE_PREPARED'], 'true')) displayName: Pause 5 minutes after 100/sec timeoutInMinutes: 6 + - bash: | + set -euo pipefail + namespace="$(RUN_ID)-r200" + deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') + if [ -n "$deleting" ]; then + echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 + exit 1 + fi + kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - + echo "##vso[task.setvariable variable=PHASE_200_NAMESPACE_PREPARED]true" + kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - + # Use a fake client ID because benchmark Pods do not access Azure resources. + kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \ + --namespace "$namespace" \ + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ + --overwrite + displayName: Prepare WI resources for 200/sec - bash: | set -euo pipefail profile="$(Agent.TempDirectory)/$(RUN_ID)-r200-load-profile.yaml" sed \ - -e 's/__RUN_NAMESPACE__/$(BENCHMARK_NAMESPACE)/g' \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r200/g' \ -e 's/__RATE__/200/g' \ -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r200/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" @@ -315,7 +340,6 @@ jobs: exit 1 fi echo "Starting 200 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r200" - echo "##vso[task.setvariable variable=PHASE_200_STARTED]true" displayName: Prepare 200/sec load profile - script: | set -euo pipefail @@ -328,22 +352,19 @@ jobs: timeoutInMinutes: 15 - bash: | set -euo pipefail - echo "Cleaning 200/sec phase Pods at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - kubectl --request-timeout=60s delete pods \ - --namespace "$(BENCHMARK_NAMESPACE)" \ - --selector "benchmark-run=$(RUN_ID)-r200" \ - --wait=true \ - --timeout=10m - echo "Finished 200/sec phase cleanup at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_200_STARTED'], 'true')) - displayName: Delete 200/sec phase Pods + kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r200" \ + --ignore-not-found=true \ + --wait=false + echo "Namespace deletion requested for 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_200_NAMESPACE_PREPARED'], 'true')) + displayName: Request 200/sec namespace deletion timeoutInMinutes: 15 - bash: | set -euo pipefail echo "Starting five-minute pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_200_STARTED'], 'true')) + condition: and(always(), eq(variables['PHASE_200_NAMESPACE_PREPARED'], 'true')) displayName: Pause 5 minutes after 200/sec timeoutInMinutes: 6 - task: AzureCLI@2 From 6a30f9496ae862c0049b77cf0d45e391952e496c Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Tue, 3 Nov 2026 13:44:46 +1000 Subject: [PATCH 10/24] Use 50/100/150 RPS for WI webhook benchmark Update phase display names, generated pipeline, and capacity estimates. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 10 ++--- kcl/workload_identity_webhook/pipeline.k | 6 +-- kcl/workload_identity_webhook/pipeline.yaml | 46 ++++++++++----------- 3 files changed, 31 insertions(+), 31 deletions(-) diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index 55b634b817..bb3af39516 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -2,7 +2,7 @@ One manual ADO job provisions a dedicated AKS Standard H2 cluster or reuses an existing cluster, and runs kperf **three times sequentially on the ADO agent**: -50, 100, then 200 Pod CREATEs/sec, each for 10 minutes. After each run, request +50, 100, then 150 Pod CREATEs/sec, each for 10 minutes. After each run, request deletion of its namespace without waiting, then pause for five minutes, including after the final run. @@ -58,7 +58,7 @@ finalizers. Namespace cleanup leaves namespaces from previous runs untouched. [load-profile.yaml](./load-profile.yaml) is a template rendered before each phase: -- `__RATE__` becomes 50, 100, or 200 Pod CREATEs/sec; 600-second generation window each. +- `__RATE__` becomes 50, 100, or 150 Pod CREATEs/sec; 600-second generation window each. - `total: 0`, `deleteRatio: 0`, `maxRetries: 0`. - 600 request workers, 20 transports; the rate is shared across workers. - WI opt-in and `schedulerName: kperf-admission-only`. @@ -96,7 +96,7 @@ then generates explicit profile, runner, namespace-deletion, and pause steps: ```text prepare r50 namespace/ServiceAccount -> 50/sec for 10m -> request namespace deletion -> pause 5m prepare r100 namespace/ServiceAccount -> 100/sec for 10m -> request namespace deletion -> pause 5m -prepare r200 namespace/ServiceAccount -> 200/sec for 10m -> request namespace deletion -> pause 5m +prepare r150 namespace/ServiceAccount -> 150/sec for 10m -> request namespace deletion -> pause 5m ``` Each driver step invokes: @@ -157,8 +157,8 @@ headroom before queueing. Confirm no scheduler handles `kperf-admission-only`; the benchmark Pods should remain unscheduled. Successful traffic at each target would create approximately 30,000, 60,000, -and 120,000 Pods respectively before that phase's cleanup. The largest phase -is about 0.458 GiB of submitted JSON at 4 KiB each, before WI/defaulting, +and 90,000 Pods respectively before that phase's cleanup. The largest phase +is about 0.343 GiB of submitted JSON at 4 KiB each, before WI/defaulting, revision history, and other storage overhead. There is no ResourceQuota, continuous storage monitor, or manual storage gate. diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index d3b5436c0f..f848529306 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -10,7 +10,7 @@ LOCATION = "westus2" # TODO: Replace the user-selected PR image with a published upstream release. RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" CREATE_NEW_CLUSTER = "and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false'))" -RATES = [50, 100, 200] +RATES = [50, 100, 150] output = ap.Pipeline { name = "Workload Identity Webhook Benchmark" @@ -40,7 +40,7 @@ output = ap.Pipeline { jobs = [ job.Job { job = "benchmark" - displayName = "Run WI webhook traffic on a new or existing cluster" + displayName = "Baseline Run: 50/100/150 RPS" timeoutInMinutes = 240 # Allow an active phase's bounded cleanup and five-minute recovery pause. cancelTimeoutInMinutes = 25 @@ -235,7 +235,7 @@ kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r${rate}" \\ --wait=false echo "Namespace deletion requested for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ - displayName = "Request ${rate}/sec namespace deletion" + displayName = "Delete namespace from ${rate}/sec run" condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" timeoutInMinutes = 15 }, diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 21241f1015..f7d9879f5d 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -17,7 +17,7 @@ parameters: pr: none jobs: - job: benchmark - displayName: Run WI webhook traffic on a new or existing cluster + displayName: 'Baseline Run: 50/100/150 RPS' timeoutInMinutes: 240 cancelTimeoutInMinutes: 25 variables: @@ -27,7 +27,7 @@ jobs: KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig PHASE_50_NAMESPACE_PREPARED: 'false' PHASE_100_NAMESPACE_PREPARED: 'false' - PHASE_200_NAMESPACE_PREPARED: 'false' + PHASE_150_NAMESPACE_PREPARED: 'false' steps: - bash: | set -euo pipefail @@ -243,7 +243,7 @@ jobs: --wait=false echo "Namespace deletion requested for 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: and(always(), eq(variables['PHASE_50_NAMESPACE_PREPARED'], 'true')) - displayName: Request 50/sec namespace deletion + displayName: Delete namespace from 50/sec run timeoutInMinutes: 15 - bash: | set -euo pipefail @@ -300,7 +300,7 @@ jobs: --wait=false echo "Namespace deletion requested for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: and(always(), eq(variables['PHASE_100_NAMESPACE_PREPARED'], 'true')) - displayName: Request 100/sec namespace deletion + displayName: Delete namespace from 100/sec run timeoutInMinutes: 15 - bash: | set -euo pipefail @@ -312,60 +312,60 @@ jobs: timeoutInMinutes: 6 - bash: | set -euo pipefail - namespace="$(RUN_ID)-r200" + namespace="$(RUN_ID)-r150" deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') if [ -n "$deleting" ]; then echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 exit 1 fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - - echo "##vso[task.setvariable variable=PHASE_200_NAMESPACE_PREPARED]true" + echo "##vso[task.setvariable variable=PHASE_150_NAMESPACE_PREPARED]true" kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \ --namespace "$namespace" \ "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ --overwrite - displayName: Prepare WI resources for 200/sec + displayName: Prepare WI resources for 150/sec - bash: | set -euo pipefail - profile="$(Agent.TempDirectory)/$(RUN_ID)-r200-load-profile.yaml" + profile="$(Agent.TempDirectory)/$(RUN_ID)-r150-load-profile.yaml" sed \ - -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r200/g' \ - -e 's/__RATE__/200/g' \ - -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r200/g' \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r150/g' \ + -e 's/__RATE__/150/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r150/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved load-profile placeholders" >&2 exit 1 fi - echo "Starting 200 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r200" - displayName: Prepare 200/sec load profile + echo "Starting 150 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r150" + displayName: Prepare 150/sec load profile - script: | set -euo pipefail set -x kperf runner run \ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r200-load-profile.yaml" \ + --config "$(Agent.TempDirectory)/$(RUN_ID)-r150-load-profile.yaml" \ --kubeconfig "$(KUBECONFIG)" - displayName: Run kperf at 200 CREATEs/sec + displayName: Run kperf at 150 CREATEs/sec timeoutInMinutes: 15 - bash: | set -euo pipefail - kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r200" \ + kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r150" \ --ignore-not-found=true \ --wait=false - echo "Namespace deletion requested for 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_200_NAMESPACE_PREPARED'], 'true')) - displayName: Request 200/sec namespace deletion + echo "Namespace deletion requested for 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_150_NAMESPACE_PREPARED'], 'true')) + displayName: Delete namespace from 150/sec run timeoutInMinutes: 15 - bash: | set -euo pipefail - echo "Starting five-minute pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Starting five-minute pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 - echo "Finished pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_200_NAMESPACE_PREPARED'], 'true')) - displayName: Pause 5 minutes after 200/sec + echo "Finished pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: and(always(), eq(variables['PHASE_150_NAMESPACE_PREPARED'], 'true')) + displayName: Pause 5 minutes after 150/sec timeoutInMinutes: 6 - task: AzureCLI@2 inputs: From 410eec23cbc98146b2b826cd9efb0a4edafce2ba Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Tue, 3 Nov 2026 15:34:24 +1000 Subject: [PATCH 11/24] Refactor WI benchmark steps and reuse reporting helpers Extract per-rate BenchmarkSteps, inline kperf execution, and use shared timestamp and ASI helpers. Simplify resource-group cleanup gating while preserving collision protection. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/lib/steps/kperf/run_benchmark.k | 21 --- kcl/workload_identity_webhook/README.md | 56 ++++--- kcl/workload_identity_webhook/pipeline.k | 165 +++++++++++--------- kcl/workload_identity_webhook/pipeline.yaml | 57 ++++++- 4 files changed, 172 insertions(+), 127 deletions(-) diff --git a/kcl/lib/steps/kperf/run_benchmark.k b/kcl/lib/steps/kperf/run_benchmark.k index c19fdf63ad..d98d854e04 100644 --- a/kcl/lib/steps/kperf/run_benchmark.k +++ b/kcl/lib/steps/kperf/run_benchmark.k @@ -1,26 +1,5 @@ import azure_pipelines.ap.steps -# Runs a custom profile in pipeline; kperf owns output formatting and exit status. -RunKperfRunner = lambda profilePath: str, kubeconfig: str = "", resultPath: str = "" -> steps.Script { - assert profilePath != "", "profilePath must not be empty" - args = [ - '--config "${profilePath}"', - '--kubeconfig "${kubeconfig}"' if kubeconfig else "", - '--result "${resultPath}"' if resultPath else "", - ] - flags = " \\\n ".join([arg for arg in args if arg]) - steps.Script { - script = """ -set -euo pipefail -set -x - -kperf runner run \\ - ${flags} -""" - displayName = "Run kperf runner" - } -} - # RunKperfBenchmark runs runkperf bench with the given subcommand and flow control settings. # Results are written to resultPath (default /tmp/tmp_results.json) for collection by CollectKperfResult. RunKperfBenchmark = lambda benchmarkSubcmd: str, benchmarkSubcmdArgs: str, flowcontrol: str, kubeconfig: str, runnerImage: str, target: str = Undefined, resultPath: str = "/tmp/tmp_results.json" -> steps.Step { diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md index bb3af39516..328f3f719a 100644 --- a/kcl/workload_identity_webhook/README.md +++ b/kcl/workload_identity_webhook/README.md @@ -91,7 +91,7 @@ which the agent's base Azure CLI does not support. The new-cluster path creates the cluster and worker pool. Both paths fetch credentials into a temporary kubeconfig and install the pinned binaries. The rate loop prepares each namespace and annotated ServiceAccount idempotently, -then generates explicit profile, runner, namespace-deletion, and pause steps: +then generates profile, runner, namespace-deletion, and pause steps: ```text prepare r50 namespace/ServiceAccount -> 50/sec for 10m -> request namespace deletion -> pause 5m @@ -99,41 +99,35 @@ prepare r100 namespace/ServiceAccount -> 100/sec for 10m -> request namespace de prepare r150 namespace/ServiceAccount -> 150/sec for 10m -> request namespace deletion -> pause 5m ``` -Each driver step invokes: +Each driver step invokes kperf directly, without a shared command wrapper: ```sh kperf runner run --config "$profile" --kubeconfig "$kubeconfig" ``` -Execution uses the shared -[`kperf.RunKperfRunner`](../lib/steps/kperf/run_benchmark.k) step: +[`common.RecordCurrentTime`](../lib/steps/common/record_current_time.k) records +one `BENCHMARK_START_TIME` after kperf installation and before the rate loop. +There are no per-rate timestamps or separately recorded end time. -```kcl -kperf.RunKperfRunner( - profilePath="$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml", - kubeconfig="$(KUBECONFIG)") | {timeoutInMinutes = 15} -``` - -Only `profilePath` is required. Optional arguments: - -- `kubeconfig`: omitted by default, letting kperf select its default kubeconfig - (`$HOME/.kube/config` outside Kubernetes, or in-cluster configuration when detected). - This pipeline still supplies its isolated kubeconfig explicitly. -- `resultPath`: omitted by default, so kperf prints its native JSON directly to - stdout. If supplied, kperf writes to that file instead; the caller owns the file. - -The helper only runs the command and propagates its exit code. It does not install -kperf, provision workload resources, parse results, capture output, or delete files. +After the loop, before resource-group deletion, +[`asi_dashboard.PrintAsiDashboardUrl`](../lib/util/asi_dashboard.k) prints +ASI Managed Cluster and API Server Analyzer URLs once, using +`$(BENCHMARK_START_TIME)` and the helper's current-time default for the end. +The links cover the overall benchmark window, including namespace preparation, +deletion requests, and recovery pauses, rather than individual rates. +The call uses the helper's default `always()` condition and `continueOnError` +behavior without a custom condition. URL-generation failures are reported but +do not fail the job; early setup failure can prevent a valid benchmark window. There are no CLI traffic overrides, Kubernetes generator Jobs, smoke/warm-up phases, manual-validation jobs, diagnostic collectors, or artifact uploads. The native result JSON appears in normal ADO logs without result validation. The resolved profile and kubeconfig live in [`Agent.TempDirectory`](https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops#agent-variables-devops-services), -which ADO cleans after each job; the shared runner does not delete caller inputs. +which ADO cleans after each job. -The caller sets a 15-minute ADO step timeout per run; the helper has no process-timeout -parameter or external timeout command. ADO cancellation governs timeout handling. +Each runner step has a 15-minute ADO timeout and no external timeout command. +ADO cancellation governs timeout handling. Nonzero kperf process exits fail the step; no run is retried. Once a phase namespace is successfully applied, deletion and the five-minute pause are attempted even if ServiceAccount setup, profile preparation, or the driver fails; later rates @@ -177,10 +171,17 @@ Recovery and equivalent fresh-cluster baselines are not guaranteed. `keep_cluster` defaults to **false**. For new clusters, the last step deletes the run's resource group, including the cluster and its Prometheus workspace, even after a benchmark failure where -ADO permits cleanup. Deletion is gated on successful resource-group creation -in this job and explicitly resolved new-cluster mode; an existing-group collision +ADO permits cleanup. Creation uses `azure.CreateResourceGroup` directly. +Final deletion checks `USE_EXISTING_CLUSTER == 'false'` and `keep_cluster`, +without a separate resource-group ownership output or a `succeeded()` gate. +The mode starts as `unresolved`: reuse sets it to `true`, while new-cluster mode +becomes `false` only after the resource-group absence check succeeds. A failed +absence check or an existing-group collision never authorizes deletion. Reused resource groups are **never deleted**, even when `keep_cluster` is false or the benchmark fails. +Once the absence check passes, cleanup is attempted even if creation or a later +step fails. If creation never produced a resource group, the deletion command can +report that the resource group was not found. With **true**, retain the cluster and Prometheus workspace, but still request deletion of every prepared phase namespace and its ServiceAccount. With **false**, @@ -196,6 +197,11 @@ cleanup; check Azure before assuming deletion completed. ## Development +`BenchmarkSteps(rate)` in [pipeline.k](./pipeline.k) returns the five per-rate +steps: WI setup, profile rendering, kperf execution, namespace deletion, and pause. +Cluster lifecycle, the overall start timestamp, and ASI reporting stay outside +the function. + ```sh kcl run kcl/workload_identity_webhook/pipeline.k -S output \ -o kcl/workload_identity_webhook/pipeline.yaml diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index f848529306..bcce698b63 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -3,7 +3,9 @@ import azure_pipelines.ap.jobs.job import azure_pipelines.ap.steps import lib.const import lib.steps.azure +import lib.steps.common import lib.steps.kperf +import lib.util.asi_dashboard SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" LOCATION = "westus2" @@ -12,6 +14,82 @@ RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014 CREATE_NEW_CLUSTER = "and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false'))" RATES = [50, 100, 150] +BenchmarkSteps = lambda rate: int -> [steps.Step] { + [ + steps.Bash { + bash = """ +set -euo pipefail +namespace="$(RUN_ID)-r${rate}" +deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') +if [ -n "$deleting" ]; then + echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 + exit 1 +fi +kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - +echo "##vso[task.setvariable variable=PHASE_${rate}_NAMESPACE_PREPARED]true" +kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - +# Use a fake client ID because benchmark Pods do not access Azure resources. +kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \\ + --namespace "$namespace" \\ + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \\ + --overwrite +""" + displayName = "Prepare WI resources for ${rate}/sec" + }, + steps.Bash { + bash = """ +set -euo pipefail +profile="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" +sed \\ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r${rate}/g' \\ + -e 's/__RATE__/${rate}/g' \\ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r${rate}/g' \\ + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" +if grep -q '__[A-Z_]*__' "$profile"; then + echo "Unresolved load-profile placeholders" >&2 + exit 1 +fi +""" + displayName = "Prepare ${rate}/sec load profile" + }, + steps.Script { + script = """ +set -euo pipefail +set -x + +kperf runner run \\ + --config "$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" \\ + --kubeconfig "$(KUBECONFIG)" +""" + displayName = "Run kperf at ${rate} CREATEs/sec" + timeoutInMinutes = 15 + }, + steps.Bash { + bash = """ +set -euo pipefail +kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r${rate}" \\ + --ignore-not-found=true \\ + --wait=false +echo "Namespace deletion requested for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" +""" + displayName = "Delete namespace from ${rate}/sec run" + condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" + timeoutInMinutes = 15 + }, + steps.Bash { + bash = """ +set -euo pipefail +echo "Starting five-minute pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" +sleep 300 +echo "Finished pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" +""" + displayName = "Pause 5 minutes after ${rate}/sec" + condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" + timeoutInMinutes = 6 + }, + ] +} + output = ap.Pipeline { name = "Workload Identity Webhook Benchmark" trigger = "none" @@ -46,7 +124,6 @@ output = ap.Pipeline { cancelTimeoutInMinutes = 25 variables = { RUN_ID = "wi-$(Build.BuildId)-$(System.JobAttempt)" - RESOURCE_GROUP_CREATED = "false" USE_EXISTING_CLUSTER = "unresolved" KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" **{"PHASE_${rate}_NAMESPACE_PREPARED" = "false" for rate in RATES} @@ -84,7 +161,9 @@ fi echo "Benchmark target: cluster=$cluster resource_group=$resource_group existing=$use_existing" echo "##vso[task.setvariable variable=RESOURCE_GROUP]$resource_group" echo "##vso[task.setvariable variable=CLUSTER]$cluster" -echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]$use_existing" +if [ "$use_existing" = "true" ]; then + echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]true" +fi """ displayName = "Resolve benchmark cluster" env = { @@ -105,8 +184,9 @@ if [ "$exists" != "false" ]; then echo "Refusing to reuse an existing or unverified resource group: $(RESOURCE_GROUP)" >&2 exit 1 fi +echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]false" """, - condition=CREATE_NEW_CLUSTER), + condition="and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'unresolved'))"), azure.CreateResourceGroup( const.DEFAULT_SERVICE_CONNECTION, "$(RESOURCE_GROUP)", @@ -117,7 +197,6 @@ fi const.DEFAULT_SERVICE_CONNECTION, "Create benchmark Prometheus workspace", """ -echo "##vso[task.setvariable variable=RESOURCE_GROUP_CREATED]true" az monitor account create \\ --subscription "${SUBSCRIPTION_ID}" \\ --resource-group "$(RESOURCE_GROUP)" \\ @@ -183,79 +262,19 @@ az aks create \\ SUBSCRIPTION_ID, file="$(KUBECONFIG)"), kperf.InstallRunkperf(RUNNER_IMAGE), - *[step for rate in RATES for step in [ - steps.Bash { - bash = """ -set -euo pipefail -namespace="$(RUN_ID)-r${rate}" -deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') -if [ -n "$deleting" ]; then - echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 - exit 1 -fi -kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - -echo "##vso[task.setvariable variable=PHASE_${rate}_NAMESPACE_PREPARED]true" -kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - -# Use a fake client ID because benchmark Pods do not access Azure resources. -kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \\ - --namespace "$namespace" \\ - "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \\ - --overwrite -""" - displayName = "Prepare WI resources for ${rate}/sec" - }, - steps.Bash { - bash = """ -set -euo pipefail -profile="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" -sed \\ - -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r${rate}/g' \\ - -e 's/__RATE__/${rate}/g' \\ - -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r${rate}/g' \\ - "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" -if grep -q '__[A-Z_]*__' "$profile"; then - echo "Unresolved load-profile placeholders" >&2 - exit 1 -fi -echo "Starting ${rate} CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r${rate}" -""" - displayName = "Prepare ${rate}/sec load profile" - }, - kperf.RunKperfRunner( - profilePath="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml", - kubeconfig="$(KUBECONFIG)") | { - displayName = "Run kperf at ${rate} CREATEs/sec" - timeoutInMinutes = 15 - }, - steps.Bash { - bash = """ -set -euo pipefail -kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r${rate}" \\ - --ignore-not-found=true \\ - --wait=false -echo "Namespace deletion requested for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" -""" - displayName = "Delete namespace from ${rate}/sec run" - condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" - timeoutInMinutes = 15 - }, - steps.Bash { - bash = """ -set -euo pipefail -echo "Starting five-minute pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" -sleep 300 -echo "Finished pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" -""" - displayName = "Pause 5 minutes after ${rate}/sec" - condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" - timeoutInMinutes = 6 - }, - ]], + common.RecordCurrentTime("BENCHMARK_START_TIME"), + *[step for rate in RATES for step in BenchmarkSteps(rate)], + asi_dashboard.PrintAsiDashboardUrl( + const.DEFAULT_SERVICE_CONNECTION, + "$(CLUSTER)", + "$(RESOURCE_GROUP)", + SUBSCRIPTION_ID, + startTime="$(BENCHMARK_START_TIME)"), azure.DeleteResourceGroup( const.DEFAULT_SERVICE_CONNECTION, "$(RESOURCE_GROUP)", SUBSCRIPTION_ID, - condition="and(always(), eq(variables['USE_EXISTING_CLUSTER'], 'false'), eq(variables['RESOURCE_GROUP_CREATED'], 'true'), not(\${{ parameters.keep_cluster }}))"), + condition="and(always(), eq(variables['USE_EXISTING_CLUSTER'], 'false'), not(\${{ parameters.keep_cluster }}))"), ] }, ] diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index f7d9879f5d..c4c0f66299 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -22,7 +22,6 @@ jobs: cancelTimeoutInMinutes: 25 variables: RUN_ID: wi-$(Build.BuildId)-$(System.JobAttempt) - RESOURCE_GROUP_CREATED: 'false' USE_EXISTING_CLUSTER: unresolved KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig PHASE_50_NAMESPACE_PREPARED: 'false' @@ -60,7 +59,10 @@ jobs: echo "Benchmark target: cluster=$cluster resource_group=$resource_group existing=$use_existing" echo "##vso[task.setvariable variable=RESOURCE_GROUP]$resource_group" echo "##vso[task.setvariable variable=CLUSTER]$cluster" - echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]$use_existing" + # New-cluster mode is published only after the resource-group absence check. + if [ "$use_existing" = "true" ]; then + echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]true" + fi displayName: Resolve benchmark cluster env: PARAM_EXISTING_RESOURCE_GROUP: ${{ parameters.existing_resource_group }} @@ -88,7 +90,8 @@ jobs: echo "Refusing to reuse an existing or unverified resource group: $(RESOURCE_GROUP)" >&2 exit 1 fi - condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) + echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]false" + condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'unresolved')) displayName: Verify resource group does not already exist - task: AzureCLI@2 inputs: @@ -111,7 +114,6 @@ jobs: scriptLocation: inlineScript inlineScript: | set -exo pipefail - echo "##vso[task.setvariable variable=RESOURCE_GROUP_CREATED]true" az monitor account create \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ --resource-group "$(RESOURCE_GROUP)" \ @@ -196,6 +198,12 @@ jobs: rm -rf $temp_dir docker rmi ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 2>/dev/null || true displayName: Install runkperf binary + - bash: | + set -exo pipefail + TIMESTAMP=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z") + echo "BENCHMARK_START_TIME: $TIMESTAMP" + echo "##vso[task.setvariable variable=BENCHMARK_START_TIME]$TIMESTAMP" + displayName: Record current time as BENCHMARK_START_TIME - bash: | set -euo pipefail namespace="$(RUN_ID)-r50" @@ -225,7 +233,6 @@ jobs: echo "Unresolved load-profile placeholders" >&2 exit 1 fi - echo "Starting 50 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r50" displayName: Prepare 50/sec load profile - script: | set -euo pipefail @@ -282,7 +289,6 @@ jobs: echo "Unresolved load-profile placeholders" >&2 exit 1 fi - echo "Starting 100 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r100" displayName: Prepare 100/sec load profile - script: | set -euo pipefail @@ -339,7 +345,6 @@ jobs: echo "Unresolved load-profile placeholders" >&2 exit 1 fi - echo "Starting 150 CREATEs/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ); ownership=$(RUN_ID)-r150" displayName: Prepare 150/sec load profile - script: | set -euo pipefail @@ -367,6 +372,42 @@ jobs: condition: and(always(), eq(variables['PHASE_150_NAMESPACE_PREPARED'], 'true')) displayName: Pause 5 minutes after 150/sec timeoutInMinutes: 6 + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -exo pipefail + RESOURCE_UID=$(az aks show \ + --resource-group "$(RESOURCE_GROUP)" \ + --name "$(CLUSTER)" \ + --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ + --query "resourceUid" -o tsv) + + if [ -z "$RESOURCE_UID" ]; then + echo "##[warning]Failed to fetch resourceUid, skipping ASI URL" + exit 1 + fi + + END_TIME="" + if [ -z "$END_TIME" ]; then + END_TIME=$(date -u +"%Y-%m-%dT%H:%M:%S.000Z") + fi + + FROM_ENCODED=$(echo "$(BENCHMARK_START_TIME)" | sed 's/:/%3A/g') + TO_ENCODED=$(echo "$END_TIME" | sed 's/:/%3A/g') + + echo "============================================" + echo "ASI Managed Cluster Dashboard URL:" + echo "https://asi.azure.ms/services/AKS/pages/Managed%20Cluster?clusterVersion=$RESOURCE_UID&globalFrom=$FROM_ENCODED&globalTo=$TO_ENCODED" + echo "" + echo "ASI API Server Analyzer URL:" + echo "https://asi.azure.ms/services/AKS/pages/API%20Server%20Analyzer?clusterVersion=$RESOURCE_UID&globalFrom=$FROM_ENCODED&globalTo=$TO_ENCODED" + echo "============================================" + condition: always() + continueOnError: true + displayName: Print ASI dashboard URL - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -375,5 +416,5 @@ jobs: inlineScript: | set -exo pipefail az group delete --name "$(RESOURCE_GROUP)" --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --yes - condition: and(always(), eq(variables['USE_EXISTING_CLUSTER'], 'false'), eq(variables['RESOURCE_GROUP_CREATED'], 'true'), not(${{ parameters.keep_cluster }})) + condition: and(always(), eq(variables['USE_EXISTING_CLUSTER'], 'false'), not(${{ parameters.keep_cluster }})) displayName: Delete resource group (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) From 32fb91283b80f1b6bdebdb6497f7e7094461056e Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Tue, 3 Nov 2026 15:54:36 +1000 Subject: [PATCH 12/24] Simplify WI benchmark provisioning and cleanup Remove cluster reuse parameters and lifecycle flags, always attempt phase cleanup and pauses, and remove the scenario README. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/README.md | 218 -------------------- kcl/workload_identity_webhook/pipeline.k | 112 ++-------- kcl/workload_identity_webhook/pipeline.yaml | 89 +------- 3 files changed, 28 insertions(+), 391 deletions(-) delete mode 100644 kcl/workload_identity_webhook/README.md diff --git a/kcl/workload_identity_webhook/README.md b/kcl/workload_identity_webhook/README.md deleted file mode 100644 index 328f3f719a..0000000000 --- a/kcl/workload_identity_webhook/README.md +++ /dev/null @@ -1,218 +0,0 @@ -# Workload Identity webhook benchmark - -One manual ADO job provisions a dedicated AKS Standard H2 cluster or reuses an -existing cluster, and runs kperf **three times sequentially on the ADO agent**: -50, 100, then 150 Pod CREATEs/sec, each for 10 minutes. After each run, request -deletion of its namespace without waiting, then pause for five minutes, -including after the final run. - -## Cluster selection - -| Parameter | Default | Behavior | -|---|---|---| -| `existing_resource_group` | `none` | Existing Azure resource group containing the cluster | -| `existing_cluster` | `none` | Existing AKS cluster name; must be supplied with the resource group | -| `keep_cluster` | `false` | Retain a newly created cluster and its Prometheus workspace; existing resource groups are always retained | - -Leave both existing-cluster parameters as `none` (or empty) to create a new cluster. -Supplying only one fails before provisioning or traffic. - -For example, reuse the retained benchmark cluster with -`existing_resource_group=wi-84842-1` and `existing_cluster=wi-webhook`. -The cluster must be in subscription `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`. -Azure resource-group names are independent of the benchmark namespaces. - -Reuse skips resource-group/cluster/node-pool and Prometheus workspace creation, -aks-preview installation, and monitoring enablement. Operators must provide an existing WI-enabled cluster. -In both modes, each rate's WI preparation idempotently applies its namespace and -ServiceAccount `pod-benchmark`, then sets `azure.workload.identity/client-id` to -the dummy UUID with `--overwrite`. Any previous client-ID annotation on this -benchmark ServiceAccount is replaced. Each namespace is dedicated to that phase. -Other reused cluster settings, including monitoring, remain unchanged. - -Both modes fetch credentials and install kperf once. The per-rate steps prepare -WI resources and render a profile using `$(RUN_ID)-r` as both the namespace -and the phase identifier, for example `wi-85212-1-r50`. New builds and job attempts -get distinct names. Repeated preparation works for an existing Active phase -namespace; a Terminating namespace fails explicitly without waiting or removing -finalizers. Namespace cleanup leaves namespaces from previous runs untouched. - -## New-cluster configuration - -- Subscription: `b8ceb4e5-f05b-4562-a9f5-14acb1f24219`; region: `westus2`. -- System pool: three `Standard_D4_v4` nodes. -- Worker pool: three `Standard_D2s_v5` nodes, retained as requested but not used - to host the traffic driver. -- OIDC and workload identity enabled; webhook resources/replicas are not tuned. -- The pipeline creates `wi-benchmark-prometheus`, an Azure Monitor workspace, - in the cluster's resource group before enabling managed Prometheus during - cluster creation. No separate `wi-benchmark-monitoring` group is required. - The pipeline identity needs permission to create the workspace and onboard - the cluster. This enables metrics, not container stdout/stderr logging; - no Log Analytics workspace is provisioned. -- A benchmark ServiceAccount annotated with dummy client ID - `00000000-0000-4000-8000-000000000001`. This preserves `AZURE_CLIENT_ID` - injection without provisioning a workload managed identity. No federated - credential or Azure role assignment is needed: this admission-only workload - does not perform token exchange. Use a real identity for token-exchange tests. - -[load-profile.yaml](./load-profile.yaml) is a template rendered before each phase: - -- `__RATE__` becomes 50, 100, or 150 Pod CREATEs/sec; 600-second generation window each. -- `total: 0`, `deleteRatio: 0`, `maxRetries: 0`. -- 600 request workers, 20 transports; the rate is shared across workers. -- WI opt-in and `schedulerName: kperf-admission-only`. -- `__RUN_NAMESPACE__` selects the run/attempt/rate namespace; `__PHASE_RUN_ID__` - becomes `$(RUN_ID)-r` in the `benchmark-run` label. Cleanup uses that - exact namespace for deletion, including its Pods and ServiceAccount; the label - remains useful for identifying the phase's Pods. -- `payloadSize: 3650` pads an environment variable, not the complete submitted - JSON. The resulting single-container Pod is approximately 4 KiB before - server-side mutation/defaulting. The phase ownership label adds a small amount - of metadata compared with the earlier unlabelled profile. - -The existing installer extracts kperf from this pinned custom image: - -```text -ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 -``` - -This is tag `sha-38567a6`, source commit -`38567a6b70337e7efa3d287988ab36cfe47f9d04` from -[Azure/kperf#260](https://github.com/Azure/kperf/pull/260). Replace the custom -image with an upstream release when available. - -## Execution and results - -For new clusters, the cluster-creation task installs `aks-preview` version `20.0.0b6` immediately -before `az aks create`. The extension provides `--control-plane-scaling-size H2`, -which the agent's base Azure CLI does not support. - -The new-cluster path creates the cluster and worker pool. Both paths fetch -credentials into a temporary kubeconfig and install the pinned binaries. The -rate loop prepares each namespace and annotated ServiceAccount idempotently, -then generates profile, runner, namespace-deletion, and pause steps: - -```text -prepare r50 namespace/ServiceAccount -> 50/sec for 10m -> request namespace deletion -> pause 5m -prepare r100 namespace/ServiceAccount -> 100/sec for 10m -> request namespace deletion -> pause 5m -prepare r150 namespace/ServiceAccount -> 150/sec for 10m -> request namespace deletion -> pause 5m -``` - -Each driver step invokes kperf directly, without a shared command wrapper: - -```sh -kperf runner run --config "$profile" --kubeconfig "$kubeconfig" -``` - -[`common.RecordCurrentTime`](../lib/steps/common/record_current_time.k) records -one `BENCHMARK_START_TIME` after kperf installation and before the rate loop. -There are no per-rate timestamps or separately recorded end time. - -After the loop, before resource-group deletion, -[`asi_dashboard.PrintAsiDashboardUrl`](../lib/util/asi_dashboard.k) prints -ASI Managed Cluster and API Server Analyzer URLs once, using -`$(BENCHMARK_START_TIME)` and the helper's current-time default for the end. -The links cover the overall benchmark window, including namespace preparation, -deletion requests, and recovery pauses, rather than individual rates. -The call uses the helper's default `always()` condition and `continueOnError` -behavior without a custom condition. URL-generation failures are reported but -do not fail the job; early setup failure can prevent a valid benchmark window. - -There are no CLI traffic overrides, Kubernetes generator Jobs, smoke/warm-up -phases, manual-validation jobs, diagnostic collectors, or artifact uploads. -The native result JSON appears in normal ADO logs without result validation. -The resolved profile and kubeconfig live in -[`Agent.TempDirectory`](https://learn.microsoft.com/en-us/azure/devops/pipelines/build/variables?view=azure-devops#agent-variables-devops-services), -which ADO cleans after each job. - -Each runner step has a 15-minute ADO timeout and no external timeout command. -ADO cancellation governs timeout handling. -Nonzero kperf process exits fail the step; no run is retried. Once a phase namespace -is successfully applied, deletion and the five-minute pause are attempted even -if ServiceAccount setup, profile preparation, or the driver fails; later rates -are skipped. A failed deletion command also blocks later rates, without skipping -the pause. Successfully requesting deletion does not require the namespace to -finish terminating before proceeding. HTTP errors in the -report do not independently fail it: kperf can exit zero despite failed requests, -as observed in build 84716. Missing or malformed reports are not checked. - -The pinned runner's `total` is the configured request total, **not an observed -success count**; it remains zero for this duration-based run. Native duration -includes drain. Per-interval dispatch rates, actual WI invocation rates, and -inflight backlog are unavailable. This is exploratory traffic generation, -not proof that the webhook sustained the configured rate. Agent-to-API-server networking -also differs from an in-cluster driver. - -## Prerequisites and cleanup - -Operators ensure version/SKU availability, quota, and control-plane storage -headroom before queueing. Confirm no scheduler handles `kperf-admission-only`; -the benchmark Pods should remain unscheduled. - -Successful traffic at each target would create approximately 30,000, 60,000, -and 90,000 Pods respectively before that phase's cleanup. The largest phase -is about 0.343 GiB of submitted JSON at 4 KiB each, before WI/defaulting, -revision history, and other storage overhead. There is no ResourceQuota, -continuous storage monitor, or manual storage gate. - -Cleanup issues one namespace deletion request with `--wait=false` and -`--ignore-not-found=true`. It uses a 60-second API request timeout and a -15-minute ADO step limit, but never polls for namespace deletion completion. -Each 300-second pause has a six-minute step limit. The job allows 25 minutes -of cancellation grace for active cleanup and recovery where ADO permits. -Skipped phases do not perform cleanup or pause. A failed namespace apply does -not enable cleanup; inspect for partially created resources after such failures. - -Namespace deletion may still be running after the pause and overlap the next -rate's traffic. Requesting deletion and pausing is not a full storage/cache reset: -etcd revisions, caches, controller state, and pre-existing objects remain. -Recovery and equivalent fresh-cluster baselines are not guaranteed. - -`keep_cluster` defaults to **false**. For new clusters, the last step deletes the run's resource -group, including the cluster and its Prometheus workspace, even after a benchmark failure where -ADO permits cleanup. Creation uses `azure.CreateResourceGroup` directly. -Final deletion checks `USE_EXISTING_CLUSTER == 'false'` and `keep_cluster`, -without a separate resource-group ownership output or a `succeeded()` gate. -The mode starts as `unresolved`: reuse sets it to `true`, while new-cluster mode -becomes `false` only after the resource-group absence check succeeds. A failed -absence check or an existing-group collision -never authorizes deletion. Reused resource groups are **never deleted**, even when -`keep_cluster` is false or the benchmark fails. -Once the absence check passes, cleanup is attempted even if creation or a later -step fails. If creation never produced a resource group, the deletion command can -report that the resource group was not found. - -With **true**, retain the cluster and Prometheus workspace, but still request -deletion of every prepared phase namespace and its ServiceAccount. With **false**, -deleting the group also deletes the workspace -and its stored metrics; export required results beforehand if historical -analysis is needed after cleanup. Existing-cluster reuse never deletes or -reconfigures its monitoring workspace. -Failed, interrupted, or still-pending namespace cleanup may leave some Pods behind. -Retained resources incur charges. Use the run's resource-group name from the -ADO logs for manual deletion when finished. There are no separate finalization -reports or deletion-verification steps. A hard agent interruption can prevent -cleanup; check Azure before assuming deletion completed. - -## Development - -`BenchmarkSteps(rate)` in [pipeline.k](./pipeline.k) returns the five per-rate -steps: WI setup, profile rendering, kperf execution, namespace deletion, and pause. -Cluster lifecycle, the overall start timestamp, and ASI reporting stay outside -the function. - -```sh -kcl run kcl/workload_identity_webhook/pipeline.k -S output \ - -o kcl/workload_identity_webhook/pipeline.yaml -``` - -The pipeline does not install a Python -dependency bundle or use a custom Python orchestrator. - -[ADO pipeline 94](https://dev.azure.com/akstelescope/telescope/_build?definitionId=94) -is registered as `Workload Identitiy Webhook Benchmark` under -`\AKS\Telescope\v2`, using `Azure/telescope:wi-web-bench` and -[pipeline.yaml](./pipeline.yaml). CI/PR triggers remain disabled. -Local changes do not affect that definition until pushed; do not queue a run -as part of local validation. diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index bcce698b63..61c8b58bcd 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -11,7 +11,6 @@ SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" LOCATION = "westus2" # TODO: Replace the user-selected PR image with a published upstream release. RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" -CREATE_NEW_CLUSTER = "and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false'))" RATES = [50, 100, 150] BenchmarkSteps = lambda rate: int -> [steps.Step] { @@ -26,7 +25,6 @@ if [ -n "$deleting" ]; then exit 1 fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - -echo "##vso[task.setvariable variable=PHASE_${rate}_NAMESPACE_PREPARED]true" kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \\ @@ -73,7 +71,7 @@ kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r${rate}" \\ echo "Namespace deletion requested for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ displayName = "Delete namespace from ${rate}/sec run" - condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" + condition = "always()" timeoutInMinutes = 15 }, steps.Bash { @@ -84,7 +82,7 @@ sleep 300 echo "Finished pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ displayName = "Pause 5 minutes after ${rate}/sec" - condition = "and(always(), eq(variables['PHASE_${rate}_NAMESPACE_PREPARED'], 'true'))" + condition = "always()" timeoutInMinutes = 6 }, ] @@ -96,18 +94,6 @@ output = ap.Pipeline { pr = "none" pool = const.DEFAULT_POOL parameters = [ - ap.Parameter { - name = "existing_resource_group" - displayName = "Existing resource group (none creates a cluster)" - type = "string" - default = "none" - }, - ap.Parameter { - name = "existing_cluster" - displayName = "Existing cluster name (provide together with resource group)" - type = "string" - default = "none" - }, ap.Parameter { name = "keep_cluster" displayName = "Keep cluster after benchmark (phase namespaces are deleted)" @@ -120,79 +106,24 @@ output = ap.Pipeline { job = "benchmark" displayName = "Baseline Run: 50/100/150 RPS" timeoutInMinutes = 240 - # Allow an active phase's bounded cleanup and five-minute recovery pause. + # Allow bounded cleanup and recovery during cancellation. cancelTimeoutInMinutes = 25 variables = { RUN_ID = "wi-$(Build.BuildId)-$(System.JobAttempt)" - USE_EXISTING_CLUSTER = "unresolved" + RESOURCE_GROUP = "$(RUN_ID)" + CLUSTER = "wi-webhook" KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" - **{"PHASE_${rate}_NAMESPACE_PREPARED" = "false" for rate in RATES} } steps = [ - steps.Bash { - bash = """ -set -euo pipefail -resource_group="$PARAM_EXISTING_RESOURCE_GROUP" -cluster="$PARAM_EXISTING_CLUSTER" -if [ "$resource_group" = "none" ]; then resource_group=""; fi -if [ "$cluster" = "none" ]; then cluster=""; fi -if { [ -z "$resource_group" ] && [ -n "$cluster" ]; } || - { [ -n "$resource_group" ] && [ -z "$cluster" ]; }; then - echo "existing_resource_group and existing_cluster must be provided together." >&2 - exit 1 -fi -if [ -n "$cluster" ]; then - use_existing=true -else - use_existing=false - resource_group="$RUN_ID" - cluster=wi-webhook -fi -if ! [[ "$resource_group" =~ ^[a-zA-Z0-9_.()-]+$ ]] || - [ "\${#resource_group}" -gt 90 ] || [[ "$resource_group" = *. ]]; then - echo "Invalid resource group name: use at most 90 letters, digits, underscores, parentheses, hyphens, or periods; do not end with a period." >&2 - exit 1 -fi -if ! [[ "$cluster" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]] || - [ "\${#cluster}" -gt 63 ]; then - echo "Invalid existing cluster name." >&2 - exit 1 -fi -echo "Benchmark target: cluster=$cluster resource_group=$resource_group existing=$use_existing" -echo "##vso[task.setvariable variable=RESOURCE_GROUP]$resource_group" -echo "##vso[task.setvariable variable=CLUSTER]$cluster" -if [ "$use_existing" = "true" ]; then - echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]true" -fi -""" - displayName = "Resolve benchmark cluster" - env = { - PARAM_EXISTING_RESOURCE_GROUP = "\${{ parameters.existing_resource_group }}" - PARAM_EXISTING_CLUSTER = "\${{ parameters.existing_cluster }}" - } - }, azure.Login( const.DEFAULT_SERVICE_CONNECTION, SUBSCRIPTION_ID, LOCATION), - azure.AzCli( - const.DEFAULT_SERVICE_CONNECTION, - "Verify resource group does not already exist", - """ -exists=$(az group exists --subscription "${SUBSCRIPTION_ID}" --name "$(RESOURCE_GROUP)") -if [ "$exists" != "false" ]; then - echo "Refusing to reuse an existing or unverified resource group: $(RESOURCE_GROUP)" >&2 - exit 1 -fi -echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]false" -""", - condition="and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'unresolved'))"), azure.CreateResourceGroup( const.DEFAULT_SERVICE_CONNECTION, "$(RESOURCE_GROUP)", LOCATION, - SUBSCRIPTION_ID, - condition=CREATE_NEW_CLUSTER), + SUBSCRIPTION_ID), azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, "Create benchmark Prometheus workspace", @@ -202,8 +133,7 @@ az monitor account create \\ --resource-group "$(RESOURCE_GROUP)" \\ --name wi-benchmark-prometheus \\ --location "${LOCATION}" -""", - condition=CREATE_NEW_CLUSTER), +"""), azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, "Create H2 cluster with OIDC and workload identity", @@ -240,21 +170,17 @@ az aks create \\ --nat-gateway-managed-outbound-ip-count 10 \\ --tags SkipAKSCluster=true \\ --yes -""", - condition=CREATE_NEW_CLUSTER), - steps.Task { - **azure.CreateNodePool( - const.DEFAULT_SERVICE_CONNECTION, - "$(CLUSTER)", - "$(RESOURCE_GROUP)", - SUBSCRIPTION_ID, - azure.NodePool { - name = "workerpool" - sku = "Standard_D2s_v5" - count = 3 - }) - condition = CREATE_NEW_CLUSTER - }, +"""), + azure.CreateNodePool( + const.DEFAULT_SERVICE_CONNECTION, + "$(CLUSTER)", + "$(RESOURCE_GROUP)", + SUBSCRIPTION_ID, + azure.NodePool { + name = "workerpool" + sku = "Standard_D2s_v5" + count = 3 + }), azure.GetCredentials( const.DEFAULT_SERVICE_CONNECTION, "$(CLUSTER)", @@ -274,7 +200,7 @@ az aks create \\ const.DEFAULT_SERVICE_CONNECTION, "$(RESOURCE_GROUP)", SUBSCRIPTION_ID, - condition="and(always(), eq(variables['USE_EXISTING_CLUSTER'], 'false'), not(\${{ parameters.keep_cluster }}))"), + condition="and(always(), not(\${{ parameters.keep_cluster }}))"), ] }, ] diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index c4c0f66299..cb43396133 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -2,14 +2,6 @@ name: Workload Identity Webhook Benchmark pool: AKS-Telescope-Airlock trigger: none parameters: -- name: existing_resource_group - displayName: Existing resource group (none creates a cluster) - type: string - default: none -- name: existing_cluster - displayName: Existing cluster name (provide together with resource group) - type: string - default: none - name: keep_cluster displayName: Keep cluster after benchmark (phase namespaces are deleted) type: boolean @@ -22,51 +14,10 @@ jobs: cancelTimeoutInMinutes: 25 variables: RUN_ID: wi-$(Build.BuildId)-$(System.JobAttempt) - USE_EXISTING_CLUSTER: unresolved + RESOURCE_GROUP: $(RUN_ID) + CLUSTER: wi-webhook KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig - PHASE_50_NAMESPACE_PREPARED: 'false' - PHASE_100_NAMESPACE_PREPARED: 'false' - PHASE_150_NAMESPACE_PREPARED: 'false' steps: - - bash: | - set -euo pipefail - resource_group="$PARAM_EXISTING_RESOURCE_GROUP" - cluster="$PARAM_EXISTING_CLUSTER" - if [ "$resource_group" = "none" ]; then resource_group=""; fi - if [ "$cluster" = "none" ]; then cluster=""; fi - if { [ -z "$resource_group" ] && [ -n "$cluster" ]; } || - { [ -n "$resource_group" ] && [ -z "$cluster" ]; }; then - echo "existing_resource_group and existing_cluster must be provided together." >&2 - exit 1 - fi - if [ -n "$cluster" ]; then - use_existing=true - else - use_existing=false - resource_group="$RUN_ID" - cluster=wi-webhook - fi - if ! [[ "$resource_group" =~ ^[a-zA-Z0-9_.()-]+$ ]] || - [ "${#resource_group}" -gt 90 ] || [[ "$resource_group" = *. ]]; then - echo "Invalid resource group name: use at most 90 letters, digits, underscores, parentheses, hyphens, or periods; do not end with a period." >&2 - exit 1 - fi - if ! [[ "$cluster" =~ ^[a-zA-Z0-9][a-zA-Z0-9_-]*$ ]] || - [ "${#cluster}" -gt 63 ]; then - echo "Invalid existing cluster name." >&2 - exit 1 - fi - echo "Benchmark target: cluster=$cluster resource_group=$resource_group existing=$use_existing" - echo "##vso[task.setvariable variable=RESOURCE_GROUP]$resource_group" - echo "##vso[task.setvariable variable=CLUSTER]$cluster" - # New-cluster mode is published only after the resource-group absence check. - if [ "$use_existing" = "true" ]; then - echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]true" - fi - displayName: Resolve benchmark cluster - env: - PARAM_EXISTING_RESOURCE_GROUP: ${{ parameters.existing_resource_group }} - PARAM_EXISTING_CLUSTER: ${{ parameters.existing_cluster }} - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -78,21 +29,6 @@ jobs: az config set defaults.location="westus2" az account show displayName: Login to Azure - - task: AzureCLI@2 - inputs: - azureSubscription: Azure-for-Telescope-internal - scriptType: bash - scriptLocation: inlineScript - inlineScript: | - set -exo pipefail - exists=$(az group exists --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --name "$(RESOURCE_GROUP)") - if [ "$exists" != "false" ]; then - echo "Refusing to reuse an existing or unverified resource group: $(RESOURCE_GROUP)" >&2 - exit 1 - fi - echo "##vso[task.setvariable variable=USE_EXISTING_CLUSTER]false" - condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'unresolved')) - displayName: Verify resource group does not already exist - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -105,7 +41,6 @@ jobs: --location "westus2" \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) displayName: Create resource group in westus2 (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) - task: AzureCLI@2 inputs: @@ -119,7 +54,6 @@ jobs: --resource-group "$(RESOURCE_GROUP)" \ --name wi-benchmark-prometheus \ --location "westus2" - condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) displayName: Create benchmark Prometheus workspace - task: AzureCLI@2 inputs: @@ -160,7 +94,6 @@ jobs: --nat-gateway-managed-outbound-ip-count 10 \ --tags SkipAKSCluster=true \ --yes - condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) displayName: Create H2 cluster with OIDC and workload identity - task: AzureCLI@2 inputs: @@ -168,7 +101,6 @@ jobs: scriptType: bash scriptLocation: inlineScript inlineScript: "set -exo pipefail\ncreate_node_pool() {\n local deadline sleep_between=30 attempt=0 output rc now remaining_retry_seconds\n deadline=$(($(date +%s) + 600))\n while :; do\n attempt=$((attempt + 1))\n if output=$(az aks nodepool add \"$@\" 2>&1); then\n rc=0\n else\n rc=$?\n fi\n echo \"$output\"\n if [ \"$rc\" -eq 0 ]; then\n return 0\n fi\n if echo \"$output\" | grep -qiE \"OperationNotAllowed\"; then\n now=$(date +%s)\n if [ \"$now\" -ge \"$deadline\" ]; then\n echo \"Retriable error persisted past 600s retry window ($attempt attempts); giving up.\"\n return \"$rc\"\n fi\n remaining_retry_seconds=$((deadline - now))\n echo \"Attempt $attempt matched retriable pattern; retrying in $sleep_between seconds ($remaining_retry_seconds seconds remain in retry window).\"\n sleep \"$sleep_between\"\n else\n echo \"Non-retriable error (rc=$rc); giving up after attempt $attempt.\"\n return \"$rc\"\n fi\n done\n}\n\n\ncreate_node_pool \\\n --cluster-name \"$(CLUSTER)\" \\\n --resource-group \"$(RESOURCE_GROUP)\" \\\n --subscription \"b8ceb4e5-f05b-4562-a9f5-14acb1f24219\" \\\n --name \"workerpool\" \\\n --node-count 3 \\\n --node-vm-size \"Standard_D2s_v5\" \\\n --mode User \\\n \n" - condition: and(succeeded(), eq(variables['USE_EXISTING_CLUSTER'], 'false')) displayName: Create node pool workerpool - task: AzureCLI@2 inputs: @@ -213,7 +145,6 @@ jobs: exit 1 fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - - echo "##vso[task.setvariable variable=PHASE_50_NAMESPACE_PREPARED]true" kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \ @@ -249,7 +180,7 @@ jobs: --ignore-not-found=true \ --wait=false echo "Namespace deletion requested for 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_50_NAMESPACE_PREPARED'], 'true')) + condition: always() displayName: Delete namespace from 50/sec run timeoutInMinutes: 15 - bash: | @@ -257,7 +188,7 @@ jobs: echo "Starting five-minute pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_50_NAMESPACE_PREPARED'], 'true')) + condition: always() displayName: Pause 5 minutes after 50/sec timeoutInMinutes: 6 - bash: | @@ -269,7 +200,6 @@ jobs: exit 1 fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - - echo "##vso[task.setvariable variable=PHASE_100_NAMESPACE_PREPARED]true" kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \ @@ -305,7 +235,7 @@ jobs: --ignore-not-found=true \ --wait=false echo "Namespace deletion requested for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_100_NAMESPACE_PREPARED'], 'true')) + condition: always() displayName: Delete namespace from 100/sec run timeoutInMinutes: 15 - bash: | @@ -313,7 +243,7 @@ jobs: echo "Starting five-minute pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_100_NAMESPACE_PREPARED'], 'true')) + condition: always() displayName: Pause 5 minutes after 100/sec timeoutInMinutes: 6 - bash: | @@ -325,7 +255,6 @@ jobs: exit 1 fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - - echo "##vso[task.setvariable variable=PHASE_150_NAMESPACE_PREPARED]true" kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \ @@ -361,7 +290,7 @@ jobs: --ignore-not-found=true \ --wait=false echo "Namespace deletion requested for 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_150_NAMESPACE_PREPARED'], 'true')) + condition: always() displayName: Delete namespace from 150/sec run timeoutInMinutes: 15 - bash: | @@ -369,7 +298,7 @@ jobs: echo "Starting five-minute pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: and(always(), eq(variables['PHASE_150_NAMESPACE_PREPARED'], 'true')) + condition: always() displayName: Pause 5 minutes after 150/sec timeoutInMinutes: 6 - task: AzureCLI@2 @@ -416,5 +345,5 @@ jobs: inlineScript: | set -exo pipefail az group delete --name "$(RESOURCE_GROUP)" --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" --yes - condition: and(always(), eq(variables['USE_EXISTING_CLUSTER'], 'false'), not(${{ parameters.keep_cluster }})) + condition: and(always(), not(${{ parameters.keep_cluster }})) displayName: Delete resource group (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) From cf314f74d271d4e35d55c48be3691fe4826a5318 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Tue, 3 Nov 2026 23:16:13 +1000 Subject: [PATCH 13/24] Remove managed Prometheus setup from WI benchmark Guard namespace cleanup when kubeconfig is unavailable and update the aks-preview pin to 21.0.0b17. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/pipeline.k | 18 ++++--------- kcl/workload_identity_webhook/pipeline.yaml | 29 +++++++++------------ 2 files changed, 18 insertions(+), 29 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 61c8b58bcd..7b294c88ca 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -65,6 +65,10 @@ kperf runner run \\ steps.Bash { bash = """ set -euo pipefail +if [ ! -s "$(KUBECONFIG)" ]; then + echo "Skipping namespace deletion for ${rate}/sec: kubeconfig is missing or empty: $(KUBECONFIG)" + exit 0 +fi kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r${rate}" \\ --ignore-not-found=true \\ --wait=false @@ -124,23 +128,13 @@ output = ap.Pipeline { "$(RESOURCE_GROUP)", LOCATION, SUBSCRIPTION_ID), - azure.AzCli( - const.DEFAULT_SERVICE_CONNECTION, - "Create benchmark Prometheus workspace", - """ -az monitor account create \\ - --subscription "${SUBSCRIPTION_ID}" \\ - --resource-group "$(RESOURCE_GROUP)" \\ - --name wi-benchmark-prometheus \\ - --location "${LOCATION}" -"""), azure.AzCli( const.DEFAULT_SERVICE_CONNECTION, "Create H2 cluster with OIDC and workload identity", """ az extension add \\ --name aks-preview \\ - --version 20.0.0b6 \\ + --version 21.0.0b17 \\ --allow-preview true \\ --yes az aks create \\ @@ -154,8 +148,6 @@ az aks create \\ --control-plane-scaling-size H2 \\ --enable-oidc-issuer \\ --enable-workload-identity \\ - --enable-azure-monitor-metrics \\ - --azure-monitor-workspace-resource-id "/subscriptions/${SUBSCRIPTION_ID}/resourceGroups/$(RESOURCE_GROUP)/providers/Microsoft.Monitor/accounts/wi-benchmark-prometheus" \\ --generate-ssh-keys \\ --nodepool-name systempool \\ --node-count 3 \\ diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index cb43396133..5ec1f7f6f9 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -42,19 +42,6 @@ jobs: --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ displayName: Create resource group in westus2 (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) - - task: AzureCLI@2 - inputs: - azureSubscription: Azure-for-Telescope-internal - scriptType: bash - scriptLocation: inlineScript - inlineScript: | - set -exo pipefail - az monitor account create \ - --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --resource-group "$(RESOURCE_GROUP)" \ - --name wi-benchmark-prometheus \ - --location "westus2" - displayName: Create benchmark Prometheus workspace - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -64,7 +51,7 @@ jobs: set -exo pipefail az extension add \ --name aks-preview \ - --version 20.0.0b6 \ + --version 21.0.0b17 \ --allow-preview true \ --yes az aks create \ @@ -78,8 +65,6 @@ jobs: --control-plane-scaling-size H2 \ --enable-oidc-issuer \ --enable-workload-identity \ - --enable-azure-monitor-metrics \ - --azure-monitor-workspace-resource-id "/subscriptions/b8ceb4e5-f05b-4562-a9f5-14acb1f24219/resourceGroups/$(RESOURCE_GROUP)/providers/Microsoft.Monitor/accounts/wi-benchmark-prometheus" \ --generate-ssh-keys \ --nodepool-name systempool \ --node-count 3 \ @@ -176,6 +161,10 @@ jobs: timeoutInMinutes: 15 - bash: | set -euo pipefail + if [ ! -s "$(KUBECONFIG)" ]; then + echo "Skipping namespace deletion for 50/sec: kubeconfig is missing or empty: $(KUBECONFIG)" + exit 0 + fi kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r50" \ --ignore-not-found=true \ --wait=false @@ -231,6 +220,10 @@ jobs: timeoutInMinutes: 15 - bash: | set -euo pipefail + if [ ! -s "$(KUBECONFIG)" ]; then + echo "Skipping namespace deletion for 100/sec: kubeconfig is missing or empty: $(KUBECONFIG)" + exit 0 + fi kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r100" \ --ignore-not-found=true \ --wait=false @@ -286,6 +279,10 @@ jobs: timeoutInMinutes: 15 - bash: | set -euo pipefail + if [ ! -s "$(KUBECONFIG)" ]; then + echo "Skipping namespace deletion for 150/sec: kubeconfig is missing or empty: $(KUBECONFIG)" + exit 0 + fi kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r150" \ --ignore-not-found=true \ --wait=false From bdd7a1c431b7ea34a0120b0b8e7dded03fd89a60 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Tue, 3 Nov 2026 23:35:07 +1000 Subject: [PATCH 14/24] Minor change --- kcl/workload_identity_webhook/pipeline.k | 6 +++--- kcl/workload_identity_webhook/pipeline.yaml | 6 +++--- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 7b294c88ca..960ffc8b17 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -11,7 +11,7 @@ SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" LOCATION = "westus2" # TODO: Replace the user-selected PR image with a published upstream release. RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" -RATES = [50, 100, 150] +POD_CREATE_RPS = [50, 100, 150] BenchmarkSteps = lambda rate: int -> [steps.Step] { [ @@ -85,7 +85,7 @@ echo "Starting five-minute pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT sleep 300 echo "Finished pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ - displayName = "Pause 5 minutes after ${rate}/sec" + displayName = "Pause 5 minutes after kperf run" condition = "always()" timeoutInMinutes = 6 }, @@ -181,7 +181,7 @@ az aks create \\ file="$(KUBECONFIG)"), kperf.InstallRunkperf(RUNNER_IMAGE), common.RecordCurrentTime("BENCHMARK_START_TIME"), - *[step for rate in RATES for step in BenchmarkSteps(rate)], + *[step for rate in POD_CREATE_RPS for step in BenchmarkSteps(rate)], asi_dashboard.PrintAsiDashboardUrl( const.DEFAULT_SERVICE_CONNECTION, "$(CLUSTER)", diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 5ec1f7f6f9..9222b795ed 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -178,7 +178,7 @@ jobs: sleep 300 echo "Finished pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: always() - displayName: Pause 5 minutes after 50/sec + displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | set -euo pipefail @@ -237,7 +237,7 @@ jobs: sleep 300 echo "Finished pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: always() - displayName: Pause 5 minutes after 100/sec + displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | set -euo pipefail @@ -296,7 +296,7 @@ jobs: sleep 300 echo "Finished pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: always() - displayName: Pause 5 minutes after 150/sec + displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - task: AzureCLI@2 inputs: From 60535714bde59d46cdecaa5b5aae5ec29147a4f2 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Wed, 4 Nov 2026 11:03:21 +1000 Subject: [PATCH 15/24] Wait for WI benchmark namespace cleanup without blocking on failure Wait up to ten minutes for namespace deletion, preserve the five-minute recovery pause, and mark cleanup failures as non-blocking. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/pipeline.k | 6 ++++-- kcl/workload_identity_webhook/pipeline.yaml | 18 ++++++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 960ffc8b17..ac5ac30662 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -71,11 +71,13 @@ if [ ! -s "$(KUBECONFIG)" ]; then fi kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r${rate}" \\ --ignore-not-found=true \\ - --wait=false -echo "Namespace deletion requested for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + --wait=true \\ + --timeout=10m +echo "Namespace cleanup completed for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ displayName = "Delete namespace from ${rate}/sec run" condition = "always()" + continueOnError = True timeoutInMinutes = 15 }, steps.Bash { diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 9222b795ed..5cc1015f4e 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -167,9 +167,11 @@ jobs: fi kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r50" \ --ignore-not-found=true \ - --wait=false - echo "Namespace deletion requested for 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + --wait=true \ + --timeout=10m + echo "Namespace cleanup completed for 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: always() + continueOnError: true displayName: Delete namespace from 50/sec run timeoutInMinutes: 15 - bash: | @@ -226,9 +228,11 @@ jobs: fi kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r100" \ --ignore-not-found=true \ - --wait=false - echo "Namespace deletion requested for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + --wait=true \ + --timeout=10m + echo "Namespace cleanup completed for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: always() + continueOnError: true displayName: Delete namespace from 100/sec run timeoutInMinutes: 15 - bash: | @@ -285,9 +289,11 @@ jobs: fi kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r150" \ --ignore-not-found=true \ - --wait=false - echo "Namespace deletion requested for 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + --wait=true \ + --timeout=10m + echo "Namespace cleanup completed for 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: always() + continueOnError: true displayName: Delete namespace from 150/sec run timeoutInMinutes: 15 - bash: | From 8e8bcd15aca3359bcd5dff523053f4011340596d Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Wed, 4 Nov 2026 12:28:03 +1000 Subject: [PATCH 16/24] Remove unused user pool from WI webhook benchmark Keep the three-node system pool for the admission-only workload and regenerate pipeline YAML. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/pipeline.k | 10 ---------- kcl/workload_identity_webhook/pipeline.yaml | 7 ------- 2 files changed, 17 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index ac5ac30662..03dd19227a 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -165,16 +165,6 @@ az aks create \\ --tags SkipAKSCluster=true \\ --yes """), - azure.CreateNodePool( - const.DEFAULT_SERVICE_CONNECTION, - "$(CLUSTER)", - "$(RESOURCE_GROUP)", - SUBSCRIPTION_ID, - azure.NodePool { - name = "workerpool" - sku = "Standard_D2s_v5" - count = 3 - }), azure.GetCredentials( const.DEFAULT_SERVICE_CONNECTION, "$(CLUSTER)", diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 5cc1015f4e..bc13dfcb5f 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -80,13 +80,6 @@ jobs: --tags SkipAKSCluster=true \ --yes displayName: Create H2 cluster with OIDC and workload identity - - task: AzureCLI@2 - inputs: - azureSubscription: Azure-for-Telescope-internal - scriptType: bash - scriptLocation: inlineScript - inlineScript: "set -exo pipefail\ncreate_node_pool() {\n local deadline sleep_between=30 attempt=0 output rc now remaining_retry_seconds\n deadline=$(($(date +%s) + 600))\n while :; do\n attempt=$((attempt + 1))\n if output=$(az aks nodepool add \"$@\" 2>&1); then\n rc=0\n else\n rc=$?\n fi\n echo \"$output\"\n if [ \"$rc\" -eq 0 ]; then\n return 0\n fi\n if echo \"$output\" | grep -qiE \"OperationNotAllowed\"; then\n now=$(date +%s)\n if [ \"$now\" -ge \"$deadline\" ]; then\n echo \"Retriable error persisted past 600s retry window ($attempt attempts); giving up.\"\n return \"$rc\"\n fi\n remaining_retry_seconds=$((deadline - now))\n echo \"Attempt $attempt matched retriable pattern; retrying in $sleep_between seconds ($remaining_retry_seconds seconds remain in retry window).\"\n sleep \"$sleep_between\"\n else\n echo \"Non-retriable error (rc=$rc); giving up after attempt $attempt.\"\n return \"$rc\"\n fi\n done\n}\n\n\ncreate_node_pool \\\n --cluster-name \"$(CLUSTER)\" \\\n --resource-group \"$(RESOURCE_GROUP)\" \\\n --subscription \"b8ceb4e5-f05b-4562-a9f5-14acb1f24219\" \\\n --name \"workerpool\" \\\n --node-count 3 \\\n --node-vm-size \"Standard_D2s_v5\" \\\n --mode User \\\n \n" - displayName: Create node pool workerpool - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal From e124911f6914981574e44ecc24234b328cea799e Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Thu, 5 Nov 2026 10:42:22 +1000 Subject: [PATCH 17/24] Address review comments Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../load-profile.yaml | 2 - kcl/workload_identity_webhook/pipeline.k | 35 +++----- kcl/workload_identity_webhook/pipeline.yaml | 85 +++++++------------ 3 files changed, 40 insertions(+), 82 deletions(-) diff --git a/kcl/workload_identity_webhook/load-profile.yaml b/kcl/workload_identity_webhook/load-profile.yaml index 4dde6cc861..aade83099d 100644 --- a/kcl/workload_identity_webhook/load-profile.yaml +++ b/kcl/workload_identity_webhook/load-profile.yaml @@ -16,8 +16,6 @@ specs: resource: pods namespace: "__RUN_NAMESPACE__" deleteRatio: 0 - # PAYLOAD environment padding, not the complete submitted JSON size. - payloadSize: 3650 pod: labels: azure.workload.identity/use: "true" diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 03dd19227a..6b5b492601 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -8,22 +8,17 @@ import lib.steps.kperf import lib.util.asi_dashboard SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" -LOCATION = "westus2" +LOCATION = "australiaeast" # TODO: Replace the user-selected PR image with a published upstream release. RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" -POD_CREATE_RPS = [50, 100, 150] +RATES = [50, 100, 150] -BenchmarkSteps = lambda rate: int -> [steps.Step] { +RunBenchmark = lambda rate: int -> [steps.Step] { [ steps.Bash { bash = """ set -euo pipefail namespace="$(RUN_ID)-r${rate}" -deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') -if [ -n "$deleting" ]; then - echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 - exit 1 -fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. @@ -56,8 +51,7 @@ set -euo pipefail set -x kperf runner run \\ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" \\ - --kubeconfig "$(KUBECONFIG)" + --config "$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" """ displayName = "Run kperf at ${rate} CREATEs/sec" timeoutInMinutes = 15 @@ -65,18 +59,13 @@ kperf runner run \\ steps.Bash { bash = """ set -euo pipefail -if [ ! -s "$(KUBECONFIG)" ]; then - echo "Skipping namespace deletion for ${rate}/sec: kubeconfig is missing or empty: $(KUBECONFIG)" - exit 0 -fi -kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r${rate}" \\ +kubectl delete namespace "$(RUN_ID)-r${rate}" \\ --ignore-not-found=true \\ - --wait=true \\ - --timeout=10m + --wait=true echo "Namespace cleanup completed for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ displayName = "Delete namespace from ${rate}/sec run" - condition = "always()" + condition = "not(canceled())" continueOnError = True timeoutInMinutes = 15 }, @@ -88,7 +77,7 @@ sleep 300 echo "Finished pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ displayName = "Pause 5 minutes after kperf run" - condition = "always()" + condition = "not(canceled())" timeoutInMinutes = 6 }, ] @@ -115,12 +104,11 @@ output = ap.Pipeline { # Allow bounded cleanup and recovery during cancellation. cancelTimeoutInMinutes = 25 variables = { - RUN_ID = "wi-$(Build.BuildId)-$(System.JobAttempt)" RESOURCE_GROUP = "$(RUN_ID)" CLUSTER = "wi-webhook" - KUBECONFIG = "$(Agent.TempDirectory)/$(RUN_ID).kubeconfig" } steps = [ + common.SetRunId(), azure.Login( const.DEFAULT_SERVICE_CONNECTION, SUBSCRIPTION_ID, @@ -169,11 +157,10 @@ az aks create \\ const.DEFAULT_SERVICE_CONNECTION, "$(CLUSTER)", "$(RESOURCE_GROUP)", - SUBSCRIPTION_ID, - file="$(KUBECONFIG)"), + SUBSCRIPTION_ID), kperf.InstallRunkperf(RUNNER_IMAGE), common.RecordCurrentTime("BENCHMARK_START_TIME"), - *[step for rate in POD_CREATE_RPS for step in BenchmarkSteps(rate)], + *[step for rate in RATES for step in RunBenchmark(rate)], asi_dashboard.PrintAsiDashboardUrl( const.DEFAULT_SERVICE_CONNECTION, "$(CLUSTER)", diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index bc13dfcb5f..2f8e3d822f 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -13,11 +13,18 @@ jobs: timeoutInMinutes: 240 cancelTimeoutInMinutes: 25 variables: - RUN_ID: wi-$(Build.BuildId)-$(System.JobAttempt) RESOURCE_GROUP: $(RUN_ID) CLUSTER: wi-webhook - KUBECONFIG: $(Agent.TempDirectory)/$(RUN_ID).kubeconfig steps: + - bash: | + set -eo pipefail + + job_id="$(System.JobId)" + RUN_ID=$(Build.BuildId)-${job_id:0:8} + echo "Run ID: $RUN_ID" + + echo "##vso[task.setvariable variable=RUN_ID]$RUN_ID" + displayName: Set Run ID - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -26,7 +33,7 @@ jobs: inlineScript: | set -exo pipefail az account set --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" - az config set defaults.location="westus2" + az config set defaults.location="australiaeast" az account show displayName: Login to Azure - task: AzureCLI@2 @@ -38,10 +45,10 @@ jobs: set -exo pipefail az group create \ --name "$(RESOURCE_GROUP)" \ - --location "westus2" \ + --location "australiaeast" \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - displayName: Create resource group in westus2 (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) + displayName: Create resource group in australiaeast (b8ceb4e5-f05b-4562-a9f5-14acb1f24219) - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -58,7 +65,7 @@ jobs: --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ --resource-group "$(RESOURCE_GROUP)" \ --name "$(CLUSTER)" \ - --location "westus2" \ + --location "australiaeast" \ --kubernetes-version "1.36" \ --dns-name-prefix "$(RUN_ID)" \ --tier standard \ @@ -91,8 +98,7 @@ jobs: --name "$(CLUSTER)" \ --resource-group "$(RESOURCE_GROUP)" \ --subscription "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" \ - --overwrite-existing \ - -f $(KUBECONFIG) + --overwrite-existing displayName: Get credentials for $(CLUSTER) - script: | set -euo pipefail @@ -117,11 +123,6 @@ jobs: - bash: | set -euo pipefail namespace="$(RUN_ID)-r50" - deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') - if [ -n "$deleting" ]; then - echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 - exit 1 - fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. @@ -148,22 +149,16 @@ jobs: set -x kperf runner run \ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml" \ - --kubeconfig "$(KUBECONFIG)" + --config "$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml" displayName: Run kperf at 50 CREATEs/sec timeoutInMinutes: 15 - bash: | set -euo pipefail - if [ ! -s "$(KUBECONFIG)" ]; then - echo "Skipping namespace deletion for 50/sec: kubeconfig is missing or empty: $(KUBECONFIG)" - exit 0 - fi - kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r50" \ + kubectl delete namespace "$(RUN_ID)-r50" \ --ignore-not-found=true \ - --wait=true \ - --timeout=10m + --wait=true echo "Namespace cleanup completed for 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: always() + condition: not(canceled()) continueOnError: true displayName: Delete namespace from 50/sec run timeoutInMinutes: 15 @@ -172,17 +167,12 @@ jobs: echo "Starting five-minute pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: always() + condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | set -euo pipefail namespace="$(RUN_ID)-r100" - deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') - if [ -n "$deleting" ]; then - echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 - exit 1 - fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. @@ -209,22 +199,16 @@ jobs: set -x kperf runner run \ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r100-load-profile.yaml" \ - --kubeconfig "$(KUBECONFIG)" + --config "$(Agent.TempDirectory)/$(RUN_ID)-r100-load-profile.yaml" displayName: Run kperf at 100 CREATEs/sec timeoutInMinutes: 15 - bash: | set -euo pipefail - if [ ! -s "$(KUBECONFIG)" ]; then - echo "Skipping namespace deletion for 100/sec: kubeconfig is missing or empty: $(KUBECONFIG)" - exit 0 - fi - kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r100" \ + kubectl delete namespace "$(RUN_ID)-r100" \ --ignore-not-found=true \ - --wait=true \ - --timeout=10m + --wait=true echo "Namespace cleanup completed for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: always() + condition: not(canceled()) continueOnError: true displayName: Delete namespace from 100/sec run timeoutInMinutes: 15 @@ -233,17 +217,12 @@ jobs: echo "Starting five-minute pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: always() + condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | set -euo pipefail namespace="$(RUN_ID)-r150" - deleting=$(kubectl --request-timeout=60s get namespace "$namespace" --ignore-not-found -o jsonpath='{.metadata.deletionTimestamp}') - if [ -n "$deleting" ]; then - echo "Namespace $namespace is already terminating; cannot prepare this phase." >&2 - exit 1 - fi kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. @@ -270,22 +249,16 @@ jobs: set -x kperf runner run \ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r150-load-profile.yaml" \ - --kubeconfig "$(KUBECONFIG)" + --config "$(Agent.TempDirectory)/$(RUN_ID)-r150-load-profile.yaml" displayName: Run kperf at 150 CREATEs/sec timeoutInMinutes: 15 - bash: | set -euo pipefail - if [ ! -s "$(KUBECONFIG)" ]; then - echo "Skipping namespace deletion for 150/sec: kubeconfig is missing or empty: $(KUBECONFIG)" - exit 0 - fi - kubectl --request-timeout=60s delete namespace "$(RUN_ID)-r150" \ + kubectl delete namespace "$(RUN_ID)-r150" \ --ignore-not-found=true \ - --wait=true \ - --timeout=10m + --wait=true echo "Namespace cleanup completed for 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: always() + condition: not(canceled()) continueOnError: true displayName: Delete namespace from 150/sec run timeoutInMinutes: 15 @@ -294,7 +267,7 @@ jobs: echo "Starting five-minute pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: always() + condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - task: AzureCLI@2 From e03fe089fe3e0482c151a80520898591971d7084 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Thu, 5 Nov 2026 11:02:04 +1000 Subject: [PATCH 18/24] Use runner groups for WI webhook benchmark Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/lib/steps/kperf/run_benchmark.k | 4 +- .../load-profile.yaml | 24 --- kcl/workload_identity_webhook/pipeline.k | 34 ++-- kcl/workload_identity_webhook/pipeline.yaml | 169 +++++++++++++++--- .../runner-group.yaml | 27 +++ 5 files changed, 200 insertions(+), 58 deletions(-) delete mode 100644 kcl/workload_identity_webhook/load-profile.yaml create mode 100644 kcl/workload_identity_webhook/runner-group.yaml diff --git a/kcl/lib/steps/kperf/run_benchmark.k b/kcl/lib/steps/kperf/run_benchmark.k index d98d854e04..ba28746057 100644 --- a/kcl/lib/steps/kperf/run_benchmark.k +++ b/kcl/lib/steps/kperf/run_benchmark.k @@ -49,7 +49,7 @@ done # RunKperfRunnerGroup runs `kperf rg run` with the specified runner image, runner # group manifest, optional flow control setting, and optional affinity selector. -RunKperfRunnerGroup = lambda runnerImage: str, runnerGroup: str, flowcontrol: str = "", affinity: str = "", target: str = Undefined -> steps.Step { +RunKperfRunnerGroup = lambda runnerImage: str, runnerGroup: str, flowcontrol: str = "", affinity: str = "", target: str = Undefined, displayName: str = "Run kperf runner group" -> steps.Step { steps.Script { script = """ set -euo pipefail @@ -94,7 +94,7 @@ until run_rg; do sleep 120 done """ - displayName = "Run kperf runner group" + displayName = displayName target = target } } diff --git a/kcl/workload_identity_webhook/load-profile.yaml b/kcl/workload_identity_webhook/load-profile.yaml deleted file mode 100644 index aade83099d..0000000000 --- a/kcl/workload_identity_webhook/load-profile.yaml +++ /dev/null @@ -1,24 +0,0 @@ -version: 1 -description: WI Pod CREATE exploratory benchmark - __RATE__ creates/sec for 10 minutes -specs: - - rate: __RATE__ - duration: 600 - total: 0 - client: 600 - conns: 20 - contentType: json - maxRetries: 0 - requests: - - shares: 1 - postDel: - group: "" - version: v1 - resource: pods - namespace: "__RUN_NAMESPACE__" - deleteRatio: 0 - pod: - labels: - azure.workload.identity/use: "true" - benchmark-run: "__PHASE_RUN_ID__" - serviceAccountName: pod-benchmark - schedulerName: kperf-admission-only diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 6b5b492601..f27543ec36 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -32,28 +32,30 @@ kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \\ steps.Bash { bash = """ set -euo pipefail -profile="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" +profile="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-runner-group.yaml" sed \\ -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r${rate}/g' \\ -e 's/__RATE__/${rate}/g' \\ -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r${rate}/g' \\ - "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then - echo "Unresolved load-profile placeholders" >&2 + echo "Unresolved runner-group placeholders" >&2 exit 1 fi """ - displayName = "Prepare ${rate}/sec load profile" + displayName = "Prepare ${rate}/sec runner group" }, - steps.Script { - script = """ + kperf.RunKperfRunnerGroup( + RUNNER_IMAGE, + "file://$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-runner-group.yaml", + affinity="agentpool=runner", + displayName="Run kperf runner group at ${rate} CREATEs/sec"), + steps.Bash { + bash = """ set -euo pipefail -set -x - -kperf runner run \\ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-load-profile.yaml" +kperf rg result --wait --timeout=15m """ - displayName = "Run kperf at ${rate} CREATEs/sec" + displayName = "Wait for ${rate}/sec runner group result" timeoutInMinutes = 15 }, steps.Bash { @@ -153,6 +155,16 @@ az aks create \\ --tags SkipAKSCluster=true \\ --yes """), + azure.CreateNodePool( + const.DEFAULT_SERVICE_CONNECTION, + "$(CLUSTER)", + "$(RESOURCE_GROUP)", + SUBSCRIPTION_ID, + azure.NodePool { + name = "runner" + sku = "Standard_D4s_v5" + count = 1 + }), azure.GetCredentials( const.DEFAULT_SERVICE_CONNECTION, "$(CLUSTER)", diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 2f8e3d822f..6141b4af4b 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -87,6 +87,13 @@ jobs: --tags SkipAKSCluster=true \ --yes displayName: Create H2 cluster with OIDC and workload identity + - task: AzureCLI@2 + inputs: + azureSubscription: Azure-for-Telescope-internal + scriptType: bash + scriptLocation: inlineScript + inlineScript: "set -exo pipefail\ncreate_node_pool() {\n local deadline sleep_between=30 attempt=0 output rc now remaining_retry_seconds\n deadline=$(($(date +%s) + 600))\n while :; do\n attempt=$((attempt + 1))\n if output=$(az aks nodepool add \"$@\" 2>&1); then\n rc=0\n else\n rc=$?\n fi\n echo \"$output\"\n if [ \"$rc\" -eq 0 ]; then\n return 0\n fi\n if echo \"$output\" | grep -qiE \"OperationNotAllowed\"; then\n now=$(date +%s)\n if [ \"$now\" -ge \"$deadline\" ]; then\n echo \"Retriable error persisted past 600s retry window ($attempt attempts); giving up.\"\n return \"$rc\"\n fi\n remaining_retry_seconds=$((deadline - now))\n echo \"Attempt $attempt matched retriable pattern; retrying in $sleep_between seconds ($remaining_retry_seconds seconds remain in retry window).\"\n sleep \"$sleep_between\"\n else\n echo \"Non-retriable error (rc=$rc); giving up after attempt $attempt.\"\n return \"$rc\"\n fi\n done\n}\n\n\ncreate_node_pool \\\n --cluster-name \"$(CLUSTER)\" \\\n --resource-group \"$(RESOURCE_GROUP)\" \\\n --subscription \"b8ceb4e5-f05b-4562-a9f5-14acb1f24219\" \\\n --name \"runner\" \\\n --node-count 1 \\\n --node-vm-size \"Standard_D4s_v5\" \\\n --mode User \\\n \n" + displayName: Create node pool runner - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal @@ -133,24 +140,64 @@ jobs: displayName: Prepare WI resources for 50/sec - bash: | set -euo pipefail - profile="$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml" + profile="$(Agent.TempDirectory)/$(RUN_ID)-r50-runner-group.yaml" sed \ -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r50/g' \ -e 's/__RATE__/50/g' \ -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r50/g' \ - "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then - echo "Unresolved load-profile placeholders" >&2 + echo "Unresolved runner-group placeholders" >&2 exit 1 fi - displayName: Prepare 50/sec load profile + displayName: Prepare 50/sec runner group - script: | set -euo pipefail set -x - kperf runner run \ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r50-load-profile.yaml" - displayName: Run kperf at 50 CREATEs/sec + run_rg() { + args=( + rg run + --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" + --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r50-runner-group.yaml" + ) + if [ -n "" ]; then + args+=(--runner-flowcontrol="") + fi + if [ -n "agentpool=runner" ]; then + args+=(--affinity="agentpool=runner") + fi + kperf "${args[@]}" + } + + cleanup_rg() { + kperf rg delete || true + kubectl -n runnergroups-kperf-io delete pod runnergroup-server \ + --force --grace-period=0 --ignore-not-found=true --timeout=120s || true + } + + cleanup_rg + + attempt=0 + max_attempts=10 + until run_rg; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + echo "kperf rg run failed after $attempt attempts" >&2 + kubectl -n runnergroups-kperf-io get pods -o wide || true + kubectl -n runnergroups-kperf-io describe pod runnergroup-server || true + kubectl -n runnergroups-kperf-io get events --sort-by=.lastTimestamp | tail -50 || true + exit 1 + fi + cleanup_rg + echo "attempt $attempt failed; cleaning up and retrying in 120s" >&2 + sleep 120 + done + displayName: Run kperf runner group at 50 CREATEs/sec + - bash: | + set -euo pipefail + kperf rg result --wait --timeout=15m + displayName: Wait for 50/sec runner group result timeoutInMinutes: 15 - bash: | set -euo pipefail @@ -183,24 +230,64 @@ jobs: displayName: Prepare WI resources for 100/sec - bash: | set -euo pipefail - profile="$(Agent.TempDirectory)/$(RUN_ID)-r100-load-profile.yaml" + profile="$(Agent.TempDirectory)/$(RUN_ID)-r100-runner-group.yaml" sed \ -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r100/g' \ -e 's/__RATE__/100/g' \ -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r100/g' \ - "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then - echo "Unresolved load-profile placeholders" >&2 + echo "Unresolved runner-group placeholders" >&2 exit 1 fi - displayName: Prepare 100/sec load profile + displayName: Prepare 100/sec runner group - script: | set -euo pipefail set -x - kperf runner run \ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r100-load-profile.yaml" - displayName: Run kperf at 100 CREATEs/sec + run_rg() { + args=( + rg run + --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" + --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r100-runner-group.yaml" + ) + if [ -n "" ]; then + args+=(--runner-flowcontrol="") + fi + if [ -n "agentpool=runner" ]; then + args+=(--affinity="agentpool=runner") + fi + kperf "${args[@]}" + } + + cleanup_rg() { + kperf rg delete || true + kubectl -n runnergroups-kperf-io delete pod runnergroup-server \ + --force --grace-period=0 --ignore-not-found=true --timeout=120s || true + } + + cleanup_rg + + attempt=0 + max_attempts=10 + until run_rg; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + echo "kperf rg run failed after $attempt attempts" >&2 + kubectl -n runnergroups-kperf-io get pods -o wide || true + kubectl -n runnergroups-kperf-io describe pod runnergroup-server || true + kubectl -n runnergroups-kperf-io get events --sort-by=.lastTimestamp | tail -50 || true + exit 1 + fi + cleanup_rg + echo "attempt $attempt failed; cleaning up and retrying in 120s" >&2 + sleep 120 + done + displayName: Run kperf runner group at 100 CREATEs/sec + - bash: | + set -euo pipefail + kperf rg result --wait --timeout=15m + displayName: Wait for 100/sec runner group result timeoutInMinutes: 15 - bash: | set -euo pipefail @@ -233,24 +320,64 @@ jobs: displayName: Prepare WI resources for 150/sec - bash: | set -euo pipefail - profile="$(Agent.TempDirectory)/$(RUN_ID)-r150-load-profile.yaml" + profile="$(Agent.TempDirectory)/$(RUN_ID)-r150-runner-group.yaml" sed \ -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r150/g' \ -e 's/__RATE__/150/g' \ -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r150/g' \ - "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/load-profile.yaml" > "$profile" + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then - echo "Unresolved load-profile placeholders" >&2 + echo "Unresolved runner-group placeholders" >&2 exit 1 fi - displayName: Prepare 150/sec load profile + displayName: Prepare 150/sec runner group - script: | set -euo pipefail set -x - kperf runner run \ - --config "$(Agent.TempDirectory)/$(RUN_ID)-r150-load-profile.yaml" - displayName: Run kperf at 150 CREATEs/sec + run_rg() { + args=( + rg run + --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" + --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r150-runner-group.yaml" + ) + if [ -n "" ]; then + args+=(--runner-flowcontrol="") + fi + if [ -n "agentpool=runner" ]; then + args+=(--affinity="agentpool=runner") + fi + kperf "${args[@]}" + } + + cleanup_rg() { + kperf rg delete || true + kubectl -n runnergroups-kperf-io delete pod runnergroup-server \ + --force --grace-period=0 --ignore-not-found=true --timeout=120s || true + } + + cleanup_rg + + attempt=0 + max_attempts=10 + until run_rg; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + echo "kperf rg run failed after $attempt attempts" >&2 + kubectl -n runnergroups-kperf-io get pods -o wide || true + kubectl -n runnergroups-kperf-io describe pod runnergroup-server || true + kubectl -n runnergroups-kperf-io get events --sort-by=.lastTimestamp | tail -50 || true + exit 1 + fi + cleanup_rg + echo "attempt $attempt failed; cleaning up and retrying in 120s" >&2 + sleep 120 + done + displayName: Run kperf runner group at 150 CREATEs/sec + - bash: | + set -euo pipefail + kperf rg result --wait --timeout=15m + displayName: Wait for 150/sec runner group result timeoutInMinutes: 15 - bash: | set -euo pipefail diff --git a/kcl/workload_identity_webhook/runner-group.yaml b/kcl/workload_identity_webhook/runner-group.yaml new file mode 100644 index 0000000000..274ae0243a --- /dev/null +++ b/kcl/workload_identity_webhook/runner-group.yaml @@ -0,0 +1,27 @@ +# One runner keeps the profile rate equal to the phase's aggregate target. +count: 1 +loadProfile: + version: 1 + description: WI Pod CREATE exploratory benchmark - __RATE__ creates/sec for 10 minutes + specs: + - rate: __RATE__ + duration: 600 + total: 0 + client: 600 + conns: 20 + contentType: json + maxRetries: 0 + requests: + - shares: 1 + postDel: + group: "" + version: v1 + resource: pods + namespace: "__RUN_NAMESPACE__" + deleteRatio: 0 + pod: + labels: + azure.workload.identity/use: "true" + benchmark-run: "__PHASE_RUN_ID__" + serviceAccountName: pod-benchmark + schedulerName: kperf-admission-only From 63349c34743288ba71f7abcd75ba5845a6a01aae Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Thu, 5 Nov 2026 12:54:39 +1000 Subject: [PATCH 19/24] Add resilient runner-group result collection helper Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/pipeline.k | 11 ++---- kcl/workload_identity_webhook/pipeline.yaml | 39 +++++++++++++++++++-- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index f27543ec36..4a4306330a 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -50,14 +50,9 @@ fi "file://$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-runner-group.yaml", affinity="agentpool=runner", displayName="Run kperf runner group at ${rate} CREATEs/sec"), - steps.Bash { - bash = """ -set -euo pipefail -kperf rg result --wait --timeout=15m -""" - displayName = "Wait for ${rate}/sec runner group result" - timeoutInMinutes = 15 - }, + kperf.FetchKperfRunnerGroupResult( + resultPath="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-result.json", + displayName="Wait for ${rate}/sec runner group result"), steps.Bash { bash = """ set -euo pipefail diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 6141b4af4b..832000b5f0 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -196,7 +196,18 @@ jobs: displayName: Run kperf runner group at 50 CREATEs/sec - bash: | set -euo pipefail - kperf rg result --wait --timeout=15m + sleep 0 + attempt=0 + max_attempts=5 + until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r50-result.json"; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + exit 1 + fi + echo "attempt $attempt failed; retry in 10s" >&2 + sleep 10 + done + continueOnError: true displayName: Wait for 50/sec runner group result timeoutInMinutes: 15 - bash: | @@ -286,7 +297,18 @@ jobs: displayName: Run kperf runner group at 100 CREATEs/sec - bash: | set -euo pipefail - kperf rg result --wait --timeout=15m + sleep 0 + attempt=0 + max_attempts=5 + until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r100-result.json"; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + exit 1 + fi + echo "attempt $attempt failed; retry in 10s" >&2 + sleep 10 + done + continueOnError: true displayName: Wait for 100/sec runner group result timeoutInMinutes: 15 - bash: | @@ -376,7 +398,18 @@ jobs: displayName: Run kperf runner group at 150 CREATEs/sec - bash: | set -euo pipefail - kperf rg result --wait --timeout=15m + sleep 0 + attempt=0 + max_attempts=5 + until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r150-result.json"; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + exit 1 + fi + echo "attempt $attempt failed; retry in 10s" >&2 + sleep 10 + done + continueOnError: true displayName: Wait for 150/sec runner group result timeoutInMinutes: 15 - bash: | From f79e0b5a63a9524823170029b928d7d9b0906360 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Thu, 5 Nov 2026 16:02:05 +1000 Subject: [PATCH 20/24] Add 200 RPS phase to WI webhook benchmark Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/pipeline.k | 4 +- kcl/workload_identity_webhook/pipeline.yaml | 103 +++++++++++++++++++- 2 files changed, 104 insertions(+), 3 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 4a4306330a..c0dabad239 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -11,7 +11,7 @@ SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" LOCATION = "australiaeast" # TODO: Replace the user-selected PR image with a published upstream release. RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" -RATES = [50, 100, 150] +RATES = [50, 100, 150, 200] RunBenchmark = lambda rate: int -> [steps.Step] { [ @@ -96,7 +96,7 @@ output = ap.Pipeline { jobs = [ job.Job { job = "benchmark" - displayName = "Baseline Run: 50/100/150 RPS" + displayName = "Baseline Run: 50/100/150/200 RPS" timeoutInMinutes = 240 # Allow bounded cleanup and recovery during cancellation. cancelTimeoutInMinutes = 25 diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 832000b5f0..710039c1fb 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -9,7 +9,7 @@ parameters: pr: none jobs: - job: benchmark - displayName: 'Baseline Run: 50/100/150 RPS' + displayName: 'Baseline Run: 50/100/150/200 RPS' timeoutInMinutes: 240 cancelTimeoutInMinutes: 25 variables: @@ -430,6 +430,107 @@ jobs: condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 + - bash: | + set -euo pipefail + namespace="$(RUN_ID)-r200" + kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - + kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - + # Use a fake client ID because benchmark Pods do not access Azure resources. + kubectl --request-timeout=60s annotate serviceaccount pod-benchmark \ + --namespace "$namespace" \ + "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ + --overwrite + displayName: Prepare WI resources for 200/sec + - bash: | + set -euo pipefail + profile="$(Agent.TempDirectory)/$(RUN_ID)-r200-runner-group.yaml" + sed \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r200/g' \ + -e 's/__RATE__/200/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r200/g' \ + "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" + if grep -q '__[A-Z_]*__' "$profile"; then + echo "Unresolved runner-group placeholders" >&2 + exit 1 + fi + displayName: Prepare 200/sec runner group + - script: | + set -euo pipefail + set -x + + run_rg() { + args=( + rg run + --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" + --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r200-runner-group.yaml" + ) + if [ -n "" ]; then + args+=(--runner-flowcontrol="") + fi + if [ -n "agentpool=runner" ]; then + args+=(--affinity="agentpool=runner") + fi + kperf "${args[@]}" + } + + cleanup_rg() { + kperf rg delete || true + kubectl -n runnergroups-kperf-io delete pod runnergroup-server \ + --force --grace-period=0 --ignore-not-found=true --timeout=120s || true + } + + cleanup_rg + + attempt=0 + max_attempts=10 + until run_rg; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + echo "kperf rg run failed after $attempt attempts" >&2 + kubectl -n runnergroups-kperf-io get pods -o wide || true + kubectl -n runnergroups-kperf-io describe pod runnergroup-server || true + kubectl -n runnergroups-kperf-io get events --sort-by=.lastTimestamp | tail -50 || true + exit 1 + fi + cleanup_rg + echo "attempt $attempt failed; cleaning up and retrying in 120s" >&2 + sleep 120 + done + displayName: Run kperf runner group at 200 CREATEs/sec + - bash: | + set -euo pipefail + attempt=0 + max_attempts=5 + until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r200-result.json"; do + attempt=$((attempt + 1)) + if [ "$attempt" -ge "$max_attempts" ]; then + echo "kperf runner group result retrieval or output write failed after $attempt attempts" >&2 + exit 1 + fi + echo "attempt $attempt failed; retry in 10s" >&2 + sleep 10 + done + continueOnError: true + displayName: Wait for 200/sec runner group result + timeoutInMinutes: 15 + - bash: | + set -euo pipefail + kubectl delete namespace "$(RUN_ID)-r200" \ + --ignore-not-found=true \ + --wait=true + echo "Namespace cleanup completed for 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: not(canceled()) + continueOnError: true + displayName: Delete namespace from 200/sec run + timeoutInMinutes: 15 + - bash: | + set -euo pipefail + echo "Starting five-minute pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + sleep 300 + echo "Finished pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + condition: not(canceled()) + displayName: Pause 5 minutes after kperf run + timeoutInMinutes: 6 - task: AzureCLI@2 inputs: azureSubscription: Azure-for-Telescope-internal From f822b3a1f7b883dc087fe62ab81a23487bb40344 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Thu, 5 Nov 2026 23:04:53 +1000 Subject: [PATCH 21/24] Update WI webhook benchmark rates to 100/150/200/250 RPS Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/pipeline.k | 4 +- kcl/workload_identity_webhook/pipeline.yaml | 132 ++++++++++---------- 2 files changed, 68 insertions(+), 68 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index c0dabad239..357d0b627c 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -11,7 +11,7 @@ SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" LOCATION = "australiaeast" # TODO: Replace the user-selected PR image with a published upstream release. RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" -RATES = [50, 100, 150, 200] +RATES = [100, 150, 200, 250] RunBenchmark = lambda rate: int -> [steps.Step] { [ @@ -96,7 +96,7 @@ output = ap.Pipeline { jobs = [ job.Job { job = "benchmark" - displayName = "Baseline Run: 50/100/150/200 RPS" + displayName = "Baseline Run: 100/150/200/250 RPS" timeoutInMinutes = 240 # Allow bounded cleanup and recovery during cancellation. cancelTimeoutInMinutes = 25 diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 710039c1fb..c569283eda 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -9,7 +9,7 @@ parameters: pr: none jobs: - job: benchmark - displayName: 'Baseline Run: 50/100/150/200 RPS' + displayName: 'Baseline Run: 100/150/200/250 RPS' timeoutInMinutes: 240 cancelTimeoutInMinutes: 25 variables: @@ -129,7 +129,7 @@ jobs: displayName: Record current time as BENCHMARK_START_TIME - bash: | set -euo pipefail - namespace="$(RUN_ID)-r50" + namespace="$(RUN_ID)-r100" kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. @@ -137,20 +137,20 @@ jobs: --namespace "$namespace" \ "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ --overwrite - displayName: Prepare WI resources for 50/sec + displayName: Prepare WI resources for 100/sec - bash: | set -euo pipefail - profile="$(Agent.TempDirectory)/$(RUN_ID)-r50-runner-group.yaml" + profile="$(Agent.TempDirectory)/$(RUN_ID)-r100-runner-group.yaml" sed \ - -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r50/g' \ - -e 's/__RATE__/50/g' \ - -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r50/g' \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r100/g' \ + -e 's/__RATE__/100/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r100/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved runner-group placeholders" >&2 exit 1 fi - displayName: Prepare 50/sec runner group + displayName: Prepare 100/sec runner group - script: | set -euo pipefail set -x @@ -159,7 +159,7 @@ jobs: args=( rg run --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" - --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r50-runner-group.yaml" + --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r100-runner-group.yaml" ) if [ -n "" ]; then args+=(--runner-flowcontrol="") @@ -193,13 +193,13 @@ jobs: echo "attempt $attempt failed; cleaning up and retrying in 120s" >&2 sleep 120 done - displayName: Run kperf runner group at 50 CREATEs/sec + displayName: Run kperf runner group at 100 CREATEs/sec - bash: | set -euo pipefail sleep 0 attempt=0 max_attempts=5 - until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r50-result.json"; do + until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r100-result.json"; do attempt=$((attempt + 1)) if [ "$attempt" -ge "$max_attempts" ]; then exit 1 @@ -208,29 +208,29 @@ jobs: sleep 10 done continueOnError: true - displayName: Wait for 50/sec runner group result + displayName: Wait for 100/sec runner group result timeoutInMinutes: 15 - bash: | set -euo pipefail - kubectl delete namespace "$(RUN_ID)-r50" \ + kubectl delete namespace "$(RUN_ID)-r100" \ --ignore-not-found=true \ --wait=true - echo "Namespace cleanup completed for 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Namespace cleanup completed for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: not(canceled()) continueOnError: true - displayName: Delete namespace from 50/sec run + displayName: Delete namespace from 100/sec run timeoutInMinutes: 15 - bash: | set -euo pipefail - echo "Starting five-minute pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Starting five-minute pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 - echo "Finished pause after 50/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Finished pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | set -euo pipefail - namespace="$(RUN_ID)-r100" + namespace="$(RUN_ID)-r150" kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. @@ -238,20 +238,20 @@ jobs: --namespace "$namespace" \ "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ --overwrite - displayName: Prepare WI resources for 100/sec + displayName: Prepare WI resources for 150/sec - bash: | set -euo pipefail - profile="$(Agent.TempDirectory)/$(RUN_ID)-r100-runner-group.yaml" + profile="$(Agent.TempDirectory)/$(RUN_ID)-r150-runner-group.yaml" sed \ - -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r100/g' \ - -e 's/__RATE__/100/g' \ - -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r100/g' \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r150/g' \ + -e 's/__RATE__/150/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r150/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved runner-group placeholders" >&2 exit 1 fi - displayName: Prepare 100/sec runner group + displayName: Prepare 150/sec runner group - script: | set -euo pipefail set -x @@ -260,7 +260,7 @@ jobs: args=( rg run --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" - --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r100-runner-group.yaml" + --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r150-runner-group.yaml" ) if [ -n "" ]; then args+=(--runner-flowcontrol="") @@ -294,13 +294,13 @@ jobs: echo "attempt $attempt failed; cleaning up and retrying in 120s" >&2 sleep 120 done - displayName: Run kperf runner group at 100 CREATEs/sec + displayName: Run kperf runner group at 150 CREATEs/sec - bash: | set -euo pipefail sleep 0 attempt=0 max_attempts=5 - until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r100-result.json"; do + until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r150-result.json"; do attempt=$((attempt + 1)) if [ "$attempt" -ge "$max_attempts" ]; then exit 1 @@ -309,29 +309,29 @@ jobs: sleep 10 done continueOnError: true - displayName: Wait for 100/sec runner group result + displayName: Wait for 150/sec runner group result timeoutInMinutes: 15 - bash: | set -euo pipefail - kubectl delete namespace "$(RUN_ID)-r100" \ + kubectl delete namespace "$(RUN_ID)-r150" \ --ignore-not-found=true \ --wait=true - echo "Namespace cleanup completed for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Namespace cleanup completed for 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: not(canceled()) continueOnError: true - displayName: Delete namespace from 100/sec run + displayName: Delete namespace from 150/sec run timeoutInMinutes: 15 - bash: | set -euo pipefail - echo "Starting five-minute pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Starting five-minute pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 - echo "Finished pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Finished pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | set -euo pipefail - namespace="$(RUN_ID)-r150" + namespace="$(RUN_ID)-r200" kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. @@ -339,20 +339,20 @@ jobs: --namespace "$namespace" \ "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ --overwrite - displayName: Prepare WI resources for 150/sec + displayName: Prepare WI resources for 200/sec - bash: | set -euo pipefail - profile="$(Agent.TempDirectory)/$(RUN_ID)-r150-runner-group.yaml" + profile="$(Agent.TempDirectory)/$(RUN_ID)-r200-runner-group.yaml" sed \ - -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r150/g' \ - -e 's/__RATE__/150/g' \ - -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r150/g' \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r200/g' \ + -e 's/__RATE__/200/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r200/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved runner-group placeholders" >&2 exit 1 fi - displayName: Prepare 150/sec runner group + displayName: Prepare 200/sec runner group - script: | set -euo pipefail set -x @@ -361,7 +361,7 @@ jobs: args=( rg run --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" - --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r150-runner-group.yaml" + --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r200-runner-group.yaml" ) if [ -n "" ]; then args+=(--runner-flowcontrol="") @@ -395,13 +395,13 @@ jobs: echo "attempt $attempt failed; cleaning up and retrying in 120s" >&2 sleep 120 done - displayName: Run kperf runner group at 150 CREATEs/sec + displayName: Run kperf runner group at 200 CREATEs/sec - bash: | set -euo pipefail sleep 0 attempt=0 max_attempts=5 - until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r150-result.json"; do + until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r200-result.json"; do attempt=$((attempt + 1)) if [ "$attempt" -ge "$max_attempts" ]; then exit 1 @@ -410,29 +410,29 @@ jobs: sleep 10 done continueOnError: true - displayName: Wait for 150/sec runner group result + displayName: Wait for 200/sec runner group result timeoutInMinutes: 15 - bash: | set -euo pipefail - kubectl delete namespace "$(RUN_ID)-r150" \ + kubectl delete namespace "$(RUN_ID)-r200" \ --ignore-not-found=true \ --wait=true - echo "Namespace cleanup completed for 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Namespace cleanup completed for 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: not(canceled()) continueOnError: true - displayName: Delete namespace from 150/sec run + displayName: Delete namespace from 200/sec run timeoutInMinutes: 15 - bash: | set -euo pipefail - echo "Starting five-minute pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Starting five-minute pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 - echo "Finished pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Finished pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | set -euo pipefail - namespace="$(RUN_ID)-r200" + namespace="$(RUN_ID)-r250" kubectl create namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - kubectl create serviceaccount pod-benchmark --namespace "$namespace" --dry-run=client -o yaml | kubectl --request-timeout=60s apply -f - # Use a fake client ID because benchmark Pods do not access Azure resources. @@ -440,20 +440,20 @@ jobs: --namespace "$namespace" \ "azure.workload.identity/client-id=00000000-0000-4000-8000-000000000001" \ --overwrite - displayName: Prepare WI resources for 200/sec + displayName: Prepare WI resources for 250/sec - bash: | set -euo pipefail - profile="$(Agent.TempDirectory)/$(RUN_ID)-r200-runner-group.yaml" + profile="$(Agent.TempDirectory)/$(RUN_ID)-r250-runner-group.yaml" sed \ - -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r200/g' \ - -e 's/__RATE__/200/g' \ - -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r200/g' \ + -e 's/__RUN_NAMESPACE__/$(RUN_ID)-r250/g' \ + -e 's/__RATE__/250/g' \ + -e 's/__PHASE_RUN_ID__/$(RUN_ID)-r250/g' \ "$(Build.SourcesDirectory)/kcl/workload_identity_webhook/runner-group.yaml" > "$profile" if grep -q '__[A-Z_]*__' "$profile"; then echo "Unresolved runner-group placeholders" >&2 exit 1 fi - displayName: Prepare 200/sec runner group + displayName: Prepare 250/sec runner group - script: | set -euo pipefail set -x @@ -462,7 +462,7 @@ jobs: args=( rg run --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" - --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r200-runner-group.yaml" + --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r250-runner-group.yaml" ) if [ -n "" ]; then args+=(--runner-flowcontrol="") @@ -496,38 +496,38 @@ jobs: echo "attempt $attempt failed; cleaning up and retrying in 120s" >&2 sleep 120 done - displayName: Run kperf runner group at 200 CREATEs/sec + displayName: Run kperf runner group at 250 CREATEs/sec - bash: | set -euo pipefail + sleep 0 attempt=0 max_attempts=5 - until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r200-result.json"; do + until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r250-result.json"; do attempt=$((attempt + 1)) if [ "$attempt" -ge "$max_attempts" ]; then - echo "kperf runner group result retrieval or output write failed after $attempt attempts" >&2 exit 1 fi echo "attempt $attempt failed; retry in 10s" >&2 sleep 10 done continueOnError: true - displayName: Wait for 200/sec runner group result + displayName: Wait for 250/sec runner group result timeoutInMinutes: 15 - bash: | set -euo pipefail - kubectl delete namespace "$(RUN_ID)-r200" \ + kubectl delete namespace "$(RUN_ID)-r250" \ --ignore-not-found=true \ --wait=true - echo "Namespace cleanup completed for 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Namespace cleanup completed for 250/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: not(canceled()) continueOnError: true - displayName: Delete namespace from 200/sec run + displayName: Delete namespace from 250/sec run timeoutInMinutes: 15 - bash: | set -euo pipefail - echo "Starting five-minute pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Starting five-minute pause after 250/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 - echo "Finished pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" + echo "Finished pause after 250/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 From 2b1436352a611e47baad6219e7630b91059da7b8 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Fri, 6 Nov 2026 13:35:41 +1000 Subject: [PATCH 22/24] Use official kperf 0.3.7 for WI benchmark Print runner-group results directly to ADO logs without writing result files. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/pipeline.k | 4 +--- kcl/workload_identity_webhook/pipeline.yaml | 24 ++++++++++----------- 2 files changed, 13 insertions(+), 15 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index 357d0b627c..ecd6a85191 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -9,8 +9,7 @@ import lib.util.asi_dashboard SUBSCRIPTION_ID = "b8ceb4e5-f05b-4562-a9f5-14acb1f24219" LOCATION = "australiaeast" -# TODO: Replace the user-selected PR image with a published upstream release. -RUNNER_IMAGE = "ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" +RUNNER_IMAGE = "ghcr.io/azure/kperf:0.3.7" RATES = [100, 150, 200, 250] RunBenchmark = lambda rate: int -> [steps.Step] { @@ -51,7 +50,6 @@ fi affinity="agentpool=runner", displayName="Run kperf runner group at ${rate} CREATEs/sec"), kperf.FetchKperfRunnerGroupResult( - resultPath="$(Agent.TempDirectory)/$(RUN_ID)-r${rate}-result.json", displayName="Wait for ${rate}/sec runner group result"), steps.Bash { bash = """ diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index c569283eda..1d4f7e3059 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -112,14 +112,14 @@ jobs: set -x temp_dir=$(mktemp -p /tmp -d kperfinstall.XXXX) - docker rmi ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 2>/dev/null || true - docker pull ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 + docker rmi ghcr.io/azure/kperf:0.3.7 2>/dev/null || true + docker pull ghcr.io/azure/kperf:0.3.7 docker run --rm -v $temp_dir:/install-dir \ - ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 bash -c "set -x; install /kperf /runkperf /install-dir" + ghcr.io/azure/kperf:0.3.7 bash -c "set -x; install /kperf /runkperf /install-dir" sudo install $temp_dir/kperf $temp_dir/runkperf /usr/local/bin rm -rf $temp_dir - docker rmi ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647 2>/dev/null || true + docker rmi ghcr.io/azure/kperf:0.3.7 2>/dev/null || true displayName: Install runkperf binary - bash: | set -exo pipefail @@ -158,7 +158,7 @@ jobs: run_rg() { args=( rg run - --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" + --runner-image="ghcr.io/azure/kperf:0.3.7" --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r100-runner-group.yaml" ) if [ -n "" ]; then @@ -199,7 +199,7 @@ jobs: sleep 0 attempt=0 max_attempts=5 - until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r100-result.json"; do + until kperf rg result --wait; do attempt=$((attempt + 1)) if [ "$attempt" -ge "$max_attempts" ]; then exit 1 @@ -259,7 +259,7 @@ jobs: run_rg() { args=( rg run - --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" + --runner-image="ghcr.io/azure/kperf:0.3.7" --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r150-runner-group.yaml" ) if [ -n "" ]; then @@ -300,7 +300,7 @@ jobs: sleep 0 attempt=0 max_attempts=5 - until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r150-result.json"; do + until kperf rg result --wait; do attempt=$((attempt + 1)) if [ "$attempt" -ge "$max_attempts" ]; then exit 1 @@ -360,7 +360,7 @@ jobs: run_rg() { args=( rg run - --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" + --runner-image="ghcr.io/azure/kperf:0.3.7" --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r200-runner-group.yaml" ) if [ -n "" ]; then @@ -401,7 +401,7 @@ jobs: sleep 0 attempt=0 max_attempts=5 - until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r200-result.json"; do + until kperf rg result --wait; do attempt=$((attempt + 1)) if [ "$attempt" -ge "$max_attempts" ]; then exit 1 @@ -461,7 +461,7 @@ jobs: run_rg() { args=( rg run - --runner-image="ghcr.io/liyu-ma/kperf@sha256:36f8e1cdbb6a4bd2fde4b29bf0cb5e4e014484ae9ddca9136f43449897ffb647" + --runner-image="ghcr.io/azure/kperf:0.3.7" --runnergroup="file://$(Agent.TempDirectory)/$(RUN_ID)-r250-runner-group.yaml" ) if [ -n "" ]; then @@ -502,7 +502,7 @@ jobs: sleep 0 attempt=0 max_attempts=5 - until kperf rg result --wait | tee "$(Agent.TempDirectory)/$(RUN_ID)-r250-result.json"; do + until kperf rg result --wait; do attempt=$((attempt + 1)) if [ "$attempt" -ge "$max_attempts" ]; then exit 1 From a074c1b5ff5d0656b7b176798d7aabaf82e600b3 Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Fri, 6 Nov 2026 13:58:32 +1000 Subject: [PATCH 23/24] Update comment --- kcl/workload_identity_webhook/pipeline.k | 1 - kcl/workload_identity_webhook/runner-group.yaml | 2 ++ 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index ecd6a85191..f71dd2ae58 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -96,7 +96,6 @@ output = ap.Pipeline { job = "benchmark" displayName = "Baseline Run: 100/150/200/250 RPS" timeoutInMinutes = 240 - # Allow bounded cleanup and recovery during cancellation. cancelTimeoutInMinutes = 25 variables = { RESOURCE_GROUP = "$(RUN_ID)" diff --git a/kcl/workload_identity_webhook/runner-group.yaml b/kcl/workload_identity_webhook/runner-group.yaml index 274ae0243a..98cd6b31ae 100644 --- a/kcl/workload_identity_webhook/runner-group.yaml +++ b/kcl/workload_identity_webhook/runner-group.yaml @@ -24,4 +24,6 @@ loadProfile: azure.workload.identity/use: "true" benchmark-run: "__PHASE_RUN_ID__" serviceAccountName: pod-benchmark + # No scheduler handles this name: Pods undergo admission but remain + # unscheduled, excluding node placement and container startup work. schedulerName: kperf-admission-only From e18bf458fd09c0fa44c7e0125b7d50369b906d5a Mon Sep 17 00:00:00 2001 From: liyu-ma Date: Fri, 13 Nov 2026 17:09:56 +1000 Subject: [PATCH 24/24] Use default WI benchmark cleanup conditions and cancel timeout Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- kcl/workload_identity_webhook/pipeline.k | 3 --- kcl/workload_identity_webhook/pipeline.yaml | 9 --------- 2 files changed, 12 deletions(-) diff --git a/kcl/workload_identity_webhook/pipeline.k b/kcl/workload_identity_webhook/pipeline.k index f71dd2ae58..ec67f1df00 100644 --- a/kcl/workload_identity_webhook/pipeline.k +++ b/kcl/workload_identity_webhook/pipeline.k @@ -60,7 +60,6 @@ kubectl delete namespace "$(RUN_ID)-r${rate}" \\ echo "Namespace cleanup completed for ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ displayName = "Delete namespace from ${rate}/sec run" - condition = "not(canceled())" continueOnError = True timeoutInMinutes = 15 }, @@ -72,7 +71,6 @@ sleep 300 echo "Finished pause after ${rate}/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" """ displayName = "Pause 5 minutes after kperf run" - condition = "not(canceled())" timeoutInMinutes = 6 }, ] @@ -96,7 +94,6 @@ output = ap.Pipeline { job = "benchmark" displayName = "Baseline Run: 100/150/200/250 RPS" timeoutInMinutes = 240 - cancelTimeoutInMinutes = 25 variables = { RESOURCE_GROUP = "$(RUN_ID)" CLUSTER = "wi-webhook" diff --git a/kcl/workload_identity_webhook/pipeline.yaml b/kcl/workload_identity_webhook/pipeline.yaml index 1d4f7e3059..d75aec1226 100755 --- a/kcl/workload_identity_webhook/pipeline.yaml +++ b/kcl/workload_identity_webhook/pipeline.yaml @@ -11,7 +11,6 @@ jobs: - job: benchmark displayName: 'Baseline Run: 100/150/200/250 RPS' timeoutInMinutes: 240 - cancelTimeoutInMinutes: 25 variables: RESOURCE_GROUP: $(RUN_ID) CLUSTER: wi-webhook @@ -216,7 +215,6 @@ jobs: --ignore-not-found=true \ --wait=true echo "Namespace cleanup completed for 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: not(canceled()) continueOnError: true displayName: Delete namespace from 100/sec run timeoutInMinutes: 15 @@ -225,7 +223,6 @@ jobs: echo "Starting five-minute pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 100/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | @@ -317,7 +314,6 @@ jobs: --ignore-not-found=true \ --wait=true echo "Namespace cleanup completed for 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: not(canceled()) continueOnError: true displayName: Delete namespace from 150/sec run timeoutInMinutes: 15 @@ -326,7 +322,6 @@ jobs: echo "Starting five-minute pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 150/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | @@ -418,7 +413,6 @@ jobs: --ignore-not-found=true \ --wait=true echo "Namespace cleanup completed for 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: not(canceled()) continueOnError: true displayName: Delete namespace from 200/sec run timeoutInMinutes: 15 @@ -427,7 +421,6 @@ jobs: echo "Starting five-minute pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 200/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - bash: | @@ -519,7 +512,6 @@ jobs: --ignore-not-found=true \ --wait=true echo "Namespace cleanup completed for 250/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: not(canceled()) continueOnError: true displayName: Delete namespace from 250/sec run timeoutInMinutes: 15 @@ -528,7 +520,6 @@ jobs: echo "Starting five-minute pause after 250/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" sleep 300 echo "Finished pause after 250/sec phase at $(date -u +%Y-%m-%dT%H:%M:%SZ)" - condition: not(canceled()) displayName: Pause 5 minutes after kperf run timeoutInMinutes: 6 - task: AzureCLI@2