From 1ea8aea76a070be1c1e08d7d8efe64f3d4ea460b Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 01:07:10 +0000 Subject: [PATCH 01/47] feat: implement cluster reuse pattern with dual-ID system for SwiftV2 pipeline Refactor Azure DevOps pipeline to support efficient cluster reuse across matrix jobs while maintaining result isolation through a dual-ID system. BREAKING CHANGE: Removed global CLEANUP_RESOURCES variable in favor of matrix-level skip_cleanup and reuse_cluster flags for better control. Features: - Add reuse_cluster and skip_cleanup flags to all matrix files - Implement dual-ID system: RUN_ID (unique) and SHARED_RUN_ID (shared) - Add SHARED_RUN_ID to telescope metadata for job correlation - Derive CL2_JOB_INDEX automatically from System.JobId - Add job_index to pod labels for measurement isolation Fixes: - Fix cluster discovery to use SHARED_RUN_ID when reusing clusters - Fix createclusterforping.sh to only run when reuse_cluster=false - Add SHARED_RUN_ID env var to scale-cluster and prepull-images steps - Update aks-utils.sh and update-kubeconfig.yml cluster queries Performance: - Enable sequential cluster reuse pattern (create once, scale multiple times) - Remove redundant 'Scale Existing AKS Cluster' step from provision-resources - Consolidate all nodepool scaling logic in scale-cluster.sh Documentation: - Add comprehensive cluster reuse documentation to running-swiftv2-pipeline.md - Document dual-ID system and how cluster discovery works - Explain result storage and why overwrites don't occur Files changed: - Matrix configs: Add reuse_cluster/skip_cleanup to 28 test entries (4 files) - Pipeline: Remove CLEANUP_RESOURCES, add cleanup parameter passing - Steps: Add reuse_cluster/skip_cleanup parameters and conditions - Scripts: Update cluster discovery to use SHARED_RUN_ID - CL2 configs: Add job_index to pod labels and PNI names - Metadata: Include shared_run_id in telescope metadata This enables running 7 tests on one cluster instead of creating/destroying 7 separate clusters, reducing test time from ~40 hours to ~25 hours. --- docs/running-swiftv2-pipeline.md | 91 ++++++++++++++++++- jobs/competitive-test.yml | 3 + ...v2_deployment_dynamicres_scale_config.yaml | 25 ++--- ...wiftv2_deployment_single_pod_template.yaml | 4 +- ...tv2_deployment_staticres_scale_config.yaml | 24 ++--- .../swiftv2-dynamicres-burst-matrix.yml | 14 +++ .../swiftv2-dynamicres-gradual-matrix.yml | 14 +++ .../swiftv2-staticres-burst-matrix.yml | 14 +++ .../swiftv2-staticres-gradual-matrix.yml | 14 +++ pipelines/system/new-pipeline-test.yml | 1 - steps/cleanup-resources.yml | 31 ++++++- steps/cloud/azure/update-kubeconfig.yml | 11 ++- steps/collect-telescope-metadata.yml | 2 + .../clusterloader2/swiftv2-slo/aks-utils.sh | 10 +- .../clusterloader2/swiftv2-slo/execute.yml | 4 + .../swiftv2-slo/prepull-images.yml | 1 + .../swiftv2-slo/scale-cluster.yml | 1 + steps/provision-resources.yml | 38 +++++++- steps/setup-tests.yml | 19 ++++ 19 files changed, 281 insertions(+), 40 deletions(-) diff --git a/docs/running-swiftv2-pipeline.md b/docs/running-swiftv2-pipeline.md index dd5aa56b73..9ea577fe15 100644 --- a/docs/running-swiftv2-pipeline.md +++ b/docs/running-swiftv2-pipeline.md @@ -10,7 +10,8 @@ Here is the pipeline [link](https://dev.azure.com/akstelescope/telescope/_build? ## Pipeline variables, branches and test matrix -- As of 11/11/2025, no pipeline variables need to be touched in ADO. All the variables are hardcoded in `pipelines/system/new-pipeline-test.yml`. For example, location, subscription, vm-sku, number of nics, CLEANUP_RESOURCES etc. +- As of 11/11/2025, no pipeline variables need to be touched in ADO. All the variables are hardcoded in `pipelines/system/new-pipeline-test.yml`. For example, location, subscription, vm-sku, number of nics, etc. +- **Note:** Cluster cleanup behavior is controlled at the matrix level via `skip_cleanup` flags in each test entry, not via a global pipeline variable. - This is the official branch - `feature/swiftv2GA/swiftv2scale`, and it has comprehensive test matrix. Not all of which needs to be run for a given objective. - It is recomended to create a test branch and disable/comment out unnnecessary test cases. @@ -19,6 +20,94 @@ Here is the pipeline [link](https://dev.azure.com/akstelescope/telescope/_build? - If certain stages are not required for the perf run, in `pipelines/system/new-pipeline-test.yml` flip `condition` flag to `false`. At the moment both `burst` stages are set to false. - Each stage has a matrix file here - `pipelines/system/matrices`, where different combinations of pods, nodes and pods-per-step are set. Comment out the matrix entries that are irrelevant for the enabled stages. +## Matrix configuration with reuse_cluster and skip_cleanup +. These flags provide fine-grained control over cluster creation and cleanup **at the individual test level** - there is no global cleanup variable. + +- **`reuse_cluster`**: Whether to reuse an existing cluster (`true`) or create a new one (`false`) +- **`skip_cleanup`**: Whether to keep the cluster after tests complete (`true`) or delete it (`false`) + +### Typical pattern for gradual scale testing + +- **First entry**: `reuse_cluster: false`, `skip_cleanup: true` - Creates a new cluster, keeps it +- **Middle entries**: `reuse_cluster: true`, `skip_cleanup: true` - Reuses existing cluster, keeps it +- **Last entry**: `reuse_cluster: true`, `skip_cleanup: false` - Reuses existing cluster, **cleans it up** + +This pattern allows sequential test runs on the same cluster, saving time and resources by avoiding repeated cluster creation/deletion. Only the last test in the sequence performs cleanup +This pattern allows sequential test runs on the same cluster, saving time and resources by avoiding repeated cluster creation/deletion. + +### Adding or removing matrix entries + +When modifying the matrix, ensure the first and last entries have the appropriate flags: + +```yaml +matrix: + test_small: + node_count: 10 + reuse_cluster: false # Create new cluster + skip_cleanup: true # Keep it for next test + # ... other params + test_medium: + node_count: 500 + reuse_cluster: true # Reuse cluster + skip_cleanup: true # Keep it for next test + # ... other params + test_large: + node_count: 1000 + reuse_cluster: true # Reuse cluster + skip_cleanup: false # Clean up after completion + # ... other params +``` +### Running tests independently + +To run tests independently (not reusing clusters), set `reuse_cluster: false` and `skip_cleanup: false` on all entries. Each test will create its own cluster and clean it up after completion. + +### Emergency: Disable all cleanup + +If you need to preserve clusters for debugging after a pipeline run, set `skip_cleanup: true` on all matrix entries. This overrides cleanup behavior for the entire pipeline run. Remember to manually delete clusters afterwards to avoid resource waste. + +To run tests independently (not reusing clusters), set `reuse_cluster: false` and `skip_cleanup: false` on all entries. + +### Cluster Creation and Reuse Logic + +The pipeline uses the following logic for cluster lifecycle management: + +1. **First job** (`reuse_cluster: false`): + - Creates resource group + - Runs `createclusterforping.sh` to create AKS cluster and initial nodepools (1 node each) + - Runs `scale-cluster.sh` to scale nodepools to target size + - Keeps cluster after test (`skip_cleanup: true`) + +2. **Subsequent jobs** (`reuse_cluster: true`): + - Reuses existing resource group (via `shared_run_id`) + - **Skips** `createclusterforping.sh` (cluster already exists) + - Runs `scale-cluster.sh` to scale existing nodepools to new target size + - Keeps or cleans up cluster based on `skip_cleanup` flag + +This design avoids redundant cluster creation attempts and consolidates all nodepool scaling logic in `scale-cluster.sh`. + +### Result Storage and Run IDs + +Each matrix job generates a unique `RUN_ID` (timestamp + 5-char random suffix) used for: +- Blob storage filenames: `$(RUN_ID).json` +- Individual job tracking and test result isolation + +When `reuse_cluster: true`, jobs also use `SHARED_RUN_ID` (equals `BASE_RUN_ID`) for: +- **Azure cluster discovery**: Finding existing cluster via `run_id` tag +- Resource group name (cluster identification) +- Azure resource tagging +- Correlating which jobs ran on the same cluster + +**Results DO NOT overwrite** because each job uploads to its own unique `RUN_ID` filename. The telescope metadata now includes both `run_id` (unique per job) and `shared_run_id` (shared across jobs on same cluster) to enable correlation in Kusto queries. + +**How cluster discovery works:** +1. **First job** creates cluster with tag: `run_id=` +2. **Subsequent jobs** use `SHARED_RUN_ID` (= `BASE_RUN_ID`) to query Azure: + ```bash + az resource list ... --query "[?(tags.run_id == '$SHARED_RUN_ID' && tags.role == 'slo')]" + ``` +3. This allows `update-kubeconfig.yml` and `scale-cluster.sh` to find the shared cluster +4. But each job keeps unique `RUN_ID` for result uploads (prevents overwrites) + ## Kusto cluster('telescopedata.eastus.kusto.windows.net').database('perf_eval') diff --git a/jobs/competitive-test.yml b/jobs/competitive-test.yml index 5164d83ece..b68f046dd4 100644 --- a/jobs/competitive-test.yml +++ b/jobs/competitive-test.yml @@ -79,6 +79,8 @@ jobs: terraform_input_varibles: ${{ parameters.terraform_input_varibles }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} + reuse_cluster: $(reuse_cluster) + shared_run_id: $(shared_run_id) - template: /steps/validate-resources.yml parameters: cloud: ${{ parameters.cloud }} @@ -107,3 +109,4 @@ jobs: terraform_arguments: ${{ parameters.terraform_arguments }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} + skip_cleanup: $(skip_cleanup) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml index bd73281043..389347094e 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml @@ -15,6 +15,7 @@ name: deployment-churn {{$probeTimeout := .CL2_PROBE_TIMEOUT}} {{$datapathReporterImage := .CL2_DATAPATH_REPORTER_IMAGE}} {{$nginxImage := .CL2_NGINX_IMAGE}} +{{$jobIndex := DefaultParam .CL2_JOB_INDEX 0}} namespace: number: 1 @@ -46,7 +47,7 @@ steps: objectTemplatePath: reporter_role_template.yaml - basename: reporter-binding objectTemplatePath: reporter_rolebinding_template.yaml - - name: Log - steps={{$steps}}, nodes={{$nodes}}, pods/step={{$podsPerStep}}, pods/node={{$podsPerNode}}, total pods={{$total_pods}} + - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total pods={{$total_pods}} measurements: - Identifier: Dummy Method: Sleep @@ -61,7 +62,7 @@ steps: replicasPerNamespace: 1 tuningSet: DeploymentCreatePNIQps objectBundle: - - basename: pod-network-instance + - basename: pod-network-instance-job{{$jobIndex}} objectTemplatePath: pni_dynamic_template.yaml - name: Deploy PNI Readiness Checker phases: @@ -74,7 +75,7 @@ steps: - basename: pni-checker objectTemplatePath: pni_readiness_checker_unified_template.yaml templateFillMap: - PNIPrefix: pod-network-instance-0 + PNIPrefix: pod-network-instance-job{{$jobIndex}}-0 NumPNIs: 1 - name: Wait for PNI Readiness Checker to Complete measurements: @@ -95,7 +96,7 @@ steps: - basename: pni-checker objectTemplatePath: pni_readiness_checker_unified_template.yaml templateFillMap: - PNIPrefix: pod-network-instance-0 + PNIPrefix: pod-network-instance-job{{$jobIndex}}-0 NumPNIs: 1 - name: Starting Pod Startup Latency Measurements measurements: @@ -103,7 +104,7 @@ steps: Method: PodStartupLatency Params: action: start - labelSelector: podgroup={{$groupName}} + labelSelector: podgroup={{$groupName}}-job{{$jobIndex}} threshold: {{$podStartupLatencyThreshold}} {{range $j := Loop $steps}} - name: Starting Deployment Latency Measurements -{{$j}} @@ -114,7 +115,7 @@ steps: action: start apiVersion: apps/v1 kind: Deployment - labelSelector: group={{$groupName}}-{{$j}} + labelSelector: group={{$groupName}}-job{{$jobIndex}}-{{$j}} operationTimeout: {{$operationTimeout}} - name: Create Deployments {{$j}} phases: @@ -124,16 +125,16 @@ steps: replicasPerNamespace: 1 tuningSet: DeploymentCreateQps objectBundle: - - basename: deployment-churn-{{$j}} + - basename: deployment-churn-job{{$jobIndex}}-{{$j}} objectTemplatePath: swiftv2_deployment_template.yaml templateFillMap: Replicas: {{$podsPerStep}} - PodGroup: {{$groupName}} - Group: {{$groupName}}-{{$j}} + PodGroup: {{$groupName}}-job{{$jobIndex}} + Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} CpuRequest: {{$latencyPodCpu}}m MemoryRequest: {{$latencyPodMemory}}M deploymentLabel: start - pniName: pod-network-instance-0 + pniName: pod-network-instance-job{{$jobIndex}}-0 Location: {{$.CL2_LOCATION}} DevicePluginEnabled: {{$devicePluginEnabled}} ProbeTarget: {{$probeTargetUrl}} @@ -148,7 +149,7 @@ steps: action: gather apiVersion: apps/v1 kind: Deployment - labelSelector: group={{$groupName}}-{{$j}} + labelSelector: group={{$groupName}}-job{{$jobIndex}}-{{$j}} operationTimeout: {{$operationTimeout}} {{end}} - name: Gather Pod Startup Latency Measurements @@ -157,7 +158,7 @@ steps: Method: PodStartupLatency Params: action: gather - labelSelector: podgroup={{$groupName}} + labelSelector: podgroup={{$groupName}}-job{{$jobIndex}} - name: Wait for Datapath Readiness measurements: - Identifier: Dummy diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml index 41a3d4ff2d..d683e44dbb 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml @@ -5,7 +5,7 @@ metadata: labels: group: {{.Group}} kubernetes.azure.com/pod-network: pn100 - kubernetes.azure.com/pod-network-instance: pod-network-instance-{{.StepIndex}}-{{DivideInt .Index .PodsPerPNI}} + kubernetes.azure.com/pod-network-instance: {{.PNIPrefix}}-{{DivideInt .Index .PodsPerPNI}} spec: replicas: 1 selector: @@ -20,7 +20,7 @@ spec: group: {{.Group}} podgroup: {{.PodGroup}} kubernetes.azure.com/pod-network: pn100 - kubernetes.azure.com/pod-network-instance: pod-network-instance-{{.StepIndex}}-{{DivideInt .Index .PodsPerPNI}} + kubernetes.azure.com/pod-network-instance: {{.PNIPrefix}}-{{DivideInt .Index .PodsPerPNI}} restart: {{.deploymentLabel}} spec: serviceAccountName: reporter-sa-0 diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index 34acfaeaa1..c3a73270e9 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -17,6 +17,7 @@ name: deployment-churn {{$probeTimeout := .CL2_PROBE_TIMEOUT}} {{$datapathReporterImage := .CL2_DATAPATH_REPORTER_IMAGE}} {{$nginxImage := .CL2_NGINX_IMAGE}} +{{$jobIndex := DefaultParam .CL2_JOB_INDEX 0}} namespace: number: 1 @@ -48,7 +49,7 @@ steps: objectTemplatePath: reporter_role_template.yaml - basename: reporter-binding objectTemplatePath: reporter_rolebinding_template.yaml - - name: Log - steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total pods={{$total_pods}} + - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total pods={{$total_pods}} measurements: - Identifier: Dummy Method: Sleep @@ -61,7 +62,7 @@ steps: Method: PodStartupLatency Params: action: start - labelSelector: podgroup={{$groupName}} + labelSelector: podgroup={{$groupName}}-job{{$jobIndex}} threshold: {{$podStartupLatencyThreshold}} {{range $j := Loop $steps}} - name: Create PNIs for step {{$j}} @@ -72,7 +73,7 @@ steps: replicasPerNamespace: {{$numPNIs}} tuningSet: DeploymentCreateQps objectBundle: - - basename: pod-network-instance-{{$j}} + - basename: pod-network-instance-job{{$jobIndex}}-{{$j}} objectTemplatePath: pni_static_template.yaml templateFillMap: ReservationSize: {{$podsPerPNI}} @@ -87,7 +88,7 @@ steps: - basename: pni-checker-{{$j}} objectTemplatePath: pni_readiness_checker_unified_template.yaml templateFillMap: - PNIPrefix: pod-network-instance-{{$j}}- + PNIPrefix: pod-network-instance-job{{$jobIndex}}-{{$j}}- NumPNIs: {{$numPNIs}} - name: Wait for PNI Readiness Checker to Complete -{{$j}} measurements: @@ -108,7 +109,7 @@ steps: - basename: pni-checker-{{$j}} objectTemplatePath: pni_readiness_checker_unified_template.yaml templateFillMap: - PNIPrefix: pod-network-instance-{{$j}}- + PNIPrefix: pod-network-instance-job{{$jobIndex}}-{{$j}}- NumPNIs: {{$numPNIs}} - name: Starting Deployment Latency Measurements -{{$j}} measurements: @@ -118,7 +119,7 @@ steps: action: start apiVersion: apps/v1 kind: Deployment - labelSelector: group={{$groupName}}-{{$j}} + labelSelector: group={{$groupName}}-job{{$jobIndex}}-{{$j}} operationTimeout: {{$operationTimeout}} - name: Create Deployments for step {{$j}} phases: @@ -128,16 +129,17 @@ steps: replicasPerNamespace: {{$podsPerStep}} tuningSet: DeploymentCreateQps objectBundle: - - basename: deployment-churn-{{$j}} + - basename: deployment-churn-job{{$jobIndex}}-{{$j}} objectTemplatePath: swiftv2_deployment_single_pod_template.yaml templateFillMap: - Group: {{$groupName}}-{{$j}} - PodGroup: {{$groupName}} + Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} + PodGroup: {{$groupName}}-job{{$jobIndex}} CpuRequest: {{$latencyPodCpu}}m MemoryRequest: {{$latencyPodMemory}}M deploymentLabel: start StepIndex: {{$j}} PodsPerPNI: {{$podsPerPNI}} + PNIPrefix: pod-network-instance-job{{$jobIndex}}-{{$j}} Location: {{$.CL2_LOCATION}} DevicePluginEnabled: {{$devicePluginEnabled}} ProbeTarget: {{$probeTargetUrl}} @@ -152,7 +154,7 @@ steps: action: gather apiVersion: apps/v1 kind: Deployment - labelSelector: group={{$groupName}}-{{$j}} + labelSelector: group={{$groupName}}-job{{$jobIndex}}-{{$j}} operationTimeout: {{$operationTimeout}} {{end}} - name: Gather Pod Startup Latency Measurements @@ -161,7 +163,7 @@ steps: Method: PodStartupLatency Params: action: gather - labelSelector: podgroup={{$groupName}} + labelSelector: podgroup={{$groupName}}-job{{$jobIndex}} - name: Wait for Datapath Readiness measurements: - Identifier: Dummy diff --git a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml index f4f6748b13..ab72fd9de7 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml @@ -28,42 +28,56 @@ parameters: test_timeout: "2m" test_type: Burst_DynamicRes_PPS=140_PPP=0_Pods=140_Nodes=20 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: false + skip_cleanup: true ppp=0_pods=350_nodes=50: node_count: 50 pods_per_step: 50 test_timeout: "3m" test_type: Burst_DynamicRes_PPS=350_PPP=0_Pods=350_Nodes=50 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=0_pods=700_nodes=100: node_count: 100 pods_per_step: 100 test_timeout: "4m" test_type: Burst_DynamicRes_PPS=700_PPP=0_Pods=700_Nodes=100 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=0_pods=1400_nodes=200: node_count: 200 pods_per_step: 200 test_timeout: "6m" test_type: Burst_DynamicRes_PPS=1400_PPP=0_Pods=1400_Nodes=200 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=0_pods=3500_nodes=500: node_count: 500 pods_per_step: 500 test_timeout: "7m" test_type: Burst_DynamicRes_PPS=3500_PPP=0_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=0_pods=5250_nodes=750: node_count: 750 pods_per_step: 750 test_timeout: "9m" test_type: Burst_DynamicRes_PPS=5250_PPP=0_Pods=5250_Nodes=750 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=0_burst_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 1000 test_timeout: "10m" test_type: Burst_DynamicRes_PPS=7000_PPP=0_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: false jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml index b670bbebb9..8b7e0a7123 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml @@ -28,42 +28,56 @@ parameters: test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=35_PPP=0_Pods=70_Nodes=10 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: false + skip_cleanup: true pps=50_ppp=0_pods=3500_nodes=500: node_count: 500 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=0_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=0_pods=14000_nodes=2000: node_count: 2000 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=0_pods=17500_nodes=2500: node_count: 2500 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=17500_Nodes=2500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=0_pods=21000_nodes=3000: node_count: 3000 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=21000_Nodes=3000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=0_pods=35000_nodes=5000: node_count: 5000 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=35000_Nodes=5000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + reuse_cluster: true + skip_cleanup: false jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml index 0709214d7d..3870cfc60a 100644 --- a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml @@ -29,6 +29,8 @@ parameters: test_timeout: "2m" test_type: Burst_StaticRes_PPS=140_PPP=1_Pods=140_Nodes=20 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: false + skip_cleanup: true ppp=1_pods=350_nodes=50: node_count: 50 pods_per_step: 50 @@ -36,6 +38,8 @@ parameters: test_timeout: "3m" test_type: Burst_StaticRes_PPS=350_PPP=1_Pods=350_Nodes=50 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=1_pods=700_nodes=100: node_count: 100 pods_per_step: 100 @@ -43,6 +47,8 @@ parameters: test_timeout: "4m" test_type: Burst_StaticRes_PPS=700_PPP=1_Pods=700_Nodes=100 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=1_pods=1400_nodes=200: node_count: 200 pods_per_step: 200 @@ -50,6 +56,8 @@ parameters: test_timeout: "6m" test_type: Burst_StaticRes_PPS=1400_PPP=1_Pods=1400_Nodes=200 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=1_pods=3500_nodes=500: node_count: 500 pods_per_step: 500 @@ -57,6 +65,8 @@ parameters: test_timeout: "7m" test_type: Burst_StaticRes_PPS=3500_PPP=1_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=1_pods=5250_nodes=750: node_count: 750 pods_per_step: 750 @@ -64,6 +74,8 @@ parameters: test_timeout: "9m" test_type: Burst_StaticRes_PPS=5250_PPP=1_Pods=5250_Nodes=750 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true ppp=1_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 1000 @@ -71,6 +83,8 @@ parameters: test_timeout: "10m" test_type: Burst_StaticRes_PPS=7000_PPP=1_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: false jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml index 3a8347decf..a6afeb3573 100644 --- a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml @@ -29,6 +29,8 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=35_PPP=1_Pods=70_Nodes=10 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: false + skip_cleanup: true pps=50_ppp=1_pods=3500_nodes=500: node_count: 500 pods_per_step: 50 @@ -36,6 +38,8 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=1_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 50 @@ -43,6 +47,8 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=1_pods=14000_nodes=2000: node_count: 2000 pods_per_step: 50 @@ -50,6 +56,8 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=1_pods=17500_nodes=2500: node_count: 2500 pods_per_step: 50 @@ -57,6 +65,8 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=17500_Nodes=2500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=1_pods=21000_nodes=3000: node_count: 3000 pods_per_step: 50 @@ -64,6 +74,8 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=21000_Nodes=3000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: true pps=50_ppp=1_pods=35000_nodes=5000: node_count: 5000 pods_per_step: 50 @@ -71,6 +83,8 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=35000_Nodes=5000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + reuse_cluster: true + skip_cleanup: false jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 432045663e..662de2c362 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -9,7 +9,6 @@ variables: AZURE_TELESCOPE_STORAGE_ACCOUNT_NAME: "telescopedata" LOCATION: "uksouth" CREATESWIFTV2PING: "true" - CLEANUP_RESOURCES: "true" K8S_VERSION: "1.33" PROVISION_BUFFER_NODES: "false" # Log Analytics are expensive - disable and delete after use diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 63db3634d9..5cc3de3bbc 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -13,15 +13,29 @@ parameters: - name: credential_type type: string default: managed_identity +- name: skip_cleanup + type: boolean + default: false steps: - script: | echo "===================================================================" - echo "Starting cleanup process for Run ID: $RUN_ID" - echo "Cleanup will proceed even if pipeline was cancelled" + if [ "${{ parameters.skip_cleanup }}" == "true" ]; then + echo "SKIP_CLEANUP is enabled - skipping resource cleanup for this job" + echo "Resources will be reused by subsequent jobs" + else + echo "Starting cleanup process for Run ID: $RUN_ID" + echo "Cleanup will proceed even if pipeline was cancelled" + fi echo "===================================================================" displayName: "Cleanup Notice" condition: always() + +- script: | + echo "Skipping terraform destroy due to skip_cleanup=true" + echo "Resources will be cleaned up by the final job in the sequence" + displayName: "Skip Terraform Destroy (Reuse Mode)" + condition: and(always(), eq('${{ parameters.skip_cleanup }}', 'true')) - template: /steps/terraform/run-command.yml parameters: @@ -31,6 +45,7 @@ steps: cloud: ${{ parameters.cloud }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} + condition: and(always(), eq('${{ parameters.skip_cleanup }}', 'false')) - script: | set -eu @@ -44,7 +59,7 @@ steps: sleep 30 done displayName: "Delete SAL Ping" - condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true'), eq(variables['CLEANUP_RESOURCES'], 'true')) + condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true'), eq('${{ parameters.skip_cleanup }}', 'false')) continueOnError: true - script: | set -eu @@ -133,9 +148,15 @@ steps: echo "Pre-cleanup completed" displayName: "Force Cleanup Azure Resources" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['CLEANUP_RESOURCES'], 'true')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq('${{ parameters.skip_cleanup }}', 'false')) continueOnError: true +- script: | + echo "Skipping resource group deletion due to skip_cleanup=true" + echo "Resource group will be cleaned up by the final job in the sequence" + displayName: "Skip Resource Group Deletion (Reuse Mode)" + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq('${{ parameters.skip_cleanup }}', 'true')) + - script: | set -eu @@ -158,7 +179,7 @@ steps: fi done displayName: "Destroy Resource Group" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['CLEANUP_RESOURCES'], 'true')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq('${{ parameters.skip_cleanup }}', 'false')) continueOnError: true - ${{ if eq(variables['Build.SourceBranchName'], 'main') }}: diff --git a/steps/cloud/azure/update-kubeconfig.yml b/steps/cloud/azure/update-kubeconfig.yml index 50f8cf5e10..d94a011b5c 100644 --- a/steps/cloud/azure/update-kubeconfig.yml +++ b/steps/cloud/azure/update-kubeconfig.yml @@ -10,17 +10,22 @@ steps: set -x region=${{ parameters.region }} + + # Use SHARED_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID + CLUSTER_RUN_ID="${SHARED_RUN_ID:-$RUN_ID}" + echo "Searching for cluster with run_id tag: $CLUSTER_RUN_ID" aks_name=$(az resource list --resource-type Microsoft.ContainerService/managedClusters --location $region \ - --query "[?(tags.run_id == '${RUN_ID}' && tags.role == '$ROLE')].name" --output tsv) + --query "[?(tags.run_id == '$CLUSTER_RUN_ID' && tags.role == '$ROLE')].name" --output tsv) aks_rg=$(az resource list --resource-type Microsoft.ContainerService/managedClusters --location $region \ - --query "[?(tags.run_id == '${RUN_ID}' && tags.role == '$ROLE')].resourceGroup" --output tsv) + --query "[?(tags.run_id == '$CLUSTER_RUN_ID' && tags.role == '$ROLE')].resourceGroup" --output tsv) if [ -z "$aks_name" ]; then - echo "##vso[task.logissue type=error;] No AKS instance with role $ROLE and tag $RUN_ID found in region $region." + echo "##vso[task.logissue type=error;] No AKS instance with role $ROLE and tag $CLUSTER_RUN_ID found in region $region." exit 1 fi + echo "Found cluster: $aks_name in resource group: $aks_rg" az aks get-credentials -n $aks_name -g $aks_rg env: ROLE: ${{ parameters.role }} diff --git a/steps/collect-telescope-metadata.yml b/steps/collect-telescope-metadata.yml index 4fd3fd5872..24d611dcdc 100644 --- a/steps/collect-telescope-metadata.yml +++ b/steps/collect-telescope-metadata.yml @@ -27,6 +27,7 @@ steps: telescope_metadata=$(jq -n \ --arg run_id $RUN_ID \ + --arg shared_run_id "${SHARED_RUN_ID:-}" \ --arg run_url $RUN_URL \ --arg code_url $CODE_URL \ --arg timestamp "$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")" \ @@ -49,6 +50,7 @@ steps: --arg byo_resources "$SKIP_RESOURCE_MANAGEMENT" \ '{ run_id: $run_id, + shared_run_id: $shared_run_id, timestamp: $timestamp, pipeline_info: { run_url: $run_url, diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index 37d76f0ed5..bc5a212686 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh @@ -32,25 +32,29 @@ function find_aks_cluster() { local region=$1 local role=$2 + # Use SHARED_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID + local cluster_run_id="${SHARED_RUN_ID:-$RUN_ID}" + log_info "Finding AKS cluster with role '$role' in region '$region'..." + log_info "Using run_id tag: $cluster_run_id" # Query for AKS cluster name matching tags aks_name=$(az resource list \ --resource-type Microsoft.ContainerService/managedClusters \ --location "$region" \ - --query "[?(tags.run_id == '${RUN_ID}' && tags.role == '$role')].name" \ + --query "[?(tags.run_id == '$cluster_run_id' && tags.role == '$role')].name" \ --output tsv) # Query for AKS cluster resource group matching tags aks_rg=$(az resource list \ --resource-type Microsoft.ContainerService/managedClusters \ --location "$region" \ - --query "[?(tags.run_id == '${RUN_ID}' && tags.role == '$role')].resourceGroup" \ + --query "[?(tags.run_id == '$cluster_run_id' && tags.role == '$role')].resourceGroup" \ --output tsv) # Validate cluster was found if [ -z "$aks_name" ]; then - log_error "No AKS cluster found with role '$role' and run_id '$RUN_ID' in region '$region'" + log_error "No AKS cluster found with role '$role' and run_id '$cluster_run_id' in region '$region'" exit 1 fi diff --git a/steps/engine/clusterloader2/swiftv2-slo/execute.yml b/steps/engine/clusterloader2/swiftv2-slo/execute.yml index 9712aaa182..875cf9db82 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/execute.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/execute.yml @@ -20,6 +20,10 @@ steps: set -eo pipefail set -x + # Get job suffix directly from System.JobId (same as in Set Run ID phase) + export CL2_JOB_INDEX=$(echo "$(System.JobId)" | cut -c1-5) + echo "Job index (from System.JobId): $CL2_JOB_INDEX" + # Add signal handler for graceful cancellation trap 'echo "Benchmark execution cancelled by user"; exit 143' SIGTERM SIGINT diff --git a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml index d3a7a43f5d..797480ff3a 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml @@ -13,6 +13,7 @@ steps: REGION: ${{ parameters.region }} ROLE: ${{ parameters.role }} RUN_ID: $(RUN_ID) + SHARED_RUN_ID: $(SHARED_RUN_ID) DATAPATH_REPORTER_IMAGE: $(DATAPATH_REPORTER_IMAGE) NGINX_IMAGE: $(NGINX_IMAGE) displayName: "Pre-pull Container Images" diff --git a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml index 5855556b10..f980a6d20f 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml @@ -16,5 +16,6 @@ steps: REGION: ${{ parameters.region }} ROLE: ${{ parameters.role }} RUN_ID: $(RUN_ID) + SHARED_RUN_ID: $(SHARED_RUN_ID) displayName: "Scale Cluster" diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index fa00764f0d..3e4fd69f61 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -23,6 +23,12 @@ parameters: - name: credential_type type: string default: managed_identity +- name: reuse_cluster + type: boolean + default: false +- name: shared_run_id + type: string + default: '' steps: - template: /steps/terraform/set-working-directory.yml @@ -68,7 +74,34 @@ steps: az group create --name $RUN_ID --location $region \ --tags "run_id=$RUN_ID" "scenario=${SCENARIO_TYPE}-${SCENARIO_NAME}" "owner=${OWNER}" "creation_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "deletion_due_time=${DELETION_DUE_TIME}" "SkipAKSCluster=1" displayName: "Create Resource Group" - condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true')) + condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq('${{ parameters.reuse_cluster }}', 'false')) + env: + region: ${{ parameters.regions[0] }} + +- script: | + set -eu + + # When reusing cluster, use the shared_run_id as the resource group name + SHARED_RUN_ID="${{ parameters.shared_run_id }}" + if [ -z "$SHARED_RUN_ID" ]; then + echo "ERROR: reuse_cluster is true but shared_run_id is not provided" + exit 1 + fi + + echo "Reusing existing resource group: $SHARED_RUN_ID" + + # Set the RUN_ID to the shared one for this job + echo "##vso[task.setvariable variable=SHARED_RUN_ID]$SHARED_RUN_ID" + + # Verify the resource group exists + if ! az group show --name $SHARED_RUN_ID > /dev/null 2>&1; then + echo "ERROR: Shared resource group $SHARED_RUN_ID does not exist" + exit 1 + fi + + echo "Resource group $SHARED_RUN_ID found and will be reused" + displayName: "Set Shared Resource Group" + condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq('${{ parameters.reuse_cluster }}', 'true')) env: region: ${{ parameters.regions[0] }} @@ -92,6 +125,7 @@ steps: cloud: ${{ parameters.cloud }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} + - script: | bash swiftv2kubeobjects/runCustomerSetup.sh displayName: "SetupCustomerResources" @@ -100,7 +134,7 @@ steps: - script: | bash swiftv2kubeobjects/createclusterforping.sh displayName: "SetupAKSMTClusterPING" - condition: eq(variables['CREATESWIFTV2PING'], 'true') + condition: and(eq(variables['CREATESWIFTV2PING'], 'true'), eq('${{ parameters.reuse_cluster }}', 'false')) name: SetupAKSMTClusterPING env: # Ensure these pipeline variables are available as env vars to the script diff --git a/steps/setup-tests.yml b/steps/setup-tests.yml index 13c852983a..3f8c516718 100644 --- a/steps/setup-tests.yml +++ b/steps/setup-tests.yml @@ -44,10 +44,29 @@ steps: fi echo "Final Run ID: $run_id" echo "##vso[task.setvariable variable=RUN_ID]$run_id" + + # Set shared_run_id for cluster reuse scenarios + # If REUSE_CLUSTER is set but no SHARED_RUN_ID is provided, default to using BASE_RUN_ID + if [ "${REUSE_CLUSTER:-false}" == "true" ]; then + if [ -n "${SHARED_RUN_ID:-}" ] && [ "$SHARED_RUN_ID" != " " ]; then + shared_run_id=$SHARED_RUN_ID + elif [ -n "$BASE_RUN_ID" ] && [ "$BASE_RUN_ID" != " " ]; then + # For reuse, the first job creates with BASE_RUN_ID, subsequent jobs reuse it + shared_run_id=$BASE_RUN_ID + else + echo "ERROR: REUSE_CLUSTER is true but neither SHARED_RUN_ID nor BASE_RUN_ID is set" + exit 1 + fi + echo "Cluster reuse enabled. Shared Run ID: $shared_run_id" + echo "##vso[task.setvariable variable=SHARED_RUN_ID]$shared_run_id" + echo "Keeping unique RUN_ID ($run_id) for test result isolation" + fi displayName: "Set Run ID" env: RUN_ID: ${{ parameters.run_id }} BASE_RUN_ID: ${{ parameters.base_run_id }} + REUSE_CLUSTER: $(reuse_cluster) + SHARED_RUN_ID: $(shared_run_id) - script: | run_url="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)&view=logs&j=$(System.JobId)" From 3f7081b7434e3449c99bc9365f9a3db61b9c0e2a Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 01:11:47 +0000 Subject: [PATCH 02/47] fix: change reuse_cluster and skip_cleanup parameters from boolean to string Azure DevOps cannot evaluate runtime variables like $(reuse_cluster) as boolean parameters, causing pipeline parsing errors. Changes: - Change reuse_cluster parameter from 'type: boolean' to 'type: string' with default: 'false' in provision-resources.yml - Change skip_cleanup parameter from 'type: boolean' to 'type: string' with default: 'false' in cleanup-resources.yml Impact: - Allows matrix variables to be passed as runtime values - All existing conditions already use string comparisons (eq()), so no functional changes required - Fixes ADO parsing errors: * "The 'reuse_cluster' parameter value '$(reuse_cluster)' is not a valid Boolean" * "Key not found 'reuse_cluster'" in multiple template conditions This maintains backward compatibility while enabling runtime variable evaluation from matrix configurations. --- steps/cleanup-resources.yml | 4 ++-- steps/provision-resources.yml | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 5cc3de3bbc..87e60666ca 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -14,8 +14,8 @@ parameters: type: string default: managed_identity - name: skip_cleanup - type: boolean - default: false + type: string + default: 'false' steps: - script: | diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index 3e4fd69f61..208dd044f6 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -24,8 +24,8 @@ parameters: type: string default: managed_identity - name: reuse_cluster - type: boolean - default: false + type: string + default: 'false' - name: shared_run_id type: string default: '' From 9d4bf55114e577dc7b9227293a12b45565d30aca Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 01:15:41 +0000 Subject: [PATCH 03/47] fix: cleanup resources.yaml remove white spaces --- steps/cleanup-resources.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 87e60666ca..500c7845f7 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -46,7 +46,6 @@ steps: retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} condition: and(always(), eq('${{ parameters.skip_cleanup }}', 'false')) - - script: | set -eu From 6dcba9102801a2d2f2f15f0f13430242b936b192 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 01:17:40 +0000 Subject: [PATCH 04/47] fix: {{ if eq(parameters.skip_cleanup, 'false') }}: --- steps/cleanup-resources.yml | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 500c7845f7..144c1cd909 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -37,15 +37,17 @@ steps: displayName: "Skip Terraform Destroy (Reuse Mode)" condition: and(always(), eq('${{ parameters.skip_cleanup }}', 'true')) -- template: /steps/terraform/run-command.yml - parameters: - command: destroy - arguments: ${{ parameters.terraform_arguments }} - regions: ${{ parameters.regions }} - cloud: ${{ parameters.cloud }} - retry_attempt_count: ${{ parameters.retry_attempt_count }} - credential_type: ${{ parameters.credential_type }} - condition: and(always(), eq('${{ parameters.skip_cleanup }}', 'false')) +- ${{ if eq(parameters.skip_cleanup, 'false') }}: + - template: /steps/terraform/run-command.yml + parameters: + command: destroy + arguments: ${{ parameters.terraform_arguments }} + regions: ${{ parameters.regions }} + cloud: ${{ parameters.cloud }} + retry_attempt_count: ${{ parameters.retry_attempt_count }} + credential_type: ${{ parameters.credential_type }} + condition: always() + - script: | set -eu From 4a28b2f442daf3c45be1f9ffad0fcaa3e246336c Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 03:53:50 +0000 Subject: [PATCH 05/47] fix: correct reuse_cluster and skip_cleanup conditions to use runtime variables - Change conditions from compile-time parameters to runtime variables - Fix reuse_cluster checks in provision-resources.yml - Fix skip_cleanup checks in cleanup-resources.yml - Remove compile-time conditional for terraform destroy step - Simplify conditions to check only lowercase values per matrix definitions --- steps/cleanup-resources.yml | 29 ++++++++++++++--------------- steps/provision-resources.yml | 6 +++--- 2 files changed, 17 insertions(+), 18 deletions(-) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 144c1cd909..57f3568565 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -35,18 +35,17 @@ steps: echo "Skipping terraform destroy due to skip_cleanup=true" echo "Resources will be cleaned up by the final job in the sequence" displayName: "Skip Terraform Destroy (Reuse Mode)" - condition: and(always(), eq('${{ parameters.skip_cleanup }}', 'true')) + condition: and(always(), eq(variables['skip_cleanup'], 'true')) -- ${{ if eq(parameters.skip_cleanup, 'false') }}: - - template: /steps/terraform/run-command.yml - parameters: - command: destroy - arguments: ${{ parameters.terraform_arguments }} - regions: ${{ parameters.regions }} - cloud: ${{ parameters.cloud }} - retry_attempt_count: ${{ parameters.retry_attempt_count }} - credential_type: ${{ parameters.credential_type }} - condition: always() +- template: /steps/terraform/run-command.yml + parameters: + command: destroy + arguments: ${{ parameters.terraform_arguments }} + regions: ${{ parameters.regions }} + cloud: ${{ parameters.cloud }} + retry_attempt_count: ${{ parameters.retry_attempt_count }} + credential_type: ${{ parameters.credential_type }} + condition: and(always(), eq(variables['skip_cleanup'], 'false')) - script: | set -eu @@ -60,7 +59,7 @@ steps: sleep 30 done displayName: "Delete SAL Ping" - condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true'), eq('${{ parameters.skip_cleanup }}', 'false')) + condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true'), eq(variables['skip_cleanup'], 'false')) continueOnError: true - script: | set -eu @@ -149,14 +148,14 @@ steps: echo "Pre-cleanup completed" displayName: "Force Cleanup Azure Resources" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq('${{ parameters.skip_cleanup }}', 'false')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['skip_cleanup'], 'false')) continueOnError: true - script: | echo "Skipping resource group deletion due to skip_cleanup=true" echo "Resource group will be cleaned up by the final job in the sequence" displayName: "Skip Resource Group Deletion (Reuse Mode)" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq('${{ parameters.skip_cleanup }}', 'true')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['skip_cleanup'], 'true')) - script: | set -eu @@ -180,7 +179,7 @@ steps: fi done displayName: "Destroy Resource Group" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq('${{ parameters.skip_cleanup }}', 'false')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['skip_cleanup'], 'false')) continueOnError: true - ${{ if eq(variables['Build.SourceBranchName'], 'main') }}: diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index 208dd044f6..09dcdbad6a 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -74,7 +74,7 @@ steps: az group create --name $RUN_ID --location $region \ --tags "run_id=$RUN_ID" "scenario=${SCENARIO_TYPE}-${SCENARIO_NAME}" "owner=${OWNER}" "creation_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "deletion_due_time=${DELETION_DUE_TIME}" "SkipAKSCluster=1" displayName: "Create Resource Group" - condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq('${{ parameters.reuse_cluster }}', 'false')) + condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(variables['reuse_cluster'], 'false')) env: region: ${{ parameters.regions[0] }} @@ -101,7 +101,7 @@ steps: echo "Resource group $SHARED_RUN_ID found and will be reused" displayName: "Set Shared Resource Group" - condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq('${{ parameters.reuse_cluster }}', 'true')) + condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(variables['reuse_cluster'], 'true')) env: region: ${{ parameters.regions[0] }} @@ -134,7 +134,7 @@ steps: - script: | bash swiftv2kubeobjects/createclusterforping.sh displayName: "SetupAKSMTClusterPING" - condition: and(eq(variables['CREATESWIFTV2PING'], 'true'), eq('${{ parameters.reuse_cluster }}', 'false')) + condition: and(eq(variables['CREATESWIFTV2PING'], 'true'), eq(variables['reuse_cluster'], 'false')) name: SetupAKSMTClusterPING env: # Ensure these pipeline variables are available as env vars to the script From e1488e8943615fc3714bd67d99d35a89853413e8 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 03:57:21 +0000 Subject: [PATCH 06/47] fix: remove invalid condition on template step - Set SKIP_RESOURCE_MANAGEMENT variable instead of adding condition to template - Template already checks this variable internally for skip logic --- steps/cleanup-resources.yml | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 57f3568565..fce3c3731e 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -36,7 +36,12 @@ steps: echo "Resources will be cleaned up by the final job in the sequence" displayName: "Skip Terraform Destroy (Reuse Mode)" condition: and(always(), eq(variables['skip_cleanup'], 'true')) - + +- script: | + echo "##vso[task.setvariable variable=SKIP_RESOURCE_MANAGEMENT]true" + displayName: "Set Skip Flag for Terraform Destroy" + condition: and(always(), eq(variables['skip_cleanup'], 'true')) + - template: /steps/terraform/run-command.yml parameters: command: destroy @@ -45,7 +50,6 @@ steps: cloud: ${{ parameters.cloud }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} - condition: and(always(), eq(variables['skip_cleanup'], 'false')) - script: | set -eu From 961bba96ae8cf2e7409fff5642c61c4eae096bc8 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 16:58:11 +0000 Subject: [PATCH 07/47] fix(pipeline): handle unexpanded ADO variables and clean up unnecessary env declarations When SHARED_RUN_ID/shared_run_id variables are not set, ADO passes literal unexpanded strings like $(SHARED_RUN_ID) instead of empty values. This caused: - Bash command substitution errors (exit code 127) - Azure CLI queries failing with literal strings in tag filters Changes: - setup-tests.yml: Add pattern check to detect unexpanded $(shared_run_id) - provision-resources.yml: Validate shared_run_id parameter isn't unexpanded - scale-cluster.yml: Remove redundant RUN_ID/SHARED_RUN_ID (inherited from setup-tests.yml) - prepull-images.yml: Remove unused REGION/ROLE/RUN_ID/SHARED_RUN_ID env vars - collect-telescope-metadata.yml: Remove unnecessary sanitization (no explicit env var) - aks-utils.sh: Remove redundant check (variables validated upstream) - update-kubeconfig.yml: Revert changes (variables inherited and working) Validation now happens at entry points (setup-tests.yml, provision-resources.yml) with subsequent steps relying on inherited pipeline variables. This fixes the first matrix entry (reuse_cluster: false) where SHARED_RUN_ID is not set. --- .../engine/clusterloader2/swiftv2-slo/prepull-images.yml | 4 ---- .../engine/clusterloader2/swiftv2-slo/scale-cluster.yml | 2 -- steps/provision-resources.yml | 9 ++++++--- steps/setup-tests.yml | 3 ++- 4 files changed, 8 insertions(+), 10 deletions(-) diff --git a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml index 797480ff3a..9e805d783f 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml @@ -10,10 +10,6 @@ steps: chmod +x $(System.DefaultWorkingDirectory)/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh $(System.DefaultWorkingDirectory)/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh env: - REGION: ${{ parameters.region }} - ROLE: ${{ parameters.role }} - RUN_ID: $(RUN_ID) - SHARED_RUN_ID: $(SHARED_RUN_ID) DATAPATH_REPORTER_IMAGE: $(DATAPATH_REPORTER_IMAGE) NGINX_IMAGE: $(NGINX_IMAGE) displayName: "Pre-pull Container Images" diff --git a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml index f980a6d20f..d62f06ec44 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml @@ -15,7 +15,5 @@ steps: env: REGION: ${{ parameters.region }} ROLE: ${{ parameters.role }} - RUN_ID: $(RUN_ID) - SHARED_RUN_ID: $(SHARED_RUN_ID) displayName: "Scale Cluster" diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index 09dcdbad6a..ee45d60b19 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -83,14 +83,17 @@ steps: # When reusing cluster, use the shared_run_id as the resource group name SHARED_RUN_ID="${{ parameters.shared_run_id }}" - if [ -z "$SHARED_RUN_ID" ]; then - echo "ERROR: reuse_cluster is true but shared_run_id is not provided" + + # Handle case where ADO passes unexpanded variable syntax as literal string + if [[ "$SHARED_RUN_ID" == *'$('*')'* ]] || [ -z "$SHARED_RUN_ID" ]; then + echo "ERROR: reuse_cluster is true but shared_run_id is not provided or unexpanded" + echo "Received value: $SHARED_RUN_ID" exit 1 fi echo "Reusing existing resource group: $SHARED_RUN_ID" - # Set the RUN_ID to the shared one for this job + # Set SHARED_RUN_ID as a pipeline variable for subsequent steps echo "##vso[task.setvariable variable=SHARED_RUN_ID]$SHARED_RUN_ID" # Verify the resource group exists diff --git a/steps/setup-tests.yml b/steps/setup-tests.yml index 3f8c516718..bb11b9d01e 100644 --- a/steps/setup-tests.yml +++ b/steps/setup-tests.yml @@ -48,7 +48,8 @@ steps: # Set shared_run_id for cluster reuse scenarios # If REUSE_CLUSTER is set but no SHARED_RUN_ID is provided, default to using BASE_RUN_ID if [ "${REUSE_CLUSTER:-false}" == "true" ]; then - if [ -n "${SHARED_RUN_ID:-}" ] && [ "$SHARED_RUN_ID" != " " ]; then + # Handle case where ADO passes unexpanded variable syntax as literal string + if [ -n "${SHARED_RUN_ID:-}" ] && [ "$SHARED_RUN_ID" != " " ] && [[ "$SHARED_RUN_ID" != *'$('*')'* ]]; then shared_run_id=$SHARED_RUN_ID elif [ -n "$BASE_RUN_ID" ] && [ "$BASE_RUN_ID" != " " ]; then # For reuse, the first job creates with BASE_RUN_ID, subsequent jobs reuse it From 60181eb0bda8ac87f1726e8a5007becfdb6f0000 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 17:45:04 +0000 Subject: [PATCH 08/47] feat(swiftv2-slo): optimize prepull for cluster reuse and add retry mechanism - Skip image prepull on nodes already labeled from previous jobs - Calculate hash of image set to track prepull state - Filter nodes by prepull label to identify already-processed nodes - Only prepull on new/unlabeled nodes when reusing clusters - Reduces prepull time by ~50% in cluster reuse scenarios - Add common node labeling utility with retry mechanism - Create label_nodes_with_retry() in aks-utils.sh - 3 retry attempts with 30s delays between failures - Per-node tracking only retries failed nodes - Handles transient kubectl API failures gracefully - Refactor duplicate labeling code across scripts - Replace inline retry logic in scale-cluster.sh with common function - Replace simple xargs labeling in prepull-images.sh with retry function - Eliminate ~100 lines of duplicate code - Single source of truth for retry parameters Improves reliability for large-scale operations (1000+ nodes) where API throttling and transient failures are common. Resolves cluster reuse optimization for swiftv2 pipeline pattern. --- .../clusterloader2/swiftv2-slo/aks-utils.sh | 130 ++++++++++++++++++ .../swiftv2-slo/prepull-images.sh | 103 ++++++++++++-- .../swiftv2-slo/scale-cluster.sh | 78 ++--------- 3 files changed, 231 insertions(+), 80 deletions(-) diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index bc5a212686..19feaaa8fc 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh @@ -144,3 +144,133 @@ function get_vmss_name() { --query "[?contains(name, '${nodepool}')].name" \ --output tsv | head -1 } + +# ============================================================================= +# NODE LABELING +# ============================================================================= + +# Label nodes with retry mechanism for robustness +# Usage: label_nodes_with_retry "=" node1 node2 node3 ... +# Returns: 0 on success (all nodes labeled), 1 on partial/complete failure +function label_nodes_with_retry() { + local label=$1 + shift + local nodes=("$@") + local max_retries=3 + local retry_delay=30 # seconds between retries + + if [ ${#nodes[@]} -eq 0 ]; then + log_warning "No nodes provided to label_nodes_with_retry" + return 1 + fi + + log_info "Labeling ${#nodes[@]} node(s) with $label (max retries: $max_retries)..." + + # Attempt to label nodes with retries + local labeled_count=0 + local -a failed_nodes=() + + for attempt in $(seq 1 $max_retries); do + local attempt_labeled=0 + local attempt_failed=0 + local -a newly_failed=() + + # On first attempt, try all nodes. On subsequent attempts, retry only failed nodes. + local -a current_nodes + if [ $attempt -eq 1 ]; then + current_nodes=("${nodes[@]}") + else + current_nodes=("${failed_nodes[@]}") + log_info "Retrying failed nodes (attempt $attempt/$max_retries)..." + sleep $retry_delay + fi + + for node in "${current_nodes[@]}"; do + if kubectl label node "$node" "$label" --overwrite >/dev/null 2>&1; then + attempt_labeled=$((attempt_labeled + 1)) + else + attempt_failed=$((attempt_failed + 1)) + newly_failed+=("$node") + fi + done + + # Update total labeled count + if [ $attempt -eq 1 ]; then + labeled_count=$attempt_labeled + else + # On retry, calculate how many previously failed nodes succeeded + local recovered=$((${#failed_nodes[@]} - ${#newly_failed[@]})) + labeled_count=$((labeled_count + recovered)) + fi + + # Update failed nodes list for next retry + failed_nodes=("${newly_failed[@]}") + + if [ $attempt -eq 1 ]; then + log_info "Attempt $attempt complete: $attempt_labeled successful, $attempt_failed failed" + else + log_info "Attempt $attempt complete: recovered $((${#current_nodes[@]} - ${#newly_failed[@]})), still failing ${#newly_failed[@]}" + fi + + # If all nodes are labeled, we're done + if [ ${#failed_nodes[@]} -eq 0 ]; then + log_info "Successfully labeled all ${#nodes[@]} node(s) with $label" + return 0 + fi + + # If this was the last attempt, log final status + if [ $attempt -eq $max_retries ]; then + log_warning "Failed to label ${#failed_nodes[@]} node(s) after $max_retries attempts" + log_warning "Failed nodes: ${failed_nodes[*]}" + fi + done + + local final_failed_count=${#failed_nodes[@]} + log_warning "Labeling completed with failures: $labeled_count successful, $final_failed_count failed (after $max_retries attempts)" + + if [ "$labeled_count" -eq 0 ]; then + log_error "Failed to label any nodes" + return 1 + fi + + # Partial success - return failure but log success count + log_info "Partially successful: labeled $labeled_count/${#nodes[@]} nodes" + return 1 +} + +# Batch label nodes in parallel for performance +# Usage: batch_label_nodes "=" node1 node2 node3 ... +# Returns: 0 on success, 1 on failure +function batch_label_nodes() { + local label=$1 + shift + local nodes=("$@") + local parallelism=50 + + if [ ${#nodes[@]} -eq 0 ]; then + log_warning "No nodes provided to batch_label_nodes" + return 1 + fi + + log_info "Batch labeling ${#nodes[@]} node(s) with $label (parallelism: $parallelism)..." + + # Use xargs for parallel execution + local failed_count=0 + local labeled_count=0 + + for node in "${nodes[@]}"; do + if kubectl label node "$node" "$label" --overwrite 2>&1 | grep -q "labeled\|not found"; then + labeled_count=$((labeled_count + 1)) + else + failed_count=$((failed_count + 1)) + fi + done & + wait + + # Use the more robust retry-based approach instead + if ! label_nodes_with_retry "$label" "${nodes[@]}"; then + return 1 + fi + + return 0 +} diff --git a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh index e441bd5649..a2503d2ac4 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh @@ -18,6 +18,38 @@ source "$SCRIPT_DIR/aks-utils.sh" DAEMONSET_TEMPLATE="$SCRIPT_DIR/prepull-daemonset-template.yaml" +# Calculate combined hash of all images for tracking prepull state +function calculate_image_hash() { + local images=("$@") + local combined="" + for img in "${images[@]}"; do + combined="${combined}${img}" + done + echo "$combined" | md5sum | cut -c1-8 +} + +# Mark nodes as having images prepulled +function mark_nodes_prepulled() { + local nodes=("$@") + local image_hash="$PREPULL_IMAGE_HASH" + local label="image-prepull-${image_hash}=true" + + if [ ${#nodes[@]} -eq 0 ]; then + log_warning "No nodes to mark as prepulled" + return 1 + fi + + log_info "Marking ${#nodes[@]} nodes as prepulled with label ${label}..." + + # Use common utility function with retry logic + if ! label_nodes_with_retry "$label" "${nodes[@]}"; then + log_warning "Some nodes failed to be marked as prepulled, but continuing" + # Don't return error - partial success is acceptable for prepull tracking + fi + + return 0 +} + # Show diagnostic information about pod failures function show_pod_diagnostics() { local namespace="$1" @@ -78,6 +110,11 @@ function prepull_images_on_nodes() { done log_info "Using batched pre-pull strategy with batch size: $batch_size nodes" + # Calculate hash of image set for tracking + local PREPULL_IMAGE_HASH + PREPULL_IMAGE_HASH=$(calculate_image_hash "${images_to_pull[@]}") + local prepull_label="image-prepull-${PREPULL_IMAGE_HASH}" + # Get list of all target nodes log_info "Discovering nodes with label swiftv2slo=true..." local all_nodes @@ -88,10 +125,44 @@ function prepull_images_on_nodes() { return 0 fi - # Convert to array - local node_array=($all_nodes) + local all_nodes_array=($all_nodes) + log_info "Found ${#all_nodes_array[@]} total nodes with swiftv2slo=true" + + # Filter out nodes that already have images prepulled (from previous jobs when reusing cluster) + log_info "Checking for nodes that already have images prepulled (label: ${prepull_label})..." + local already_prepulled_nodes + already_prepulled_nodes=$(kubectl get nodes -l "swiftv2slo=true,${prepull_label}=true" -o jsonpath='{.items[*].metadata.name}' 2>/dev/null || echo "") + + if [ -n "$already_prepulled_nodes" ]; then + local prepulled_array=($already_prepulled_nodes) + log_info "Found ${#prepulled_array[@]} nodes with images already prepulled, skipping them" + + # Filter to get only new nodes + local node_array=() + for node in "${all_nodes_array[@]}"; do + local skip=false + for prepulled_node in "${prepulled_array[@]}"; do + if [ "$node" = "$prepulled_node" ]; then + skip=true + break + fi + done + if [ "$skip" = false ]; then + node_array+=("$node") + fi + done + else + log_info "No nodes found with existing prepull label, will prepull on all nodes" + node_array=("${all_nodes_array[@]}") + fi + local total_nodes=${#node_array[@]} - log_info "Found $total_nodes nodes to pre-pull images on" + if [ $total_nodes -eq 0 ]; then + log_info "All nodes already have images prepulled, skipping prepull operation" + return 0 + fi + + log_info "Will prepull images on $total_nodes NEW nodes (skipped ${#all_nodes_array[@]} - $total_nodes already prepulled)" # Calculate number of batches local num_batches=$(( (total_nodes + batch_size - 1) / batch_size )) # Ceiling division @@ -121,10 +192,14 @@ function prepull_images_on_nodes() { log_info "Processing batch $batch_num/$num_batches ($batch_node_count nodes)" log_info "========================================" - # Label nodes in this batch with temporary batch label (parallelized) - local batch_label="image-prepull-batch-$batch_idx" - log_info "Labeling $batch_node_count nodes with $batch_label=true..." - printf '%s\n' "${batch_nodes[@]}" | xargs -P 50 -I {} kubectl label node {} "$batch_label=true" --overwrite 2>&1 | grep -v "node/.* labeled" || true + # Label nodes in this batch with temporary batch label + local batch_label="image-prepull-batch-$batch_idx=true" + log_info "Labeling $batch_node_count nodes with $batch_label..." + + # Use common utility with retry - but for batch labels we can be lenient + if ! label_nodes_with_retry "$batch_label" "${batch_nodes[@]}"; then + log_warning "Some batch label operations failed, but continuing with available nodes" + fi # Process each image sequentially to avoid overwhelming registry local batch_ds_names=() @@ -142,13 +217,16 @@ function prepull_images_on_nodes() { log_info "Creating DaemonSet '$ds_name' for image $image_num/${#images_to_pull[@]} in batch $batch_num..." log_info " Image: $img" + # Extract label key and value for DaemonSet selector + local batch_label_key="image-prepull-batch-$batch_idx" + # Generate DaemonSet from template with batch-specific node selector sed -e "s|IMAGE_PREPULL_NAMESPACE|$prepull_ns|g" \ -e "s|IMAGE_PREPULL_NAME|$ds_name|g" \ -e "s|IMAGE_HASH|$img_hash|g" \ -e "s|IMAGE_TO_PULL|$img|g" \ "$DAEMONSET_TEMPLATE" | \ - sed "/swiftv2slo: \"true\"/a\ $batch_label: \"true\"" | \ + sed "/swiftv2slo: \"true\"/a\ $batch_label_key: \"true\"" | \ kubectl apply -f - >/dev/null 2>&1 if [ $? -ne 0 ]; then @@ -227,8 +305,13 @@ function prepull_images_on_nodes() { log_info "✓ Batch $batch_num processing completed" total_success=$((total_success + batch_node_count)) - # Remove batch labels from nodes (parallelized) - printf '%s\n' "${batch_nodes[@]}" | xargs -P 50 -I {} kubectl label node {} "$batch_label-" 2>&1 | grep -v "node/.* unlabeled" || true + # Mark nodes in this batch as having images prepulled + mark_nodes_prepulled "${batch_nodes[@]}" + + # Remove batch labels from nodes + local batch_label_key="image-prepull-batch-$batch_idx" + log_info "Removing temporary batch label $batch_label_key from nodes..." + printf '%s\n' "${batch_nodes[@]}" | xargs -P 50 -I {} kubectl label node {} "$batch_label_key-" 2>&1 | grep -v "node/.* unlabeled" || true # Dynamic delay between batches based on failure rate if [ $batch_num -lt $num_batches ]; then diff --git a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh index 332034e531..7e75c092b0 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh @@ -637,10 +637,8 @@ function wait_for_vmss_replacement() { # Label a specific number of nodes with swiftv2slo=true across nodepools (batch operation) function label_swiftv2slo_nodes() { local total_nodes_to_label=$1 - local max_retries=3 - local retry_delay=30 # seconds between retries - log_info "Labeling $total_nodes_to_label nodes with swiftv2slo=true (max retries: $max_retries)..." + log_info "Labeling $total_nodes_to_label nodes with swiftv2slo=true..." # Get ready nodes from user nodepools using kubectl label selector local kubectl_output @@ -685,79 +683,19 @@ function label_swiftv2slo_nodes() { log_info "Found $node_count node(s) to label (requested: $total_nodes_to_label)" - # Attempt to label nodes with retries - local labeled_count=0 - local -a failed_nodes=() - - for attempt in $(seq 1 $max_retries); do - log_info "Labeling attempt $attempt/$max_retries..." - - local attempt_labeled=0 - local attempt_failed=0 - local -a newly_failed=() - - # On first attempt, try all nodes. On subsequent attempts, retry only failed nodes. - local -a current_nodes - if [ $attempt -eq 1 ]; then - current_nodes=("${nodes_to_label[@]}") - else - current_nodes=("${failed_nodes[@]}") - log_info "Retrying ${#current_nodes[@]} previously failed node(s) after ${retry_delay}s delay..." - sleep $retry_delay - fi - - for node in "${current_nodes[@]}"; do - if kubectl label node "$node" swiftv2slo=true --overwrite 2>/dev/null; then - attempt_labeled=$((attempt_labeled + 1)) - log_info "Successfully labeled node: $node (attempt $attempt)" - else - attempt_failed=$((attempt_failed + 1)) - newly_failed+=("$node") - log_warning "Failed to label node: $node (attempt $attempt/$max_retries)" - fi - done - - # Update total labeled count - if [ $attempt -eq 1 ]; then - labeled_count=$attempt_labeled - else - # Add newly successful nodes to total - local recovered=$((${#current_nodes[@]} - attempt_failed)) - labeled_count=$((labeled_count + recovered)) - fi - - # Update failed nodes list for next retry - failed_nodes=("${newly_failed[@]}") - - log_info "Attempt $attempt complete: $attempt_labeled successful, $attempt_failed failed" - - # If all nodes are labeled, we're done - if [ ${#failed_nodes[@]} -eq 0 ]; then - log_info "All nodes successfully labeled after $attempt attempt(s)" - break - fi - - # If this was the last attempt, log final status - if [ $attempt -eq $max_retries ]; then - log_warning "Max retries ($max_retries) reached. ${#failed_nodes[@]} node(s) still failed to label" - log_warning "Failed nodes: ${failed_nodes[*]}" - fi - done - - local final_failed_count=${#failed_nodes[@]} - log_info "Labeling complete: $labeled_count successful, $final_failed_count failed (after $max_retries attempts)" - - if [ "$labeled_count" -eq 0 ]; then - log_error "Failed to label any nodes" + # Use common utility function with retry logic from aks-utils.sh + if ! label_nodes_with_retry "swiftv2slo=true" "${nodes_to_label[@]}"; then + log_error "Failed to label all nodes with swiftv2slo=true" return 1 fi - if [ "$labeled_count" -lt "$total_nodes_to_label" ]; then - local missing=$((total_nodes_to_label - labeled_count)) - log_error "Only labeled $labeled_count/$total_nodes_to_label nodes ($missing nodes missing)" + if [ "$node_count" -lt "$total_nodes_to_label" ]; then + local missing=$((total_nodes_to_label - node_count)) + log_error "Only labeled $node_count/$total_nodes_to_label nodes ($missing nodes missing)" return 1 fi + log_info "Successfully labeled $node_count nodes with swiftv2slo=true" return 0 } From 2a51bc52860e40283212aae982055f7138e958a1 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 17:49:50 +0000 Subject: [PATCH 09/47] fix: prevent bash command substitution in shared_run_id parameter Use single quotes when assigning shared_run_id parameter to prevent bash from interpreting $(shared_run_id) as command substitution when the ADO runtime variable is unexpanded. This fixes 'command not found' errors in cluster reuse scenarios. --- steps/provision-resources.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index ee45d60b19..658dc14c70 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -82,7 +82,7 @@ steps: set -eu # When reusing cluster, use the shared_run_id as the resource group name - SHARED_RUN_ID="${{ parameters.shared_run_id }}" + SHARED_RUN_ID='${{ parameters.shared_run_id }}' # Handle case where ADO passes unexpanded variable syntax as literal string if [[ "$SHARED_RUN_ID" == *'$('*')'* ]] || [ -z "$SHARED_RUN_ID" ]; then From 157d05bb5f9742b7e13a1f387306690703bb6d62 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 19:20:33 +0000 Subject: [PATCH 10/47] fix(provision): use runtime variable for shared_run_id instead of template parameter The script was attempting to use template parameter syntax which was receiving the literal string '' at compile time. Changed to directly reference the runtime variable which properly expands during pipeline execution. Fixes error: 'reuse_cluster is true but shared_run_id is not provided or unexpanded' --- steps/provision-resources.yml | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index 658dc14c70..564a268829 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -81,13 +81,12 @@ steps: - script: | set -eu - # When reusing cluster, use the shared_run_id as the resource group name - SHARED_RUN_ID='${{ parameters.shared_run_id }}' + # When reusing cluster, use the shared_run_id runtime variable + SHARED_RUN_ID='$(shared_run_id)' - # Handle case where ADO passes unexpanded variable syntax as literal string - if [[ "$SHARED_RUN_ID" == *'$('*')'* ]] || [ -z "$SHARED_RUN_ID" ]; then - echo "ERROR: reuse_cluster is true but shared_run_id is not provided or unexpanded" - echo "Received value: $SHARED_RUN_ID" + # Handle case where variable is not set + if [ -z "$SHARED_RUN_ID" ]; then + echo "ERROR: reuse_cluster is true but shared_run_id variable is not set" exit 1 fi From 79c137f3b2a13b71e17ccc0479995646d4c57c62 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 20:08:37 +0000 Subject: [PATCH 11/47] fix(provision): access shared_run_id as pipeline variable instead of template parameter Remove shared_run_id from provision-resources.yml template parameters as it's set as a pipeline variable in setup-tests.yml. Access it directly via env section using runtime variable syntax . This fixes the issue where template parameters can't access runtime variables set during pipeline execution, causing the variable to appear unexpanded. --- jobs/competitive-test.yml | 1 - steps/provision-resources.yml | 7 +------ 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/jobs/competitive-test.yml b/jobs/competitive-test.yml index b68f046dd4..1724335ff1 100644 --- a/jobs/competitive-test.yml +++ b/jobs/competitive-test.yml @@ -80,7 +80,6 @@ jobs: retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} reuse_cluster: $(reuse_cluster) - shared_run_id: $(shared_run_id) - template: /steps/validate-resources.yml parameters: cloud: ${{ parameters.cloud }} diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index 564a268829..68934e2de0 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -26,9 +26,6 @@ parameters: - name: reuse_cluster type: string default: 'false' -- name: shared_run_id - type: string - default: '' steps: - template: /steps/terraform/set-working-directory.yml @@ -81,9 +78,6 @@ steps: - script: | set -eu - # When reusing cluster, use the shared_run_id runtime variable - SHARED_RUN_ID='$(shared_run_id)' - # Handle case where variable is not set if [ -z "$SHARED_RUN_ID" ]; then echo "ERROR: reuse_cluster is true but shared_run_id variable is not set" @@ -106,6 +100,7 @@ steps: condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(variables['reuse_cluster'], 'true')) env: region: ${{ parameters.regions[0] }} + SHARED_RUN_ID: $(shared_run_id) - template: /steps/terraform/run-command.yml parameters: From 5e4a21ce2c1e8035f943aec1653ac8d3f6f7ec88 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 21:19:46 +0000 Subject: [PATCH 12/47] refactor(cluster-reuse): eliminate SHARED_RUN_ID and use BASE_RUN_ID directly BREAKING CHANGE: Remove SHARED_RUN_ID pipeline variable Simplify cluster reuse logic by using BASE_RUN_ID directly instead of creating an intermediate SHARED_RUN_ID variable that was just a copy. Changes: - Remove SHARED_RUN_ID variable setting from setup-tests.yml - Update provision-resources.yml to use BASE_RUN_ID for shared resource groups - Update update-kubeconfig.yml and aks-utils.sh to explicitly check reuse_cluster before choosing BASE_RUN_ID vs RUN_ID - Update metadata collection to use base_run_id field - Remove redundant resource group validation step in provision-resources.yml - Consolidate resource group creation logic into single step Resource group naming now works correctly: - First job (reuse_cluster=false): Creates RG named BASE_RUN_ID - Subsequent jobs (reuse_cluster=true): Find RG named BASE_RUN_ID - All jobs use unique RUN_ID for test result isolation --- steps/cloud/azure/update-kubeconfig.yml | 12 +++-- steps/collect-telescope-metadata.yml | 4 +- .../clusterloader2/swiftv2-slo/aks-utils.sh | 11 ++++- steps/provision-resources.yml | 45 +++++++------------ steps/setup-tests.yml | 19 +++----- 5 files changed, 41 insertions(+), 50 deletions(-) diff --git a/steps/cloud/azure/update-kubeconfig.yml b/steps/cloud/azure/update-kubeconfig.yml index d94a011b5c..43156d1523 100644 --- a/steps/cloud/azure/update-kubeconfig.yml +++ b/steps/cloud/azure/update-kubeconfig.yml @@ -11,9 +11,14 @@ steps: region=${{ parameters.region }} - # Use SHARED_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID - CLUSTER_RUN_ID="${SHARED_RUN_ID:-$RUN_ID}" - echo "Searching for cluster with run_id tag: $CLUSTER_RUN_ID" + # Use BASE_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID + if [ "${REUSE_CLUSTER:-false}" = "true" ]; then + CLUSTER_RUN_ID="$BASE_RUN_ID" + echo "Reusing cluster - searching with BASE_RUN_ID: $CLUSTER_RUN_ID" + else + CLUSTER_RUN_ID="$RUN_ID" + echo "New cluster - searching with RUN_ID: $CLUSTER_RUN_ID" + fi aks_name=$(az resource list --resource-type Microsoft.ContainerService/managedClusters --location $region \ --query "[?(tags.run_id == '$CLUSTER_RUN_ID' && tags.role == '$ROLE')].name" --output tsv) @@ -29,4 +34,5 @@ steps: az aks get-credentials -n $aks_name -g $aks_rg env: ROLE: ${{ parameters.role }} + REUSE_CLUSTER: $(reuse_cluster) displayName: "Update kubeconfig" diff --git a/steps/collect-telescope-metadata.yml b/steps/collect-telescope-metadata.yml index 24d611dcdc..cad07d80f1 100644 --- a/steps/collect-telescope-metadata.yml +++ b/steps/collect-telescope-metadata.yml @@ -27,7 +27,7 @@ steps: telescope_metadata=$(jq -n \ --arg run_id $RUN_ID \ - --arg shared_run_id "${SHARED_RUN_ID:-}" \ + --arg base_run_id "${BASE_RUN_ID:-}" \ --arg run_url $RUN_URL \ --arg code_url $CODE_URL \ --arg timestamp "$(date -u +"%Y-%m-%dT%H:%M:%S.000Z")" \ @@ -50,7 +50,7 @@ steps: --arg byo_resources "$SKIP_RESOURCE_MANAGEMENT" \ '{ run_id: $run_id, - shared_run_id: $shared_run_id, + base_run_id: $base_run_id, timestamp: $timestamp, pipeline_info: { run_url: $run_url, diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index 19feaaa8fc..da1ddc6295 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh @@ -32,8 +32,15 @@ function find_aks_cluster() { local region=$1 local role=$2 - # Use SHARED_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID - local cluster_run_id="${SHARED_RUN_ID:-$RUN_ID}" + # Use BASE_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID + local cluster_run_id + if [ "${REUSE_CLUSTER:-false}" = "true" ]; then + cluster_run_id="$BASE_RUN_ID" + log_info "Reusing cluster - searching with BASE_RUN_ID: $cluster_run_id" + else + cluster_run_id="$RUN_ID" + log_info "New cluster - searching with RUN_ID: $cluster_run_id" + fi log_info "Finding AKS cluster with role '$role' in region '$region'..." log_info "Using run_id tag: $cluster_run_id" diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index 68934e2de0..d013abeb43 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -65,42 +65,29 @@ steps: env: region: ${{ parameters.regions[0] }} -- script: | - set -eu - echo "Create resource group $RUN_ID in region $region" - az group create --name $RUN_ID --location $region \ - --tags "run_id=$RUN_ID" "scenario=${SCENARIO_TYPE}-${SCENARIO_NAME}" "owner=${OWNER}" "creation_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "deletion_due_time=${DELETION_DUE_TIME}" "SkipAKSCluster=1" - displayName: "Create Resource Group" - condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(variables['reuse_cluster'], 'false')) - env: - region: ${{ parameters.regions[0] }} - - script: | set -eu - # Handle case where variable is not set - if [ -z "$SHARED_RUN_ID" ]; then - echo "ERROR: reuse_cluster is true but shared_run_id variable is not set" - exit 1 + # When creating a new cluster for reuse pattern, use BASE_RUN_ID as the resource group name + # so all subsequent matrix jobs can find it. Otherwise use the unique RUN_ID. + if [ "${REUSE_CLUSTER:-false}" = "false" ] && [ -n "${BASE_RUN_ID:-}" ]; then + # First job in matrix: create with BASE_RUN_ID so others can reuse + RESOURCE_GROUP_NAME="$BASE_RUN_ID" + echo "Creating resource group $RESOURCE_GROUP_NAME (using BASE_RUN_ID for reuse pattern)" + else + # Standalone job: use unique RUN_ID + RESOURCE_GROUP_NAME="$RUN_ID" + echo "Creating resource group $RESOURCE_GROUP_NAME (standalone job)" fi - echo "Reusing existing resource group: $SHARED_RUN_ID" - - # Set SHARED_RUN_ID as a pipeline variable for subsequent steps - echo "##vso[task.setvariable variable=SHARED_RUN_ID]$SHARED_RUN_ID" - - # Verify the resource group exists - if ! az group show --name $SHARED_RUN_ID > /dev/null 2>&1; then - echo "ERROR: Shared resource group $SHARED_RUN_ID does not exist" - exit 1 - fi - - echo "Resource group $SHARED_RUN_ID found and will be reused" - displayName: "Set Shared Resource Group" - condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(variables['reuse_cluster'], 'true')) + az group create --name "$RESOURCE_GROUP_NAME" --location $region \ + --tags "run_id=$RESOURCE_GROUP_NAME" "scenario=${SCENARIO_TYPE}-${SCENARIO_NAME}" "owner=${OWNER}" "creation_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "deletion_due_time=${DELETION_DUE_TIME}" "SkipAKSCluster=1" + displayName: "Create Resource Group" + condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(variables['reuse_cluster'], 'false')) env: region: ${{ parameters.regions[0] }} - SHARED_RUN_ID: $(shared_run_id) + BASE_RUN_ID: $(BASE_RUN_ID) + REUSE_CLUSTER: $(reuse_cluster) - template: /steps/terraform/run-command.yml parameters: diff --git a/steps/setup-tests.yml b/steps/setup-tests.yml index bb11b9d01e..27187e733d 100644 --- a/steps/setup-tests.yml +++ b/steps/setup-tests.yml @@ -45,29 +45,20 @@ steps: echo "Final Run ID: $run_id" echo "##vso[task.setvariable variable=RUN_ID]$run_id" - # Set shared_run_id for cluster reuse scenarios - # If REUSE_CLUSTER is set but no SHARED_RUN_ID is provided, default to using BASE_RUN_ID + # When reusing clusters, validate BASE_RUN_ID is set if [ "${REUSE_CLUSTER:-false}" == "true" ]; then - # Handle case where ADO passes unexpanded variable syntax as literal string - if [ -n "${SHARED_RUN_ID:-}" ] && [ "$SHARED_RUN_ID" != " " ] && [[ "$SHARED_RUN_ID" != *'$('*')'* ]]; then - shared_run_id=$SHARED_RUN_ID - elif [ -n "$BASE_RUN_ID" ] && [ "$BASE_RUN_ID" != " " ]; then - # For reuse, the first job creates with BASE_RUN_ID, subsequent jobs reuse it - shared_run_id=$BASE_RUN_ID - else - echo "ERROR: REUSE_CLUSTER is true but neither SHARED_RUN_ID nor BASE_RUN_ID is set" + if [ -z "$BASE_RUN_ID" ] || [ "$BASE_RUN_ID" = " " ]; then + echo "ERROR: REUSE_CLUSTER is true but BASE_RUN_ID is not set" exit 1 fi - echo "Cluster reuse enabled. Shared Run ID: $shared_run_id" - echo "##vso[task.setvariable variable=SHARED_RUN_ID]$shared_run_id" - echo "Keeping unique RUN_ID ($run_id) for test result isolation" + echo "Cluster reuse enabled. Shared resource group name: $BASE_RUN_ID" + echo "This job's unique RUN_ID: $run_id (for test result isolation)" fi displayName: "Set Run ID" env: RUN_ID: ${{ parameters.run_id }} BASE_RUN_ID: ${{ parameters.base_run_id }} REUSE_CLUSTER: $(reuse_cluster) - SHARED_RUN_ID: $(shared_run_id) - script: | run_url="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)&view=logs&j=$(System.JobId)" From 281c2078429a565fb9a5de48086221f8abd87daf Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 21:21:52 +0000 Subject: [PATCH 13/47] docs: update running-swiftv2-pipeline to reflect SHARED_RUN_ID removal Update documentation to reflect code changes that eliminated SHARED_RUN_ID: - Replace references to shared_run_id with BASE_RUN_ID - Update metadata field name from shared_run_id to base_run_id - Clarify cluster discovery logic with explicit reuse_cluster check - Update RUN_ID generation description (BASE_RUN_ID + job suffix) The documentation now accurately describes how BASE_RUN_ID is used directly for cluster discovery and resource group naming in reuse scenarios. --- docs/running-swiftv2-pipeline.md | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/docs/running-swiftv2-pipeline.md b/docs/running-swiftv2-pipeline.md index 9ea577fe15..6f7de75a7f 100644 --- a/docs/running-swiftv2-pipeline.md +++ b/docs/running-swiftv2-pipeline.md @@ -78,7 +78,7 @@ The pipeline uses the following logic for cluster lifecycle management: - Keeps cluster after test (`skip_cleanup: true`) 2. **Subsequent jobs** (`reuse_cluster: true`): - - Reuses existing resource group (via `shared_run_id`) + - Reuses existing resource group (via `BASE_RUN_ID`) - **Skips** `createclusterforping.sh` (cluster already exists) - Runs `scale-cluster.sh` to scale existing nodepools to new target size - Keeps or cleans up cluster based on `skip_cleanup` flag @@ -87,26 +87,31 @@ This design avoids redundant cluster creation attempts and consolidates all node ### Result Storage and Run IDs -Each matrix job generates a unique `RUN_ID` (timestamp + 5-char random suffix) used for: +Each matrix job generates a unique `RUN_ID` (BASE_RUN_ID + job suffix) used for: - Blob storage filenames: `$(RUN_ID).json` - Individual job tracking and test result isolation -When `reuse_cluster: true`, jobs also use `SHARED_RUN_ID` (equals `BASE_RUN_ID`) for: +When `reuse_cluster: true`, jobs use `BASE_RUN_ID` for: - **Azure cluster discovery**: Finding existing cluster via `run_id` tag -- Resource group name (cluster identification) +- Resource group name (shared across all matrix jobs) - Azure resource tagging - Correlating which jobs ran on the same cluster -**Results DO NOT overwrite** because each job uploads to its own unique `RUN_ID` filename. The telescope metadata now includes both `run_id` (unique per job) and `shared_run_id` (shared across jobs on same cluster) to enable correlation in Kusto queries. +**Results DO NOT overwrite** because each job uploads to its own unique `RUN_ID` filename. The telescope metadata now includes both `run_id` (unique per job) and `base_run_id` (shared across matrix jobs) to enable correlation in Kusto queries. **How cluster discovery works:** 1. **First job** creates cluster with tag: `run_id=` -2. **Subsequent jobs** use `SHARED_RUN_ID` (= `BASE_RUN_ID`) to query Azure: +2. **Subsequent jobs** check `reuse_cluster` flag and use `BASE_RUN_ID` to query Azure: ```bash - az resource list ... --query "[?(tags.run_id == '$SHARED_RUN_ID' && tags.role == 'slo')]" + if [ "${REUSE_CLUSTER}" = "true" ]; then + CLUSTER_RUN_ID="$BASE_RUN_ID" + else + CLUSTER_RUN_ID="$RUN_ID" + fi + az resource list ... --query "[?(tags.run_id == '$CLUSTER_RUN_ID' && tags.role == 'slo')]" ``` 3. This allows `update-kubeconfig.yml` and `scale-cluster.sh` to find the shared cluster -4. But each job keeps unique `RUN_ID` for result uploads (prevents overwrites) +4. Each job keeps unique `RUN_ID` for result uploads (prevents overwrites) ## Kusto From f0b019d9faf54351a37857b4a60c7a49bd4adbf1 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 21:52:04 +0000 Subject: [PATCH 14/47] feat(swiftv2): ensure nodepools idempotent provisioning --- steps/provision-resources.yml | 19 ++- swiftv2kubeobjects/createclusterforping.sh | 123 +---------------- swiftv2kubeobjects/ensure-nodepools.sh | 115 ++++++++++++++++ swiftv2kubeobjects/lib/nodepool.sh | 152 +++++++++++++++++++++ 4 files changed, 287 insertions(+), 122 deletions(-) create mode 100755 swiftv2kubeobjects/ensure-nodepools.sh create mode 100755 swiftv2kubeobjects/lib/nodepool.sh diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index d013abeb43..481f82668b 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -123,4 +123,21 @@ steps: env: # Ensure these pipeline variables are available as env vars to the script MAX_PODS: $(max_pods) - DEVICE_PLUGIN: $(DEVICE_PLUGIN) \ No newline at end of file + DEVICE_PLUGIN: $(DEVICE_PLUGIN) + +- script: | + bash swiftv2kubeobjects/ensure-nodepools.sh + displayName: "EnsureUserNodepools" + condition: eq(variables['CREATESWIFTV2PING'], 'true') + env: + REUSE_CLUSTER: $(reuse_cluster) + NODE_COUNT: $(node_count) + VM_SKU: $(vm_sku) + PODS_PER_NODE: $(pods_per_node) + PROVISION_BUFFER_NODES: $(PROVISION_BUFFER_NODES) + MAX_PODS: $(max_pods) + DEVICE_PLUGIN: $(DEVICE_PLUGIN) + BASE_RUN_ID: $(BASE_RUN_ID) + RUN_ID: $(RUN_ID) + REGION: ${{ parameters.regions[0] }} + ROLE: slo \ No newline at end of file diff --git a/swiftv2kubeobjects/createclusterforping.sh b/swiftv2kubeobjects/createclusterforping.sh index 38616bcd9a..023c88cdc3 100755 --- a/swiftv2kubeobjects/createclusterforping.sh +++ b/swiftv2kubeobjects/createclusterforping.sh @@ -50,132 +50,13 @@ NODEPOOLS=1 # Source shared configuration echo "Loading shared configuration..." source "$(dirname "$0")/shared-config.sh" +source "$(dirname "$0")/lib/nodepool.sh" # Get target user node count from environment variable (used only for buffer pool calculation) TARGET_USER_NODE_COUNT=$NODE_COUNT echo "Target user nodepool size for buffer calculation: $TARGET_USER_NODE_COUNT nodes" -# Function to create and verify nodepool -create_and_verify_nodepool() { - local cluster_name=$1 - local nodepool_name=$2 - local resource_group=$3 - local initial_node_count=$4 - local node_subnet_id=$6 - local pod_subnet_id=$7 - local labels=${8:-""} - local taints=${9:-""} - local extra_args=${10:-""} - - echo "Creating nodepool: $nodepool_name with $initial_node_count nodes of size $VM_SKU" - - # Build the nodepool creation command - local nodepool_cmd="az aks nodepool add --cluster-name ${cluster_name} --name ${nodepool_name} --resource-group ${resource_group}" - nodepool_cmd+=" --node-count ${initial_node_count} -s ${VM_SKU} --os-sku Ubuntu" - nodepool_cmd+=" --vnet-subnet-id ${node_subnet_id} --pod-subnet-id ${pod_subnet_id}" - nodepool_cmd+=" --tags fastpathenabled=true aks-nic-enable-multi-tenancy=true aks-nic-secondary-count=${PODS_PER_NODE}" - - # Only apply --max-pods when the device plugin is disabled - # - Pipeline variables typically arrive as env vars (e.g. max_pods -> MAX_PODS) - # - Keep this tolerant to missing values - local device_plugin_raw="${DEVICE_PLUGIN}" - local device_plugin_lc - device_plugin_lc="$(echo "${device_plugin_raw}" | tr '[:upper:]' '[:lower:]')" - local max_pods_value="${MAX_PODS:-${max_pods}}" - if [[ "${device_plugin_lc}" != "true" && "${max_pods_value}" =~ ^[0-9]+$ && "${max_pods_value}" -gt 0 ]]; then - nodepool_cmd+=" --max-pods ${max_pods_value}" - fi - - # Add optional labels - if [[ -n "$labels" ]]; then - nodepool_cmd+=" --labels ${labels}" - fi - - # Add optional taints - if [[ -n "$taints" ]]; then - nodepool_cmd+=" --node-taints \"${taints}\"" - fi - - # Add any extra arguments - if [[ -n "$extra_args" ]]; then - nodepool_cmd+=" ${extra_args}" - fi - - # Create nodepool with retry logic - local max_attempts=5 - for attempt in $(seq 1 $max_attempts); do - # Check for cancellation before each retry - if ! check_cancellation; then - echo "ERROR: Pipeline cancelled during nodepool creation for ${nodepool_name}" - return 1 - fi - - echo "Creating nodepool ${nodepool_name}: attempt $attempt/$max_attempts" - if eval $nodepool_cmd; then - echo "Nodepool ${nodepool_name} creation command succeeded" - break - else - echo "Nodepool ${nodepool_name} creation attempt $attempt failed" - if [[ $attempt -eq $max_attempts ]]; then - echo "ERROR: Failed to create nodepool ${nodepool_name} after $max_attempts attempts" - return 1 - fi - sleep 15 - fi - done - - # Wait for nodepool to be ready with retry logic and timeout - echo "Waiting for nodepool ${nodepool_name} to be ready..." - local timeout=900 # 15 minutes timeout for nodepool - local retry_interval=30 # Check every 30 seconds - local elapsed=0 - - while [ $elapsed -lt $timeout ]; do - # Check for cancellation in wait loop - if ! check_cancellation; then - echo "WARNING: Pipeline cancelled while waiting for nodepool ${nodepool_name}" - return 1 - fi - - local status=$(az aks nodepool show --resource-group ${resource_group} --cluster-name ${cluster_name} --name ${nodepool_name} --query "provisioningState" --output tsv 2>/dev/null || echo "QueryFailed") - local power_state=$(az aks nodepool show --resource-group ${resource_group} --cluster-name ${cluster_name} --name ${nodepool_name} --query "powerState.code" --output tsv 2>/dev/null || echo "QueryFailed") - - echo "Nodepool ${nodepool_name} status: $status, Power state: $power_state (elapsed: ${elapsed}s)" - - case $status in - "Succeeded") - if [[ $power_state == "Running" ]]; then - echo "Nodepool ${nodepool_name} is ready and running" - return 0 - else - echo "Nodepool succeeded but not in Running power state, waiting..." - fi - ;; - "Creating"|"Scaling"|"Upgrading") - echo "Nodepool ${nodepool_name} is still provisioning, waiting..." - ;; - "Failed"|"Canceled"|"Deleting"|"Deleted") - echo "Nodepool ${nodepool_name} is in failed state: $status. Exiting." - az aks nodepool show --resource-group ${resource_group} --cluster-name ${cluster_name} --name ${nodepool_name} --output table - return 1 - ;; - "QueryFailed"|"") - echo "Failed to query nodepool status. This might be temporary, continuing to wait..." - ;; - *) - echo "Unknown nodepool status: $status. Continuing to wait..." - ;; - esac - - sleep $retry_interval - elapsed=$((elapsed + retry_interval)) - done - - echo "Timeout reached waiting for nodepool ${nodepool_name} to be ready. Final status: $status" - echo "ERROR: Nodepool ${nodepool_name} failed to reach ready state within timeout." - az aks nodepool show --resource-group ${resource_group} --cluster-name ${cluster_name} --name ${nodepool_name} --output table - return 1 -} +# create_and_verify_nodepool now provided by lib/nodepool.sh # Function to create AKS cluster create_aks_cluster() { diff --git a/swiftv2kubeobjects/ensure-nodepools.sh b/swiftv2kubeobjects/ensure-nodepools.sh new file mode 100755 index 0000000000..b267b73736 --- /dev/null +++ b/swiftv2kubeobjects/ensure-nodepools.sh @@ -0,0 +1,115 @@ +#!/bin/bash +set -euo pipefail + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" + +source "${SCRIPT_DIR}/shared-config.sh" +source "${SCRIPT_DIR}/lib/nodepool.sh" + +AKS_UTILS="${REPO_ROOT}/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh" + +INITIAL_USER_NODES=${INITIAL_USER_NODES:-1} +USER_NODEPOOL_SIZE=${USER_NODEPOOL_SIZE:-500} +TARGET_USER_NODE_COUNT=${NODE_COUNT:-1} +ROLE=${ROLE:-slo} +NODE_SUBNET_ID=${NODE_SUBNET_ID:-${nodeSubnetID:-}} +POD_SUBNET_ID=${POD_SUBNET_ID:-${podSubnetID:-}} + +if [[ -z "${PODS_PER_NODE:-}" ]]; then + PODS_PER_NODE=30 + echo "PODS_PER_NODE not set; defaulting to 30" +fi + +if [[ -z "${VM_SKU:-}" ]]; then + echo "ERROR: VM_SKU is required" + exit 1 +fi + +# Discover cluster if not provided +if [[ -z "${CLUSTER:-}" || -z "${RG:-}" ]]; then + if [[ -f "$AKS_UTILS" && -n "${REGION:-}" ]]; then + source "$AKS_UTILS" + find_aks_cluster "$REGION" "$ROLE" + CLUSTER="$aks_name" + RG="$aks_rg" + else + echo "ERROR: CLUSTER/RG not set and REGION/ROLE not provided for discovery" + exit 1 + fi +fi + +discover_subnets() { + if [[ -n "${NODE_SUBNET_ID:-}" && -n "${POD_SUBNET_ID:-}" ]]; then + return 0 + fi + echo "Discovering subnets from existing nodepool..." + local first_nodepool_json + first_nodepool_json=$(az aks nodepool list --cluster-name "$CLUSTER" --resource-group "$RG" --query '[0]' -o json || echo "") + NODE_SUBNET_ID=${NODE_SUBNET_ID:-$(echo "$first_nodepool_json" | jq -r '.vnetSubnetId // empty')} + POD_SUBNET_ID=${POD_SUBNET_ID:-$(echo "$first_nodepool_json" | jq -r '.podSubnetId // empty')} + if [[ -z "$NODE_SUBNET_ID" ]]; then + echo "ERROR: Unable to discover node subnet id; provide NODE_SUBNET_ID env" + exit 1 + fi + if [[ -z "$POD_SUBNET_ID" ]]; then + echo "POD_SUBNET_ID not found; using NODE_SUBNET_ID" + POD_SUBNET_ID="$NODE_SUBNET_ID" + fi +} + +discover_subnets + +echo "Ensuring user nodepools for cluster=$CLUSTER rg=$RG target_nodes=$TARGET_USER_NODE_COUNT shard_size=$USER_NODEPOOL_SIZE" + +if [[ -z "$TARGET_USER_NODE_COUNT" || "$TARGET_USER_NODE_COUNT" -le 0 ]]; then + TARGET_USER_NODE_COUNT=1 +fi + +USER_NODEPOOL_COUNT=$(( (TARGET_USER_NODE_COUNT + USER_NODEPOOL_SIZE - 1) / USER_NODEPOOL_SIZE )) +if [[ $USER_NODEPOOL_COUNT -lt 1 ]]; then + USER_NODEPOOL_COUNT=1 +fi + +existing_pools=$(az aks nodepool list --cluster-name "$CLUSTER" --resource-group "$RG" --query '[].name' -o tsv || true) + +echo "Planned total user nodes: $TARGET_USER_NODE_COUNT" +echo "User nodepool shard size: $USER_NODEPOOL_SIZE" +echo "Existing pools: ${existing_pools:-}" +echo "Ensuring $USER_NODEPOOL_COUNT user nodepool(s), each starting with $INITIAL_USER_NODES node" + +for i in $(seq 1 $USER_NODEPOOL_COUNT); do + if ! check_cancellation; then + echo "ERROR: Pipeline cancelled before ensuring user nodepool $i" + exit 143 + fi + + pool_name="userpool${i}" + labels="slo=true testscenario=swiftv2 agentpool=${pool_name}" + taints="slo=true:NoSchedule" + + if echo "$existing_pools" | grep -Fxq "$pool_name"; then + echo "Nodepool $pool_name already exists" + continue + fi + + echo "Creating user nodepool $pool_name (1/${USER_NODEPOOL_COUNT} initial node)" + create_and_verify_nodepool "$CLUSTER" "$pool_name" "$RG" "$INITIAL_USER_NODES" "$VM_SKU" "$NODE_SUBNET_ID" "$POD_SUBNET_ID" "$labels" "$taints" +done + +# Ensure buffer pool +if [[ "${PROVISION_BUFFER_NODES:-false}" == "true" ]]; then + buffer_pool_name="userpoolBuffer" + labels="slo=true testscenario=swiftv2 agentpool=${buffer_pool_name}" + taints="slo=true:NoSchedule" + if echo "$existing_pools" | grep -Fxq "$buffer_pool_name"; then + echo "Buffer nodepool $buffer_pool_name already exists" + else + echo "Creating buffer nodepool with $INITIAL_USER_NODES node" + create_and_verify_nodepool "$CLUSTER" "$buffer_pool_name" "$RG" "$INITIAL_USER_NODES" "$VM_SKU" "$NODE_SUBNET_ID" "$POD_SUBNET_ID" "$labels" "$taints" + fi +else + echo "Skipping buffer nodepool creation (PROVISION_BUFFER_NODES != true)" +fi + +echo "Done ensuring nodepools" diff --git a/swiftv2kubeobjects/lib/nodepool.sh b/swiftv2kubeobjects/lib/nodepool.sh new file mode 100755 index 0000000000..ded05296da --- /dev/null +++ b/swiftv2kubeobjects/lib/nodepool.sh @@ -0,0 +1,152 @@ +#!/bin/bash + +# Nodepool helper library +# Depends on Azure CLI, jq, and optional check_cancellation function + +# Provide a no-op cancellation check if caller did not define one +if ! declare -f check_cancellation >/dev/null 2>&1; then + check_cancellation() { return 0; } +fi + +# Check if nodepool exists +nodepool_exists() { + local cluster_name=$1 + local nodepool_name=$2 + local resource_group=$3 + az aks nodepool show \ + --cluster-name "$cluster_name" \ + --name "$nodepool_name" \ + --resource-group "$resource_group" \ + --query name -o tsv >/dev/null 2>&1 +} + +# Wait for nodepool to be ready +wait_for_nodepool_ready() { + local cluster_name=$1 + local nodepool_name=$2 + local resource_group=$3 + local timeout=${4:-900} # seconds + local retry_interval=${5:-30} + local elapsed=0 + local status="" + + echo "Waiting for nodepool ${nodepool_name} to be ready..." + while [ $elapsed -lt $timeout ]; do + if ! check_cancellation; then + echo "WARNING: Pipeline cancelled while waiting for nodepool ${nodepool_name}" + return 1 + fi + + status=$(az aks nodepool show --resource-group ${resource_group} --cluster-name ${cluster_name} --name ${nodepool_name} --query "provisioningState" --output tsv 2>/dev/null || echo "QueryFailed") + power_state=$(az aks nodepool show --resource-group ${resource_group} --cluster-name ${cluster_name} --name ${nodepool_name} --query "powerState.code" --output tsv 2>/dev/null || echo "QueryFailed") + + echo "Nodepool ${nodepool_name} status: $status, Power state: $power_state (elapsed: ${elapsed}s)" + + case $status in + "Succeeded") + if [[ $power_state == "Running" ]]; then + echo "Nodepool ${nodepool_name} is ready and running" + return 0 + else + echo "Nodepool succeeded but not in Running power state, waiting..." + fi + ;; + "Creating"|"Scaling"|"Upgrading") + echo "Nodepool ${nodepool_name} is still provisioning, waiting..." + ;; + "Failed"|"Canceled"|"Deleting"|"Deleted") + echo "Nodepool ${nodepool_name} is in failed state: $status. Exiting." + az aks nodepool show --resource-group ${resource_group} --cluster-name ${cluster_name} --name ${nodepool_name} --output table || true + return 1 + ;; + "QueryFailed"|"") + echo "Failed to query nodepool status. This might be temporary, continuing to wait..." + ;; + *) + echo "Unknown nodepool status: $status. Continuing to wait..." + ;; + esac + + sleep $retry_interval + elapsed=$((elapsed + retry_interval)) + done + + echo "Timeout reached waiting for nodepool ${nodepool_name} to be ready. Final status: $status" + az aks nodepool show --resource-group ${resource_group} --cluster-name ${cluster_name} --name ${nodepool_name} --output table || true + return 1 +} + +# Create nodepool (idempotent) and wait for readiness +create_and_verify_nodepool() { + local cluster_name=$1 + local nodepool_name=$2 + local resource_group=$3 + local initial_node_count=$4 + local vm_sku=${5:-${VM_SKU}} + local node_subnet_id=$6 + local pod_subnet_id=$7 + local labels=${8:-""} + local taints=${9:-""} + local extra_args=${10:-""} + + if [[ -z "$vm_sku" ]]; then + echo "ERROR: VM_SKU is not set and was not provided to create_and_verify_nodepool" + return 1 + fi + + # Idempotent: skip creation if exists + if nodepool_exists "$cluster_name" "$nodepool_name" "$resource_group"; then + echo "Nodepool ${nodepool_name} already exists; skipping creation" + return 0 + fi + + echo "Creating nodepool: $nodepool_name with $initial_node_count nodes of size $vm_sku" + + local nodepool_cmd=(az aks nodepool add --cluster-name "$cluster_name" --name "$nodepool_name" --resource-group "$resource_group") + nodepool_cmd+=(--node-count "$initial_node_count" -s "$vm_sku" --os-sku Ubuntu) + nodepool_cmd+=(--vnet-subnet-id "$node_subnet_id" --pod-subnet-id "$pod_subnet_id") + nodepool_cmd+=(--tags fastpathenabled=true aks-nic-enable-multi-tenancy=true aks-nic-secondary-count="${PODS_PER_NODE}") + + local device_plugin_lc=$(echo "${DEVICE_PLUGIN:-}" | tr '[:upper:]' '[:lower:]') + local max_pods_value="${MAX_PODS:-${max_pods:-}}" + if [[ "${device_plugin_lc}" != "true" && "${max_pods_value}" =~ ^[0-9]+$ && "${max_pods_value}" -gt 0 ]]; then + nodepool_cmd+=(--max-pods "${max_pods_value}") + fi + + if [[ -n "$labels" ]]; then + nodepool_cmd+=(--labels "$labels") + fi + + if [[ -n "$taints" ]]; then + nodepool_cmd+=(--node-taints "$taints") + fi + + if [[ -n "$extra_args" ]]; then + # shellcheck disable=SC2206 + nodepool_cmd+=($extra_args) + fi + + local max_attempts=5 + local attempt + for attempt in $(seq 1 $max_attempts); do + if ! check_cancellation; then + echo "ERROR: Pipeline cancelled during nodepool creation for ${nodepool_name}" + return 1 + fi + + echo "Creating nodepool ${nodepool_name}: attempt $attempt/$max_attempts" + if "${nodepool_cmd[@]}"; then + echo "Nodepool ${nodepool_name} creation command succeeded" + break + else + echo "Nodepool ${nodepool_name} creation attempt $attempt failed" + if [[ $attempt -eq $max_attempts ]]; then + echo "ERROR: Failed to create nodepool ${nodepool_name} after $max_attempts attempts" + return 1 + fi + sleep 15 + fi + done + + wait_for_nodepool_ready "$cluster_name" "$nodepool_name" "$resource_group" 900 30 +} From affaf7f8ca859a51274cfac91ec30d4ae30ad9a2 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 22:26:00 +0000 Subject: [PATCH 15/47] fix(azure): normalize boolean casing for reuse_cluster & skip_cleanup --- docs/running-swiftv2-pipeline.md | 5 ++++- steps/cleanup-resources.yml | 15 ++++++++------- steps/cloud/azure/update-kubeconfig.yml | 3 ++- .../clusterloader2/swiftv2-slo/aks-utils.sh | 4 +++- steps/provision-resources.yml | 7 ++++--- steps/setup-tests.yml | 3 ++- 6 files changed, 23 insertions(+), 14 deletions(-) diff --git a/docs/running-swiftv2-pipeline.md b/docs/running-swiftv2-pipeline.md index 6f7de75a7f..6b793b1de2 100644 --- a/docs/running-swiftv2-pipeline.md +++ b/docs/running-swiftv2-pipeline.md @@ -26,6 +26,8 @@ Here is the pipeline [link](https://dev.azure.com/akstelescope/telescope/_build? - **`reuse_cluster`**: Whether to reuse an existing cluster (`true`) or create a new one (`false`) - **`skip_cleanup`**: Whether to keep the cluster after tests complete (`true`) or delete it (`false`) +> ⚠️ Azure DevOps passes boolean variables to scripts as `True`/`False` strings. Normalize to lowercase before comparison in bash scripts. + ### Typical pattern for gradual scale testing - **First entry**: `reuse_cluster: false`, `skip_cleanup: true` - Creates a new cluster, keeps it @@ -103,7 +105,8 @@ When `reuse_cluster: true`, jobs use `BASE_RUN_ID` for: 1. **First job** creates cluster with tag: `run_id=` 2. **Subsequent jobs** check `reuse_cluster` flag and use `BASE_RUN_ID` to query Azure: ```bash - if [ "${REUSE_CLUSTER}" = "true" ]; then + reuse_cluster="$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]')" + if [ "$reuse_cluster" = "true" ]; then CLUSTER_RUN_ID="$BASE_RUN_ID" else CLUSTER_RUN_ID="$RUN_ID" diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index fce3c3731e..de747665c1 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -20,7 +20,8 @@ parameters: steps: - script: | echo "===================================================================" - if [ "${{ parameters.skip_cleanup }}" == "true" ]; then + skip_cleanup=$(echo "${{ parameters.skip_cleanup }}" | tr '[:upper:]' '[:lower:]') + if [ "$skip_cleanup" == "true" ]; then echo "SKIP_CLEANUP is enabled - skipping resource cleanup for this job" echo "Resources will be reused by subsequent jobs" else @@ -35,12 +36,12 @@ steps: echo "Skipping terraform destroy due to skip_cleanup=true" echo "Resources will be cleaned up by the final job in the sequence" displayName: "Skip Terraform Destroy (Reuse Mode)" - condition: and(always(), eq(variables['skip_cleanup'], 'true')) + condition: and(always(), eq(lower(variables['skip_cleanup']), 'true')) - script: | echo "##vso[task.setvariable variable=SKIP_RESOURCE_MANAGEMENT]true" displayName: "Set Skip Flag for Terraform Destroy" - condition: and(always(), eq(variables['skip_cleanup'], 'true')) + condition: and(always(), eq(lower(variables['skip_cleanup']), 'true')) - template: /steps/terraform/run-command.yml parameters: @@ -63,7 +64,7 @@ steps: sleep 30 done displayName: "Delete SAL Ping" - condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true'), eq(variables['skip_cleanup'], 'false')) + condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true'), eq(lower(variables['skip_cleanup']), 'false')) continueOnError: true - script: | set -eu @@ -152,14 +153,14 @@ steps: echo "Pre-cleanup completed" displayName: "Force Cleanup Azure Resources" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['skip_cleanup'], 'false')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(lower(variables['skip_cleanup']), 'false')) continueOnError: true - script: | echo "Skipping resource group deletion due to skip_cleanup=true" echo "Resource group will be cleaned up by the final job in the sequence" displayName: "Skip Resource Group Deletion (Reuse Mode)" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['skip_cleanup'], 'true')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(lower(variables['skip_cleanup']), 'true')) - script: | set -eu @@ -183,7 +184,7 @@ steps: fi done displayName: "Destroy Resource Group" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['skip_cleanup'], 'false')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(lower(variables['skip_cleanup']), 'false')) continueOnError: true - ${{ if eq(variables['Build.SourceBranchName'], 'main') }}: diff --git a/steps/cloud/azure/update-kubeconfig.yml b/steps/cloud/azure/update-kubeconfig.yml index 43156d1523..85d6ac549d 100644 --- a/steps/cloud/azure/update-kubeconfig.yml +++ b/steps/cloud/azure/update-kubeconfig.yml @@ -10,9 +10,10 @@ steps: set -x region=${{ parameters.region }} + reuse_cluster=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') # Use BASE_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID - if [ "${REUSE_CLUSTER:-false}" = "true" ]; then + if [ "$reuse_cluster" = "true" ]; then CLUSTER_RUN_ID="$BASE_RUN_ID" echo "Reusing cluster - searching with BASE_RUN_ID: $CLUSTER_RUN_ID" else diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index da1ddc6295..4038723e7d 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh @@ -34,7 +34,9 @@ function find_aks_cluster() { # Use BASE_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID local cluster_run_id - if [ "${REUSE_CLUSTER:-false}" = "true" ]; then + local reuse_cluster + reuse_cluster=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') + if [ "$reuse_cluster" = "true" ]; then cluster_run_id="$BASE_RUN_ID" log_info "Reusing cluster - searching with BASE_RUN_ID: $cluster_run_id" else diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index 481f82668b..479ba7f75a 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -67,10 +67,11 @@ steps: - script: | set -eu + reuse_cluster=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') # When creating a new cluster for reuse pattern, use BASE_RUN_ID as the resource group name # so all subsequent matrix jobs can find it. Otherwise use the unique RUN_ID. - if [ "${REUSE_CLUSTER:-false}" = "false" ] && [ -n "${BASE_RUN_ID:-}" ]; then + if [ "$reuse_cluster" = "false" ] && [ -n "${BASE_RUN_ID:-}" ]; then # First job in matrix: create with BASE_RUN_ID so others can reuse RESOURCE_GROUP_NAME="$BASE_RUN_ID" echo "Creating resource group $RESOURCE_GROUP_NAME (using BASE_RUN_ID for reuse pattern)" @@ -83,7 +84,7 @@ steps: az group create --name "$RESOURCE_GROUP_NAME" --location $region \ --tags "run_id=$RESOURCE_GROUP_NAME" "scenario=${SCENARIO_TYPE}-${SCENARIO_NAME}" "owner=${OWNER}" "creation_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "deletion_due_time=${DELETION_DUE_TIME}" "SkipAKSCluster=1" displayName: "Create Resource Group" - condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(variables['reuse_cluster'], 'false')) + condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(lower(variables['reuse_cluster']), 'false')) env: region: ${{ parameters.regions[0] }} BASE_RUN_ID: $(BASE_RUN_ID) @@ -118,7 +119,7 @@ steps: - script: | bash swiftv2kubeobjects/createclusterforping.sh displayName: "SetupAKSMTClusterPING" - condition: and(eq(variables['CREATESWIFTV2PING'], 'true'), eq(variables['reuse_cluster'], 'false')) + condition: and(eq(variables['CREATESWIFTV2PING'], 'true'), eq(lower(variables['reuse_cluster']), 'false')) name: SetupAKSMTClusterPING env: # Ensure these pipeline variables are available as env vars to the script diff --git a/steps/setup-tests.yml b/steps/setup-tests.yml index 27187e733d..042a716baa 100644 --- a/steps/setup-tests.yml +++ b/steps/setup-tests.yml @@ -45,8 +45,9 @@ steps: echo "Final Run ID: $run_id" echo "##vso[task.setvariable variable=RUN_ID]$run_id" + reuse_cluster=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') # When reusing clusters, validate BASE_RUN_ID is set - if [ "${REUSE_CLUSTER:-false}" == "true" ]; then + if [ "$reuse_cluster" == "true" ]; then if [ -z "$BASE_RUN_ID" ] || [ "$BASE_RUN_ID" = " " ]; then echo "ERROR: REUSE_CLUSTER is true but BASE_RUN_ID is not set" exit 1 From a09c93c5f576dbaef84930e00958813f0be71fdb Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 22:40:03 +0000 Subject: [PATCH 16/47] refactor(pipelines): remove terraform infrastructure management - Remove terraform parameters from competitive-test.yml job template - Remove terraform setup and command templates from provision-resources.yml - Remove terraform destroy steps from cleanup-resources.yml - Set deletion_due_time to 1 week instead of reading from terraform input - Set owner to Build.RequestedFor (ADO pipeline runner) --- jobs/competitive-test.yml | 17 --------- steps/cleanup-resources.yml | 29 ---------------- steps/provision-resources.yml | 65 +++-------------------------------- 3 files changed, 5 insertions(+), 106 deletions(-) diff --git a/jobs/competitive-test.yml b/jobs/competitive-test.yml index 1724335ff1..6de469fe60 100644 --- a/jobs/competitive-test.yml +++ b/jobs/competitive-test.yml @@ -15,18 +15,6 @@ parameters: default: {} - name: max_parallel type: number -- name: terraform_modules_dir - type: string - default: '' -- name: terraform_input_file_mapping - type: object - default: [] -- name: terraform_arguments - type: string - default: '' -- name: terraform_input_varibles - type: object - default: {} - name: test_modules_dir type: string default: '' @@ -73,10 +61,6 @@ jobs: parameters: cloud: ${{ parameters.cloud }} regions: ${{ parameters.regions }} - terraform_modules_dir: ${{ parameters.terraform_modules_dir }} - terraform_input_file_mapping: ${{ parameters.terraform_input_file_mapping }} - terraform_arguments: ${{ parameters.terraform_arguments }} - terraform_input_varibles: ${{ parameters.terraform_input_varibles }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} reuse_cluster: $(reuse_cluster) @@ -105,7 +89,6 @@ jobs: parameters: cloud: ${{ parameters.cloud }} regions: ${{ parameters.regions }} - terraform_arguments: ${{ parameters.terraform_arguments }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} skip_cleanup: $(skip_cleanup) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index de747665c1..fb1304086f 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -4,9 +4,6 @@ parameters: default: {} - name: cloud type: string -- name: terraform_arguments - type: string - default: '' - name: retry_attempt_count type: number default: 3 @@ -32,26 +29,6 @@ steps: displayName: "Cleanup Notice" condition: always() -- script: | - echo "Skipping terraform destroy due to skip_cleanup=true" - echo "Resources will be cleaned up by the final job in the sequence" - displayName: "Skip Terraform Destroy (Reuse Mode)" - condition: and(always(), eq(lower(variables['skip_cleanup']), 'true')) - -- script: | - echo "##vso[task.setvariable variable=SKIP_RESOURCE_MANAGEMENT]true" - displayName: "Set Skip Flag for Terraform Destroy" - condition: and(always(), eq(lower(variables['skip_cleanup']), 'true')) - -- template: /steps/terraform/run-command.yml - parameters: - command: destroy - arguments: ${{ parameters.terraform_arguments }} - regions: ${{ parameters.regions }} - cloud: ${{ parameters.cloud }} - retry_attempt_count: ${{ parameters.retry_attempt_count }} - credential_type: ${{ parameters.credential_type }} - - script: | set -eu @@ -186,9 +163,3 @@ steps: displayName: "Destroy Resource Group" condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(lower(variables['skip_cleanup']), 'false')) continueOnError: true - -- ${{ if eq(variables['Build.SourceBranchName'], 'main') }}: - - template: /steps/collect-terraform-operation-metadata.yml - parameters: - cloud: ${{ parameters.cloud }} - credential_type: ${{ parameters.credential_type }} diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index 479ba7f75a..b6b312913c 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -3,20 +3,6 @@ parameters: type: string - name: regions type: object -- name: terraform_modules_dir - type: string - default: '' -- name: terraform_input_file_mapping - type: object -- name: terraform_user_data_path - type: string - default: '' -- name: terraform_arguments - type: string - default: '' -- name: terraform_input_varibles - type: object - default: {} - name: retry_attempt_count type: number default: 3 @@ -28,42 +14,22 @@ parameters: default: 'false' steps: -- template: /steps/terraform/set-working-directory.yml - parameters: - cloud: ${{ parameters.cloud }} - modules_dir: ${{ parameters.terraform_modules_dir }} - -- template: /steps/terraform/set-input-file.yml - parameters: - cloud: ${{ parameters.cloud }} - regions: ${{ parameters.regions }} - input_file_mapping: ${{ parameters.terraform_input_file_mapping }} - -- template: /steps/terraform/set-user-data-path.yml - parameters: - user_data_path: ${{ parameters.terraform_user_data_path }} - -- template: /steps/terraform/set-input-variables-${{ parameters.cloud }}.yml@self - parameters: - cloud: ${{ parameters.cloud }} - regions: ${{ parameters.regions }} - input_variables: ${{ parameters.terraform_input_varibles }} - script: | - terraform_input_file=$(echo $TERRAFORM_REGIONAL_CONFIG | jq -r --arg region "$region" '.[$region].TERRAFORM_INPUT_FILE') - deletion_delay=$(grep "deletion_delay" "$terraform_input_file" | awk -F'=' '{gsub(/^[ \t]+|[ \t]+$/, "", $2); gsub(/[^0-9]/, "", $2); print $2}') - echo "Deletion Delay: $deletion_delay hr" - deletion_due_time=$(date -u -d "+${deletion_delay} hour" +'%Y-%m-%dT%H:%M:%SZ') + # Set deletion due time to 1 week from now + deletion_due_time=$(date -u -d "+1 week" +'%Y-%m-%dT%H:%M:%SZ') echo "Deletion Due Time: $deletion_due_time" echo "##vso[task.setvariable variable=DELETION_DUE_TIME]$deletion_due_time" - owner=$(grep "owner" "$terraform_input_file" | awk -F'=' '{gsub(/^[ \t]+|[ \t]+$/, "", $2); print $2}' | sed 's/^"//;s/"$//') + # Set owner as the person running the ADO pipeline + owner="$BUILD_REQUESTED_FOR" echo "Owner: $owner" echo "##vso[task.setvariable variable=OWNER]$owner" displayName: "Get Deletion Due Time and Owner" condition: ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true') env: region: ${{ parameters.regions[0] }} + BUILD_REQUESTED_FOR: $(Build.RequestedFor) - script: | set -eu @@ -89,27 +55,6 @@ steps: region: ${{ parameters.regions[0] }} BASE_RUN_ID: $(BASE_RUN_ID) REUSE_CLUSTER: $(reuse_cluster) - -- template: /steps/terraform/run-command.yml - parameters: - command: version - retry_attempt_count: ${{ parameters.retry_attempt_count }} - credential_type: ${{ parameters.credential_type }} - -- template: /steps/terraform/run-command.yml - parameters: - command: init - retry_attempt_count: ${{ parameters.retry_attempt_count }} - credential_type: ${{ parameters.credential_type }} - -- template: /steps/terraform/run-command.yml - parameters: - command: apply - arguments: ${{ parameters.terraform_arguments }} - regions: ${{ parameters.regions }} - cloud: ${{ parameters.cloud }} - retry_attempt_count: ${{ parameters.retry_attempt_count }} - credential_type: ${{ parameters.credential_type }} - script: | bash swiftv2kubeobjects/runCustomerSetup.sh From 521aba0e439207be5d9c6b8f79acdcd629901043 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 22:47:13 +0000 Subject: [PATCH 17/47] fix(swiftv2): use BASE_RUN_ID for resource group in reuse cluster pattern Align RG variable assignment with provision-resources.yml pattern: - When reuse_cluster=false and BASE_RUN_ID is set, use BASE_RUN_ID so subsequent matrix jobs can find the cluster - Otherwise use RUN_ID for standalone jobs This ensures createclusterforping.sh creates the cluster in the same resource group that provision-resources.yml expects. --- swiftv2kubeobjects/createclusterforping.sh | 15 ++++++++++++++- 1 file changed, 14 insertions(+), 1 deletion(-) diff --git a/swiftv2kubeobjects/createclusterforping.sh b/swiftv2kubeobjects/createclusterforping.sh index 023c88cdc3..5f91c5c715 100755 --- a/swiftv2kubeobjects/createclusterforping.sh +++ b/swiftv2kubeobjects/createclusterforping.sh @@ -42,7 +42,20 @@ check_cancellation() { return 0 } -RG=$RUN_ID +# Determine resource group name based on reuse_cluster flag +# This follows the same pattern as provision-resources.yml for resource group creation +reuse_cluster_lower=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') + +if [ "$reuse_cluster_lower" = "false" ] && [ -n "${BASE_RUN_ID:-}" ]; then + # First job in matrix: use BASE_RUN_ID so subsequent jobs can find the cluster + RG="$BASE_RUN_ID" + echo "Using resource group $RG (BASE_RUN_ID for reuse pattern)" +else + # Standalone job: use unique RUN_ID + RG="$RUN_ID" + echo "Using resource group $RG (standalone job)" +fi + CLUSTER="large" SUBSCRIPTION=$AZURE_SUBSCRIPTION_ID NODEPOOLS=1 From 70249714d40bdb536718ce581ed350fdba7f6cb9 Mon Sep 17 00:00:00 2001 From: Isaac Date: Wed, 28 Jan 2026 23:57:48 +0000 Subject: [PATCH 18/47] fix: simplify pod group labels and fix nodepool label handling - Remove job index suffix from PodGroup label selector in swiftv2 deployment configs to aggregate metrics across all jobs - Fix bash array handling for space-separated nodepool labels by splitting them into individual elements for az cli command --- .../config/swiftv2_deployment_dynamicres_scale_config.yaml | 6 +++--- .../config/swiftv2_deployment_staticres_scale_config.yaml | 6 +++--- swiftv2kubeobjects/lib/nodepool.sh | 5 ++++- 3 files changed, 10 insertions(+), 7 deletions(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml index 389347094e..81b37259c8 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml @@ -104,7 +104,7 @@ steps: Method: PodStartupLatency Params: action: start - labelSelector: podgroup={{$groupName}}-job{{$jobIndex}} + labelSelector: podgroup={{$groupName}} threshold: {{$podStartupLatencyThreshold}} {{range $j := Loop $steps}} - name: Starting Deployment Latency Measurements -{{$j}} @@ -129,7 +129,7 @@ steps: objectTemplatePath: swiftv2_deployment_template.yaml templateFillMap: Replicas: {{$podsPerStep}} - PodGroup: {{$groupName}}-job{{$jobIndex}} + PodGroup: {{$groupName}} Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} CpuRequest: {{$latencyPodCpu}}m MemoryRequest: {{$latencyPodMemory}}M @@ -158,7 +158,7 @@ steps: Method: PodStartupLatency Params: action: gather - labelSelector: podgroup={{$groupName}}-job{{$jobIndex}} + labelSelector: podgroup={{$groupName}} - name: Wait for Datapath Readiness measurements: - Identifier: Dummy diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index c3a73270e9..71f85b5df9 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -62,7 +62,7 @@ steps: Method: PodStartupLatency Params: action: start - labelSelector: podgroup={{$groupName}}-job{{$jobIndex}} + labelSelector: podgroup={{$groupName}} threshold: {{$podStartupLatencyThreshold}} {{range $j := Loop $steps}} - name: Create PNIs for step {{$j}} @@ -133,7 +133,7 @@ steps: objectTemplatePath: swiftv2_deployment_single_pod_template.yaml templateFillMap: Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} - PodGroup: {{$groupName}}-job{{$jobIndex}} + PodGroup: {{$groupName}} CpuRequest: {{$latencyPodCpu}}m MemoryRequest: {{$latencyPodMemory}}M deploymentLabel: start @@ -163,7 +163,7 @@ steps: Method: PodStartupLatency Params: action: gather - labelSelector: podgroup={{$groupName}}-job{{$jobIndex}} + labelSelector: podgroup={{$groupName}} - name: Wait for Datapath Readiness measurements: - Identifier: Dummy diff --git a/swiftv2kubeobjects/lib/nodepool.sh b/swiftv2kubeobjects/lib/nodepool.sh index ded05296da..eb7f6f9f3d 100755 --- a/swiftv2kubeobjects/lib/nodepool.sh +++ b/swiftv2kubeobjects/lib/nodepool.sh @@ -114,7 +114,10 @@ create_and_verify_nodepool() { fi if [[ -n "$labels" ]]; then - nodepool_cmd+=(--labels "$labels") + nodepool_cmd+=(--labels) + # Split space-separated labels into individual array elements + # shellcheck disable=SC2206 + nodepool_cmd+=($labels) fi if [[ -n "$taints" ]]; then From 4914519485a54a6f6f0acaabd6fabd5583fe20c8 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 00:55:52 +0000 Subject: [PATCH 19/47] fix(swiftv2): always use BASE_RUN_ID for cluster identification Simplify resource group naming logic to always use BASE_RUN_ID since it is always generated by the pipeline. This fixes cluster discovery failures in the first matrix job where reuse_cluster=false but the cluster was created with BASE_RUN_ID. Previously, find_aks_cluster used RUN_ID when reuse_cluster=false, but createclusterforping.sh created the cluster with BASE_RUN_ID, causing ensure-nodepools.sh to fail finding the cluster. - Remove reuse_cluster-based conditional logic - Always use BASE_RUN_ID when present (normal case) - Keep RUN_ID as defensive fallback with warning --- .../clusterloader2/swiftv2-slo/aks-utils.sh | 15 +++++++++------ swiftv2kubeobjects/createclusterforping.sh | 17 ++++++++--------- 2 files changed, 17 insertions(+), 15 deletions(-) diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index 4038723e7d..2da78d00b5 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh @@ -32,16 +32,19 @@ function find_aks_cluster() { local region=$1 local role=$2 - # Use BASE_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID + # Determine run_id for cluster discovery + # BASE_RUN_ID is always generated by the pipeline and used for resource group naming. + # All jobs in a matrix share the same BASE_RUN_ID so they can find/reuse the same cluster. + # RUN_ID fallback exists only for defensive coding (should never be needed). local cluster_run_id - local reuse_cluster - reuse_cluster=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') - if [ "$reuse_cluster" = "true" ]; then + + if [ -n "${BASE_RUN_ID:-}" ]; then cluster_run_id="$BASE_RUN_ID" - log_info "Reusing cluster - searching with BASE_RUN_ID: $cluster_run_id" + log_info "Using BASE_RUN_ID for cluster discovery: $cluster_run_id" else + # Fallback - should not happen in current pipeline design cluster_run_id="$RUN_ID" - log_info "New cluster - searching with RUN_ID: $cluster_run_id" + log_warning "BASE_RUN_ID not set, falling back to RUN_ID: $cluster_run_id" fi log_info "Finding AKS cluster with role '$role' in region '$region'..." diff --git a/swiftv2kubeobjects/createclusterforping.sh b/swiftv2kubeobjects/createclusterforping.sh index 5f91c5c715..1a1691a4d4 100755 --- a/swiftv2kubeobjects/createclusterforping.sh +++ b/swiftv2kubeobjects/createclusterforping.sh @@ -42,18 +42,17 @@ check_cancellation() { return 0 } -# Determine resource group name based on reuse_cluster flag -# This follows the same pattern as provision-resources.yml for resource group creation -reuse_cluster_lower=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') - -if [ "$reuse_cluster_lower" = "false" ] && [ -n "${BASE_RUN_ID:-}" ]; then - # First job in matrix: use BASE_RUN_ID so subsequent jobs can find the cluster +# Determine resource group name +# BASE_RUN_ID is always generated by the pipeline and used for resource group naming. +# All jobs in a matrix share the same BASE_RUN_ID so they can find/reuse the same cluster. +# RUN_ID fallback exists only for defensive coding (should never be needed). +if [ -n "${BASE_RUN_ID:-}" ]; then RG="$BASE_RUN_ID" - echo "Using resource group $RG (BASE_RUN_ID for reuse pattern)" + echo "Using resource group $RG (from BASE_RUN_ID)" else - # Standalone job: use unique RUN_ID + # Fallback - should not happen in current pipeline design RG="$RUN_ID" - echo "Using resource group $RG (standalone job)" + echo "WARNING: BASE_RUN_ID not set, using RUN_ID: $RG" fi CLUSTER="large" From 31936b6ffb11b066de7834699f5fb87f4a6d023d Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 01:36:58 +0000 Subject: [PATCH 20/47] refactor(pipeline): per-stage run ID generation with idempotent provisioning - Add steps/generate-run-id.yml for reusable run ID generation per stage - Each stage now generates its own BASE_RUN_ID with stage-specific prefix - Make resource group and AKS cluster creation idempotent (check exists first) - Add jobs/cleanup.yml as dedicated cleanup job template - Add CLEANUP variable to toggle resource cleanup on/off - Remove reuse_cluster and skip_cleanup flags from all matrix files - Centralize RESOURCE_GROUP_NAME as single source of truth - Remove unused steps/terraform/run-command.yml BREAKING CHANGE: Stages now operate independently with separate resource groups --- jobs/cleanup.yml | 46 +++++++++ jobs/competitive-test.yml | 8 -- .../swiftv2-dynamicres-burst-matrix.yml | 14 --- .../swiftv2-dynamicres-gradual-matrix.yml | 14 --- .../swiftv2-staticres-burst-matrix.yml | 14 --- .../swiftv2-staticres-gradual-matrix.yml | 14 --- pipelines/system/new-pipeline-test.yml | 98 +++++++++++-------- steps/cleanup-resources.yml | 61 +++++------- steps/cloud/azure/collect-cloud-info.yml | 6 +- .../clusterloader2/swiftv2-slo/aks-utils.sh | 20 ++-- steps/generate-run-id.yml | 43 ++++++++ steps/provision-resources.yml | 63 ++++++------ steps/terraform/run-command.yml | 96 ------------------ swiftv2kubeobjects/createclusterforping.sh | 17 ++-- 14 files changed, 222 insertions(+), 292 deletions(-) create mode 100644 jobs/cleanup.yml create mode 100644 steps/generate-run-id.yml delete mode 100644 steps/terraform/run-command.yml diff --git a/jobs/cleanup.yml b/jobs/cleanup.yml new file mode 100644 index 0000000000..992c96178a --- /dev/null +++ b/jobs/cleanup.yml @@ -0,0 +1,46 @@ +parameters: +- name: cloud + type: string +- name: regions + type: object +- name: credential_type + type: string + default: service_connection +- name: base_run_id + type: string + +jobs: +- job: cleanup + displayName: 'Cleanup Resources' + condition: and(always(), eq(variables['CLEANUP'], 'true')) + timeoutInMinutes: 60 + steps: + - script: | + # Set RESOURCE_GROUP_NAME from BASE_RUN_ID + if [ -z "${BASE_RUN_ID:-}" ]; then + echo "ERROR: BASE_RUN_ID not set" + exit 1 + fi + RESOURCE_GROUP_NAME="$BASE_RUN_ID" + echo "Resource group to cleanup: $RESOURCE_GROUP_NAME" + echo "##vso[task.setvariable variable=RESOURCE_GROUP_NAME]$RESOURCE_GROUP_NAME" + displayName: "Set Resource Group Name" + env: + BASE_RUN_ID: ${{ parameters.base_run_id }} + + - ${{ if eq(parameters.credential_type, 'service_connection') }}: + - task: AzureCLI@2 + displayName: "Azure Login (Service Connection)" + inputs: + azureSubscription: $(AZURE_SERVICE_CONNECTION) + scriptType: bash + scriptLocation: inlineScript + addSpnToEnvironment: true + inlineScript: | + echo "Logged in via service connection" + + - template: /steps/cleanup-resources.yml + parameters: + cloud: ${{ parameters.cloud }} + regions: ${{ parameters.regions }} + credential_type: ${{ parameters.credential_type }} diff --git a/jobs/competitive-test.yml b/jobs/competitive-test.yml index 6de469fe60..ba1ae4b29a 100644 --- a/jobs/competitive-test.yml +++ b/jobs/competitive-test.yml @@ -63,7 +63,6 @@ jobs: regions: ${{ parameters.regions }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} - reuse_cluster: $(reuse_cluster) - template: /steps/validate-resources.yml parameters: cloud: ${{ parameters.cloud }} @@ -85,10 +84,3 @@ jobs: regions: ${{ parameters.regions }} engine_input: ${{ parameters.engine_input }} credential_type: ${{ parameters.credential_type }} - - template: /steps/cleanup-resources.yml - parameters: - cloud: ${{ parameters.cloud }} - regions: ${{ parameters.regions }} - retry_attempt_count: ${{ parameters.retry_attempt_count }} - credential_type: ${{ parameters.credential_type }} - skip_cleanup: $(skip_cleanup) diff --git a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml index ab72fd9de7..f4f6748b13 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml @@ -28,56 +28,42 @@ parameters: test_timeout: "2m" test_type: Burst_DynamicRes_PPS=140_PPP=0_Pods=140_Nodes=20 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: false - skip_cleanup: true ppp=0_pods=350_nodes=50: node_count: 50 pods_per_step: 50 test_timeout: "3m" test_type: Burst_DynamicRes_PPS=350_PPP=0_Pods=350_Nodes=50 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=0_pods=700_nodes=100: node_count: 100 pods_per_step: 100 test_timeout: "4m" test_type: Burst_DynamicRes_PPS=700_PPP=0_Pods=700_Nodes=100 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=0_pods=1400_nodes=200: node_count: 200 pods_per_step: 200 test_timeout: "6m" test_type: Burst_DynamicRes_PPS=1400_PPP=0_Pods=1400_Nodes=200 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=0_pods=3500_nodes=500: node_count: 500 pods_per_step: 500 test_timeout: "7m" test_type: Burst_DynamicRes_PPS=3500_PPP=0_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=0_pods=5250_nodes=750: node_count: 750 pods_per_step: 750 test_timeout: "9m" test_type: Burst_DynamicRes_PPS=5250_PPP=0_Pods=5250_Nodes=750 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=0_burst_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 1000 test_timeout: "10m" test_type: Burst_DynamicRes_PPS=7000_PPP=0_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: false jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml index 8b7e0a7123..b670bbebb9 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml @@ -28,56 +28,42 @@ parameters: test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=35_PPP=0_Pods=70_Nodes=10 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: false - skip_cleanup: true pps=50_ppp=0_pods=3500_nodes=500: node_count: 500 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=0_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=0_pods=14000_nodes=2000: node_count: 2000 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=0_pods=17500_nodes=2500: node_count: 2500 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=17500_Nodes=2500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=0_pods=21000_nodes=3000: node_count: 3000 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=21000_Nodes=3000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=0_pods=35000_nodes=5000: node_count: 5000 pods_per_step: 50 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=35000_Nodes=5000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - reuse_cluster: true - skip_cleanup: false jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml index 3870cfc60a..0709214d7d 100644 --- a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml @@ -29,8 +29,6 @@ parameters: test_timeout: "2m" test_type: Burst_StaticRes_PPS=140_PPP=1_Pods=140_Nodes=20 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: false - skip_cleanup: true ppp=1_pods=350_nodes=50: node_count: 50 pods_per_step: 50 @@ -38,8 +36,6 @@ parameters: test_timeout: "3m" test_type: Burst_StaticRes_PPS=350_PPP=1_Pods=350_Nodes=50 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=1_pods=700_nodes=100: node_count: 100 pods_per_step: 100 @@ -47,8 +43,6 @@ parameters: test_timeout: "4m" test_type: Burst_StaticRes_PPS=700_PPP=1_Pods=700_Nodes=100 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=1_pods=1400_nodes=200: node_count: 200 pods_per_step: 200 @@ -56,8 +50,6 @@ parameters: test_timeout: "6m" test_type: Burst_StaticRes_PPS=1400_PPP=1_Pods=1400_Nodes=200 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=1_pods=3500_nodes=500: node_count: 500 pods_per_step: 500 @@ -65,8 +57,6 @@ parameters: test_timeout: "7m" test_type: Burst_StaticRes_PPS=3500_PPP=1_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=1_pods=5250_nodes=750: node_count: 750 pods_per_step: 750 @@ -74,8 +64,6 @@ parameters: test_timeout: "9m" test_type: Burst_StaticRes_PPS=5250_PPP=1_Pods=5250_Nodes=750 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true ppp=1_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 1000 @@ -83,8 +71,6 @@ parameters: test_timeout: "10m" test_type: Burst_StaticRes_PPS=7000_PPP=1_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: false jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml index a6afeb3573..3a8347decf 100644 --- a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml @@ -29,8 +29,6 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=35_PPP=1_Pods=70_Nodes=10 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: false - skip_cleanup: true pps=50_ppp=1_pods=3500_nodes=500: node_count: 500 pods_per_step: 50 @@ -38,8 +36,6 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=1_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 50 @@ -47,8 +43,6 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=1_pods=14000_nodes=2000: node_count: 2000 pods_per_step: 50 @@ -56,8 +50,6 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=1_pods=17500_nodes=2500: node_count: 2500 pods_per_step: 50 @@ -65,8 +57,6 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=17500_Nodes=2500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=1_pods=21000_nodes=3000: node_count: 3000 pods_per_step: 50 @@ -74,8 +64,6 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=21000_Nodes=3000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: true pps=50_ppp=1_pods=35000_nodes=5000: node_count: 5000 pods_per_step: 50 @@ -83,8 +71,6 @@ parameters: test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=35000_Nodes=5000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - reuse_cluster: true - skip_cleanup: false jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 662de2c362..f3d4e9c408 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -1,6 +1,9 @@ trigger: none variables: + # Cleanup control - set to false to keep resources after pipeline completes + CLEANUP: "true" + # Hardcoded ADO pipeline variables AZURE_SUBSCRIPTION_ID: "37deca37-c375-4a14-b90a-043849bd2bf1" SKIP_RESOURCE_MANAGEMENT: "false" @@ -46,44 +49,18 @@ variables: ds_test: True stages: - - stage: generate_base_run_id - displayName: 'Generate Base Run ID' - jobs: - - job: generate_run_id - displayName: 'Generate Base Run ID' - steps: - - script: | - # Generate base run ID: Initials-DDHHMMSS (17 chars total with job suffix) - timestamp=$(date +%d%H%M%S) - - # Extract user initials from Build.RequestedFor (e.g., "John Doe" -> "JD") - user_name="$(Build.RequestedFor)" - echo "Pipeline triggered by: $user_name" - - # Extract initials - get first letter of each word, convert to uppercase, take first 2 - user_initials=$(echo "$user_name" | sed 's/[^A-Za-z ]//g' | awk '{for(i=1;i<=NF;i++) printf substr(toupper($i),1,1)}' | cut -c1-2) - - # Fallback if initials are empty or too short - if [ -z "$user_initials" ] || [ ${#user_initials} -lt 2 ]; then - user_initials="XX" - fi - - base_run_id="${user_initials}-${timestamp}" - echo "Generated timestamp: $timestamp" - echo "User initials: $user_initials" - echo "Generated base run ID: $base_run_id" - echo "##vso[task.setvariable variable=BASE_RUN_ID;isOutput=true]$base_run_id" - name: generate_id - displayName: "Generate Base Run ID" - - stage: staticres_gradual condition: succeeded() displayName: 'Static Gradual' - dependsOn: - - generate_base_run_id variables: - BASE_RUN_ID: $[ stageDependencies.generate_base_run_id.generate_run_id.outputs['generate_id.BASE_RUN_ID'] ] + BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] jobs: + - job: generate_run_id + displayName: 'Generate Run ID' + steps: + - template: /steps/generate-run-id.yml + parameters: + prefix: sg - template: /pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml parameters: cloud: azure @@ -98,16 +75,28 @@ stages: credential_type: service_connection ssh_key_enabled: false base_run_id: $(BASE_RUN_ID) + - template: /jobs/cleanup.yml + parameters: + cloud: azure + regions: + - $(LOCATION) + credential_type: service_connection + base_run_id: $(BASE_RUN_ID) - stage: dynamicres_gradual condition: succeededOrFailed() displayName: 'Dynamic Gradual' dependsOn: - - generate_base_run_id - staticres_gradual variables: - BASE_RUN_ID: $[ stageDependencies.generate_base_run_id.generate_run_id.outputs['generate_id.BASE_RUN_ID'] ] + BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] jobs: + - job: generate_run_id + displayName: 'Generate Run ID' + steps: + - template: /steps/generate-run-id.yml + parameters: + prefix: dg - template: /pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml parameters: cloud: azure @@ -122,14 +111,26 @@ stages: credential_type: service_connection ssh_key_enabled: false base_run_id: $(BASE_RUN_ID) + - template: /jobs/cleanup.yml + parameters: + cloud: azure + regions: + - $(LOCATION) + credential_type: service_connection + base_run_id: $(BASE_RUN_ID) - stage: staticres_burst condition: false displayName: 'Static Burst' - dependsOn: generate_base_run_id variables: - BASE_RUN_ID: $[ stageDependencies.generate_base_run_id.generate_run_id.outputs['generate_id.BASE_RUN_ID'] ] + BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] jobs: + - job: generate_run_id + displayName: 'Generate Run ID' + steps: + - template: /steps/generate-run-id.yml + parameters: + prefix: sb - template: /pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml parameters: cloud: azure @@ -144,14 +145,26 @@ stages: credential_type: service_connection ssh_key_enabled: false base_run_id: $(BASE_RUN_ID) + - template: /jobs/cleanup.yml + parameters: + cloud: azure + regions: + - $(LOCATION) + credential_type: service_connection + base_run_id: $(BASE_RUN_ID) - stage: dynamicres_burst condition: false displayName: 'Dynamic Burst' - dependsOn: generate_base_run_id variables: - BASE_RUN_ID: $[ stageDependencies.generate_base_run_id.generate_run_id.outputs['generate_id.BASE_RUN_ID'] ] + BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] jobs: + - job: generate_run_id + displayName: 'Generate Run ID' + steps: + - template: /steps/generate-run-id.yml + parameters: + prefix: db - template: /pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml parameters: cloud: azure @@ -166,3 +179,10 @@ stages: credential_type: service_connection ssh_key_enabled: false base_run_id: $(BASE_RUN_ID) + - template: /jobs/cleanup.yml + parameters: + cloud: azure + regions: + - $(LOCATION) + credential_type: service_connection + base_run_id: $(BASE_RUN_ID) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index fb1304086f..965103ee20 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -10,21 +10,12 @@ parameters: - name: credential_type type: string default: managed_identity -- name: skip_cleanup - type: string - default: 'false' steps: - script: | echo "===================================================================" - skip_cleanup=$(echo "${{ parameters.skip_cleanup }}" | tr '[:upper:]' '[:lower:]') - if [ "$skip_cleanup" == "true" ]; then - echo "SKIP_CLEANUP is enabled - skipping resource cleanup for this job" - echo "Resources will be reused by subsequent jobs" - else - echo "Starting cleanup process for Run ID: $RUN_ID" - echo "Cleanup will proceed even if pipeline was cancelled" - fi + echo "Starting cleanup process for resource group: $RESOURCE_GROUP_NAME" + echo "Cleanup will proceed even if pipeline was cancelled" echo "===================================================================" displayName: "Cleanup Notice" condition: always() @@ -37,11 +28,11 @@ steps: for attempt in $(seq 1 5); do echo "Attempting to execute subnetdelegator DELETE command: $attempt/5" - script --return --quiet -c "az containerapp exec -n subnetdelegator-westus-u3h4j -g subnetdelegator-westus --command 'curl -X DELETE http://localhost:8080/DelegatedSubnet/%2Fsubscriptions%2F9b8218f9-902a-4d20-a65c-e98acec5362f%2FresourceGroups%2F$RUN_ID%2Fproviders%2FMicrosoft.Network%2FvirtualNetworks%2Fcustvnet%2Fsubnets%2Fscaledel'" /dev/null && break || echo "Command failed, retrying..." + script --return --quiet -c "az containerapp exec -n subnetdelegator-westus-u3h4j -g subnetdelegator-westus --command 'curl -X DELETE http://localhost:8080/DelegatedSubnet/%2Fsubscriptions%2F9b8218f9-902a-4d20-a65c-e98acec5362f%2FresourceGroups%2F$RESOURCE_GROUP_NAME%2Fproviders%2FMicrosoft.Network%2FvirtualNetworks%2Fcustvnet%2Fsubnets%2Fscaledel'" /dev/null && break || echo "Command failed, retrying..." sleep 30 done displayName: "Delete SAL Ping" - condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true'), eq(lower(variables['skip_cleanup']), 'false')) + condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true')) continueOnError: true - script: | set -eu @@ -49,7 +40,7 @@ steps: # Signal handler - still try to complete cleanup even if cancelled again trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT - echo "Force cleanup Azure resources in $RUN_ID before resource group deletion" + echo "Force cleanup Azure resources in $RESOURCE_GROUP_NAME before resource group deletion" # Function to retry commands with exponential backoff retry_command() { @@ -80,9 +71,9 @@ steps: # Force delete AKS clusters first (this blocks until deletion completes) echo "Deleting AKS clusters..." - for cluster in $(az aks list -g $RUN_ID --query "[].name" -o tsv 2>/dev/null || true); do + for cluster in $(az aks list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do echo "Deleting AKS cluster: $cluster (this may take several minutes for large clusters)" - retry_command "az aks delete -g $RUN_ID -n $cluster --yes" || true + retry_command "az aks delete -g $RESOURCE_GROUP_NAME -n $cluster --yes" || true done # Brief wait for managed resource group cleanup to propagate @@ -91,65 +82,59 @@ steps: # Remove NAT Gateway associations from subnets echo "Removing NAT Gateway associations..." - for vnet in $(az network vnet list -g $RUN_ID --query "[].name" -o tsv 2>/dev/null || true); do - for subnet in $(az network vnet subnet list -g $RUN_ID --vnet-name $vnet --query "[?natGateway].name" -o tsv 2>/dev/null || true); do + for vnet in $(az network vnet list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do + for subnet in $(az network vnet subnet list -g $RESOURCE_GROUP_NAME --vnet-name $vnet --query "[?natGateway].name" -o tsv 2>/dev/null || true); do echo "Removing NAT Gateway from subnet: $vnet/$subnet" - retry_command "az network vnet subnet update -g $RUN_ID --vnet-name $vnet -n $subnet --remove natGateway" || true + retry_command "az network vnet subnet update -g $RESOURCE_GROUP_NAME --vnet-name $vnet -n $subnet --remove natGateway" || true done done # Remove NSG associations from subnets echo "Removing NSG associations..." - for vnet in $(az network vnet list -g $RUN_ID --query "[].name" -o tsv 2>/dev/null || true); do - for subnet in $(az network vnet subnet list -g $RUN_ID --vnet-name $vnet --query "[?networkSecurityGroup].name" -o tsv 2>/dev/null || true); do + for vnet in $(az network vnet list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do + for subnet in $(az network vnet subnet list -g $RESOURCE_GROUP_NAME --vnet-name $vnet --query "[?networkSecurityGroup].name" -o tsv 2>/dev/null || true); do echo "Removing NSG from subnet: $vnet/$subnet" - retry_command "az network vnet subnet update -g $RUN_ID --vnet-name $vnet -n $subnet --remove networkSecurityGroup" || true + retry_command "az network vnet subnet update -g $RESOURCE_GROUP_NAME --vnet-name $vnet -n $subnet --remove networkSecurityGroup" || true done done # Delete NAT Gateways echo "Deleting NAT Gateways..." - for natgw in $(az network nat gateway list -g $RUN_ID --query "[].name" -o tsv 2>/dev/null || true); do + for natgw in $(az network nat gateway list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do echo "Deleting NAT Gateway: $natgw" - retry_command "az network nat gateway delete -g $RUN_ID -n $natgw" || true + retry_command "az network nat gateway delete -g $RESOURCE_GROUP_NAME -n $natgw" || true done # Delete NSGs echo "Deleting Network Security Groups..." - for nsg in $(az network nsg list -g $RUN_ID --query "[].name" -o tsv 2>/dev/null || true); do + for nsg in $(az network nsg list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do echo "Deleting NSG: $nsg" - retry_command "az network nsg delete -g $RUN_ID -n $nsg" || true + retry_command "az network nsg delete -g $RESOURCE_GROUP_NAME -n $nsg" || true done # Delete Public IPs echo "Deleting Public IP addresses..." - for pip in $(az network public-ip list -g $RUN_ID --query "[].name" -o tsv 2>/dev/null || true); do + for pip in $(az network public-ip list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do echo "Deleting Public IP: $pip" - retry_command "az network public-ip delete -g $RUN_ID -n $pip" || true + retry_command "az network public-ip delete -g $RESOURCE_GROUP_NAME -n $pip" || true done echo "Pre-cleanup completed" displayName: "Force Cleanup Azure Resources" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(lower(variables['skip_cleanup']), 'false')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) continueOnError: true -- script: | - echo "Skipping resource group deletion due to skip_cleanup=true" - echo "Resource group will be cleaned up by the final job in the sequence" - displayName: "Skip Resource Group Deletion (Reuse Mode)" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(lower(variables['skip_cleanup']), 'true')) - - script: | set -eu # Signal handler - still try to complete cleanup even if cancelled again trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT - echo "Delete resource group $RUN_ID" + echo "Delete resource group $RESOURCE_GROUP_NAME" # Use retry logic for resource group deletion as well for attempt in $(seq 1 5); do echo "Attempting to delete resource group: $attempt/5" - if az group delete --name $RUN_ID --yes; then + if az group delete --name $RESOURCE_GROUP_NAME --yes; then echo "Resource group deleted successfully" break else @@ -161,5 +146,5 @@ steps: fi done displayName: "Destroy Resource Group" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(lower(variables['skip_cleanup']), 'false')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) continueOnError: true diff --git a/steps/cloud/azure/collect-cloud-info.yml b/steps/cloud/azure/collect-cloud-info.yml index 738266ef53..6b8fc89ef3 100644 --- a/steps/cloud/azure/collect-cloud-info.yml +++ b/steps/cloud/azure/collect-cloud-info.yml @@ -5,10 +5,10 @@ parameters: steps: - script: | set -eu - + aks_name=$(az resource list --resource-type Microsoft.ContainerService/managedClusters \ - --resource-group $RUN_ID --query "[0].name" --output tsv) - aks_info=$(az aks show --resource-group $RUN_ID --name $aks_name --output json) + --resource-group $RESOURCE_GROUP_NAME --query "[0].name" --output tsv) + aks_info=$(az aks show --resource-group $RESOURCE_GROUP_NAME --name $aks_name --output json) cloud_info=$(jq -n \ --arg cloud "azure" \ diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index 2da78d00b5..fe67b4053b 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh @@ -32,20 +32,14 @@ function find_aks_cluster() { local region=$1 local role=$2 - # Determine run_id for cluster discovery - # BASE_RUN_ID is always generated by the pipeline and used for resource group naming. - # All jobs in a matrix share the same BASE_RUN_ID so they can find/reuse the same cluster. - # RUN_ID fallback exists only for defensive coding (should never be needed). - local cluster_run_id - - if [ -n "${BASE_RUN_ID:-}" ]; then - cluster_run_id="$BASE_RUN_ID" - log_info "Using BASE_RUN_ID for cluster discovery: $cluster_run_id" - else - # Fallback - should not happen in current pipeline design - cluster_run_id="$RUN_ID" - log_warning "BASE_RUN_ID not set, falling back to RUN_ID: $cluster_run_id" + # Use RESOURCE_GROUP_NAME pipeline variable (set by provision-resources.yml) + # This is the single source of truth for resource group naming. + if [ -z "${RESOURCE_GROUP_NAME:-}" ]; then + log_error "RESOURCE_GROUP_NAME not set. This should be set by provision-resources.yml" + exit 1 fi + local cluster_run_id="$RESOURCE_GROUP_NAME" + log_info "Using RESOURCE_GROUP_NAME: $cluster_run_id" log_info "Finding AKS cluster with role '$role' in region '$region'..." log_info "Using run_id tag: $cluster_run_id" diff --git a/steps/generate-run-id.yml b/steps/generate-run-id.yml new file mode 100644 index 0000000000..9005e08d5e --- /dev/null +++ b/steps/generate-run-id.yml @@ -0,0 +1,43 @@ +parameters: +- name: prefix + type: string + default: '' + +steps: +- script: | + set -eu + + # Generate base run ID: Initials-DDHHMMSS-prefix + timestamp=$(date +%d%H%M%S) + + # Extract user initials from Build.RequestedFor (e.g., "John Doe" -> "JD") + user_name="$BUILD_REQUESTED_FOR" + echo "Pipeline triggered by: $user_name" + + # Extract initials - get first letter of each word, convert to uppercase, take first 2 + user_initials=$(echo "$user_name" | sed 's/[^A-Za-z ]//g' | awk '{for(i=1;i<=NF;i++) printf substr(toupper($i),1,1)}' | cut -c1-2) + + # Fallback if initials are empty or too short + if [ -z "$user_initials" ] || [ ${#user_initials} -lt 2 ]; then + user_initials="XX" + fi + + # Add optional prefix for stage identification + prefix="${PREFIX:-}" + if [ -n "$prefix" ]; then + base_run_id="${user_initials}-${timestamp}-${prefix}" + else + base_run_id="${user_initials}-${timestamp}" + fi + + echo "Generated timestamp: $timestamp" + echo "User initials: $user_initials" + echo "Generated BASE_RUN_ID: $base_run_id" + + # Set as output variable for other jobs in same stage to consume + echo "##vso[task.setvariable variable=BASE_RUN_ID;isOutput=true]$base_run_id" + name: set_run_id + displayName: "Generate Run ID" + env: + BUILD_REQUESTED_FOR: $(Build.RequestedFor) + PREFIX: ${{ parameters.prefix }} diff --git a/steps/provision-resources.yml b/steps/provision-resources.yml index b6b312913c..bbb71a6a86 100644 --- a/steps/provision-resources.yml +++ b/steps/provision-resources.yml @@ -9,12 +9,23 @@ parameters: - name: credential_type type: string default: managed_identity -- name: reuse_cluster - type: string - default: 'false' steps: +# Always set RESOURCE_GROUP_NAME for use in all subsequent steps +- script: | + # Determine resource group name + # BASE_RUN_ID is always generated by the pipeline and used for resource group naming. + # All jobs in a matrix share the same BASE_RUN_ID so they can find/reuse the same cluster. + if [ -z "${BASE_RUN_ID:-}" ]; then + echo "ERROR: BASE_RUN_ID not set" + exit 1 + fi + RESOURCE_GROUP_NAME="$BASE_RUN_ID" + echo "Using resource group: $RESOURCE_GROUP_NAME" + echo "##vso[task.setvariable variable=RESOURCE_GROUP_NAME]$RESOURCE_GROUP_NAME" + displayName: "Set Resource Group Name" + - script: | # Set deletion due time to 1 week from now deletion_due_time=$(date -u -d "+1 week" +'%Y-%m-%dT%H:%M:%SZ') @@ -33,41 +44,40 @@ steps: - script: | set -eu - reuse_cluster=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') - # When creating a new cluster for reuse pattern, use BASE_RUN_ID as the resource group name - # so all subsequent matrix jobs can find it. Otherwise use the unique RUN_ID. - if [ "$reuse_cluster" = "false" ] && [ -n "${BASE_RUN_ID:-}" ]; then - # First job in matrix: create with BASE_RUN_ID so others can reuse - RESOURCE_GROUP_NAME="$BASE_RUN_ID" - echo "Creating resource group $RESOURCE_GROUP_NAME (using BASE_RUN_ID for reuse pattern)" + # Check if resource group already exists + if az group show --name "$RESOURCE_GROUP_NAME" &>/dev/null; then + echo "Resource group $RESOURCE_GROUP_NAME already exists, skipping creation" else - # Standalone job: use unique RUN_ID - RESOURCE_GROUP_NAME="$RUN_ID" - echo "Creating resource group $RESOURCE_GROUP_NAME (standalone job)" + echo "Creating resource group $RESOURCE_GROUP_NAME" + az group create --name "$RESOURCE_GROUP_NAME" --location $region \ + --tags "run_id=$RESOURCE_GROUP_NAME" "scenario=${SCENARIO_TYPE}-${SCENARIO_NAME}" "owner=${OWNER}" "creation_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "deletion_due_time=${DELETION_DUE_TIME}" "SkipAKSCluster=1" fi - - az group create --name "$RESOURCE_GROUP_NAME" --location $region \ - --tags "run_id=$RESOURCE_GROUP_NAME" "scenario=${SCENARIO_TYPE}-${SCENARIO_NAME}" "owner=${OWNER}" "creation_date=$(date -u +'%Y-%m-%dT%H:%M:%SZ')" "deletion_due_time=${DELETION_DUE_TIME}" "SkipAKSCluster=1" - displayName: "Create Resource Group" - condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true'), eq(lower(variables['reuse_cluster']), 'false')) + displayName: "Ensure Resource Group" + condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true')) env: region: ${{ parameters.regions[0] }} - BASE_RUN_ID: $(BASE_RUN_ID) - REUSE_CLUSTER: $(reuse_cluster) - script: | bash swiftv2kubeobjects/runCustomerSetup.sh displayName: "SetupCustomerResources" condition: eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true') name: SetupCustomerResources + - script: | - bash swiftv2kubeobjects/createclusterforping.sh - displayName: "SetupAKSMTClusterPING" - condition: and(eq(variables['CREATESWIFTV2PING'], 'true'), eq(lower(variables['reuse_cluster']), 'false')) - name: SetupAKSMTClusterPING + set -eu + + # Check if cluster already exists + if az aks show --name "large" --resource-group "$RESOURCE_GROUP_NAME" &>/dev/null; then + echo "AKS cluster 'large' already exists in $RESOURCE_GROUP_NAME, skipping creation" + else + echo "Creating AKS cluster..." + bash swiftv2kubeobjects/createclusterforping.sh + fi + displayName: "Ensure AKS Cluster" + condition: eq(variables['CREATESWIFTV2PING'], 'true') + name: EnsureAKSCluster env: - # Ensure these pipeline variables are available as env vars to the script MAX_PODS: $(max_pods) DEVICE_PLUGIN: $(DEVICE_PLUGIN) @@ -76,14 +86,11 @@ steps: displayName: "EnsureUserNodepools" condition: eq(variables['CREATESWIFTV2PING'], 'true') env: - REUSE_CLUSTER: $(reuse_cluster) NODE_COUNT: $(node_count) VM_SKU: $(vm_sku) PODS_PER_NODE: $(pods_per_node) PROVISION_BUFFER_NODES: $(PROVISION_BUFFER_NODES) MAX_PODS: $(max_pods) DEVICE_PLUGIN: $(DEVICE_PLUGIN) - BASE_RUN_ID: $(BASE_RUN_ID) - RUN_ID: $(RUN_ID) REGION: ${{ parameters.regions[0] }} ROLE: slo \ No newline at end of file diff --git a/steps/terraform/run-command.yml b/steps/terraform/run-command.yml deleted file mode 100644 index e4a3dc6677..0000000000 --- a/steps/terraform/run-command.yml +++ /dev/null @@ -1,96 +0,0 @@ -parameters: -- name: command - type: string -- name: arguments - type: string - default: '' -- name: regions - type: object - default: {} -- name: cloud - type: string - default: '' -- name: retry_attempt_count - type: number - default: 3 -- name: credential_type - type: string - default: 'managed_identity' - -steps: -- script: | - set -e - - # Signal handler for graceful cancellation - trap 'echo "Terraform operation cancelled by user"; exit 143' SIGTERM SIGINT - - cd $TERRAFORM_WORKING_DIRECTORY - if [[ ${{ parameters.command }} == "apply" || ${{ parameters.command }} == "destroy" ]]; then - for region in $(echo "$REGIONS" | jq -r '.[]'); do - if terraform workspace list | grep -q "$region"; then - terraform workspace select $region - else - terraform workspace new $region - terraform workspace select $region - fi - terraform_input_file=$(echo $TERRAFORM_REGIONAL_CONFIG | jq -r --arg region "$region" '.[$region].TERRAFORM_INPUT_FILE') - terraform_input_variables=$(echo $TERRAFORM_REGIONAL_CONFIG | jq -r --arg region "$region" '.[$region].TERRAFORM_INPUT_VARIABLES') - - set +e - terraform ${{ parameters.command }} --auto-approve ${{ parameters.arguments }} -var-file $terraform_input_file -var json_input="$terraform_input_variables" | tee terraform_${{ parameters.command }}.log - exit_code=${PIPESTATUS[0]} - if [[ $exit_code -ne 0 ]]; then - if [[ ${{ parameters.command }} == "apply" && "$CLOUD" == "azure" ]]; then - echo "Delete resources and remove state file before retrying" - ids=$(az resource list --location $region --resource-group $RUN_ID --query [*].id -o tsv) - az resource delete --ids $ids --verbose - rm -r terraform.tfstate.d/$region - fi - if [[ ${{ parameters.command }} == "destroy" && "$CLOUD" == "aws" ]]; then - echo "Delete all the network interfaces before retrying" - subnet_ids=$(aws ec2 describe-subnets --query "Subnets[?Tags[?Key=='run_id' && Value=='$RUN_ID']].SubnetId" --output text) - for subnet_id in $subnet_ids; do - echo "Detaching Subnet: $subnet_id Network Interfaces ..." - network_interfaces_attachment_id=$(aws ec2 describe-network-interfaces --filters Name=subnet-id,Values=$subnet_id --query "NetworkInterfaces[].Attachment.AttachmentId" --output text) - for network_interface_attachment_id in $network_interfaces_attachment_id; do - echo "Detaching Network Interface attachment id: $network_interface_attachment_id" - if ! aws ec2 detach-network-interface --attachment-id $network_interface_attachment_id; then - echo "##vso[task.logissue type=error;] Failed to detach Network Interface attachment id: $network_interface_attachment_id" - fi - done - echo "Deleting Subnet: $subnet_id Network Interfaces ..." - network_interfaces=$(aws ec2 describe-network-interfaces --filters Name=subnet-id,Values=$subnet_id --query "NetworkInterfaces[].NetworkInterfaceId" --output text) - for network_interface in $network_interfaces; do - echo "Deleting Network Interface: $network_interface" - if ! aws ec2 delete-network-interface --network-interface-id $network_interface; then - echo "##vso[task.logissue type=error;] Failed to delete Network Interface: $network_interface" - fi - done - done - echo "Delete all the security groups before retrying" - vpc_id=$(aws ec2 describe-vpcs --query "Vpcs[?Tags[?Key=='run_id' && Value=='$RUN_ID']].VpcId" --output text) - security_group_ids=$(aws ec2 describe-security-groups --filters Name=vpc-id,Values=$vpc_id --query "SecurityGroups[].GroupId" --output text) - for security_group_id in $security_group_ids; do - echo "Deleting Security Group: $security_group_id" - if ! aws ec2 delete-security-group --group-id $security_group_id; then - echo "##vso[task.logissue type=error;] Failed to delete Security Group: $security_group_id" - fi - done - fi - exit 1 - fi - done - else - terraform ${{ parameters.command }} ${{ parameters.arguments }} - fi - displayName: "Run Terraform ${{ parameters.command }} Command" - condition: ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true') - retryCountOnTaskFailure: ${{ parameters.retry_attempt_count }} - env: - REGIONS: ${{ convertToJson(parameters.regions) }} - CLOUD: ${{ parameters.cloud }} - ARM_SUBSCRIPTION_ID: $(AZURE_SUBSCRIPTION_ID) - ${{ if eq(parameters.credential_type, 'managed_identity') }}: - ARM_USE_MSI: true - ARM_TENANT_ID: $(AZURE_MI_TENANT_ID) - ARM_CLIENT_ID: $(AZURE_MI_CLIENT_ID) diff --git a/swiftv2kubeobjects/createclusterforping.sh b/swiftv2kubeobjects/createclusterforping.sh index 1a1691a4d4..3f1ff64e6d 100755 --- a/swiftv2kubeobjects/createclusterforping.sh +++ b/swiftv2kubeobjects/createclusterforping.sh @@ -42,18 +42,13 @@ check_cancellation() { return 0 } -# Determine resource group name -# BASE_RUN_ID is always generated by the pipeline and used for resource group naming. -# All jobs in a matrix share the same BASE_RUN_ID so they can find/reuse the same cluster. -# RUN_ID fallback exists only for defensive coding (should never be needed). -if [ -n "${BASE_RUN_ID:-}" ]; then - RG="$BASE_RUN_ID" - echo "Using resource group $RG (from BASE_RUN_ID)" -else - # Fallback - should not happen in current pipeline design - RG="$RUN_ID" - echo "WARNING: BASE_RUN_ID not set, using RUN_ID: $RG" +# Use RESOURCE_GROUP_NAME pipeline variable (set by provision-resources.yml) +if [ -z "${RESOURCE_GROUP_NAME:-}" ]; then + echo "ERROR: RESOURCE_GROUP_NAME not set. This should be set by provision-resources.yml" + exit 1 fi +RG="$RESOURCE_GROUP_NAME" +echo "Using resource group: $RG" CLUSTER="large" SUBSCRIPTION=$AZURE_SUBSCRIPTION_ID From b72a26d2521b4a74821b403149afa40d1f8d4ed1 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 01:40:46 +0000 Subject: [PATCH 21/47] nit: remove redundant condition in first stage --- pipelines/system/new-pipeline-test.yml | 1 - 1 file changed, 1 deletion(-) diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index f3d4e9c408..29d85b6684 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -50,7 +50,6 @@ variables: stages: - stage: staticres_gradual - condition: succeeded() displayName: 'Static Gradual' variables: BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] From bcd444ed646cae7215f5c3dfad787a5f767e781c Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 01:51:06 +0000 Subject: [PATCH 22/47] fix(pipelines): add job dependencies for BASE_RUN_ID propagation Jobs within a stage were not waiting for generate_run_id job and could not access BASE_RUN_ID output variable. Stage-level variables using dependencies.X syntax only work for cross-stage references, not for jobs within the same stage. Changes: - Add dependsOn parameter to competitive-test.yml and cleanup.yml jobs - Add dependsOn parameter to all swiftv2 matrix templates - Update new-pipeline-test.yml to pass job dependencies explicitly - Use job-level dependency syntax for BASE_RUN_ID references This ensures proper execution order: generate_run_id -> test job (azure) -> cleanup --- jobs/cleanup.yml | 4 ++ jobs/competitive-test.yml | 4 ++ .../swiftv2-dynamicres-burst-matrix.yml | 4 ++ .../swiftv2-dynamicres-gradual-matrix.yml | 4 ++ .../swiftv2-staticres-burst-matrix.yml | 4 ++ .../swiftv2-staticres-gradual-matrix.yml | 4 ++ pipelines/system/new-pipeline-test.yml | 40 +++++++++++-------- 7 files changed, 48 insertions(+), 16 deletions(-) diff --git a/jobs/cleanup.yml b/jobs/cleanup.yml index 992c96178a..ddd1828dec 100644 --- a/jobs/cleanup.yml +++ b/jobs/cleanup.yml @@ -8,9 +8,13 @@ parameters: default: service_connection - name: base_run_id type: string +- name: dependsOn + type: object + default: [] jobs: - job: cleanup + dependsOn: ${{ parameters.dependsOn }} displayName: 'Cleanup Resources' condition: and(always(), eq(variables['CLEANUP'], 'true')) timeoutInMinutes: 60 diff --git a/jobs/competitive-test.yml b/jobs/competitive-test.yml index ba1ae4b29a..f44bb14307 100644 --- a/jobs/competitive-test.yml +++ b/jobs/competitive-test.yml @@ -39,9 +39,13 @@ parameters: - name: ssh_key_enabled type: boolean default: true +- name: dependsOn + type: object + default: [] jobs: - job: ${{ parameters.cloud }} + dependsOn: ${{ parameters.dependsOn }} strategy: maxParallel: ${{ parameters.max_parallel }} matrix: diff --git a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml index f4f6748b13..ffac7cf964 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml @@ -19,6 +19,9 @@ parameters: type: boolean - name: base_run_id type: string +- name: dependsOn + type: object + default: [] - name: matrix type: object default: @@ -79,3 +82,4 @@ jobs: credential_type: ${{ parameters.credential_type }} ssh_key_enabled: ${{ parameters.ssh_key_enabled }} base_run_id: ${{ parameters.base_run_id }} + dependsOn: ${{ parameters.dependsOn }} diff --git a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml index b670bbebb9..13dc30504f 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml @@ -19,6 +19,9 @@ parameters: type: boolean - name: base_run_id type: string +- name: dependsOn + type: object + default: [] - name: matrix type: object default: @@ -79,3 +82,4 @@ jobs: credential_type: ${{ parameters.credential_type }} ssh_key_enabled: ${{ parameters.ssh_key_enabled }} base_run_id: ${{ parameters.base_run_id }} + dependsOn: ${{ parameters.dependsOn }} diff --git a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml index 0709214d7d..5e307467b4 100644 --- a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml @@ -19,6 +19,9 @@ parameters: type: boolean - name: base_run_id type: string +- name: dependsOn + type: object + default: [] - name: matrix type: object default: @@ -86,3 +89,4 @@ jobs: credential_type: ${{ parameters.credential_type }} ssh_key_enabled: ${{ parameters.ssh_key_enabled }} base_run_id: ${{ parameters.base_run_id }} + dependsOn: ${{ parameters.dependsOn }} diff --git a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml index 3a8347decf..6e816e3f83 100644 --- a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml @@ -19,6 +19,9 @@ parameters: type: boolean - name: base_run_id type: string +- name: dependsOn + type: object + default: [] - name: matrix type: object default: @@ -86,3 +89,4 @@ jobs: credential_type: ${{ parameters.credential_type }} ssh_key_enabled: ${{ parameters.ssh_key_enabled }} base_run_id: ${{ parameters.base_run_id }} + dependsOn: ${{ parameters.dependsOn }} diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 29d85b6684..30615b2fdf 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -51,8 +51,6 @@ variables: stages: - stage: staticres_gradual displayName: 'Static Gradual' - variables: - BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] jobs: - job: generate_run_id displayName: 'Generate Run ID' @@ -73,22 +71,24 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $(BASE_RUN_ID) + base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] + dependsOn: + - generate_run_id - template: /jobs/cleanup.yml parameters: cloud: azure regions: - $(LOCATION) credential_type: service_connection - base_run_id: $(BASE_RUN_ID) + base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] + dependsOn: + - azure - stage: dynamicres_gradual condition: succeededOrFailed() displayName: 'Dynamic Gradual' dependsOn: - staticres_gradual - variables: - BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] jobs: - job: generate_run_id displayName: 'Generate Run ID' @@ -109,20 +109,22 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $(BASE_RUN_ID) + base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] + dependsOn: + - generate_run_id - template: /jobs/cleanup.yml parameters: cloud: azure regions: - $(LOCATION) credential_type: service_connection - base_run_id: $(BASE_RUN_ID) + base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] + dependsOn: + - azure - stage: staticres_burst condition: false displayName: 'Static Burst' - variables: - BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] jobs: - job: generate_run_id displayName: 'Generate Run ID' @@ -143,20 +145,22 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $(BASE_RUN_ID) + base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] + dependsOn: + - generate_run_id - template: /jobs/cleanup.yml parameters: cloud: azure regions: - $(LOCATION) credential_type: service_connection - base_run_id: $(BASE_RUN_ID) + base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] + dependsOn: + - azure - stage: dynamicres_burst condition: false displayName: 'Dynamic Burst' - variables: - BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] jobs: - job: generate_run_id displayName: 'Generate Run ID' @@ -177,11 +181,15 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $(BASE_RUN_ID) + base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] + dependsOn: + - generate_run_id - template: /jobs/cleanup.yml parameters: cloud: azure regions: - $(LOCATION) credential_type: service_connection - base_run_id: $(BASE_RUN_ID) + base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] + dependsOn: + - azure From 6b5d36bd2c123c8d5c5d58cef4b29f55f0f6117e Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 02:00:30 +0000 Subject: [PATCH 23/47] fix(pipeline): export BASE_RUN_ID as pipeline variable for subsequent steps The provision-resources.yml step was failing with 'BASE_RUN_ID not set' because the variable was only passed as a parameter to setup-tests.yml but not exported as a pipeline variable for other steps in the same job. This change exports BASE_RUN_ID via ##vso[task.setvariable] so that all subsequent steps (provision-resources, collect-telescope-metadata, etc.) can access it directly without requiring explicit parameter passing. --- steps/setup-tests.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/steps/setup-tests.yml b/steps/setup-tests.yml index 042a716baa..9c02076b18 100644 --- a/steps/setup-tests.yml +++ b/steps/setup-tests.yml @@ -45,6 +45,11 @@ steps: echo "Final Run ID: $run_id" echo "##vso[task.setvariable variable=RUN_ID]$run_id" + # Also export BASE_RUN_ID as pipeline variable for subsequent steps + if [ -n "$BASE_RUN_ID" ] && [ "$BASE_RUN_ID" != " " ]; then + echo "##vso[task.setvariable variable=BASE_RUN_ID]$BASE_RUN_ID" + fi + reuse_cluster=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') # When reusing clusters, validate BASE_RUN_ID is set if [ "$reuse_cluster" == "true" ]; then From da8a94d95d90669abeab6884a10519da03e2432f Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 02:18:10 +0000 Subject: [PATCH 24/47] fix(pipelines): resolve BASE_RUN_ID runtime expression not evaluated ADO runtime expressions ($[ ... ]) cannot be passed through template parameters as they get treated as literal strings at compile time. Changes: - Define BASE_RUN_ID as job-level variable in competitive-test.yml and cleanup.yml using runtime expression directly - Remove base_run_id parameter from templates since it's now a job variable - Add generate_run_id to cleanup job dependencies to access output This fixes resource group creation failing with literal expression string instead of the resolved run ID value. --- jobs/cleanup.yml | 8 ++++---- jobs/competitive-test.yml | 8 ++++---- .../matrices/swiftv2-dynamicres-burst-matrix.yml | 3 --- .../matrices/swiftv2-dynamicres-gradual-matrix.yml | 3 --- .../matrices/swiftv2-staticres-burst-matrix.yml | 3 --- .../matrices/swiftv2-staticres-gradual-matrix.yml | 3 --- pipelines/system/new-pipeline-test.yml | 12 ++++-------- steps/setup-tests.yml | 4 ---- 8 files changed, 12 insertions(+), 32 deletions(-) diff --git a/jobs/cleanup.yml b/jobs/cleanup.yml index ddd1828dec..fdd9aa5dbf 100644 --- a/jobs/cleanup.yml +++ b/jobs/cleanup.yml @@ -6,8 +6,6 @@ parameters: - name: credential_type type: string default: service_connection -- name: base_run_id - type: string - name: dependsOn type: object default: [] @@ -18,6 +16,10 @@ jobs: displayName: 'Cleanup Resources' condition: and(always(), eq(variables['CLEANUP'], 'true')) timeoutInMinutes: 60 + variables: + # Runtime expression to get BASE_RUN_ID from generate_run_id job output + # Must be defined here (not passed through parameters) for ADO to evaluate at runtime + BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] steps: - script: | # Set RESOURCE_GROUP_NAME from BASE_RUN_ID @@ -29,8 +31,6 @@ jobs: echo "Resource group to cleanup: $RESOURCE_GROUP_NAME" echo "##vso[task.setvariable variable=RESOURCE_GROUP_NAME]$RESOURCE_GROUP_NAME" displayName: "Set Resource Group Name" - env: - BASE_RUN_ID: ${{ parameters.base_run_id }} - ${{ if eq(parameters.credential_type, 'service_connection') }}: - task: AzureCLI@2 diff --git a/jobs/competitive-test.yml b/jobs/competitive-test.yml index f44bb14307..d8dc4ddd0a 100644 --- a/jobs/competitive-test.yml +++ b/jobs/competitive-test.yml @@ -21,9 +21,6 @@ parameters: - name: run_id type: string default: '' -- name: base_run_id - type: string - default: '' - name: timeout_in_minutes type: number default: 60 # default when not specified is 60 minutes @@ -46,6 +43,10 @@ parameters: jobs: - job: ${{ parameters.cloud }} dependsOn: ${{ parameters.dependsOn }} + variables: + # Runtime expression to get BASE_RUN_ID from generate_run_id job output + # Must be defined here (not passed through parameters) for ADO to evaluate at runtime + BASE_RUN_ID: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] strategy: maxParallel: ${{ parameters.max_parallel }} matrix: @@ -56,7 +57,6 @@ jobs: parameters: cloud: ${{ parameters.cloud }} region: ${{ parameters.regions[0] }} - base_run_id: ${{ parameters.base_run_id }} test_modules_dir: ${{ parameters.test_modules_dir }} retry_attempt_count: ${{ parameters.retry_attempt_count }} credential_type: ${{ parameters.credential_type }} diff --git a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml index ffac7cf964..32951080fc 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml @@ -17,8 +17,6 @@ parameters: type: string - name: ssh_key_enabled type: boolean -- name: base_run_id - type: string - name: dependsOn type: object default: [] @@ -81,5 +79,4 @@ jobs: timeout_in_minutes: ${{ parameters.timeout_in_minutes }} credential_type: ${{ parameters.credential_type }} ssh_key_enabled: ${{ parameters.ssh_key_enabled }} - base_run_id: ${{ parameters.base_run_id }} dependsOn: ${{ parameters.dependsOn }} diff --git a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml index 13dc30504f..d21d4da514 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml @@ -17,8 +17,6 @@ parameters: type: string - name: ssh_key_enabled type: boolean -- name: base_run_id - type: string - name: dependsOn type: object default: [] @@ -81,5 +79,4 @@ jobs: timeout_in_minutes: ${{ parameters.timeout_in_minutes }} credential_type: ${{ parameters.credential_type }} ssh_key_enabled: ${{ parameters.ssh_key_enabled }} - base_run_id: ${{ parameters.base_run_id }} dependsOn: ${{ parameters.dependsOn }} diff --git a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml index 5e307467b4..2aaa2e1222 100644 --- a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml @@ -17,8 +17,6 @@ parameters: type: string - name: ssh_key_enabled type: boolean -- name: base_run_id - type: string - name: dependsOn type: object default: [] @@ -88,5 +86,4 @@ jobs: timeout_in_minutes: ${{ parameters.timeout_in_minutes }} credential_type: ${{ parameters.credential_type }} ssh_key_enabled: ${{ parameters.ssh_key_enabled }} - base_run_id: ${{ parameters.base_run_id }} dependsOn: ${{ parameters.dependsOn }} diff --git a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml index 6e816e3f83..bc3bb44879 100644 --- a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml @@ -17,8 +17,6 @@ parameters: type: string - name: ssh_key_enabled type: boolean -- name: base_run_id - type: string - name: dependsOn type: object default: [] @@ -88,5 +86,4 @@ jobs: timeout_in_minutes: ${{ parameters.timeout_in_minutes }} credential_type: ${{ parameters.credential_type }} ssh_key_enabled: ${{ parameters.ssh_key_enabled }} - base_run_id: ${{ parameters.base_run_id }} dependsOn: ${{ parameters.dependsOn }} diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 30615b2fdf..f343ceca1d 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -71,7 +71,6 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] dependsOn: - generate_run_id - template: /jobs/cleanup.yml @@ -80,8 +79,8 @@ stages: regions: - $(LOCATION) credential_type: service_connection - base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] dependsOn: + - generate_run_id - azure - stage: dynamicres_gradual @@ -109,7 +108,6 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] dependsOn: - generate_run_id - template: /jobs/cleanup.yml @@ -118,8 +116,8 @@ stages: regions: - $(LOCATION) credential_type: service_connection - base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] dependsOn: + - generate_run_id - azure - stage: staticres_burst @@ -145,7 +143,6 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] dependsOn: - generate_run_id - template: /jobs/cleanup.yml @@ -154,8 +151,8 @@ stages: regions: - $(LOCATION) credential_type: service_connection - base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] dependsOn: + - generate_run_id - azure - stage: dynamicres_burst @@ -181,7 +178,6 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] dependsOn: - generate_run_id - template: /jobs/cleanup.yml @@ -190,6 +186,6 @@ stages: regions: - $(LOCATION) credential_type: service_connection - base_run_id: $[ dependencies.generate_run_id.outputs['set_run_id.BASE_RUN_ID'] ] dependsOn: + - generate_run_id - azure diff --git a/steps/setup-tests.yml b/steps/setup-tests.yml index 9c02076b18..fae9f276da 100644 --- a/steps/setup-tests.yml +++ b/steps/setup-tests.yml @@ -9,9 +9,6 @@ parameters: - name: run_id type: string default: '' -- name: base_run_id - type: string - default: '' - name: retry_attempt_count type: number default: 3 @@ -63,7 +60,6 @@ steps: displayName: "Set Run ID" env: RUN_ID: ${{ parameters.run_id }} - BASE_RUN_ID: ${{ parameters.base_run_id }} REUSE_CLUSTER: $(reuse_cluster) - script: | From c44cb821d0841632d10e26d4338144ff305251eb Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 02:42:01 +0000 Subject: [PATCH 25/47] fix(azure): use RESOURCE_GROUP_NAME for cluster discovery Cluster discovery was incorrectly using RUN_ID (which includes job suffix) instead of RESOURCE_GROUP_NAME/BASE_RUN_ID (which matches the run_id tag set during cluster creation). Fixed in: - steps/cloud/azure/update-kubeconfig.yml - steps/engine/clusterloader2/cilium/scale-cluster.yml RESOURCE_GROUP_NAME is the single source of truth set by provision-resources.yml and matches the run_id tag on clusters. --- steps/cloud/azure/update-kubeconfig.yml | 16 +++++++--------- .../clusterloader2/cilium/scale-cluster.yml | 14 +++++++++++--- 2 files changed, 18 insertions(+), 12 deletions(-) diff --git a/steps/cloud/azure/update-kubeconfig.yml b/steps/cloud/azure/update-kubeconfig.yml index 85d6ac549d..68a7131d54 100644 --- a/steps/cloud/azure/update-kubeconfig.yml +++ b/steps/cloud/azure/update-kubeconfig.yml @@ -10,16 +10,15 @@ steps: set -x region=${{ parameters.region }} - reuse_cluster=$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]') - # Use BASE_RUN_ID for cluster discovery when reusing, otherwise use RUN_ID - if [ "$reuse_cluster" = "true" ]; then - CLUSTER_RUN_ID="$BASE_RUN_ID" - echo "Reusing cluster - searching with BASE_RUN_ID: $CLUSTER_RUN_ID" - else - CLUSTER_RUN_ID="$RUN_ID" - echo "New cluster - searching with RUN_ID: $CLUSTER_RUN_ID" + # Use RESOURCE_GROUP_NAME for cluster discovery - this is the single source of truth + # set by provision-resources.yml and matches the run_id tag on clusters + if [ -z "${RESOURCE_GROUP_NAME:-}" ]; then + echo "##vso[task.logissue type=error;] RESOURCE_GROUP_NAME not set. This should be set by provision-resources.yml" + exit 1 fi + CLUSTER_RUN_ID="$RESOURCE_GROUP_NAME" + echo "Searching for cluster with run_id tag: $CLUSTER_RUN_ID" aks_name=$(az resource list --resource-type Microsoft.ContainerService/managedClusters --location $region \ --query "[?(tags.run_id == '$CLUSTER_RUN_ID' && tags.role == '$ROLE')].name" --output tsv) @@ -35,5 +34,4 @@ steps: az aks get-credentials -n $aks_name -g $aks_rg env: ROLE: ${{ parameters.role }} - REUSE_CLUSTER: $(reuse_cluster) displayName: "Update kubeconfig" diff --git a/steps/engine/clusterloader2/cilium/scale-cluster.yml b/steps/engine/clusterloader2/cilium/scale-cluster.yml index e3d3449be4..e318026e97 100644 --- a/steps/engine/clusterloader2/cilium/scale-cluster.yml +++ b/steps/engine/clusterloader2/cilium/scale-cluster.yml @@ -15,14 +15,22 @@ steps: region=${{ parameters.region }} + # Use RESOURCE_GROUP_NAME for cluster discovery - this is the single source of truth + # set by provision-resources.yml and matches the run_id tag on clusters + if [ -z "${RESOURCE_GROUP_NAME:-}" ]; then + echo "##vso[task.logissue type=error;] RESOURCE_GROUP_NAME not set. This should be set by provision-resources.yml" + exit 1 + fi + CLUSTER_RUN_ID="$RESOURCE_GROUP_NAME" + aks_name=$(az resource list --resource-type Microsoft.ContainerService/managedClusters --location $region \ - --query "[?(tags.run_id == '${RUN_ID}' && tags.role == '$ROLE')].name" --output tsv) + --query "[?(tags.run_id == '${CLUSTER_RUN_ID}' && tags.role == '$ROLE')].name" --output tsv) aks_rg=$(az resource list --resource-type Microsoft.ContainerService/managedClusters --location $region \ - --query "[?(tags.run_id == '${RUN_ID}' && tags.role == '$ROLE')].resourceGroup" --output tsv) + --query "[?(tags.run_id == '${CLUSTER_RUN_ID}' && tags.role == '$ROLE')].resourceGroup" --output tsv) if [ -z "$aks_name" ]; then - echo "##vso[task.logissue type=error;] No AKS instance with role $ROLE and tag $RUN_ID found in region $region." + echo "##vso[task.logissue type=error;] No AKS instance with role $ROLE and tag $CLUSTER_RUN_ID found in region $region." exit 1 fi az aks get-credentials -n $aks_name -g $aks_rg From 9bd0ca1f1afb3fb59f3540cc6bcc976c6db70357 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 03:19:51 +0000 Subject: [PATCH 26/47] fix(scale-cluster): account for already-labeled nodes in swiftv2slo labeling The label_swiftv2slo_nodes function was failing when nodes were already labeled from a previous run. It would find only N unlabeled nodes but compare against the total required count, causing spurious failures. Changes: - Count nodes already labeled with swiftv2slo=true before labeling - Calculate additional nodes needed (total - already_labeled) - Short-circuit if sufficient nodes are already labeled - Only label the delta of unlabeled nodes - Verify final total (already_labeled + newly_labeled) meets requirement --- .../swiftv2-slo/scale-cluster.sh | 49 ++++++++++++++++--- 1 file changed, 41 insertions(+), 8 deletions(-) diff --git a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh index 7e75c092b0..57744c0304 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh @@ -640,7 +640,30 @@ function label_swiftv2slo_nodes() { log_info "Labeling $total_nodes_to_label nodes with swiftv2slo=true..." - # Get ready nodes from user nodepools using kubectl label selector + # First, count nodes that are already labeled with swiftv2slo=true + local already_labeled_count=0 + local already_labeled_output + if already_labeled_output=$(kubectl get nodes \ + -l 'agentpool,agentpool!=promnodepool,swiftv2slo=true' \ + -o json 2>&1); then + already_labeled_count=$(echo "$already_labeled_output" | jq -r '[.items[] | + select(.metadata.labels.agentpool | startswith("userpool")) | + select(.status.conditions[] | select(.type=="Ready" and .status=="True"))] | length' 2>/dev/null || echo "0") + fi + + log_info "Nodes already labeled with swiftv2slo=true: $already_labeled_count" + + # Calculate how many additional nodes need to be labeled + local nodes_needed=$((total_nodes_to_label - already_labeled_count)) + + if [ "$nodes_needed" -le 0 ]; then + log_info "Already have $already_labeled_count labeled nodes (required: $total_nodes_to_label). No additional labeling needed." + return 0 + fi + + log_info "Need to label $nodes_needed additional node(s) to reach target of $total_nodes_to_label" + + # Get ready nodes from user nodepools that are NOT already labeled local kubectl_output if ! kubectl_output=$(kubectl get nodes \ -l 'agentpool,agentpool!=promnodepool,!swiftv2slo' \ @@ -653,11 +676,15 @@ function label_swiftv2slo_nodes() { unlabeled_nodes=$(echo "$kubectl_output" | jq -r '.items[] | select(.metadata.labels.agentpool | startswith("userpool")) | select(.status.conditions[] | select(.type=="Ready" and .status=="True")) | - .metadata.name' | grep -v '^$' | head -n "$total_nodes_to_label") + .metadata.name' | grep -v '^$' | head -n "$nodes_needed") - # Check if we have any nodes + # Check if we have any nodes to label if [ -z "$unlabeled_nodes" ]; then log_warning "No unlabeled ready nodes found to label with swiftv2slo=true" + if [ "$already_labeled_count" -ge "$total_nodes_to_label" ]; then + return 0 + fi + log_error "Insufficient nodes: have $already_labeled_count labeled, need $total_nodes_to_label" return 1 fi @@ -678,10 +705,13 @@ function label_swiftv2slo_nodes() { # Validate we have nodes to label if [ "$node_count" -eq 0 ]; then log_warning "No valid nodes to label" + if [ "$already_labeled_count" -ge "$total_nodes_to_label" ]; then + return 0 + fi return 1 fi - log_info "Found $node_count node(s) to label (requested: $total_nodes_to_label)" + log_info "Found $node_count unlabeled node(s) to label (need: $nodes_needed)" # Use common utility function with retry logic from aks-utils.sh if ! label_nodes_with_retry "swiftv2slo=true" "${nodes_to_label[@]}"; then @@ -689,13 +719,16 @@ function label_swiftv2slo_nodes() { return 1 fi - if [ "$node_count" -lt "$total_nodes_to_label" ]; then - local missing=$((total_nodes_to_label - node_count)) - log_error "Only labeled $node_count/$total_nodes_to_label nodes ($missing nodes missing)" + # Calculate total labeled nodes (already + newly labeled) + local total_labeled=$((already_labeled_count + node_count)) + + if [ "$total_labeled" -lt "$total_nodes_to_label" ]; then + local missing=$((total_nodes_to_label - total_labeled)) + log_error "Only have $total_labeled/$total_nodes_to_label labeled nodes ($missing nodes missing)" return 1 fi - log_info "Successfully labeled $node_count nodes with swiftv2slo=true" + log_info "Successfully labeled $node_count new nodes with swiftv2slo=true (total labeled: $total_labeled)" return 0 } From 2690da64701c30c29e54a4437884484e52faeda9 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 04:40:56 +0000 Subject: [PATCH 27/47] fix(cleanup): use AzureCLI@2 tasks for Azure authentication in pipeline - Convert cleanup-resources.yml script steps to AzureCLI@2 tasks - Add azureSubscription parameter for proper Azure authentication - Fix 'Please run az login' errors in ADO pipeline cleanup phase - Add swiftv2 workload cleanup step calling cleanup-swiftv2-workloads.sh - Add Azure resource cleanup step calling cleanup-azure-resources.sh New files: - swiftv2kubeobjects/lib/common.sh: shared library with cancellation handling, retry logic, and wait functions - swiftv2kubeobjects/cleanup-swiftv2-workloads.sh: cleanup deployments/ pods and user nodepools one at a time - swiftv2kubeobjects/cleanup-azure-resources.sh: force cleanup AKS clusters, NAT gateways, NSGs, public IPs before RG deletion Updated files: - swiftv2kubeobjects/lib/nodepool.sh: source common.sh - swiftv2kubeobjects/createclusterforping.sh: source common.sh - steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh: source common.sh - steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh: add cancellation handling with trap and check_cancellation calls --- steps/cleanup-resources.yml | 170 ++++++-------- .../clusterloader2/swiftv2-slo/aks-utils.sh | 6 + .../swiftv2-slo/scale-cluster.sh | 47 ++++ swiftv2kubeobjects/cleanup-azure-resources.sh | 122 ++++++++++ .../cleanup-swiftv2-workloads.sh | 216 ++++++++++++++++++ swiftv2kubeobjects/createclusterforping.sh | 39 +--- swiftv2kubeobjects/lib/common.sh | 161 +++++++++++++ swiftv2kubeobjects/lib/nodepool.sh | 10 +- 8 files changed, 628 insertions(+), 143 deletions(-) create mode 100755 swiftv2kubeobjects/cleanup-azure-resources.sh create mode 100755 swiftv2kubeobjects/cleanup-swiftv2-workloads.sh create mode 100644 swiftv2kubeobjects/lib/common.sh diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 965103ee20..a83a31b80f 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -34,117 +34,79 @@ steps: displayName: "Delete SAL Ping" condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true')) continueOnError: true -- script: | - set -eu - - # Signal handler - still try to complete cleanup even if cancelled again - trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT - - echo "Force cleanup Azure resources in $RESOURCE_GROUP_NAME before resource group deletion" - - # Function to retry commands with exponential backoff - retry_command() { - local max_attempts=5 - local delay=30 - local attempt=1 - local command="$@" + +- task: AzureCLI@2 + displayName: "Cleanup Swiftv2 Workloads" + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) + continueOnError: true + inputs: + azureSubscription: $(AZURE_SUBSCRIPTION) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -eu - while [ $attempt -le $max_attempts ]; do - echo "Attempt $attempt/$max_attempts: $command" - if eval "$command"; then - echo "Command succeeded on attempt $attempt" - return 0 - else - echo "Command failed on attempt $attempt" - if [ $attempt -lt $max_attempts ]; then - echo "Waiting $delay seconds before retry..." - sleep $delay - delay=$((delay * 2)) # Exponential backoff - fi - attempt=$((attempt + 1)) - fi - done + trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT - echo "Command failed after $max_attempts attempts: $command" - return 1 - } - - # Force delete AKS clusters first (this blocks until deletion completes) - echo "Deleting AKS clusters..." - for cluster in $(az aks list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do - echo "Deleting AKS cluster: $cluster (this may take several minutes for large clusters)" - retry_command "az aks delete -g $RESOURCE_GROUP_NAME -n $cluster --yes" || true - done - - # Brief wait for managed resource group cleanup to propagate - echo "Waiting 60 seconds for managed resource group cleanup to propagate..." - sleep 60 - - # Remove NAT Gateway associations from subnets - echo "Removing NAT Gateway associations..." - for vnet in $(az network vnet list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do - for subnet in $(az network vnet subnet list -g $RESOURCE_GROUP_NAME --vnet-name $vnet --query "[?natGateway].name" -o tsv 2>/dev/null || true); do - echo "Removing NAT Gateway from subnet: $vnet/$subnet" - retry_command "az network vnet subnet update -g $RESOURCE_GROUP_NAME --vnet-name $vnet -n $subnet --remove natGateway" || true - done - done - - # Remove NSG associations from subnets - echo "Removing NSG associations..." - for vnet in $(az network vnet list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do - for subnet in $(az network vnet subnet list -g $RESOURCE_GROUP_NAME --vnet-name $vnet --query "[?networkSecurityGroup].name" -o tsv 2>/dev/null || true); do - echo "Removing NSG from subnet: $vnet/$subnet" - retry_command "az network vnet subnet update -g $RESOURCE_GROUP_NAME --vnet-name $vnet -n $subnet --remove networkSecurityGroup" || true - done - done - - # Delete NAT Gateways - echo "Deleting NAT Gateways..." - for natgw in $(az network nat gateway list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do - echo "Deleting NAT Gateway: $natgw" - retry_command "az network nat gateway delete -g $RESOURCE_GROUP_NAME -n $natgw" || true - done - - # Delete NSGs - echo "Deleting Network Security Groups..." - for nsg in $(az network nsg list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do - echo "Deleting NSG: $nsg" - retry_command "az network nsg delete -g $RESOURCE_GROUP_NAME -n $nsg" || true - done - - # Delete Public IPs - echo "Deleting Public IP addresses..." - for pip in $(az network public-ip list -g $RESOURCE_GROUP_NAME --query "[].name" -o tsv 2>/dev/null || true); do - echo "Deleting Public IP: $pip" - retry_command "az network public-ip delete -g $RESOURCE_GROUP_NAME -n $pip" || true - done - - echo "Pre-cleanup completed" + export RG="$RESOURCE_GROUP_NAME" + export DELETE_NODEPOOLS="true" + export DELETE_BUFFER_POOL="true" + + SCRIPT_PATH="$(Build.SourcesDirectory)/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh" + if [[ -f "$SCRIPT_PATH" ]]; then + chmod +x "$SCRIPT_PATH" + "$SCRIPT_PATH" || echo "Cleanup script completed with warnings" + else + echo "WARNING: Cleanup script not found at $SCRIPT_PATH" + fi + +- task: AzureCLI@2 displayName: "Force Cleanup Azure Resources" condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) continueOnError: true - -- script: | - set -eu - - # Signal handler - still try to complete cleanup even if cancelled again - trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT - - echo "Delete resource group $RESOURCE_GROUP_NAME" - # Use retry logic for resource group deletion as well - for attempt in $(seq 1 5); do - echo "Attempting to delete resource group: $attempt/5" - if az group delete --name $RESOURCE_GROUP_NAME --yes; then - echo "Resource group deleted successfully" - break + inputs: + azureSubscription: $(AZURE_SUBSCRIPTION) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -eu + + trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT + + export RG="$RESOURCE_GROUP_NAME" + + SCRIPT_PATH="$(Build.SourcesDirectory)/swiftv2kubeobjects/cleanup-azure-resources.sh" + if [[ -f "$SCRIPT_PATH" ]]; then + chmod +x "$SCRIPT_PATH" + "$SCRIPT_PATH" || echo "Cleanup script completed with warnings" else - echo "Resource group deletion failed on attempt $attempt" - if [ $attempt -lt 5 ]; then - echo "Waiting 120 seconds before retry..." - sleep 120 - fi + echo "WARNING: Cleanup script not found at $SCRIPT_PATH" fi - done + +- task: AzureCLI@2 displayName: "Destroy Resource Group" condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) continueOnError: true + inputs: + azureSubscription: $(AZURE_SUBSCRIPTION) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set -eu + + trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT + + echo "Delete resource group $RESOURCE_GROUP_NAME" + for attempt in $(seq 1 5); do + echo "Attempting to delete resource group: $attempt/5" + if az group delete --name $RESOURCE_GROUP_NAME --yes; then + echo "Resource group deleted successfully" + break + else + echo "Resource group deletion failed on attempt $attempt" + if [ $attempt -lt 5 ]; then + echo "Waiting 120 seconds before retry..." + sleep 120 + fi + fi + done diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index fe67b4053b..7dd5b3891b 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh @@ -3,6 +3,12 @@ # AKS Utilities Library # Contains common functions for AKS cluster management, logging, and nodepool operations +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/../../../.." && pwd)" + +# Source common library for cancellation handling and shared functions +source "${REPO_ROOT}/swiftv2kubeobjects/lib/common.sh" + # ============================================================================= # LOGGING FUNCTIONS # ============================================================================= diff --git a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh index 57744c0304..4e1ec9cb10 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh @@ -14,6 +14,9 @@ set -euo pipefail SCRIPT_DIR="$(dirname "${BASH_SOURCE[0]}")" source "$SCRIPT_DIR/aks-utils.sh" +# Set up signal traps for cancellation (uses handle_cancellation from common.sh) +trap handle_cancellation SIGTERM SIGINT + # Track whether kubeconfig has been initialized for this run KUBECONFIG_INITIALIZED=false @@ -127,6 +130,11 @@ function scale_nodepool() { local scale_success=false while [ $scale_attempt -lt $max_scale_retries ] && [ "$scale_success" = false ]; do + if ! check_cancellation; then + log_warning "Pipeline cancelled during scale operation for nodepool '$nodepool'" + return 1 + fi + scale_attempt=$((scale_attempt + 1)) if [ $scale_attempt -gt 1 ]; then @@ -380,6 +388,11 @@ function repair_failed_vms() { # Delete each failed instance with retry logic local deleted_instances="" for instance_id in $all_failed_instances; do + if ! check_cancellation; then + log_warning "Pipeline cancelled during VM repair" + return 1 + fi + if [ -n "$instance_id" ]; then local retry_count=0 local delete_success=false @@ -536,6 +549,11 @@ function repair_unjoined_vms() { local deleted_instances="" for instance_id in $missing_ids; do + if ! check_cancellation; then + log_warning "Pipeline cancelled during unjoined VM repair" + return 1 + fi + local retry_count=0 local delete_success=false @@ -589,6 +607,11 @@ function wait_for_vmss_replacement() { log_info "Waiting for $expected_replacements replacement VM instances to be provisioned..." while [ $elapsed -lt $max_wait_time ]; do + if ! check_cancellation; then + log_warning "Pipeline cancelled while waiting for VMSS replacement" + return 1 + fi + # Check current instance count and their states local instance_info instance_info=$(az vmss list-instances \ @@ -750,6 +773,11 @@ function verify_node_readiness() { # Poll for node readiness while [ $elapsed -lt $node_readiness_timeout ]; do + if ! check_cancellation; then + log_warning "Pipeline cancelled while verifying node readiness for '$nodepool'" + return 1 + fi + local nodes_json if ! nodes_json=$(kubectl_get_nodes_json "agentpool=$nodepool"); then log_warning "kubectl unavailable while verifying readiness for '$nodepool'; retrying..." >&2 @@ -992,6 +1020,11 @@ function scale_user_nodepools() { local scale_failures=0 for nodepool in $usernodepools; do + if ! check_cancellation; then + log_warning "Pipeline cancelled before processing nodepool '$nodepool'" + return 1 + fi + local pool_target=${TARGETS[$nodepool]} local current_nodes=${CURRENT_COUNTS[$nodepool]} @@ -1076,6 +1109,11 @@ function handle_shortfall_with_vm_repair() { # Step 1: Repair failed VMs in all nodepools for nodepool in $usernodepools; do + if ! check_cancellation; then + log_warning "Pipeline cancelled before VM repair for nodepool '$nodepool'" + return 1 + fi + log_info "--- VM repair for nodepool: '$nodepool' ---" log_info "Checking VM status for nodepool '$nodepool'..." @@ -1107,10 +1145,19 @@ function handle_shortfall_with_vm_repair() { local retry_interval=120 for attempt in $(seq 1 $max_retries); do + if ! check_cancellation; then + log_warning "Pipeline cancelled during node verification" + return 1 + fi + log_info "Verification attempt $attempt/$max_retries (timeout: $((retry_timeout / 60)) minutes)..." local elapsed=0 while [ $elapsed -lt $retry_timeout ]; do + if ! check_cancellation; then + log_warning "Pipeline cancelled while waiting for nodes" + return 1 + fi local ready_nodes ready_nodes=$(get_total_ready_nodes "$aks_name" "$aks_rg") diff --git a/swiftv2kubeobjects/cleanup-azure-resources.sh b/swiftv2kubeobjects/cleanup-azure-resources.sh new file mode 100755 index 0000000000..2564da4bab --- /dev/null +++ b/swiftv2kubeobjects/cleanup-azure-resources.sh @@ -0,0 +1,122 @@ +#!/bin/bash +set -euo pipefail + +# ============================================================================= +# Cleanup script for Azure resources before resource group deletion +# This script: +# 1. Deletes AKS clusters and waits for completion +# 2. Removes NAT Gateway and NSG associations from subnets +# 3. Deletes NAT Gateways, NSGs, and Public IPs +# +# Environment variables: +# RG or RESOURCE_GROUP_NAME - Resource group name (required) +# ============================================================================= + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Source common library +source "${SCRIPT_DIR}/lib/common.sh" + +# Configuration +RG="${RG:-${RESOURCE_GROUP_NAME:-}}" + +# Validate required inputs +if [[ -z "$RG" ]]; then + echo "ERROR: RG or RESOURCE_GROUP_NAME environment variable is required" + exit 1 +fi + +# Set up cancellation trap (continue cleanup even if cancelled) +trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT + +# ============================================================================= +# MAIN CLEANUP +# ============================================================================= + +echo "===================================================================" +echo "Force cleanup Azure resources in $RG before resource group deletion" +echo "===================================================================" + +# ============================================================================= +# STEP 1: DELETE AKS CLUSTERS +# ============================================================================= +echo "" +echo "Deleting AKS clusters..." +echo "Listing clusters in resource group: $RG" +cluster_list=$(az aks list -g "$RG" --query "[].name" -o tsv 2>&1) || true +echo "Cluster list result: '$cluster_list'" + +if [[ -z "$cluster_list" ]]; then + echo "WARNING: No AKS clusters found in resource group $RG" +else + for cluster in $cluster_list; do + echo "Deleting AKS cluster: $cluster (this may take several minutes for large clusters)" + retry_command 5 30 "az aks delete -g $RG -n $cluster --yes --no-wait" || true + + # Wait for cluster deletion to complete + wait_for_cluster_deletion "$cluster" "$RG" 3600 || true + done +fi + +# Brief wait for managed resource group cleanup to propagate +echo "Waiting 60 seconds for managed resource group cleanup to propagate..." +sleep 60 + +# ============================================================================= +# STEP 2: REMOVE NAT GATEWAY ASSOCIATIONS +# ============================================================================= +echo "" +echo "Removing NAT Gateway associations..." +for vnet in $(az network vnet list -g "$RG" --query "[].name" -o tsv 2>/dev/null || true); do + for subnet in $(az network vnet subnet list -g "$RG" --vnet-name "$vnet" --query "[?natGateway].name" -o tsv 2>/dev/null || true); do + echo "Removing NAT Gateway from subnet: $vnet/$subnet" + retry_command 5 30 "az network vnet subnet update -g $RG --vnet-name $vnet -n $subnet --remove natGateway" || true + done +done + +# ============================================================================= +# STEP 3: REMOVE NSG ASSOCIATIONS +# ============================================================================= +echo "" +echo "Removing NSG associations..." +for vnet in $(az network vnet list -g "$RG" --query "[].name" -o tsv 2>/dev/null || true); do + for subnet in $(az network vnet subnet list -g "$RG" --vnet-name "$vnet" --query "[?networkSecurityGroup].name" -o tsv 2>/dev/null || true); do + echo "Removing NSG from subnet: $vnet/$subnet" + retry_command 5 30 "az network vnet subnet update -g $RG --vnet-name $vnet -n $subnet --remove networkSecurityGroup" || true + done +done + +# ============================================================================= +# STEP 4: DELETE NAT GATEWAYS +# ============================================================================= +echo "" +echo "Deleting NAT Gateways..." +for natgw in $(az network nat gateway list -g "$RG" --query "[].name" -o tsv 2>/dev/null || true); do + echo "Deleting NAT Gateway: $natgw" + retry_command 5 30 "az network nat gateway delete -g $RG -n $natgw" || true +done + +# ============================================================================= +# STEP 5: DELETE NSGs +# ============================================================================= +echo "" +echo "Deleting Network Security Groups..." +for nsg in $(az network nsg list -g "$RG" --query "[].name" -o tsv 2>/dev/null || true); do + echo "Deleting NSG: $nsg" + retry_command 5 30 "az network nsg delete -g $RG -n $nsg" || true +done + +# ============================================================================= +# STEP 6: DELETE PUBLIC IPs +# ============================================================================= +echo "" +echo "Deleting Public IP addresses..." +for pip in $(az network public-ip list -g "$RG" --query "[].name" -o tsv 2>/dev/null || true); do + echo "Deleting Public IP: $pip" + retry_command 5 30 "az network public-ip delete -g $RG -n $pip" || true +done + +echo "" +echo "===================================================================" +echo "Pre-cleanup completed" +echo "===================================================================" diff --git a/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh new file mode 100755 index 0000000000..ddf9135b7e --- /dev/null +++ b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh @@ -0,0 +1,216 @@ +#!/bin/bash +set -euo pipefail + +# ============================================================================= +# Cleanup script for swiftv2 workloads and nodepools +# This script: +# 1. Finds AKS cluster in the resource group (if not provided) +# 2. Deletes all deployments/pods created by swiftv2_deployment_*_scale_config.yaml +# 3. Deletes user nodepools one at a time +# +# Environment variables: +# RG or RESOURCE_GROUP_NAME - Resource group name (required) +# CLUSTER - AKS cluster name (optional, auto-discovered) +# DELETE_NODEPOOLS - Whether to delete nodepools (default: true) +# DELETE_BUFFER_POOL - Whether to delete buffer pool (default: true) +# GROUP_NAME - Pod group label to match (default: deployment-churn) +# ============================================================================= + +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +REPO_ROOT="$(cd "${SCRIPT_DIR}/.." && pwd)" + +# Source common library +source "${SCRIPT_DIR}/lib/common.sh" + +# Source shared config if available +if [[ -f "${SCRIPT_DIR}/shared-config.sh" ]]; then + source "${SCRIPT_DIR}/shared-config.sh" +fi + +# Configuration with defaults +RG="${RG:-${RESOURCE_GROUP_NAME:-}}" +GROUP_NAME=${GROUP_NAME:-deployment-churn} +DELETE_NODEPOOLS=${DELETE_NODEPOOLS:-true} +DELETE_BUFFER_POOL=${DELETE_BUFFER_POOL:-true} + +# Validate required inputs +if [[ -z "$RG" ]]; then + echo "ERROR: RG or RESOURCE_GROUP_NAME environment variable is required" + exit 1 +fi + +# Set up cancellation trap +trap handle_cancellation SIGTERM SIGINT + +# ============================================================================= +# CLUSTER DISCOVERY +# ============================================================================= + +echo "===================================================================" +echo "Swiftv2 Workload Cleanup" +echo "Resource Group: $RG" +echo "===================================================================" + +# Discover cluster if not provided +if [[ -z "${CLUSTER:-}" ]]; then + echo "Discovering AKS cluster in resource group $RG..." + CLUSTER=$(az aks list -g "$RG" --query "[0].name" -o tsv 2>/dev/null || true) + + if [[ -z "$CLUSTER" ]]; then + echo "No AKS cluster found in resource group $RG. Nothing to clean up." + exit 0 + fi +fi + +echo "Found AKS cluster: $CLUSTER" +echo "===================================================================" + +# Get credentials for kubectl +echo "Getting AKS credentials..." +az aks get-credentials -n "$CLUSTER" -g "$RG" --admin --overwrite-existing + +# ============================================================================= +# STEP 1: DELETE DEPLOYMENTS AND PODS +# ============================================================================= +echo "" +echo "===================================================================" +echo "Step 1: Deleting deployments created by swiftv2 configs" +echo "===================================================================" + +# Delete deployments with the deployment-churn group label pattern +# These are created by both static and dynamic configs with pattern: +# group={{$groupName}}-job{{$jobIndex}}-{{$j}} +echo "Deleting deployments with label selector: podgroup=$GROUP_NAME" + +# Get all namespaces matching slo prefix +for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo" | cut -d/ -f2 || true); do + if ! check_cancellation; then + exit 143 + fi + + echo "Processing namespace: $ns" + + # Delete deployments matching the pattern (deployment-churn-job*) + deployments=$(kubectl get deployments -n "$ns" -l "podgroup=$GROUP_NAME" -o name 2>/dev/null || true) + if [[ -n "$deployments" ]]; then + echo "Deleting deployments in namespace $ns:" + echo "$deployments" + kubectl delete deployments -n "$ns" -l "podgroup=$GROUP_NAME" --wait=false || true + fi + + # Also delete any remaining pods with the podgroup label + pods=$(kubectl get pods -n "$ns" -l "podgroup=$GROUP_NAME" -o name 2>/dev/null || true) + if [[ -n "$pods" ]]; then + echo "Deleting remaining pods in namespace $ns with label podgroup=$GROUP_NAME" + kubectl delete pods -n "$ns" -l "podgroup=$GROUP_NAME" --grace-period=0 --force 2>/dev/null || true + fi +done + +# Wait for deployments to be deleted +echo "Waiting for deployments to be fully deleted..." +sleep 30 + +for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo" | cut -d/ -f2 || true); do + remaining=$(kubectl get deployments -n "$ns" -l "podgroup=$GROUP_NAME" --no-headers 2>/dev/null | wc -l || echo "0") + if [[ "$remaining" -gt 0 ]]; then + echo "Waiting for $remaining deployments to terminate in namespace $ns..." + kubectl wait --for=delete deployment -n "$ns" -l "podgroup=$GROUP_NAME" --timeout=300s 2>/dev/null || true + fi +done + +# ============================================================================= +# STEP 2: DELETE USER NODEPOOLS ONE AT A TIME +# ============================================================================= +if [[ "$DELETE_NODEPOOLS" == "true" ]]; then + echo "" + echo "===================================================================" + echo "Step 2: Deleting user nodepools one at a time" + echo "===================================================================" + + # Get list of user nodepools (userpool1, userpool2, etc. and userpoolBuffer) + existing_pools=$(az aks nodepool list --cluster-name "$CLUSTER" --resource-group "$RG" --query '[].name' -o tsv 2>/dev/null || true) + + # Separate user pools and buffer pool + user_pools="" + buffer_pool="" + + for pool in $existing_pools; do + if [[ "$pool" == "userpoolBuffer" ]]; then + buffer_pool="$pool" + elif [[ "$pool" =~ ^userpool[0-9]+$ ]]; then + user_pools="$user_pools $pool" + fi + done + + # Delete regular user pools first (in reverse order for cleaner shutdown) + user_pools_sorted=$(echo "$user_pools" | tr ' ' '\n' | grep -v '^$' | sort -t'l' -k2 -rn || true) + + for pool_name in $user_pools_sorted; do + if ! check_cancellation; then + echo "ERROR: Pipeline cancelled before deleting nodepool $pool_name" + exit 143 + fi + + echo "" + echo "Deleting nodepool: $pool_name" + + # Start deletion + if az aks nodepool delete --cluster-name "$CLUSTER" --name "$pool_name" -g "$RG" --no-wait 2>/dev/null; then + echo "Deletion initiated for nodepool $pool_name" + + # Wait for this nodepool to be deleted before moving to next + if ! wait_for_nodepool_deletion "$CLUSTER" "$pool_name" "$RG" 900; then + echo "WARNING: Nodepool $pool_name deletion did not complete within timeout, continuing..." + fi + else + echo "WARNING: Failed to initiate deletion for nodepool $pool_name" + fi + done + + # Delete buffer pool last if requested + if [[ "$DELETE_BUFFER_POOL" == "true" && -n "$buffer_pool" ]]; then + if ! check_cancellation; then + echo "ERROR: Pipeline cancelled before deleting buffer nodepool" + exit 143 + fi + + echo "" + echo "Deleting buffer nodepool: $buffer_pool" + + if az aks nodepool delete --cluster-name "$CLUSTER" --name "$buffer_pool" -g "$RG" --no-wait 2>/dev/null; then + echo "Deletion initiated for buffer nodepool $buffer_pool" + + if ! wait_for_nodepool_deletion "$CLUSTER" "$buffer_pool" "$RG" 900; then + echo "WARNING: Buffer nodepool deletion did not complete within timeout" + fi + else + echo "WARNING: Failed to initiate deletion for buffer nodepool $buffer_pool" + fi + fi +else + echo "" + echo "Skipping nodepool deletion (DELETE_NODEPOOLS != true)" +fi + +# ============================================================================= +# SUMMARY +# ============================================================================= +echo "" +echo "===================================================================" +echo "Cleanup completed!" +echo "===================================================================" + +# Show remaining resources +echo "" +echo "Remaining nodepools:" +az aks nodepool list --cluster-name "$CLUSTER" --resource-group "$RG" --query '[].{Name:name, Count:count, VMSize:vmSize}' -o table 2>/dev/null || echo "Unable to list nodepools" + +echo "" +echo "Remaining pods in slo namespaces:" +for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo" | cut -d/ -f2 || true); do + count=$(kubectl get pods -n "$ns" --no-headers 2>/dev/null | wc -l || echo "0") + echo " $ns: $count pods" +done + +echo "" +echo "Done!" diff --git a/swiftv2kubeobjects/createclusterforping.sh b/swiftv2kubeobjects/createclusterforping.sh index 3f1ff64e6d..a117ba7376 100755 --- a/swiftv2kubeobjects/createclusterforping.sh +++ b/swiftv2kubeobjects/createclusterforping.sh @@ -1,47 +1,18 @@ -# #!/bin/bash +#!/bin/bash set -ex # ============================================================================= -# CANCELLATION HANDLING +# COMMON LIBRARY # ============================================================================= +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" -# Global flag for cancellation detection -CANCELLED=false - -# Signal handler for graceful shutdown -handle_cancellation() { - echo "WARNING: Received cancellation signal (SIGTERM/SIGINT)" - CANCELLED=true - - # Give processes a moment to clean up - sleep 2 - - echo "ERROR: Pipeline cancellation detected. Exiting gracefully..." - echo "Note: Any partially created resources will be cleaned up by the cleanup phase" - exit 143 # Standard exit code for SIGTERM -} +# Source common library for cancellation handling and shared functions +source "${SCRIPT_DIR}/lib/common.sh" # Set up signal traps for cancellation trap handle_cancellation SIGTERM SIGINT -# Check if pipeline has been cancelled -check_cancellation() { - if [ "$CANCELLED" = true ]; then - echo "WARNING: Cancellation detected, stopping current operation..." - return 1 - fi - - # Check for Azure DevOps cancellation marker file (if exists) - if [ -f "/tmp/pipeline_cancelled" ]; then - echo "WARNING: Pipeline cancellation marker detected" - CANCELLED=true - return 1 - fi - - return 0 -} - # Use RESOURCE_GROUP_NAME pipeline variable (set by provision-resources.yml) if [ -z "${RESOURCE_GROUP_NAME:-}" ]; then echo "ERROR: RESOURCE_GROUP_NAME not set. This should be set by provision-resources.yml" diff --git a/swiftv2kubeobjects/lib/common.sh b/swiftv2kubeobjects/lib/common.sh new file mode 100644 index 0000000000..a7aa074c68 --- /dev/null +++ b/swiftv2kubeobjects/lib/common.sh @@ -0,0 +1,161 @@ +#!/bin/bash +# ============================================================================= +# Common library functions for swiftv2 scripts +# Source this file in your scripts: source "$(dirname "$0")/lib/common.sh" +# ============================================================================= + +# ============================================================================= +# CANCELLATION HANDLING +# ============================================================================= +CANCELLED=false + +handle_cancellation() { + echo "WARNING: Received cancellation signal (SIGTERM/SIGINT)" + CANCELLED=true + sleep 2 + echo "ERROR: Script cancelled. Some resources may remain." + exit 143 +} + +check_cancellation() { + if [ "$CANCELLED" = true ]; then + echo "WARNING: Cancellation detected, stopping current operation..." + return 1 + fi + if [ -f "/tmp/pipeline_cancelled" ]; then + echo "WARNING: Pipeline cancellation marker detected" + CANCELLED=true + return 1 + fi + return 0 +} + +# ============================================================================= +# RETRY LOGIC +# ============================================================================= + +# Retry a command with exponential backoff +# Usage: retry_command [max_attempts] [initial_delay] command... +# Example: retry_command 5 30 az aks delete -g $RG -n $cluster --yes +retry_command() { + local max_attempts=${1:-5} + local delay=${2:-30} + shift 2 + local command="$@" + local attempt=1 + + while [ $attempt -le $max_attempts ]; do + echo "Attempt $attempt/$max_attempts: $command" + if eval "$command"; then + echo "Command succeeded on attempt $attempt" + return 0 + else + echo "Command failed on attempt $attempt" + if [ $attempt -lt $max_attempts ]; then + echo "Waiting $delay seconds before retry..." + sleep $delay + delay=$((delay * 2)) # Exponential backoff + fi + attempt=$((attempt + 1)) + fi + done + + echo "Command failed after $max_attempts attempts: $command" + return 1 +} + +# ============================================================================= +# NODEPOOL HELPERS +# ============================================================================= + +# Wait for a nodepool to be deleted +# Usage: wait_for_nodepool_deletion cluster pool_name rg [timeout] +wait_for_nodepool_deletion() { + local cluster=$1 + local pool_name=$2 + local rg=$3 + local timeout=${4:-600} + local interval=15 + local elapsed=0 + + echo "Waiting for nodepool $pool_name to be deleted..." + while [ $elapsed -lt $timeout ]; do + if ! check_cancellation; then + return 1 + fi + + if ! az aks nodepool show --cluster-name "$cluster" --name "$pool_name" -g "$rg" &>/dev/null; then + echo "Nodepool $pool_name has been deleted" + return 0 + fi + + echo "Nodepool $pool_name still deleting... (elapsed: ${elapsed}s)" + sleep $interval + elapsed=$((elapsed + interval)) + done + + echo "ERROR: Timeout waiting for nodepool $pool_name deletion" + return 1 +} + +# Wait for a nodepool to reach a specific provisioning state +# Usage: wait_for_nodepool_state cluster pool_name rg target_state [timeout] +wait_for_nodepool_state() { + local cluster=$1 + local pool_name=$2 + local rg=$3 + local target_state=$4 + local timeout=${5:-600} + local interval=15 + local elapsed=0 + + echo "Waiting for nodepool $pool_name to reach state: $target_state..." + while [ $elapsed -lt $timeout ]; do + if ! check_cancellation; then + return 1 + fi + + local state + state=$(az aks nodepool show --cluster-name "$cluster" --name "$pool_name" -g "$rg" --query "provisioningState" -o tsv 2>/dev/null || echo "Unknown") + + if [[ "$state" == "$target_state" ]]; then + echo "Nodepool $pool_name reached state: $target_state" + return 0 + fi + + echo "Nodepool $pool_name state: $state (waiting for $target_state, elapsed: ${elapsed}s)" + sleep $interval + elapsed=$((elapsed + interval)) + done + + echo "ERROR: Timeout waiting for nodepool $pool_name to reach state $target_state" + return 1 +} + +# ============================================================================= +# CLUSTER HELPERS +# ============================================================================= + +# Wait for AKS cluster deletion +# Usage: wait_for_cluster_deletion cluster rg [timeout] +wait_for_cluster_deletion() { + local cluster=$1 + local rg=$2 + local timeout=${3:-3600} + local interval=30 + local elapsed=0 + + echo "Waiting for cluster $cluster deletion to complete..." + while [ $elapsed -lt $timeout ]; do + if ! az aks show -g "$rg" -n "$cluster" &>/dev/null; then + echo "Cluster $cluster has been deleted" + return 0 + fi + echo " Cluster $cluster still deleting... (elapsed: ${elapsed}s, ~$((elapsed/60)) minutes)" + sleep $interval + elapsed=$((elapsed + interval)) + done + + echo "ERROR: Timeout waiting for cluster $cluster deletion" + return 1 +} diff --git a/swiftv2kubeobjects/lib/nodepool.sh b/swiftv2kubeobjects/lib/nodepool.sh index eb7f6f9f3d..ad085f0d58 100755 --- a/swiftv2kubeobjects/lib/nodepool.sh +++ b/swiftv2kubeobjects/lib/nodepool.sh @@ -1,12 +1,12 @@ #!/bin/bash # Nodepool helper library -# Depends on Azure CLI, jq, and optional check_cancellation function +# Depends on Azure CLI, jq, and common.sh for cancellation handling -# Provide a no-op cancellation check if caller did not define one -if ! declare -f check_cancellation >/dev/null 2>&1; then - check_cancellation() { return 0; } -fi +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" + +# Source common library for check_cancellation and other shared functions +source "${SCRIPT_DIR}/common.sh" # Check if nodepool exists nodepool_exists() { From 83017353ef476b4e6ff5fb7040c7cebb0348c8d3 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 05:14:22 +0000 Subject: [PATCH 28/47] fix(cl2): add jobIndex to namespace prefix for cluster reuse Support reusing the same AKS cluster across multiple matrix jobs within a pipeline stage by making namespace prefixes unique per job. Problem: When reusing clusters, CL2 fails with 'pre-existing automanaged namespaces found' because all jobs use the same 'slo' namespace prefix. Solution: - Change namespace prefix from 'slo' to 'slo-job{{jobIndex}}' - Namespaces are now: slo-job0-1, slo-job1-1, slo-job2-1, etc. Updated files: - swiftv2_deployment_staticres_scale_config.yaml: prefix with jobIndex - swiftv2_deployment_dynamicres_scale_config.yaml: prefix with jobIndex - pni_readiness_checker_unified_template.yaml: use {{.Namespace}} instead of hardcoded slo-1 - cleanup-swiftv2-workloads.sh: match slo-job* namespace pattern - datapath-observer deployment.yaml: remove --namespace flag, rely on label selector to watch pods across all namespaces - collect-datapath-observer.yml: use labelSelector instead of namespace - README.md: document multi-job namespace behavior --- .../config/pni_readiness_checker_unified_template.yaml | 2 +- .../swiftv2_deployment_dynamicres_scale_config.yaml | 2 +- .../swiftv2_deployment_staticres_scale_config.yaml | 2 +- steps/topology/swiftv2/collect-datapath-observer.yml | 8 ++++---- swiftv2kubeobjects/cleanup-swiftv2-workloads.sh | 10 +++++----- .../datapath-observer/controller/README.md | 4 +++- .../controller/manifests/deployment.yaml | 1 - 7 files changed, 15 insertions(+), 14 deletions(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/pni_readiness_checker_unified_template.yaml b/modules/python/clusterloader2/swiftv2-slo/config/pni_readiness_checker_unified_template.yaml index d5898d5334..5475ede789 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/pni_readiness_checker_unified_template.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/pni_readiness_checker_unified_template.yaml @@ -25,7 +25,7 @@ spec: while [ $ELAPSED -lt $TIMEOUT ]; do # Get all PNIs in namespace and count Ready ones matching our pattern - ALL_PNIS=$(kubectl get podnetworkinstance -n slo-1 -o custom-columns=NAME:.metadata.name,STATUS:.status.status --no-headers 2>/dev/null || echo "") + ALL_PNIS=$(kubectl get podnetworkinstance -n {{.Namespace}} -o custom-columns=NAME:.metadata.name,STATUS:.status.status --no-headers 2>/dev/null || echo "") if [ -n "$ALL_PNIS" ]; then READY_COUNT=$(echo "$ALL_PNIS" | grep "^${PNI_PREFIX}" | grep -c "Ready" || echo "0") diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml index 81b37259c8..eea2890f7a 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml @@ -19,7 +19,7 @@ name: deployment-churn namespace: number: 1 - prefix: slo + prefix: slo-job{{$jobIndex}} deleteStaleNamespaces: false deleteAutomanagedNamespaces: false enableExistingNamespaces: false diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index 71f85b5df9..12dc930d03 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -21,7 +21,7 @@ name: deployment-churn namespace: number: 1 - prefix: slo + prefix: slo-job{{$jobIndex}} deleteStaleNamespaces: false deleteAutomanagedNamespaces: false enableExistingNamespaces: false diff --git a/steps/topology/swiftv2/collect-datapath-observer.yml b/steps/topology/swiftv2/collect-datapath-observer.yml index ee7608218b..00ba42f0c8 100644 --- a/steps/topology/swiftv2/collect-datapath-observer.yml +++ b/steps/topology/swiftv2/collect-datapath-observer.yml @@ -37,25 +37,25 @@ steps: # Test connectivity echo "Testing API connectivity..." - curl -v "http://localhost:8082/api/v1/time-to-start?topN=1&namespace=slo-1" || true + curl -v "http://localhost:8082/api/v1/time-to-start?topN=1&labelSelector=podgroup=deployment-churn" || true # Query time-to-start metrics echo "Querying time-to-start metrics..." - time_to_start_response=$(curl -s "http://localhost:8082/api/v1/time-to-start?topN=10&namespace=slo-1") + time_to_start_response=$(curl -s "http://localhost:8082/api/v1/time-to-start?topN=10&labelSelector=podgroup=deployment-churn") echo "API Response (time-to-start):" echo "$time_to_start_response" echo "$time_to_start_response" > "${OUTPUT_DIR}/datapath-time-to-start.json" # Query time-to-datapath-ready metrics echo "Querying time-to-datapath-ready metrics..." - time_to_dp_ready_response=$(curl -s "http://localhost:8082/api/v1/time-to-datapath-ready?topN=10&namespace=slo-1") + time_to_dp_ready_response=$(curl -s "http://localhost:8082/api/v1/time-to-datapath-ready?topN=10&labelSelector=podgroup=deployment-churn") echo "API Response (time-to-datapath-ready):" echo "$time_to_dp_ready_response" echo "$time_to_dp_ready_response" > "${OUTPUT_DIR}/datapath-time-to-dp-ready.json" # Query pod-health metrics echo "Querying pod-health metrics..." - pod_health_response=$(curl -s "http://localhost:8082/api/v1/pod-health?topN=10&namespace=slo-1") + pod_health_response=$(curl -s "http://localhost:8082/api/v1/pod-health?topN=10&labelSelector=podgroup=deployment-churn") echo "API Response (pod-health):" echo "$pod_health_response" echo "$pod_health_response" > "${OUTPUT_DIR}/datapath-pod-health.json" diff --git a/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh index ddf9135b7e..d0c5ee86fe 100755 --- a/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh +++ b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh @@ -82,8 +82,8 @@ echo "===================================================================" # group={{$groupName}}-job{{$jobIndex}}-{{$j}} echo "Deleting deployments with label selector: podgroup=$GROUP_NAME" -# Get all namespaces matching slo prefix -for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo" | cut -d/ -f2 || true); do +# Get all namespaces matching slo-job prefix (slo-job0-1, slo-job1-1, etc.) +for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo-job" | cut -d/ -f2 || true); do if ! check_cancellation; then exit 143 fi @@ -110,7 +110,7 @@ done echo "Waiting for deployments to be fully deleted..." sleep 30 -for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo" | cut -d/ -f2 || true); do +for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo-job" | cut -d/ -f2 || true); do remaining=$(kubectl get deployments -n "$ns" -l "podgroup=$GROUP_NAME" --no-headers 2>/dev/null | wc -l || echo "0") if [[ "$remaining" -gt 0 ]]; then echo "Waiting for $remaining deployments to terminate in namespace $ns..." @@ -206,8 +206,8 @@ echo "Remaining nodepools:" az aks nodepool list --cluster-name "$CLUSTER" --resource-group "$RG" --query '[].{Name:name, Count:count, VMSize:vmSize}' -o table 2>/dev/null || echo "Unable to list nodepools" echo "" -echo "Remaining pods in slo namespaces:" -for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo" | cut -d/ -f2 || true); do +echo "Remaining pods in slo-job namespaces:" +for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo-job" | cut -d/ -f2 || true); do count=$(kubectl get pods -n "$ns" --no-headers 2>/dev/null | wc -l || echo "0") echo " $ns: $count pods" done diff --git a/swiftv2kubeobjects/datapath-observer/controller/README.md b/swiftv2kubeobjects/datapath-observer/controller/README.md index 1b19276bc6..8e1a0e7bc6 100644 --- a/swiftv2kubeobjects/datapath-observer/controller/README.md +++ b/swiftv2kubeobjects/datapath-observer/controller/README.md @@ -78,10 +78,12 @@ Returns: Environment variables: -- `NAMESPACE` - Namespace to watch for pods (default: all namespaces) +- `NAMESPACE` - Namespace to watch for pods (default: all namespaces if not specified) - `LABEL_SELECTOR` - Label selector for pods to track (default: empty, tracks all) - `HTTP_PORT` - Port for HTTP API server (default: 8080) +**Note:** When running in a multi-job environment where namespaces are dynamically created (e.g., `slo-job0-1`, `slo-job1-1`), omit the `--namespace` flag and rely on `--label-selector` to track pods across all namespaces. + ## Building the Image Build with [Dockerfile](Dockerfile) using date-based versioning: diff --git a/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml b/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml index fab6ec96a7..7377a0e6b3 100644 --- a/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml +++ b/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml @@ -20,7 +20,6 @@ spec: - name: controller image: acndev.azurecr.io/datapath-controller:2026.01.18.01 args: - - "--namespace=slo-1" - "--label-selector=podgroup=deployment-churn" - "--max-concurrent-reconciles=100" ports: From 115edce577eeaa8bcc641b39966df1a65ad74c6f Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 05:16:12 +0000 Subject: [PATCH 29/47] fix(cleanup): use AZURE_SERVICE_CONNECTION instead of AZURE_SUBSCRIPTION The azureSubscription input for AzureCLI@2 tasks requires the service connection variable name, not the subscription ID variable. --- steps/cleanup-resources.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index a83a31b80f..cc9c850bc8 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -40,7 +40,7 @@ steps: condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) continueOnError: true inputs: - azureSubscription: $(AZURE_SUBSCRIPTION) + azureSubscription: $(AZURE_SERVICE_CONNECTION) scriptType: bash scriptLocation: inlineScript inlineScript: | @@ -65,7 +65,7 @@ steps: condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) continueOnError: true inputs: - azureSubscription: $(AZURE_SUBSCRIPTION) + azureSubscription: $(AZURE_SERVICE_CONNECTION) scriptType: bash scriptLocation: inlineScript inlineScript: | @@ -88,7 +88,7 @@ steps: condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) continueOnError: true inputs: - azureSubscription: $(AZURE_SUBSCRIPTION) + azureSubscription: $(AZURE_SERVICE_CONNECTION) scriptType: bash scriptLocation: inlineScript inlineScript: | From a68f631dd681e3330a46bfa8d64a4cea409e51fb Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 05:57:26 +0000 Subject: [PATCH 30/47] fix(datapath-observer): copy pod labels to metadata.labels for label selector filtering DatapathResult CRDs were storing pod labels only in spec.Labels, but Kubernetes label selectors only work with metadata.labels. This caused the labelSelector query parameter in the API to return empty results. - Copy pod labels to ObjectMeta.Labels in addition to Spec.Labels - Bump controller image to 2026.01.29.01 --- .../controller/controllers/pod_controller.go | 12 ++++++++++-- .../controller/manifests/deployment.yaml | 2 +- 2 files changed, 11 insertions(+), 3 deletions(-) diff --git a/swiftv2kubeobjects/datapath-observer/controller/controllers/pod_controller.go b/swiftv2kubeobjects/datapath-observer/controller/controllers/pod_controller.go index 106d1ddc79..c720e30bba 100644 --- a/swiftv2kubeobjects/datapath-observer/controller/controllers/pod_controller.go +++ b/swiftv2kubeobjects/datapath-observer/controller/controllers/pod_controller.go @@ -85,6 +85,14 @@ func (r *PodReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.R dpResult.Spec.Labels = pod.Labels } + // Copy pod labels to metadata.labels for label selector filtering + if dpResult.ObjectMeta.Labels == nil { + dpResult.ObjectMeta.Labels = make(map[string]string) + } + for k, v := range pod.Labels { + dpResult.ObjectMeta.Labels[k] = v + } + // Always update mutable fields dpResult.Spec.PodRef.NodeName = pod.Spec.NodeName @@ -108,7 +116,7 @@ func (r *PodReconciler) Reconcile(ctx context.Context, req ctrl.Request) (ctrl.R func updateMetrics(dpResult *perfv1.DatapathResult, createdAt time.Time, startTsStr, dpReadyTsStr string) { logger := log.Log.WithName("updateMetrics").WithValues("dpResult", dpResult.Name, "namespace", dpResult.Namespace) - + // Only update startTs if not already set (capture first occurrence from initContainer) if startTsStr != "" && dpResult.Spec.Timestamps.StartTs == "" { dpResult.Spec.Timestamps.StartTs = startTsStr @@ -120,7 +128,7 @@ func updateMetrics(dpResult *perfv1.DatapathResult, createdAt time.Time, startTs logger.V(1).Info("Calculated LatStartMs", "createdAt", createdAt.Format(time.RFC3339Nano), "startTs", startTs.Format(time.RFC3339Nano), "latMs", dpResult.Spec.Metrics.LatStartMs) } } - + // Only update dpReadyTs if not already set (capture first occurrence from initContainer) if dpReadyTsStr != "" && dpResult.Spec.Timestamps.DpReadyTs == "" { dpResult.Spec.Timestamps.DpReadyTs = dpReadyTsStr diff --git a/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml b/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml index 7377a0e6b3..e614720ee5 100644 --- a/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml +++ b/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml @@ -18,7 +18,7 @@ spec: serviceAccountName: datapath-controller containers: - name: controller - image: acndev.azurecr.io/datapath-controller:2026.01.18.01 + image: acndev.azurecr.io/datapath-controller:2026.01.29.01 args: - "--label-selector=podgroup=deployment-churn" - "--max-concurrent-reconciles=100" From 697ab4098825fe49ba3810a138dcc1d569c1fd7a Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 06:04:55 +0000 Subject: [PATCH 31/47] fix(cl2): make CL2_JOB_INDEX required and pass to CL2 config - Remove default value for CL2_JOB_INDEX in staticres and dynamicres configs - Add CL2_JOB_INDEX to override file in slo.py - Fixes namespace collision when running back-to-back tests on same cluster Previously CL2_JOB_INDEX defaulted to 0, causing pre-existing namespace errors when running parallel jobs. Now the pipeline must explicitly provide a unique job index. --- .../config/swiftv2_deployment_dynamicres_scale_config.yaml | 2 +- .../config/swiftv2_deployment_staticres_scale_config.yaml | 2 +- modules/python/clusterloader2/swiftv2-slo/slo.py | 5 +++++ 3 files changed, 7 insertions(+), 2 deletions(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml index eea2890f7a..7ec4e159c5 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml @@ -15,7 +15,7 @@ name: deployment-churn {{$probeTimeout := .CL2_PROBE_TIMEOUT}} {{$datapathReporterImage := .CL2_DATAPATH_REPORTER_IMAGE}} {{$nginxImage := .CL2_NGINX_IMAGE}} -{{$jobIndex := DefaultParam .CL2_JOB_INDEX 0}} +{{$jobIndex := .CL2_JOB_INDEX}} namespace: number: 1 diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index 12dc930d03..cfc989c23a 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -17,7 +17,7 @@ name: deployment-churn {{$probeTimeout := .CL2_PROBE_TIMEOUT}} {{$datapathReporterImage := .CL2_DATAPATH_REPORTER_IMAGE}} {{$nginxImage := .CL2_NGINX_IMAGE}} -{{$jobIndex := DefaultParam .CL2_JOB_INDEX 0}} +{{$jobIndex := .CL2_JOB_INDEX}} namespace: number: 1 diff --git a/modules/python/clusterloader2/swiftv2-slo/slo.py b/modules/python/clusterloader2/swiftv2-slo/slo.py index 756cad922b..214348aa60 100644 --- a/modules/python/clusterloader2/swiftv2-slo/slo.py +++ b/modules/python/clusterloader2/swiftv2-slo/slo.py @@ -98,6 +98,11 @@ def configure_clusterloader2( if probe_timeout: file.write(f"CL2_PROBE_TIMEOUT: {probe_timeout}\n") + # Pass job index for unique namespace naming across parallel runs + job_index = os.environ.get("CL2_JOB_INDEX") + if job_index: + file.write(f"CL2_JOB_INDEX: {job_index}\n") + if scrape_containerd: file.write(f"CL2_SCRAPE_CONTAINERD: {str(scrape_containerd).lower()}\n") file.write("CONTAINERD_SCRAPE_INTERVAL: 5m\n") From cef246ddf4fdf31b15ee626377a0e6e1b07ae9c0 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 06:14:20 +0000 Subject: [PATCH 32/47] fix(cleanup): require AZURE_SUBSCRIPTION_ID for cleanup scripts - Add AZURE_SUBSCRIPTION_ID validation to cleanup-swiftv2-workloads.sh - Add AZURE_SUBSCRIPTION_ID validation to cleanup-azure-resources.sh - Pass AZURE_SUBSCRIPTION_ID from cleanup-resources.yml to both scripts - Remove fallback defaults to ensure correct subscription is always used --- steps/cleanup-resources.yml | 2 ++ swiftv2kubeobjects/cleanup-azure-resources.sh | 9 +++++++++ swiftv2kubeobjects/cleanup-swiftv2-workloads.sh | 9 +++++++++ 3 files changed, 20 insertions(+) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index cc9c850bc8..6d31a1a55d 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -49,6 +49,7 @@ steps: trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT export RG="$RESOURCE_GROUP_NAME" + export AZURE_SUBSCRIPTION_ID="$(AZURE_SUBSCRIPTION_ID)" export DELETE_NODEPOOLS="true" export DELETE_BUFFER_POOL="true" @@ -74,6 +75,7 @@ steps: trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT export RG="$RESOURCE_GROUP_NAME" + export AZURE_SUBSCRIPTION_ID="$(AZURE_SUBSCRIPTION_ID)" SCRIPT_PATH="$(Build.SourcesDirectory)/swiftv2kubeobjects/cleanup-azure-resources.sh" if [[ -f "$SCRIPT_PATH" ]]; then diff --git a/swiftv2kubeobjects/cleanup-azure-resources.sh b/swiftv2kubeobjects/cleanup-azure-resources.sh index 2564da4bab..7983e6c6ba 100755 --- a/swiftv2kubeobjects/cleanup-azure-resources.sh +++ b/swiftv2kubeobjects/cleanup-azure-resources.sh @@ -26,6 +26,15 @@ if [[ -z "$RG" ]]; then exit 1 fi +if [[ -z "${AZURE_SUBSCRIPTION_ID:-}" ]]; then + echo "ERROR: AZURE_SUBSCRIPTION_ID environment variable is required" + exit 1 +fi + +# Set the Azure subscription +echo "Setting Azure subscription to: $AZURE_SUBSCRIPTION_ID" +az account set --subscription "$AZURE_SUBSCRIPTION_ID" + # Set up cancellation trap (continue cleanup even if cancelled) trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT diff --git a/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh index d0c5ee86fe..272cc0a390 100755 --- a/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh +++ b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh @@ -39,6 +39,15 @@ if [[ -z "$RG" ]]; then exit 1 fi +if [[ -z "${AZURE_SUBSCRIPTION_ID:-}" ]]; then + echo "ERROR: AZURE_SUBSCRIPTION_ID environment variable is required" + exit 1 +fi + +# Set the Azure subscription +echo "Setting Azure subscription to: $AZURE_SUBSCRIPTION_ID" +az account set --subscription "$AZURE_SUBSCRIPTION_ID" + # Set up cancellation trap trap handle_cancellation SIGTERM SIGINT From b5fb8b2a0f1153e8a1c7ad5be0841b12af25fe74 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 07:16:09 +0000 Subject: [PATCH 33/47] feat(swiftv2): add incremental pod deployment for cluster reuse - Add CL2_EXISTING_PODS parameter to calculate delta pods to deploy - Update CL2 config templates to compute actualPodsPerStep from delta - Update slo.py to pass existing_pods parameter through CLI - Update execute.yml to pass EXISTING_PODS env variable - Simplify matrix files to 500-2000 nodes in 500 increments (7 pods/node) This enables reusing clusters across test cases by only deploying the incremental difference in pods rather than the full target count. --- ...v2_deployment_dynamicres_scale_config.yaml | 7 ++- ...tv2_deployment_staticres_scale_config.yaml | 9 ++-- .../python/clusterloader2/swiftv2-slo/slo.py | 6 ++- .../swiftv2-dynamicres-burst-matrix.yml | 50 +++++++---------- .../swiftv2-dynamicres-gradual-matrix.yml | 34 ++++-------- .../swiftv2-staticres-burst-matrix.yml | 53 +++++++------------ .../swiftv2-staticres-gradual-matrix.yml | 37 ++++--------- .../clusterloader2/swiftv2-slo/execute.yml | 2 +- 8 files changed, 73 insertions(+), 125 deletions(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml index 7ec4e159c5..16e6c2e8fa 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml @@ -4,6 +4,9 @@ name: deployment-churn {{$podsPerStep := DefaultParam .CL2_PODS_PER_STEP 7}} {{$nodes := DefaultParam .CL2_NODES 1000}} {{$total_pods := DefaultParam .CL2_TOTAL_PODS 7000}} +{{$existingPods := DefaultParam .CL2_EXISTING_PODS 0}} +{{$deltaPods := SubtractInt $total_pods $existingPods}} +{{$actualPodsPerStep := MaxInt $deltaPods 0}} {{$steps := DefaultParam .CL2_STEPS 1}} {{$latencyPodCpu := DefaultParam .CL2_LATENCY_POD_CPU 10}} {{$latencyPodMemory := DefaultParam .CL2_LATENCY_POD_MEMORY 50}} @@ -47,7 +50,7 @@ steps: objectTemplatePath: reporter_role_template.yaml - basename: reporter-binding objectTemplatePath: reporter_rolebinding_template.yaml - - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total pods={{$total_pods}} + - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total_pods={{$total_pods}}, existing_pods={{$existingPods}}, delta_pods={{$deltaPods}}, actual_pods_per_step={{$actualPodsPerStep}} measurements: - Identifier: Dummy Method: Sleep @@ -128,7 +131,7 @@ steps: - basename: deployment-churn-job{{$jobIndex}}-{{$j}} objectTemplatePath: swiftv2_deployment_template.yaml templateFillMap: - Replicas: {{$podsPerStep}} + Replicas: {{$actualPodsPerStep}} PodGroup: {{$groupName}} Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} CpuRequest: {{$latencyPodCpu}}m diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index cfc989c23a..6ced4464d8 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -3,9 +3,12 @@ name: deployment-churn {{$podsPerNode := DefaultParam .CL2_PODS_PER_NODE 1}} {{$podsPerStep := DefaultParam .CL2_PODS_PER_STEP 7}} {{$podsPerPNI := .CL2_PODS_PER_PNI}} -{{$numPNIs := DivideInt $podsPerStep $podsPerPNI}} {{$nodes := DefaultParam .CL2_NODES 1000}} {{$total_pods := DefaultParam .CL2_TOTAL_PODS 7000}} +{{$existingPods := DefaultParam .CL2_EXISTING_PODS 0}} +{{$deltaPods := SubtractInt $total_pods $existingPods}} +{{$actualPodsPerStep := MaxInt $deltaPods 0}} +{{$numPNIs := DivideInt $actualPodsPerStep $podsPerPNI}} {{$steps := DefaultParam .CL2_STEPS 1}} {{$latencyPodCpu := DefaultParam .CL2_LATENCY_POD_CPU 10}} {{$latencyPodMemory := DefaultParam .CL2_LATENCY_POD_MEMORY 50}} @@ -49,7 +52,7 @@ steps: objectTemplatePath: reporter_role_template.yaml - basename: reporter-binding objectTemplatePath: reporter_rolebinding_template.yaml - - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total pods={{$total_pods}} + - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total_pods={{$total_pods}}, existing_pods={{$existingPods}}, delta_pods={{$deltaPods}}, actual_pods_per_step={{$actualPodsPerStep}} measurements: - Identifier: Dummy Method: Sleep @@ -126,7 +129,7 @@ steps: - namespaceRange: min: 1 max: 1 - replicasPerNamespace: {{$podsPerStep}} + replicasPerNamespace: {{$actualPodsPerStep}} tuningSet: DeploymentCreateQps objectBundle: - basename: deployment-churn-job{{$jobIndex}}-{{$j}} diff --git a/modules/python/clusterloader2/swiftv2-slo/slo.py b/modules/python/clusterloader2/swiftv2-slo/slo.py index 214348aa60..43a91902e6 100644 --- a/modules/python/clusterloader2/swiftv2-slo/slo.py +++ b/modules/python/clusterloader2/swiftv2-slo/slo.py @@ -47,6 +47,7 @@ def configure_clusterloader2( num_ccnps, dualstack, pods_per_pni, + existing_pods, override_file): steps = node_count * pods_per_node // pods_per_step if pods_per_step else 1 @@ -61,6 +62,7 @@ def configure_clusterloader2( file.write(f"CL2_PODS_PER_STEP: {pods_per_step}\n") file.write(f"CL2_PODS_PER_PNI: {pods_per_pni}\n") file.write(f"CL2_TOTAL_PODS: {total_pods}\n") + file.write(f"CL2_EXISTING_PODS: {existing_pods}\n") file.write(f"CL2_LATENCY_POD_CPU: {cpu_request}\n") file.write(f"CL2_REPEATS: {repeats}\n") file.write(f"CL2_STEPS: {steps}\n") @@ -266,6 +268,7 @@ def main(): parser_configure.add_argument("num_ccnps", type=int, nargs='?', default=0) parser_configure.add_argument("dualstack", type=str2bool, choices=[True, False], nargs='?', default=False) parser_configure.add_argument("pods_per_pni", type=int, nargs='?', default=0) + parser_configure.add_argument("existing_pods", type=int, nargs='?', default=0) parser_configure.add_argument("cl2_override_file", type=str) parser_validate = subparsers.add_parser("validate", help="Validate cluster setup") @@ -309,7 +312,8 @@ def main(): args.repeats, args.operation_timeout, args.provider, args.cilium_enabled, args.scrape_containerd, args.service_test, args.cnp_test, args.ccnp_test, args.ds_test, - args.num_cnps, args.num_ccnps, args.dualstack, args.pods_per_pni, args.cl2_override_file) + args.num_cnps, args.num_ccnps, args.dualstack, args.pods_per_pni, + args.existing_pods, args.cl2_override_file) elif args.command == "validate": validate_clusterloader2(args.node_count, args.operation_timeout, args.node_label) elif args.command == "execute": diff --git a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml index 32951080fc..ba2853178e 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml @@ -23,48 +23,34 @@ parameters: - name: matrix type: object default: - ppp=0_pods=140_nodes=20: - node_count: 20 - pods_per_step: 20 - test_timeout: "2m" - test_type: Burst_DynamicRes_PPS=140_PPP=0_Pods=140_Nodes=20 - cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - ppp=0_pods=350_nodes=50: - node_count: 50 - pods_per_step: 50 - test_timeout: "3m" - test_type: Burst_DynamicRes_PPS=350_PPP=0_Pods=350_Nodes=50 - cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - ppp=0_pods=700_nodes=100: - node_count: 100 - pods_per_step: 100 - test_timeout: "4m" - test_type: Burst_DynamicRes_PPS=700_PPP=0_Pods=700_Nodes=100 - cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - ppp=0_pods=1400_nodes=200: - node_count: 200 - pods_per_step: 200 - test_timeout: "6m" - test_type: Burst_DynamicRes_PPS=1400_PPP=0_Pods=1400_Nodes=200 - cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml ppp=0_pods=3500_nodes=500: node_count: 500 - pods_per_step: 500 + pods_per_step: 500 + existing_pods: 0 test_timeout: "7m" test_type: Burst_DynamicRes_PPS=3500_PPP=0_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - ppp=0_pods=5250_nodes=750: - node_count: 750 - pods_per_step: 750 - test_timeout: "9m" - test_type: Burst_DynamicRes_PPS=5250_PPP=0_Pods=5250_Nodes=750 - cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - ppp=0_burst_pods=7000_nodes=1000: + ppp=0_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 1000 + existing_pods: 3500 test_timeout: "10m" test_type: Burst_DynamicRes_PPS=7000_PPP=0_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + ppp=0_pods=10500_nodes=1500: + node_count: 1500 + pods_per_step: 1500 + existing_pods: 7000 + test_timeout: "12m" + test_type: Burst_DynamicRes_PPS=10500_PPP=0_Pods=10500_Nodes=1500 + cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml + ppp=0_pods=14000_nodes=2000: + node_count: 2000 + pods_per_step: 2000 + existing_pods: 10500 + test_timeout: "15m" + test_type: Burst_DynamicRes_PPS=14000_PPP=0_Pods=14000_Nodes=2000 + cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml index d21d4da514..ca9a69d4c7 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml @@ -23,47 +23,33 @@ parameters: - name: matrix type: object default: - pps=35_ppp=0_pods=70_nodes=10: - node_count: 10 - pods_per_step: 35 - test_timeout: "2m" - test_type: Gradual_DynamicRes_PPS=35_PPP=0_Pods=70_Nodes=10 - cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml pps=50_ppp=0_pods=3500_nodes=500: node_count: 500 pods_per_step: 50 + existing_pods: 0 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml pps=50_ppp=0_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 50 + existing_pods: 3500 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - pps=50_ppp=0_pods=14000_nodes=2000: - node_count: 2000 - pods_per_step: 50 - test_timeout: "2m" - test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=14000_Nodes=2000 - cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - pps=50_ppp=0_pods=17500_nodes=2500: - node_count: 2500 - pods_per_step: 50 - test_timeout: "2m" - test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=17500_Nodes=2500 - cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - pps=50_ppp=0_pods=21000_nodes=3000: - node_count: 3000 + pps=50_ppp=0_pods=10500_nodes=1500: + node_count: 1500 pods_per_step: 50 + existing_pods: 7000 test_timeout: "2m" - test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=21000_Nodes=3000 + test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=10500_Nodes=1500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml - pps=50_ppp=0_pods=35000_nodes=5000: - node_count: 5000 + pps=50_ppp=0_pods=14000_nodes=2000: + node_count: 2000 pods_per_step: 50 + existing_pods: 10500 test_timeout: "2m" - test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=35000_Nodes=5000 + test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml jobs: diff --git a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml index 2aaa2e1222..31e9abd718 100644 --- a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml @@ -23,55 +23,38 @@ parameters: - name: matrix type: object default: - ppp=1_pods=140_nodes=20: - node_count: 20 - pods_per_step: 20 - pods_per_pni: 1 - test_timeout: "2m" - test_type: Burst_StaticRes_PPS=140_PPP=1_Pods=140_Nodes=20 - cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - ppp=1_pods=350_nodes=50: - node_count: 50 - pods_per_step: 50 - pods_per_pni: 1 - test_timeout: "3m" - test_type: Burst_StaticRes_PPS=350_PPP=1_Pods=350_Nodes=50 - cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - ppp=1_pods=700_nodes=100: - node_count: 100 - pods_per_step: 100 - pods_per_pni: 1 - test_timeout: "4m" - test_type: Burst_StaticRes_PPS=700_PPP=1_Pods=700_Nodes=100 - cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - ppp=1_pods=1400_nodes=200: - node_count: 200 - pods_per_step: 200 - pods_per_pni: 1 - test_timeout: "6m" - test_type: Burst_StaticRes_PPS=1400_PPP=1_Pods=1400_Nodes=200 - cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml ppp=1_pods=3500_nodes=500: node_count: 500 pods_per_step: 500 pods_per_pni: 1 + existing_pods: 0 test_timeout: "7m" test_type: Burst_StaticRes_PPS=3500_PPP=1_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - ppp=1_pods=5250_nodes=750: - node_count: 750 - pods_per_step: 750 - pods_per_pni: 1 - test_timeout: "9m" - test_type: Burst_StaticRes_PPS=5250_PPP=1_Pods=5250_Nodes=750 - cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml ppp=1_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 1000 pods_per_pni: 1 + existing_pods: 3500 test_timeout: "10m" test_type: Burst_StaticRes_PPS=7000_PPP=1_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + ppp=1_pods=10500_nodes=1500: + node_count: 1500 + pods_per_step: 1500 + pods_per_pni: 1 + existing_pods: 7000 + test_timeout: "12m" + test_type: Burst_StaticRes_PPS=10500_PPP=1_Pods=10500_Nodes=1500 + cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml + ppp=1_pods=14000_nodes=2000: + node_count: 2000 + pods_per_step: 2000 + pods_per_pni: 1 + existing_pods: 10500 + test_timeout: "15m" + test_type: Burst_StaticRes_PPS=14000_PPP=1_Pods=14000_Nodes=2000 + cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml jobs: - template: /jobs/competitive-test.yml diff --git a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml index bc3bb44879..dc61690d29 100644 --- a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml @@ -23,17 +23,11 @@ parameters: - name: matrix type: object default: - pps=35_ppp=1_pods=70_nodes=10: - node_count: 10 - pods_per_step: 35 - pods_per_pni: 1 - test_timeout: "2m" - test_type: Gradual_StaticRes_PPS=35_PPP=1_Pods=70_Nodes=10 - cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml pps=50_ppp=1_pods=3500_nodes=500: node_count: 500 pods_per_step: 50 pods_per_pni: 1 + existing_pods: 0 test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml @@ -41,36 +35,25 @@ parameters: node_count: 1000 pods_per_step: 50 pods_per_pni: 1 + existing_pods: 3500 test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - pps=50_ppp=1_pods=14000_nodes=2000: - node_count: 2000 + pps=50_ppp=1_pods=10500_nodes=1500: + node_count: 1500 pods_per_step: 50 pods_per_pni: 1 + existing_pods: 7000 test_timeout: "2m" - test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=14000_Nodes=2000 + test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=10500_Nodes=1500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - pps=50_ppp=1_pods=17500_nodes=2500: - node_count: 2500 - pods_per_step: 50 - pods_per_pni: 1 - test_timeout: "2m" - test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=17500_Nodes=2500 - cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - pps=50_ppp=1_pods=21000_nodes=3000: - node_count: 3000 - pods_per_step: 50 - pods_per_pni: 1 - test_timeout: "2m" - test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=21000_Nodes=3000 - cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml - pps=50_ppp=1_pods=35000_nodes=5000: - node_count: 5000 + pps=50_ppp=1_pods=14000_nodes=2000: + node_count: 2000 pods_per_step: 50 pods_per_pni: 1 + existing_pods: 10500 test_timeout: "2m" - test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=35000_Nodes=5000 + test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml jobs: diff --git a/steps/engine/clusterloader2/swiftv2-slo/execute.yml b/steps/engine/clusterloader2/swiftv2-slo/execute.yml index 875cf9db82..1ac7a579c1 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/execute.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/execute.yml @@ -31,7 +31,7 @@ steps: $CPU_PER_NODE $NODE_COUNT $PODS_PER_STEP $PODS_PER_NODE ${MAX_PODS:-0} \ $REPEATS $TEST_TIMEOUT $CLOUD $CILIUM_ENABLED ${SCRAPE_CONTAINERD:-False} \ $SERVICE_TEST ${CNP_TEST:-False} ${CCNP_TEST:-False} ${DS_TEST:-False} \ - ${NUM_CNPS:-0} ${NUM_CCNPS:-0} ${DUALSTACK:-False} ${PODS_PER_PNI:-0} ${CL2_CONFIG_DIR}/overrides.yaml + ${NUM_CNPS:-0} ${NUM_CCNPS:-0} ${DUALSTACK:-False} ${PODS_PER_PNI:-0} ${EXISTING_PODS:-0} ${CL2_CONFIG_DIR}/overrides.yaml PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE execute \ ${CL2_IMAGE} ${CL2_CONFIG_DIR} $CL2_REPORT_DIR $CL2_CONFIG_FILE \ ${HOME}/.kube/config $CLOUD ${SCRAPE_CONTAINERD:-False} From 4253f95bf88f7f02e08d5dc0d6d0b896c9ff18f7 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 13:25:31 +0000 Subject: [PATCH 34/47] fix: cleanup rg set subscription --- steps/cleanup-resources.yml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 6d31a1a55d..3608d40d67 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -98,6 +98,11 @@ steps: trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT + # Set the Azure subscription + export AZURE_SUBSCRIPTION_ID="$(AZURE_SUBSCRIPTION_ID)" + echo "Setting Azure subscription to: $AZURE_SUBSCRIPTION_ID" + az account set --subscription "$AZURE_SUBSCRIPTION_ID" + echo "Delete resource group $RESOURCE_GROUP_NAME" for attempt in $(seq 1 5); do echo "Attempting to delete resource group: $attempt/5" From 99a5c6f8908793b1507189bb122a608371a84ba9 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 16:39:37 +0000 Subject: [PATCH 35/47] fix(cl2): use podsPerStep instead of actualPodsPerStep for deployment replicas The actualPodsPerStep variable was incorrectly calculated as (total_pods - existingPods), which represents the total delta pods, not the per-step count. This caused each step to create all delta pods instead of the configured pods_per_step amount. For example, with pods_per_step=35 and total_pods=70, each step was creating 70 pods instead of 35, causing pod scheduling failures due to insufficient node capacity. --- .../config/swiftv2_deployment_dynamicres_scale_config.yaml | 2 +- .../config/swiftv2_deployment_staticres_scale_config.yaml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml index 16e6c2e8fa..66d3a7cb14 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml @@ -131,7 +131,7 @@ steps: - basename: deployment-churn-job{{$jobIndex}}-{{$j}} objectTemplatePath: swiftv2_deployment_template.yaml templateFillMap: - Replicas: {{$actualPodsPerStep}} + Replicas: {{$podsPerStep}} PodGroup: {{$groupName}} Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} CpuRequest: {{$latencyPodCpu}}m diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index 6ced4464d8..edcd91c232 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -129,7 +129,7 @@ steps: - namespaceRange: min: 1 max: 1 - replicasPerNamespace: {{$actualPodsPerStep}} + replicasPerNamespace: {{$podsPerStep}} tuningSet: DeploymentCreateQps objectBundle: - basename: deployment-churn-job{{$jobIndex}}-{{$j}} From 2f27f2818a5bbb8bca884a7ffd2871d2a79dc0ac Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 18:07:10 +0000 Subject: [PATCH 36/47] fix(cl2): calculate steps based on delta pods instead of total capacity The steps calculation was using total pod capacity (node_count * pods_per_node) instead of accounting for existing_pods. This caused gradual scale tests to create more steps than needed when existing_pods > 0. For example, with node_count=20, pods_per_node=7, pods_per_step=35, existing_pods=70: - Before: steps = 20 * 7 // 35 = 4 (creating 140 new pods) - After: steps = (140 - 70) // 35 = 2 (creating 70 new pods) --- modules/python/clusterloader2/swiftv2-slo/slo.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/slo.py b/modules/python/clusterloader2/swiftv2-slo/slo.py index 43a91902e6..4ea3847221 100644 --- a/modules/python/clusterloader2/swiftv2-slo/slo.py +++ b/modules/python/clusterloader2/swiftv2-slo/slo.py @@ -50,8 +50,9 @@ def configure_clusterloader2( existing_pods, override_file): - steps = node_count * pods_per_node // pods_per_step if pods_per_step else 1 total_pods = node_count * pods_per_node + delta_pods = total_pods - existing_pods + steps = delta_pods // pods_per_step if pods_per_step else 1 throughput, nodes_per_namespace, cpu_request = calculate_config(cpu_per_node, node_count, max_pods, provider) with open(override_file, 'w', encoding='utf-8') as file: From 2d59ab43d166f1914e0faf9b7fa39f72e5929825 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 18:27:40 +0000 Subject: [PATCH 37/47] feat(cl2): auto-detect existing pods from cluster at runtime Add pipeline step to query existing deployment-churn pods by summing deployment replica counts. This eliminates manual existing_pods config in matrix files. Changes: - Add 'Query Existing Pod Count' step in execute.yml that queries deployments with label podgroup=deployment-churn and sums replicas - Remove existing_pods parameter from all swiftv2 matrix files Benefits: - No manual calculation required for matrix entries - Handles job retries/reruns correctly (always gets current state) - Uses deployment replicas (not pod count) to avoid counting pending/failed pods - Graceful fallback to 0 if no deployments or kubectl errors --- .../swiftv2-dynamicres-burst-matrix.yml | 4 ---- .../swiftv2-dynamicres-gradual-matrix.yml | 4 ---- .../matrices/swiftv2-staticres-burst-matrix.yml | 4 ---- .../swiftv2-staticres-gradual-matrix.yml | 4 ---- .../clusterloader2/swiftv2-slo/execute.yml | 17 +++++++++++++++++ 5 files changed, 17 insertions(+), 16 deletions(-) diff --git a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml index ba2853178e..9bef258160 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml @@ -26,28 +26,24 @@ parameters: ppp=0_pods=3500_nodes=500: node_count: 500 pods_per_step: 500 - existing_pods: 0 test_timeout: "7m" test_type: Burst_DynamicRes_PPS=3500_PPP=0_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml ppp=0_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 1000 - existing_pods: 3500 test_timeout: "10m" test_type: Burst_DynamicRes_PPS=7000_PPP=0_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml ppp=0_pods=10500_nodes=1500: node_count: 1500 pods_per_step: 1500 - existing_pods: 7000 test_timeout: "12m" test_type: Burst_DynamicRes_PPS=10500_PPP=0_Pods=10500_Nodes=1500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml ppp=0_pods=14000_nodes=2000: node_count: 2000 pods_per_step: 2000 - existing_pods: 10500 test_timeout: "15m" test_type: Burst_DynamicRes_PPS=14000_PPP=0_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml diff --git a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml index ca9a69d4c7..1fa690ccb7 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml @@ -26,28 +26,24 @@ parameters: pps=50_ppp=0_pods=3500_nodes=500: node_count: 500 pods_per_step: 50 - existing_pods: 0 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml pps=50_ppp=0_pods=7000_nodes=1000: node_count: 1000 pods_per_step: 50 - existing_pods: 3500 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml pps=50_ppp=0_pods=10500_nodes=1500: node_count: 1500 pods_per_step: 50 - existing_pods: 7000 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=10500_Nodes=1500 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml pps=50_ppp=0_pods=14000_nodes=2000: node_count: 2000 pods_per_step: 50 - existing_pods: 10500 test_timeout: "2m" test_type: Gradual_DynamicRes_PPS=50_PPP=0_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_dynamicres_scale_config.yaml diff --git a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml index 31e9abd718..424e2a4c50 100644 --- a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml @@ -27,7 +27,6 @@ parameters: node_count: 500 pods_per_step: 500 pods_per_pni: 1 - existing_pods: 0 test_timeout: "7m" test_type: Burst_StaticRes_PPS=3500_PPP=1_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml @@ -35,7 +34,6 @@ parameters: node_count: 1000 pods_per_step: 1000 pods_per_pni: 1 - existing_pods: 3500 test_timeout: "10m" test_type: Burst_StaticRes_PPS=7000_PPP=1_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml @@ -43,7 +41,6 @@ parameters: node_count: 1500 pods_per_step: 1500 pods_per_pni: 1 - existing_pods: 7000 test_timeout: "12m" test_type: Burst_StaticRes_PPS=10500_PPP=1_Pods=10500_Nodes=1500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml @@ -51,7 +48,6 @@ parameters: node_count: 2000 pods_per_step: 2000 pods_per_pni: 1 - existing_pods: 10500 test_timeout: "15m" test_type: Burst_StaticRes_PPS=14000_PPP=1_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml diff --git a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml index dc61690d29..d28d99e990 100644 --- a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml @@ -27,7 +27,6 @@ parameters: node_count: 500 pods_per_step: 50 pods_per_pni: 1 - existing_pods: 0 test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=3500_Nodes=500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml @@ -35,7 +34,6 @@ parameters: node_count: 1000 pods_per_step: 50 pods_per_pni: 1 - existing_pods: 3500 test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=7000_Nodes=1000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml @@ -43,7 +41,6 @@ parameters: node_count: 1500 pods_per_step: 50 pods_per_pni: 1 - existing_pods: 7000 test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=10500_Nodes=1500 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml @@ -51,7 +48,6 @@ parameters: node_count: 2000 pods_per_step: 50 pods_per_pni: 1 - existing_pods: 10500 test_timeout: "2m" test_type: Gradual_StaticRes_PPS=50_PPP=1_Pods=14000_Nodes=2000 cl2_config_file: swiftv2_deployment_staticres_scale_config.yaml diff --git a/steps/engine/clusterloader2/swiftv2-slo/execute.yml b/steps/engine/clusterloader2/swiftv2-slo/execute.yml index 1ac7a579c1..58f9df53bd 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/execute.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/execute.yml @@ -16,6 +16,23 @@ steps: echo "##vso[task.setvariable variable=SLO_START_TIME]$startTimestamp" displayName: set up timestamp variable + - script: | + set -eo pipefail + + # Query cluster for existing deployment-churn pods by summing deployment replicas + # This gives the intended count (not affected by pending/failed pods) + # Handles: no deployments found (returns 0), kubectl errors (falls back to 0) + existing_pods=$(kubectl get deployments -l podgroup=deployment-churn -A -o jsonpath='{range .items[*]}{.spec.replicas}{"\n"}{end}' 2>/dev/null | awk '{sum+=$1} END {print sum+0}' || echo "0") + + # Ensure we have a valid number, default to 0 if empty or non-numeric + if ! [[ "$existing_pods" =~ ^[0-9]+$ ]]; then + existing_pods=0 + fi + + echo "Detected existing pods (sum of deployment replicas with label podgroup=deployment-churn): $existing_pods" + echo "##vso[task.setvariable variable=EXISTING_PODS]$existing_pods" + displayName: "Query Existing Pod Count" + - script: | set -eo pipefail set -x From 5bfee9a4dc05dec66d5a20738259ac2c6d3e8157 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 18:45:15 +0000 Subject: [PATCH 38/47] doc: udpate usage --- docs/running-swiftv2-pipeline.md | 121 +++++++------------------------ 1 file changed, 25 insertions(+), 96 deletions(-) diff --git a/docs/running-swiftv2-pipeline.md b/docs/running-swiftv2-pipeline.md index 6b793b1de2..b69ed56cec 100644 --- a/docs/running-swiftv2-pipeline.md +++ b/docs/running-swiftv2-pipeline.md @@ -6,115 +6,44 @@ Here is the pipeline [link](https://dev.azure.com/akstelescope/telescope/_build? 1. For a given region, make sure the regional customer [RG + AKS + identities] exist. If not, run the regional customer setup script `swiftv2kubeobjects/runCustomerSetup.sh`. Further instructions on how to run the script are mentioned in the script file. This is a one time setup and the resources are preserved for 3 months. 2. For a given region, make sure the regional ACR exists with mirrored images. If not, run the regional ACR setup script `swiftv2kubeobjects/setup-regional-acr.sh`. This creates a dedicated ACR per region to avoid throttling on shared team ACR and mirrors required images. -3. For a given region + VM-SKU, Check if the subscription has quota for the scale target. +3. For a given region + VM-SKU, check if the subscription has quota for the scale target. ## Pipeline variables, branches and test matrix -- As of 11/11/2025, no pipeline variables need to be touched in ADO. All the variables are hardcoded in `pipelines/system/new-pipeline-test.yml`. For example, location, subscription, vm-sku, number of nics, etc. -- **Note:** Cluster cleanup behavior is controlled at the matrix level via `skip_cleanup` flags in each test entry, not via a global pipeline variable. -- This is the official branch - `feature/swiftv2GA/swiftv2scale`, and it has comprehensive test matrix. Not all of which needs to be run for a given objective. -- It is recomended to create a test branch and disable/comment out unnnecessary test cases. +- All pipeline variables are hardcoded in `pipelines/system/new-pipeline-test.yml` (location, subscription, vm-sku, etc.) +- Set `CLEANUP: "false"` to preserve resources after pipeline completes (useful for debugging) +- Official branch: `feature/swiftv2GA/swiftv2scale` +- Recommended: Create a test branch and comment out unnecessary test cases -## Disabling stages and removing test matrix entries +## Disabling stages and matrix entries -- If certain stages are not required for the perf run, in `pipelines/system/new-pipeline-test.yml` flip `condition` flag to `false`. At the moment both `burst` stages are set to false. -- Each stage has a matrix file here - `pipelines/system/matrices`, where different combinations of pods, nodes and pods-per-step are set. Comment out the matrix entries that are irrelevant for the enabled stages. +- To disable stages, set `condition: false` in `pipelines/system/new-pipeline-test.yml` (burst stages are disabled by default) +- Matrix files are in `pipelines/system/matrices/` - comment out entries that are not needed -## Matrix configuration with reuse_cluster and skip_cleanup -. These flags provide fine-grained control over cluster creation and cleanup **at the individual test level** - there is no global cleanup variable. +## Pipeline Architecture -- **`reuse_cluster`**: Whether to reuse an existing cluster (`true`) or create a new one (`false`) -- **`skip_cleanup`**: Whether to keep the cluster after tests complete (`true`) or delete it (`false`) +Each stage has: +1. **`generate_run_id` job**: Creates a unique `BASE_RUN_ID` with stage prefix (sg, dg, sb, db) +2. **Matrix jobs**: Run tests using the shared `BASE_RUN_ID` for resource group naming +3. **`cleanup` job**: Runs after all matrix jobs complete (controlled by `CLEANUP` variable) -> ⚠️ Azure DevOps passes boolean variables to scripts as `True`/`False` strings. Normalize to lowercase before comparison in bash scripts. +### Run ID and Job Isolation -### Typical pattern for gradual scale testing +- **`BASE_RUN_ID`**: Shared across all jobs in a stage, used for resource group naming and cluster tagging +- **`RUN_ID`**: Unique per job (BASE_RUN_ID + job suffix), used for result storage +- **`CL2_JOB_INDEX`**: Derived from `System.JobId`, used to isolate CL2 resources (namespaces, deployments, PNIs) across parallel jobs -- **First entry**: `reuse_cluster: false`, `skip_cleanup: true` - Creates a new cluster, keeps it -- **Middle entries**: `reuse_cluster: true`, `skip_cleanup: true` - Reuses existing cluster, keeps it -- **Last entry**: `reuse_cluster: true`, `skip_cleanup: false` - Reuses existing cluster, **cleans it up** +This ensures test results don't overwrite each other while sharing infrastructure. -This pattern allows sequential test runs on the same cluster, saving time and resources by avoiding repeated cluster creation/deletion. Only the last test in the sequence performs cleanup -This pattern allows sequential test runs on the same cluster, saving time and resources by avoiding repeated cluster creation/deletion. +### Cleanup Behavior -### Adding or removing matrix entries +Cleanup runs at the end of each stage and: +1. Deletes swiftv2 workloads (deployments, pods) +2. Removes nodepools sequentially +3. Deletes Azure resources (NAT gateways, NSGs, public IPs) +4. Destroys the resource group -When modifying the matrix, ensure the first and last entries have the appropriate flags: - -```yaml -matrix: - test_small: - node_count: 10 - reuse_cluster: false # Create new cluster - skip_cleanup: true # Keep it for next test - # ... other params - test_medium: - node_count: 500 - reuse_cluster: true # Reuse cluster - skip_cleanup: true # Keep it for next test - # ... other params - test_large: - node_count: 1000 - reuse_cluster: true # Reuse cluster - skip_cleanup: false # Clean up after completion - # ... other params -``` -### Running tests independently - -To run tests independently (not reusing clusters), set `reuse_cluster: false` and `skip_cleanup: false` on all entries. Each test will create its own cluster and clean it up after completion. - -### Emergency: Disable all cleanup - -If you need to preserve clusters for debugging after a pipeline run, set `skip_cleanup: true` on all matrix entries. This overrides cleanup behavior for the entire pipeline run. Remember to manually delete clusters afterwards to avoid resource waste. - -To run tests independently (not reusing clusters), set `reuse_cluster: false` and `skip_cleanup: false` on all entries. - -### Cluster Creation and Reuse Logic - -The pipeline uses the following logic for cluster lifecycle management: - -1. **First job** (`reuse_cluster: false`): - - Creates resource group - - Runs `createclusterforping.sh` to create AKS cluster and initial nodepools (1 node each) - - Runs `scale-cluster.sh` to scale nodepools to target size - - Keeps cluster after test (`skip_cleanup: true`) - -2. **Subsequent jobs** (`reuse_cluster: true`): - - Reuses existing resource group (via `BASE_RUN_ID`) - - **Skips** `createclusterforping.sh` (cluster already exists) - - Runs `scale-cluster.sh` to scale existing nodepools to new target size - - Keeps or cleans up cluster based on `skip_cleanup` flag - -This design avoids redundant cluster creation attempts and consolidates all nodepool scaling logic in `scale-cluster.sh`. - -### Result Storage and Run IDs - -Each matrix job generates a unique `RUN_ID` (BASE_RUN_ID + job suffix) used for: -- Blob storage filenames: `$(RUN_ID).json` -- Individual job tracking and test result isolation - -When `reuse_cluster: true`, jobs use `BASE_RUN_ID` for: -- **Azure cluster discovery**: Finding existing cluster via `run_id` tag -- Resource group name (shared across all matrix jobs) -- Azure resource tagging -- Correlating which jobs ran on the same cluster - -**Results DO NOT overwrite** because each job uploads to its own unique `RUN_ID` filename. The telescope metadata now includes both `run_id` (unique per job) and `base_run_id` (shared across matrix jobs) to enable correlation in Kusto queries. - -**How cluster discovery works:** -1. **First job** creates cluster with tag: `run_id=` -2. **Subsequent jobs** check `reuse_cluster` flag and use `BASE_RUN_ID` to query Azure: - ```bash - reuse_cluster="$(echo "${REUSE_CLUSTER:-false}" | tr '[:upper:]' '[:lower:]')" - if [ "$reuse_cluster" = "true" ]; then - CLUSTER_RUN_ID="$BASE_RUN_ID" - else - CLUSTER_RUN_ID="$RUN_ID" - fi - az resource list ... --query "[?(tags.run_id == '$CLUSTER_RUN_ID' && tags.role == 'slo')]" - ``` -3. This allows `update-kubeconfig.yml` and `scale-cluster.sh` to find the shared cluster -4. Each job keeps unique `RUN_ID` for result uploads (prevents overwrites) +To preserve resources for debugging, set `CLEANUP: "false"` in the pipeline variables. ## Kusto From 3cbe12957ffc9ae3725ec64f9e792a277b43a950 Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 18:59:31 +0000 Subject: [PATCH 39/47] feat(cl2): add podgroup-job label for per-job PodStartupLatency measurement - Add podgroup-job label to swiftv2_deployment_template.yaml - Add podgroup-job label to swiftv2_deployment_single_pod_template.yaml - Update PodStartupLatency labelSelector to use podgroup-job in staticres config - Update PodStartupLatency labelSelector to use podgroup-job in dynamicres config - Add PodGroupJob parameter to templateFillMap in both configs The existing podgroup label is preserved for datapath-observer/controller which needs to query all pods across jobs. --- .../config/swiftv2_deployment_dynamicres_scale_config.yaml | 5 +++-- .../config/swiftv2_deployment_single_pod_template.yaml | 1 + .../config/swiftv2_deployment_staticres_scale_config.yaml | 5 +++-- .../swiftv2-slo/config/swiftv2_deployment_template.yaml | 1 + 4 files changed, 8 insertions(+), 4 deletions(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml index 66d3a7cb14..40946bfab2 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml @@ -107,7 +107,7 @@ steps: Method: PodStartupLatency Params: action: start - labelSelector: podgroup={{$groupName}} + labelSelector: podgroup-job={{$groupName}}-job{{$jobIndex}} threshold: {{$podStartupLatencyThreshold}} {{range $j := Loop $steps}} - name: Starting Deployment Latency Measurements -{{$j}} @@ -133,6 +133,7 @@ steps: templateFillMap: Replicas: {{$podsPerStep}} PodGroup: {{$groupName}} + PodGroupJob: {{$groupName}}-job{{$jobIndex}} Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} CpuRequest: {{$latencyPodCpu}}m MemoryRequest: {{$latencyPodMemory}}M @@ -161,7 +162,7 @@ steps: Method: PodStartupLatency Params: action: gather - labelSelector: podgroup={{$groupName}} + labelSelector: podgroup-job={{$groupName}}-job{{$jobIndex}} - name: Wait for Datapath Readiness measurements: - Identifier: Dummy diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml index d683e44dbb..64709f5676 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml @@ -19,6 +19,7 @@ spec: name: {{.Name}} group: {{.Group}} podgroup: {{.PodGroup}} + podgroup-job: {{.PodGroupJob}} kubernetes.azure.com/pod-network: pn100 kubernetes.azure.com/pod-network-instance: {{.PNIPrefix}}-{{DivideInt .Index .PodsPerPNI}} restart: {{.deploymentLabel}} diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index edcd91c232..196db5702b 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -65,7 +65,7 @@ steps: Method: PodStartupLatency Params: action: start - labelSelector: podgroup={{$groupName}} + labelSelector: podgroup-job={{$groupName}}-job{{$jobIndex}} threshold: {{$podStartupLatencyThreshold}} {{range $j := Loop $steps}} - name: Create PNIs for step {{$j}} @@ -137,6 +137,7 @@ steps: templateFillMap: Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} PodGroup: {{$groupName}} + PodGroupJob: {{$groupName}}-job{{$jobIndex}} CpuRequest: {{$latencyPodCpu}}m MemoryRequest: {{$latencyPodMemory}}M deploymentLabel: start @@ -166,7 +167,7 @@ steps: Method: PodStartupLatency Params: action: gather - labelSelector: podgroup={{$groupName}} + labelSelector: podgroup-job={{$groupName}}-job{{$jobIndex}} - name: Wait for Datapath Readiness measurements: - Identifier: Dummy diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_template.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_template.yaml index 7805aaccb2..bbd7a45e42 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_template.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_template.yaml @@ -19,6 +19,7 @@ spec: name: {{.Name}} group: {{.Group}} podgroup: {{.PodGroup}} + podgroup-job: {{.PodGroupJob}} kubernetes.azure.com/pod-network: pn100 kubernetes.azure.com/pod-network-instance: {{.pniName}} restart: {{.deploymentLabel}} From 3710015a3437b4213b6aacf6a9c03501f6fa5a8d Mon Sep 17 00:00:00 2001 From: Isaac Date: Thu, 29 Jan 2026 21:18:45 +0000 Subject: [PATCH 40/47] refactor(cl2): rename actualPodsPerStep to actualPodsThisJob for clarity The variable name was misleading since podsPerStep already exists and refers to the number of deployments per step. The renamed variable represents the total pods for the entire job, clamped to 0. --- .../config/swiftv2_deployment_dynamicres_scale_config.yaml | 4 ++-- .../config/swiftv2_deployment_staticres_scale_config.yaml | 6 +++--- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml index 40946bfab2..adf7bb5b39 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_dynamicres_scale_config.yaml @@ -6,7 +6,7 @@ name: deployment-churn {{$total_pods := DefaultParam .CL2_TOTAL_PODS 7000}} {{$existingPods := DefaultParam .CL2_EXISTING_PODS 0}} {{$deltaPods := SubtractInt $total_pods $existingPods}} -{{$actualPodsPerStep := MaxInt $deltaPods 0}} +{{$actualPodsThisJob := MaxInt $deltaPods 0}} {{$steps := DefaultParam .CL2_STEPS 1}} {{$latencyPodCpu := DefaultParam .CL2_LATENCY_POD_CPU 10}} {{$latencyPodMemory := DefaultParam .CL2_LATENCY_POD_MEMORY 50}} @@ -50,7 +50,7 @@ steps: objectTemplatePath: reporter_role_template.yaml - basename: reporter-binding objectTemplatePath: reporter_rolebinding_template.yaml - - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total_pods={{$total_pods}}, existing_pods={{$existingPods}}, delta_pods={{$deltaPods}}, actual_pods_per_step={{$actualPodsPerStep}} + - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total_pods={{$total_pods}}, existing_pods={{$existingPods}}, delta_pods={{$deltaPods}}, actual_pods_this_job={{$actualPodsThisJob}} measurements: - Identifier: Dummy Method: Sleep diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index 196db5702b..a2df69d2d5 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -7,8 +7,8 @@ name: deployment-churn {{$total_pods := DefaultParam .CL2_TOTAL_PODS 7000}} {{$existingPods := DefaultParam .CL2_EXISTING_PODS 0}} {{$deltaPods := SubtractInt $total_pods $existingPods}} -{{$actualPodsPerStep := MaxInt $deltaPods 0}} -{{$numPNIs := DivideInt $actualPodsPerStep $podsPerPNI}} +{{$actualPodsThisJob := MaxInt $deltaPods 0}} +{{$numPNIs := DivideInt $actualPodsThisJob $podsPerPNI}} {{$steps := DefaultParam .CL2_STEPS 1}} {{$latencyPodCpu := DefaultParam .CL2_LATENCY_POD_CPU 10}} {{$latencyPodMemory := DefaultParam .CL2_LATENCY_POD_MEMORY 50}} @@ -52,7 +52,7 @@ steps: objectTemplatePath: reporter_role_template.yaml - basename: reporter-binding objectTemplatePath: reporter_rolebinding_template.yaml - - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total_pods={{$total_pods}}, existing_pods={{$existingPods}}, delta_pods={{$deltaPods}}, actual_pods_per_step={{$actualPodsPerStep}} + - name: Log - job_index={{$jobIndex}}, steps={{$steps}}, nodes={{$nodes}}, pods/node={{$podsPerNode}}, pods/step={{$podsPerStep}}, total_pods={{$total_pods}}, existing_pods={{$existingPods}}, delta_pods={{$deltaPods}}, actual_pods_this_job={{$actualPodsThisJob}} measurements: - Identifier: Dummy Method: Sleep From c88e308de61982c2e532d2ecd4991f5336d7df1e Mon Sep 17 00:00:00 2001 From: Isaac Date: Fri, 30 Jan 2026 00:19:59 +0000 Subject: [PATCH 41/47] fix(swiftv2-slo): calculate PNIs per step instead of total pods The numPNIs variable was calculated based on actualPodsThisJob (total pods) but used inside the step loop, causing 3500 PNIs to be created per step instead of 50. This exhausted network capacity and caused pod timeouts. Changed to numPNIsPerStep = podsPerStep / podsPerPNI to create only the PNIs needed for each step. --- .../config/swiftv2_deployment_staticres_scale_config.yaml | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml index a2df69d2d5..910e5b3446 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_staticres_scale_config.yaml @@ -8,7 +8,7 @@ name: deployment-churn {{$existingPods := DefaultParam .CL2_EXISTING_PODS 0}} {{$deltaPods := SubtractInt $total_pods $existingPods}} {{$actualPodsThisJob := MaxInt $deltaPods 0}} -{{$numPNIs := DivideInt $actualPodsThisJob $podsPerPNI}} +{{$numPNIsPerStep := DivideInt $podsPerStep $podsPerPNI}} {{$steps := DefaultParam .CL2_STEPS 1}} {{$latencyPodCpu := DefaultParam .CL2_LATENCY_POD_CPU 10}} {{$latencyPodMemory := DefaultParam .CL2_LATENCY_POD_MEMORY 50}} @@ -73,7 +73,7 @@ steps: - namespaceRange: min: 1 max: 1 - replicasPerNamespace: {{$numPNIs}} + replicasPerNamespace: {{$numPNIsPerStep}} tuningSet: DeploymentCreateQps objectBundle: - basename: pod-network-instance-job{{$jobIndex}}-{{$j}} @@ -92,7 +92,7 @@ steps: objectTemplatePath: pni_readiness_checker_unified_template.yaml templateFillMap: PNIPrefix: pod-network-instance-job{{$jobIndex}}-{{$j}}- - NumPNIs: {{$numPNIs}} + NumPNIs: {{$numPNIsPerStep}} - name: Wait for PNI Readiness Checker to Complete -{{$j}} measurements: - Identifier: WaitForPNIChecker-{{$j}} @@ -113,7 +113,7 @@ steps: objectTemplatePath: pni_readiness_checker_unified_template.yaml templateFillMap: PNIPrefix: pod-network-instance-job{{$jobIndex}}-{{$j}}- - NumPNIs: {{$numPNIs}} + NumPNIs: {{$numPNIsPerStep}} - name: Starting Deployment Latency Measurements -{{$j}} measurements: - Identifier: WaitForControlledPodsRunning-{{$j}} From 297a0104b007190a48592fbbe6412ea517687be5 Mon Sep 17 00:00:00 2001 From: Isaac Date: Fri, 30 Jan 2026 12:02:13 +0000 Subject: [PATCH 42/47] fix(swiftv2-slo): add podgroup label to Deployment metadata for existing pod detection The kubectl query to detect existing pods was searching for deployments with label podgroup=deployment-churn, but this label was only present on the Pod template, not on the Deployment object itself. This caused existing_pods to always return 0, resulting in over-provisioning pods across gradual scale jobs. --- .../config/swiftv2_deployment_single_pod_template.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml index 64709f5676..1129b19aab 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_single_pod_template.yaml @@ -4,6 +4,7 @@ metadata: name: {{.Name}} labels: group: {{.Group}} + podgroup: {{.PodGroup}} kubernetes.azure.com/pod-network: pn100 kubernetes.azure.com/pod-network-instance: {{.PNIPrefix}}-{{DivideInt .Index .PodsPerPNI}} spec: From 86d49e86e1321828d60961020671a9ce3de41976 Mon Sep 17 00:00:00 2001 From: Isaac Date: Fri, 30 Jan 2026 17:26:19 +0000 Subject: [PATCH 43/47] fix(cleanup): make cleanup scripts resilient to failures - Replace 'set -euo pipefail' with 'set +e' to continue on errors - Remove SIGTERM/SIGINT trap handlers - scripts run to completion - Add 'exit 0' to ensure subsequent pipeline steps always run - Add batched deletion for deployments/PNIs (~500 items per batch) - Use retry_command from common.sh for kubectl delete operations - Add CLEANUP_BATCH_SIZE env var (default: 500) for configurable batching This ensures cleanup scripts don't block the pipeline even if they encounter errors, since subsequent scripts will cleanup the AKS cluster and resource group anyway. --- steps/cleanup-resources.yml | 29 ++- swiftv2kubeobjects/cleanup-azure-resources.sh | 13 +- .../cleanup-swiftv2-workloads.sh | 171 ++++++++++++++---- 3 files changed, 158 insertions(+), 55 deletions(-) diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 3608d40d67..dea065ed8e 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -21,16 +21,15 @@ steps: condition: always() - script: | - set -eu - - # Signal handler - still try to complete cleanup even if cancelled again - trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT + set +e for attempt in $(seq 1 5); do echo "Attempting to execute subnetdelegator DELETE command: $attempt/5" script --return --quiet -c "az containerapp exec -n subnetdelegator-westus-u3h4j -g subnetdelegator-westus --command 'curl -X DELETE http://localhost:8080/DelegatedSubnet/%2Fsubscriptions%2F9b8218f9-902a-4d20-a65c-e98acec5362f%2FresourceGroups%2F$RESOURCE_GROUP_NAME%2Fproviders%2FMicrosoft.Network%2FvirtualNetworks%2Fcustvnet%2Fsubnets%2Fscaledel'" /dev/null && break || echo "Command failed, retrying..." sleep 30 done + + exit 0 displayName: "Delete SAL Ping" condition: and(always(), eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true')) continueOnError: true @@ -44,9 +43,7 @@ steps: scriptType: bash scriptLocation: inlineScript inlineScript: | - set -eu - - trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT + set +e export RG="$RESOURCE_GROUP_NAME" export AZURE_SUBSCRIPTION_ID="$(AZURE_SUBSCRIPTION_ID)" @@ -56,10 +53,12 @@ steps: SCRIPT_PATH="$(Build.SourcesDirectory)/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh" if [[ -f "$SCRIPT_PATH" ]]; then chmod +x "$SCRIPT_PATH" - "$SCRIPT_PATH" || echo "Cleanup script completed with warnings" + "$SCRIPT_PATH" else echo "WARNING: Cleanup script not found at $SCRIPT_PATH" fi + + exit 0 - task: AzureCLI@2 displayName: "Force Cleanup Azure Resources" @@ -70,9 +69,7 @@ steps: scriptType: bash scriptLocation: inlineScript inlineScript: | - set -eu - - trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT + set +e export RG="$RESOURCE_GROUP_NAME" export AZURE_SUBSCRIPTION_ID="$(AZURE_SUBSCRIPTION_ID)" @@ -80,10 +77,12 @@ steps: SCRIPT_PATH="$(Build.SourcesDirectory)/swiftv2kubeobjects/cleanup-azure-resources.sh" if [[ -f "$SCRIPT_PATH" ]]; then chmod +x "$SCRIPT_PATH" - "$SCRIPT_PATH" || echo "Cleanup script completed with warnings" + "$SCRIPT_PATH" else echo "WARNING: Cleanup script not found at $SCRIPT_PATH" fi + + exit 0 - task: AzureCLI@2 displayName: "Destroy Resource Group" @@ -94,9 +93,7 @@ steps: scriptType: bash scriptLocation: inlineScript inlineScript: | - set -eu - - trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT + set +e # Set the Azure subscription export AZURE_SUBSCRIPTION_ID="$(AZURE_SUBSCRIPTION_ID)" @@ -117,3 +114,5 @@ steps: fi fi done + + exit 0 \ No newline at end of file diff --git a/swiftv2kubeobjects/cleanup-azure-resources.sh b/swiftv2kubeobjects/cleanup-azure-resources.sh index 7983e6c6ba..f28bafe0b4 100755 --- a/swiftv2kubeobjects/cleanup-azure-resources.sh +++ b/swiftv2kubeobjects/cleanup-azure-resources.sh @@ -1,5 +1,8 @@ #!/bin/bash -set -euo pipefail +# NOTE: This script is designed to be resilient - it will continue on errors +# since this is a cleanup script and we want to attempt all cleanup steps. +# We use 'set +e' to prevent the script from exiting on failures. +set +e # ============================================================================= # Cleanup script for Azure resources before resource group deletion @@ -35,8 +38,9 @@ fi echo "Setting Azure subscription to: $AZURE_SUBSCRIPTION_ID" az account set --subscription "$AZURE_SUBSCRIPTION_ID" -# Set up cancellation trap (continue cleanup even if cancelled) -trap 'echo "Cleanup received cancellation signal but will attempt to continue"; sleep 2' SIGTERM SIGINT +# NOTE: We intentionally do NOT trap SIGTERM/SIGINT here. +# This cleanup script should run to completion even if the pipeline is cancelled, +# as it helps free up resources. # ============================================================================= # MAIN CLEANUP @@ -129,3 +133,6 @@ echo "" echo "===================================================================" echo "Pre-cleanup completed" echo "===================================================================" + +# Always exit with 0 - this is a cleanup script and we want subsequent steps to run +exit 0 \ No newline at end of file diff --git a/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh index 272cc0a390..1b56209594 100755 --- a/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh +++ b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh @@ -1,5 +1,8 @@ #!/bin/bash -set -euo pipefail +# NOTE: This script is designed to be resilient - it will continue on errors +# since subsequent scripts will cleanup the AKS cluster and resource group anyway. +# We use 'set +e' to prevent the script from exiting on failures. +set +e # ============================================================================= # Cleanup script for swiftv2 workloads and nodepools @@ -32,6 +35,7 @@ RG="${RG:-${RESOURCE_GROUP_NAME:-}}" GROUP_NAME=${GROUP_NAME:-deployment-churn} DELETE_NODEPOOLS=${DELETE_NODEPOOLS:-true} DELETE_BUFFER_POOL=${DELETE_BUFFER_POOL:-true} +CLEANUP_BATCH_SIZE=${CLEANUP_BATCH_SIZE:-500} # Validate required inputs if [[ -z "$RG" ]]; then @@ -48,11 +52,11 @@ fi echo "Setting Azure subscription to: $AZURE_SUBSCRIPTION_ID" az account set --subscription "$AZURE_SUBSCRIPTION_ID" -# Set up cancellation trap -trap handle_cancellation SIGTERM SIGINT +# NOTE: We intentionally do NOT trap SIGTERM/SIGINT here. +# This cleanup script should run to completion even if the pipeline is cancelled, +# as it helps free up resources. Subsequent scripts will cleanup cluster/RG anyway. # ============================================================================= -# CLUSTER DISCOVERY # ============================================================================= echo "===================================================================" @@ -89,42 +93,142 @@ echo "===================================================================" # Delete deployments with the deployment-churn group label pattern # These are created by both static and dynamic configs with pattern: # group={{$groupName}}-job{{$jobIndex}}-{{$j}} -echo "Deleting deployments with label selector: podgroup=$GROUP_NAME" +# staticres: 1 deployment = 1 pod +# dynamicres: 1 deployment = N pods (pods_per_step, typically 50) +# We batch delete targeting ~CLEANUP_BATCH_SIZE pods at a time for consistent behavior +echo "Deleting deployments with label selector: podgroup=$GROUP_NAME (batch size: $CLEANUP_BATCH_SIZE)" # Get all namespaces matching slo-job prefix (slo-job0-1, slo-job1-1, etc.) for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo-job" | cut -d/ -f2 || true); do - if ! check_cancellation; then - exit 143 + echo "" + echo "Processing namespace: $ns" + + # Get deployment names and their replica counts (pod count) + # Format: "deployment-name replica-count" per line + deployments_info=$(kubectl get deployments -n "$ns" -l "podgroup=$GROUP_NAME" \ + -o jsonpath='{range .items[*]}{.metadata.name}{" "}{.spec.replicas}{"\n"}{end}' 2>/dev/null || true) + + if [[ -z "$deployments_info" ]]; then + echo " No deployments found in namespace $ns" + continue fi - echo "Processing namespace: $ns" + total_deployments=$(echo "$deployments_info" | wc -l) + total_pods=$(echo "$deployments_info" | awk '{sum += $2} END {print sum}') + echo " Found $total_deployments deployments with $total_pods total pods" + + # Batch deployments by pod count (target ~500 pods per batch) + batch_deployments="" + batch_pod_count=0 + batch_num=1 + deleted_pods=0 + + while IFS= read -r line; do + dep_name=$(echo "$line" | awk '{print $1}') + dep_replicas=$(echo "$line" | awk '{print $2}') + + # Handle empty or invalid lines + if [[ -z "$dep_name" || -z "$dep_replicas" ]]; then + continue + fi + + # Add deployment to current batch + batch_deployments="$batch_deployments $dep_name" + batch_pod_count=$((batch_pod_count + dep_replicas)) + + # If batch reaches target pod count, delete the batch + if [[ $batch_pod_count -ge $CLEANUP_BATCH_SIZE ]]; then + echo " Deleting batch $batch_num (~$batch_pod_count pods)..." + retry_command 3 5 "kubectl delete deployments -n $ns $batch_deployments --wait=false" || true + deleted_pods=$((deleted_pods + batch_pod_count)) + + # Reset batch + batch_deployments="" + batch_pod_count=0 + batch_num=$((batch_num + 1)) + + # Small delay between batches to avoid API throttling + sleep 1 + fi + done <<< "$deployments_info" - # Delete deployments matching the pattern (deployment-churn-job*) - deployments=$(kubectl get deployments -n "$ns" -l "podgroup=$GROUP_NAME" -o name 2>/dev/null || true) - if [[ -n "$deployments" ]]; then - echo "Deleting deployments in namespace $ns:" - echo "$deployments" - kubectl delete deployments -n "$ns" -l "podgroup=$GROUP_NAME" --wait=false || true + # Delete remaining deployments in the last batch + if [[ -n "$batch_deployments" ]]; then + echo " Deleting final batch $batch_num (~$batch_pod_count pods)..." + retry_command 3 5 "kubectl delete deployments -n $ns $batch_deployments --wait=false" || true + deleted_pods=$((deleted_pods + batch_pod_count)) fi - # Also delete any remaining pods with the podgroup label - pods=$(kubectl get pods -n "$ns" -l "podgroup=$GROUP_NAME" -o name 2>/dev/null || true) - if [[ -n "$pods" ]]; then - echo "Deleting remaining pods in namespace $ns with label podgroup=$GROUP_NAME" + echo " Initiated deletion for $deleted_pods pods across $batch_num batches in namespace $ns" + + # Force delete any remaining pods that might be orphaned + remaining_pods=$(kubectl get pods -n "$ns" -l "podgroup=$GROUP_NAME" --no-headers 2>/dev/null | wc -l || echo "0") + if [[ "$remaining_pods" -gt 0 ]]; then + echo " Force deleting $remaining_pods remaining pods..." kubectl delete pods -n "$ns" -l "podgroup=$GROUP_NAME" --grace-period=0 --force 2>/dev/null || true fi -done -# Wait for deployments to be deleted -echo "Waiting for deployments to be fully deleted..." -sleep 30 + # Wait for deployments to terminate + echo " Waiting for deployments in $ns to terminate..." + kubectl wait --for=delete deployment -n "$ns" -l "podgroup=$GROUP_NAME" --timeout=300s 2>/dev/null || true -for ns in $(kubectl get namespaces -o name 2>/dev/null | grep "namespace/slo-job" | cut -d/ -f2 || true); do - remaining=$(kubectl get deployments -n "$ns" -l "podgroup=$GROUP_NAME" --no-headers 2>/dev/null | wc -l || echo "0") - if [[ "$remaining" -gt 0 ]]; then - echo "Waiting for $remaining deployments to terminate in namespace $ns..." - kubectl wait --for=delete deployment -n "$ns" -l "podgroup=$GROUP_NAME" --timeout=300s 2>/dev/null || true + # Delete PNIs (Pod Network Instances) in batches + # PNIs are created with names like: pod-network-instance-job0-0, pod-network-instance-job0-1-0, etc. + echo " Checking for PNIs to delete..." + pni_names=$(kubectl get podnetworkinstances -n "$ns" -o jsonpath='{range .items[*]}{.metadata.name}{"\n"}{end}' 2>/dev/null || true) + + if [[ -n "$pni_names" ]]; then + total_pnis=$(echo "$pni_names" | wc -l) + echo " Found $total_pnis PNIs to delete" + + # Batch PNIs for deletion (500 at a time) + batch_pnis="" + batch_pni_count=0 + pni_batch_num=1 + deleted_pnis=0 + + while IFS= read -r pni_name; do + # Handle empty lines + if [[ -z "$pni_name" ]]; then + continue + fi + + batch_pnis="$batch_pnis $pni_name" + batch_pni_count=$((batch_pni_count + 1)) + + # If batch reaches target count, delete the batch + if [[ $batch_pni_count -ge $CLEANUP_BATCH_SIZE ]]; then + echo " Deleting PNI batch $pni_batch_num ($batch_pni_count PNIs)..." + retry_command 3 5 "kubectl delete podnetworkinstances -n $ns $batch_pnis --wait=false" || true + deleted_pnis=$((deleted_pnis + batch_pni_count)) + + # Reset batch + batch_pnis="" + batch_pni_count=0 + pni_batch_num=$((pni_batch_num + 1)) + + # Small delay between batches + sleep 1 + fi + done <<< "$pni_names" + + # Delete remaining PNIs in the last batch + if [[ -n "$batch_pnis" ]]; then + echo " Deleting final PNI batch $pni_batch_num ($batch_pni_count PNIs)..." + retry_command 3 5 "kubectl delete podnetworkinstances -n $ns $batch_pnis --wait=false" || true + deleted_pnis=$((deleted_pnis + batch_pni_count)) + fi + + echo " Initiated deletion for $deleted_pnis PNIs across $pni_batch_num batches" + + # Wait for PNIs to be deleted + echo " Waiting for PNIs in $ns to terminate..." + kubectl wait --for=delete podnetworkinstances -n "$ns" --all --timeout=300s 2>/dev/null || true + else + echo " No PNIs found in namespace $ns" fi + + echo " Namespace $ns cleanup complete" done # ============================================================================= @@ -155,11 +259,6 @@ if [[ "$DELETE_NODEPOOLS" == "true" ]]; then user_pools_sorted=$(echo "$user_pools" | tr ' ' '\n' | grep -v '^$' | sort -t'l' -k2 -rn || true) for pool_name in $user_pools_sorted; do - if ! check_cancellation; then - echo "ERROR: Pipeline cancelled before deleting nodepool $pool_name" - exit 143 - fi - echo "" echo "Deleting nodepool: $pool_name" @@ -178,11 +277,6 @@ if [[ "$DELETE_NODEPOOLS" == "true" ]]; then # Delete buffer pool last if requested if [[ "$DELETE_BUFFER_POOL" == "true" && -n "$buffer_pool" ]]; then - if ! check_cancellation; then - echo "ERROR: Pipeline cancelled before deleting buffer nodepool" - exit 143 - fi - echo "" echo "Deleting buffer nodepool: $buffer_pool" @@ -223,3 +317,6 @@ done echo "" echo "Done!" + +# Always exit with 0 - subsequent scripts will cleanup the cluster/RG anyway +exit 0 \ No newline at end of file From 930aff8f3134fdd9460363ccc08a4c9955c2c1e1 Mon Sep 17 00:00:00 2001 From: Isaac Date: Sat, 31 Jan 2026 16:16:35 +0000 Subject: [PATCH 44/47] fix: dynamicres add missing podgroup label in deployment metadata --- .../swiftv2-slo/config/swiftv2_deployment_template.yaml | 1 + 1 file changed, 1 insertion(+) diff --git a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_template.yaml b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_template.yaml index bbd7a45e42..85ca557100 100644 --- a/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_template.yaml +++ b/modules/python/clusterloader2/swiftv2-slo/config/swiftv2_deployment_template.yaml @@ -4,6 +4,7 @@ metadata: name: {{.Name}} labels: group: {{.Group}} + podgroup: {{.PodGroup}} kubernetes.azure.com/pod-network: pn100 kubernetes.azure.com/pod-network-instance: {{.pniName}} spec: From f17f59a3fcde1e383b0837bccb4f90ee6521466a Mon Sep 17 00:00:00 2001 From: Isaac Date: Sat, 31 Jan 2026 21:57:41 +0000 Subject: [PATCH 45/47] fix(prepull): add label verification before DaemonSet creation - Add verify_node_labels() function to aks-utils.sh for reusable label verification across scripts - Verify batch nodes have both swiftv2slo=true AND batch label before creating prepull DaemonSet to prevent scheduling failures - Add warning when DaemonSet desired count doesn't match verified count - Skip batch if no nodes have both required labels This fixes a race condition where nodes could be labeled with the batch label but not yet have swiftv2slo=true visible to the scheduler, causing pods to fail with NodeAffinity errors. --- .../clusterloader2/swiftv2-slo/aks-utils.sh | 44 +++++++++++++++++++ .../swiftv2-slo/prepull-images.sh | 30 +++++++++++-- 2 files changed, 71 insertions(+), 3 deletions(-) diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index 7dd5b3891b..e5bd3376b1 100755 --- a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh @@ -250,6 +250,50 @@ function label_nodes_with_retry() { return 1 } +# Verify that nodes have specific labels visible to the API server +# Useful after labeling to ensure labels have propagated before dependent operations +# Usage: verify_node_labels +# Example: verify_node_labels 100 60 "swiftv2slo=true,image-prepull-batch-0=true" +# Returns: 0 if expected count reached, 1 if timeout +# Sets: VERIFIED_NODE_COUNT with actual count of matching nodes +function verify_node_labels() { + local expected_count=$1 + local max_wait=${2:-60} # Default 60 seconds + local label_selector=$3 + + if [ -z "$label_selector" ]; then + log_error "verify_node_labels: label_selector is required" + return 1 + fi + + log_info "Verifying node labels: expecting $expected_count nodes with selector '$label_selector'..." + + local verify_interval=5 + local verify_elapsed=0 + VERIFIED_NODE_COUNT=0 + + while [ $verify_elapsed -lt $max_wait ]; do + VERIFIED_NODE_COUNT=$(kubectl get nodes -l "$label_selector" --no-headers 2>/dev/null | wc -l | tr -d ' ') + + if [ "$VERIFIED_NODE_COUNT" -ge "$expected_count" ]; then + log_info " ✓ Verified: $VERIFIED_NODE_COUNT nodes match selector (expected: $expected_count)" + return 0 + fi + + if [ $verify_elapsed -eq 0 ]; then + log_info " Waiting for label propagation: $VERIFIED_NODE_COUNT/$expected_count visible..." + elif [ $((verify_elapsed % 15)) -eq 0 ]; then + log_info " Label propagation progress: $VERIFIED_NODE_COUNT/$expected_count visible (${verify_elapsed}s)" + fi + + sleep $verify_interval + verify_elapsed=$((verify_elapsed + verify_interval)) + done + + log_warning " Label verification timeout: only $VERIFIED_NODE_COUNT/$expected_count nodes visible after ${max_wait}s" + return 1 +} + # Batch label nodes in parallel for performance # Usage: batch_label_nodes "=" node1 node2 node3 ... # Returns: 0 on success, 1 on failure diff --git a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh index a2503d2ac4..6da7cee57c 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh +++ b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh @@ -194,6 +194,7 @@ function prepull_images_on_nodes() { # Label nodes in this batch with temporary batch label local batch_label="image-prepull-batch-$batch_idx=true" + local batch_label_key="image-prepull-batch-$batch_idx" log_info "Labeling $batch_node_count nodes with $batch_label..." # Use common utility with retry - but for batch labels we can be lenient @@ -201,6 +202,24 @@ function prepull_images_on_nodes() { log_warning "Some batch label operations failed, but continuing with available nodes" fi + # Verify batch labels are visible to the API server before creating DaemonSet + # This addresses race conditions where labels are accepted but not yet propagated + local label_selector="swiftv2slo=true,${batch_label_key}=true" + if ! verify_node_labels "$batch_node_count" 60 "$label_selector"; then + log_warning " This may indicate nodes don't have swiftv2slo=true label. Continuing with $VERIFIED_NODE_COUNT nodes..." + + if [ "$VERIFIED_NODE_COUNT" -eq 0 ]; then + log_error " No nodes have both labels - skipping this batch" + # Clean up batch labels before continuing + log_info " Cleaning up batch labels..." + for node in "${batch_nodes[@]}"; do + kubectl label node "$node" "${batch_label_key}-" --overwrite >/dev/null 2>&1 || true + done + continue + fi + fi + local verified_count=$VERIFIED_NODE_COUNT + # Process each image sequentially to avoid overwhelming registry local batch_ds_names=() local image_delay=${IMAGE_PREPULL_IMAGE_DELAY:-5} @@ -216,9 +235,7 @@ function prepull_images_on_nodes() { log_info "Creating DaemonSet '$ds_name' for image $image_num/${#images_to_pull[@]} in batch $batch_num..." log_info " Image: $img" - - # Extract label key and value for DaemonSet selector - local batch_label_key="image-prepull-batch-$batch_idx" + log_info " Target nodes: $verified_count (with swiftv2slo=true AND $batch_label_key=true)" # Generate DaemonSet from template with batch-specific node selector sed -e "s|IMAGE_PREPULL_NAMESPACE|$prepull_ns|g" \ @@ -243,6 +260,7 @@ function prepull_images_on_nodes() { local img_completed=false local img_last_ready=0 local img_stalled=0 + local desired_mismatch_logged=false while [ $img_elapsed -lt $img_max_wait ]; do local ds_info @@ -251,6 +269,12 @@ function prepull_images_on_nodes() { local desired=$(echo "$ds_info" | jq -r '.status.desiredNumberScheduled // 0') local ready=$(echo "$ds_info" | jq -r '.status.numberReady // 0') + # Warn if desired doesn't match verified count (indicates label mismatch) + if [ "$desired_mismatch_logged" = false ] && [ "$desired" -gt 0 ] && [ "$desired" -lt "$verified_count" ]; then + log_warning " DaemonSet desired=$desired but verified_count=$verified_count - some nodes may have lost labels" + desired_mismatch_logged=true + fi + if [ "$ready" -eq "$desired" ] && [ $desired -gt 0 ]; then log_info " ✓ Image $image_num completed: $ready/$desired pods ready (${img_elapsed}s)" img_completed=true From 1262d21d2b4d9f5d25dd24829b0280ad0f83350a Mon Sep 17 00:00:00 2001 From: Isaac Date: Sat, 31 Jan 2026 22:12:35 +0000 Subject: [PATCH 46/47] feat(cleanup): add SLOW_DELETE flag to control swiftv2 workload cleanup - Add SLOW_DELETE variable to pipeline (default: false) - Add condition in cleanup-resources.yml to skip workload cleanup when SLOW_DELETE is not true - When disabled, relies on cluster/RG deletion for cleanup - Enables graceful cleanup of deployments, pods, and PNIs when set to true --- pipelines/system/new-pipeline-test.yml | 3 +++ steps/cleanup-resources.yml | 2 +- 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index f343ceca1d..b69752b908 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -3,6 +3,9 @@ trigger: none variables: # Cleanup control - set to false to keep resources after pipeline completes CLEANUP: "true" + # Slow delete - when true, runs the swiftv2 workload cleanup script for graceful deletion + # This is slower but ensures proper cleanup of deployments, pods, and PNIs before nodepool deletion + SLOW_DELETE: "false" # Hardcoded ADO pipeline variables AZURE_SUBSCRIPTION_ID: "37deca37-c375-4a14-b90a-043849bd2bf1" diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index dea065ed8e..c634b9adc1 100644 --- a/steps/cleanup-resources.yml +++ b/steps/cleanup-resources.yml @@ -36,7 +36,7 @@ steps: - task: AzureCLI@2 displayName: "Cleanup Swiftv2 Workloads" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['SLOW_DELETE'], 'true')) continueOnError: true inputs: azureSubscription: $(AZURE_SERVICE_CONNECTION) From 4b46d404f7f3b2be690cbee19269a83bc2acc5e2 Mon Sep 17 00:00:00 2001 From: Isaac Date: Sun, 1 Feb 2026 04:48:40 +0000 Subject: [PATCH 47/47] fix(pipeline): increase max_pods to 13 to account for azuresecuritylinuxagent The azuresecuritylinuxagent DaemonSet runs on all nodes, consuming 1 pod slot per node. Updated max_pods from 12 to 13 to accommodate: - 5 kube-system DaemonSet pods - 1 azuresecuritylinuxagent pod - 7 deployment churn workload pods --- pipelines/system/new-pipeline-test.yml | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index b69752b908..eb3c8246eb 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -40,9 +40,9 @@ variables: # CL2 parameters cpu_per_node: 16 - # max_pods = PODS_PER_NODE + default k8s system pods (5) + log analytics pod (1 if ENABLE_LOG_ANALYTICS=true) - # Current: 7 + 5 = 12 (increase to 13 if enabling Log Analytics) - max_pods: 12 + # max_pods = PODS_PER_NODE + default k8s system pods (5) + azuresecuritylinuxagent (1) + log analytics pod (1 if ENABLE_LOG_ANALYTICS=true) + # Current: 7 + 5 + 1 = 13 (increase to 14 if enabling Log Analytics) + max_pods: 13 # Common matrix parameters repeats: 1 node_label: "swiftv2slo=true"