diff --git a/docs/running-swiftv2-pipeline.md b/docs/running-swiftv2-pipeline.md index dd5aa56b73..b69ed56cec 100644 --- a/docs/running-swiftv2-pipeline.md +++ b/docs/running-swiftv2-pipeline.md @@ -6,18 +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, CLEANUP_RESOURCES etc. -- 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 + +## Pipeline Architecture + +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) + +### Run ID and Job Isolation + +- **`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 + +This ensures test results don't overwrite each other while sharing infrastructure. + +### Cleanup Behavior + +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 + +To preserve resources for debugging, set `CLEANUP: "false"` in the pipeline variables. ## Kusto diff --git a/jobs/cleanup.yml b/jobs/cleanup.yml new file mode 100644 index 0000000000..fdd9aa5dbf --- /dev/null +++ b/jobs/cleanup.yml @@ -0,0 +1,50 @@ +parameters: +- name: cloud + type: string +- name: regions + type: object +- name: credential_type + type: string + default: service_connection +- name: dependsOn + type: object + default: [] + +jobs: +- job: cleanup + dependsOn: ${{ parameters.dependsOn }} + 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 + 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" + + - ${{ 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 5164d83ece..d8dc4ddd0a 100644 --- a/jobs/competitive-test.yml +++ b/jobs/competitive-test.yml @@ -15,27 +15,12 @@ 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: '' - 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 @@ -51,9 +36,17 @@ parameters: - name: ssh_key_enabled type: boolean default: true +- name: dependsOn + type: object + default: [] 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: @@ -64,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 }} @@ -73,10 +65,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 }} - template: /steps/validate-resources.yml @@ -100,10 +88,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 }} - terraform_arguments: ${{ parameters.terraform_arguments }} - retry_attempt_count: ${{ parameters.retry_attempt_count }} - credential_type: ${{ parameters.credential_type }} 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 bd73281043..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 @@ -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}} +{{$actualPodsThisJob := MaxInt $deltaPods 0}} {{$steps := DefaultParam .CL2_STEPS 1}} {{$latencyPodCpu := DefaultParam .CL2_LATENCY_POD_CPU 10}} {{$latencyPodMemory := DefaultParam .CL2_LATENCY_POD_MEMORY 50}} @@ -15,10 +18,11 @@ name: deployment-churn {{$probeTimeout := .CL2_PROBE_TIMEOUT}} {{$datapathReporterImage := .CL2_DATAPATH_REPORTER_IMAGE}} {{$nginxImage := .CL2_NGINX_IMAGE}} +{{$jobIndex := .CL2_JOB_INDEX}} namespace: number: 1 - prefix: slo + prefix: slo-job{{$jobIndex}} deleteStaleNamespaces: false deleteAutomanagedNamespaces: false enableExistingNamespaces: false @@ -46,7 +50,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}}, existing_pods={{$existingPods}}, delta_pods={{$deltaPods}}, actual_pods_this_job={{$actualPodsThisJob}} measurements: - Identifier: Dummy Method: Sleep @@ -61,7 +65,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 +78,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 +99,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 +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}} @@ -114,7 +118,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 +128,17 @@ 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}} + PodGroupJob: {{$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 +153,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 +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 41a3d4ff2d..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,8 +4,9 @@ metadata: name: {{.Name}} labels: 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}} spec: replicas: 1 selector: @@ -19,8 +20,9 @@ spec: name: {{.Name}} group: {{.Group}} podgroup: {{.PodGroup}} + podgroup-job: {{.PodGroupJob}} 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..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 @@ -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}} +{{$actualPodsThisJob := MaxInt $deltaPods 0}} +{{$numPNIsPerStep := DivideInt $podsPerStep $podsPerPNI}} {{$steps := DefaultParam .CL2_STEPS 1}} {{$latencyPodCpu := DefaultParam .CL2_LATENCY_POD_CPU 10}} {{$latencyPodMemory := DefaultParam .CL2_LATENCY_POD_MEMORY 50}} @@ -17,10 +20,11 @@ name: deployment-churn {{$probeTimeout := .CL2_PROBE_TIMEOUT}} {{$datapathReporterImage := .CL2_DATAPATH_REPORTER_IMAGE}} {{$nginxImage := .CL2_NGINX_IMAGE}} +{{$jobIndex := .CL2_JOB_INDEX}} namespace: number: 1 - prefix: slo + prefix: slo-job{{$jobIndex}} deleteStaleNamespaces: false deleteAutomanagedNamespaces: false enableExistingNamespaces: false @@ -48,7 +52,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}}, existing_pods={{$existingPods}}, delta_pods={{$deltaPods}}, actual_pods_this_job={{$actualPodsThisJob}} measurements: - Identifier: Dummy Method: Sleep @@ -61,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}} @@ -69,10 +73,10 @@ steps: - namespaceRange: min: 1 max: 1 - replicasPerNamespace: {{$numPNIs}} + replicasPerNamespace: {{$numPNIsPerStep}} tuningSet: DeploymentCreateQps objectBundle: - - basename: pod-network-instance-{{$j}} + - basename: pod-network-instance-job{{$jobIndex}}-{{$j}} objectTemplatePath: pni_static_template.yaml templateFillMap: ReservationSize: {{$podsPerPNI}} @@ -87,8 +91,8 @@ steps: - basename: pni-checker-{{$j}} objectTemplatePath: pni_readiness_checker_unified_template.yaml templateFillMap: - PNIPrefix: pod-network-instance-{{$j}}- - NumPNIs: {{$numPNIs}} + PNIPrefix: pod-network-instance-job{{$jobIndex}}-{{$j}}- + NumPNIs: {{$numPNIsPerStep}} - name: Wait for PNI Readiness Checker to Complete -{{$j}} measurements: - Identifier: WaitForPNIChecker-{{$j}} @@ -108,8 +112,8 @@ steps: - basename: pni-checker-{{$j}} objectTemplatePath: pni_readiness_checker_unified_template.yaml templateFillMap: - PNIPrefix: pod-network-instance-{{$j}}- - NumPNIs: {{$numPNIs}} + PNIPrefix: pod-network-instance-job{{$jobIndex}}-{{$j}}- + NumPNIs: {{$numPNIsPerStep}} - name: Starting Deployment Latency Measurements -{{$j}} measurements: - Identifier: WaitForControlledPodsRunning-{{$j}} @@ -118,7 +122,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 +132,18 @@ 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}} + Group: {{$groupName}}-job{{$jobIndex}}-{{$j}} PodGroup: {{$groupName}} + PodGroupJob: {{$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 +158,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 +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..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: @@ -19,6 +20,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}} diff --git a/modules/python/clusterloader2/swiftv2-slo/slo.py b/modules/python/clusterloader2/swiftv2-slo/slo.py index 756cad922b..4ea3847221 100644 --- a/modules/python/clusterloader2/swiftv2-slo/slo.py +++ b/modules/python/clusterloader2/swiftv2-slo/slo.py @@ -47,10 +47,12 @@ 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 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: @@ -61,6 +63,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") @@ -98,6 +101,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") @@ -261,6 +269,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") @@ -304,7 +313,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 f4f6748b13..9bef258160 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-burst-matrix.yml @@ -17,53 +17,36 @@ parameters: type: string - name: ssh_key_enabled type: boolean -- name: base_run_id - type: string +- name: dependsOn + type: object + default: [] - 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 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 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 + 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 + 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 @@ -78,4 +61,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 b670bbebb9..1fa690ccb7 100644 --- a/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-dynamicres-gradual-matrix.yml @@ -17,17 +17,12 @@ parameters: type: string - name: ssh_key_enabled type: boolean -- name: base_run_id - type: string +- name: dependsOn + type: object + default: [] - 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 @@ -40,29 +35,17 @@ parameters: 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 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 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: @@ -78,4 +61,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 0709214d7d..424e2a4c50 100644 --- a/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-burst-matrix.yml @@ -17,39 +17,12 @@ parameters: type: string - name: ssh_key_enabled type: boolean -- name: base_run_id - type: string +- name: dependsOn + type: object + default: [] - 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 @@ -57,13 +30,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 - 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 @@ -71,6 +37,20 @@ 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 + ppp=1_pods=10500_nodes=1500: + node_count: 1500 + pods_per_step: 1500 + pods_per_pni: 1 + 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 + 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 @@ -85,4 +65,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 3a8347decf..d28d99e990 100644 --- a/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml +++ b/pipelines/system/matrices/swiftv2-staticres-gradual-matrix.yml @@ -17,18 +17,12 @@ parameters: type: string - name: ssh_key_enabled type: boolean -- name: base_run_id - type: string +- name: dependsOn + type: object + default: [] - 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 @@ -43,33 +37,19 @@ 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 - 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 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 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: @@ -85,4 +65,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 432045663e..eb3c8246eb 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -1,6 +1,12 @@ 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" SKIP_RESOURCE_MANAGEMENT: "false" @@ -9,7 +15,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 @@ -35,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" @@ -47,44 +52,15 @@ 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'] ] 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,17 +74,30 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $(BASE_RUN_ID) + dependsOn: + - generate_run_id + - template: /jobs/cleanup.yml + parameters: + cloud: azure + regions: + - $(LOCATION) + credential_type: service_connection + dependsOn: + - generate_run_id + - azure - 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'] ] 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,15 +111,28 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $(BASE_RUN_ID) + dependsOn: + - generate_run_id + - template: /jobs/cleanup.yml + parameters: + cloud: azure + regions: + - $(LOCATION) + credential_type: service_connection + dependsOn: + - generate_run_id + - azure - 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'] ] 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,15 +146,28 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $(BASE_RUN_ID) + dependsOn: + - generate_run_id + - template: /jobs/cleanup.yml + parameters: + cloud: azure + regions: + - $(LOCATION) + credential_type: service_connection + dependsOn: + - generate_run_id + - azure - 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'] ] 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,4 +181,14 @@ stages: timeout_in_minutes: 2160 credential_type: service_connection ssh_key_enabled: false - base_run_id: $(BASE_RUN_ID) + dependsOn: + - generate_run_id + - template: /jobs/cleanup.yml + parameters: + cloud: azure + regions: + - $(LOCATION) + credential_type: service_connection + dependsOn: + - generate_run_id + - azure diff --git a/steps/cleanup-resources.yml b/steps/cleanup-resources.yml index 63db3634d9..c634b9adc1 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 @@ -17,152 +14,105 @@ parameters: steps: - script: | echo "===================================================================" - echo "Starting cleanup process for Run ID: $RUN_ID" + 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() - -- 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 - - # 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$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 + + exit 0 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')) 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 $RUN_ID 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') }}, eq(variables['SLOW_DELETE'], 'true')) + continueOnError: true + inputs: + azureSubscription: $(AZURE_SERVICE_CONNECTION) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set +e - 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 + export RG="$RESOURCE_GROUP_NAME" + export AZURE_SUBSCRIPTION_ID="$(AZURE_SUBSCRIPTION_ID)" + export DELETE_NODEPOOLS="true" + export DELETE_BUFFER_POOL="true" - 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 $RUN_ID --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 - 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 $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 - 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 - 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 - 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 - 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 - echo "Deleting NAT Gateway: $natgw" - retry_command "az network nat gateway delete -g $RUN_ID -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 - echo "Deleting NSG: $nsg" - retry_command "az network nsg delete -g $RUN_ID -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 - echo "Deleting Public IP: $pip" - retry_command "az network public-ip delete -g $RUN_ID -n $pip" || true - done - - echo "Pre-cleanup completed" + SCRIPT_PATH="$(Build.SourcesDirectory)/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh" + if [[ -f "$SCRIPT_PATH" ]]; then + chmod +x "$SCRIPT_PATH" + "$SCRIPT_PATH" + else + echo "WARNING: Cleanup script not found at $SCRIPT_PATH" + fi + + exit 0 + +- task: AzureCLI@2 displayName: "Force Cleanup Azure Resources" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['CLEANUP_RESOURCES'], 'true')) + 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 $RUN_ID" - # 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 - echo "Resource group deleted successfully" - break + inputs: + azureSubscription: $(AZURE_SERVICE_CONNECTION) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set +e + + 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 + chmod +x "$SCRIPT_PATH" + "$SCRIPT_PATH" 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 + + exit 0 + +- task: AzureCLI@2 displayName: "Destroy Resource Group" - condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}, eq(variables['CLEANUP_RESOURCES'], 'true')) + condition: and(always(), ${{ eq(parameters.cloud, 'azure') }}) continueOnError: true + inputs: + azureSubscription: $(AZURE_SERVICE_CONNECTION) + scriptType: bash + scriptLocation: inlineScript + inlineScript: | + set +e + + # 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" -- ${{ if eq(variables['Build.SourceBranchName'], 'main') }}: - - template: /steps/collect-terraform-operation-metadata.yml - parameters: - cloud: ${{ parameters.cloud }} - credential_type: ${{ parameters.credential_type }} + 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 + + exit 0 \ No newline at end of file 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/cloud/azure/update-kubeconfig.yml b/steps/cloud/azure/update-kubeconfig.yml index 50f8cf5e10..68a7131d54 100644 --- a/steps/cloud/azure/update-kubeconfig.yml +++ b/steps/cloud/azure/update-kubeconfig.yml @@ -10,17 +10,27 @@ steps: set -x 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" + 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..cad07d80f1 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 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")" \ @@ -49,6 +50,7 @@ steps: --arg byo_resources "$SKIP_RESOURCE_MANAGEMENT" \ '{ run_id: $run_id, + base_run_id: $base_run_id, timestamp: $timestamp, pipeline_info: { run_url: $run_url, 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 diff --git a/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh b/steps/engine/clusterloader2/swiftv2-slo/aks-utils.sh index 37d76f0ed5..e5bd3376b1 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 # ============================================================================= @@ -32,25 +38,35 @@ function find_aks_cluster() { local region=$1 local role=$2 + # 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" # 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 @@ -140,3 +156,177 @@ 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 +} + +# 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 +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/execute.yml b/steps/engine/clusterloader2/swiftv2-slo/execute.yml index 9712aaa182..58f9df53bd 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/execute.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/execute.yml @@ -16,10 +16,31 @@ 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 + # 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 @@ -27,7 +48,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} diff --git a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.sh index e441bd5649..6da7cee57c 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,33 @@ 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" + 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 + if ! label_nodes_with_retry "$batch_label" "${batch_nodes[@]}"; then + 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=() @@ -141,6 +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" + 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" \ @@ -148,7 +243,7 @@ function prepull_images_on_nodes() { -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 @@ -165,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 @@ -173,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 @@ -227,8 +329,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/prepull-images.yml b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml index d3a7a43f5d..9e805d783f 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/prepull-images.yml @@ -10,9 +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) 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.sh b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.sh index 332034e531..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 \ @@ -637,12 +660,33 @@ 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 + # 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' \ @@ -655,11 +699,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 @@ -680,84 +728,30 @@ 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)" - - # 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)" + log_info "Found $node_count unlabeled node(s) to label (need: $nodes_needed)" - 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)" + # 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 new nodes with swiftv2slo=true (total labeled: $total_labeled)" return 0 } @@ -779,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 @@ -1021,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]} @@ -1105,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'..." @@ -1136,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/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml index 5855556b10..d62f06ec44 100644 --- a/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml +++ b/steps/engine/clusterloader2/swiftv2-slo/scale-cluster.yml @@ -15,6 +15,5 @@ steps: env: REGION: ${{ parameters.region }} ROLE: ${{ parameters.role }} - RUN_ID: $(RUN_ID) displayName: "Scale Cluster" 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 fa00764f0d..bbb71a6a86 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 @@ -25,84 +11,86 @@ parameters: default: managed_identity 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 }} +# 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: | - 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 - 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" + + # 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 + 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 + displayName: "Ensure Resource Group" condition: and(${{ eq(parameters.cloud, 'azure') }}, ne(variables['SKIP_RESOURCE_MANAGEMENT'], 'true')) env: region: ${{ parameters.regions[0] }} - -- 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 displayName: "SetupCustomerResources" condition: eq(variables['CREATE_CUSTOMER_RESOURCES'], 'true') name: SetupCustomerResources + +- script: | + 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: + MAX_PODS: $(max_pods) + DEVICE_PLUGIN: $(DEVICE_PLUGIN) + - script: | - bash swiftv2kubeobjects/createclusterforping.sh - displayName: "SetupAKSMTClusterPING" + bash swiftv2kubeobjects/ensure-nodepools.sh + displayName: "EnsureUserNodepools" condition: eq(variables['CREATESWIFTV2PING'], 'true') - name: SetupAKSMTClusterPING env: - # Ensure these pipeline variables are available as env vars to the script + 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) \ No newline at end of file + DEVICE_PLUGIN: $(DEVICE_PLUGIN) + REGION: ${{ parameters.regions[0] }} + ROLE: slo \ No newline at end of file diff --git a/steps/setup-tests.yml b/steps/setup-tests.yml index 13c852983a..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 @@ -44,10 +41,26 @@ steps: fi 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 + 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 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) - script: | run_url="$(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)&view=logs&j=$(System.JobId)" 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/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-azure-resources.sh b/swiftv2kubeobjects/cleanup-azure-resources.sh new file mode 100755 index 0000000000..f28bafe0b4 --- /dev/null +++ b/swiftv2kubeobjects/cleanup-azure-resources.sh @@ -0,0 +1,138 @@ +#!/bin/bash +# 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 +# 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 + +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" + +# 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 +# ============================================================================= + +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 "===================================================================" + +# 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 new file mode 100755 index 0000000000..1b56209594 --- /dev/null +++ b/swiftv2kubeobjects/cleanup-swiftv2-workloads.sh @@ -0,0 +1,322 @@ +#!/bin/bash +# 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 +# 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} +CLEANUP_BATCH_SIZE=${CLEANUP_BATCH_SIZE:-500} + +# Validate required inputs +if [[ -z "$RG" ]]; then + echo "ERROR: RG or RESOURCE_GROUP_NAME environment variable is required" + 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" + +# 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. + +# ============================================================================= +# ============================================================================= + +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}} +# 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 + 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 + + 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 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 + + 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 + + # 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 + + # 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 + +# ============================================================================= +# 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 + 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 + 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-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 + +echo "" +echo "Done!" + +# Always exit with 0 - subsequent scripts will cleanup the cluster/RG anyway +exit 0 \ No newline at end of file diff --git a/swiftv2kubeobjects/createclusterforping.sh b/swiftv2kubeobjects/createclusterforping.sh index 38616bcd9a..a117ba7376 100755 --- a/swiftv2kubeobjects/createclusterforping.sh +++ b/swiftv2kubeobjects/createclusterforping.sh @@ -1,48 +1,26 @@ -# #!/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" + exit 1 +fi +RG="$RESOURCE_GROUP_NAME" +echo "Using resource group: $RG" -RG=$RUN_ID CLUSTER="large" SUBSCRIPTION=$AZURE_SUBSCRIPTION_ID NODEPOOLS=1 @@ -50,132 +28,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/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/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 fab6ec96a7..e614720ee5 100644 --- a/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml +++ b/swiftv2kubeobjects/datapath-observer/controller/manifests/deployment.yaml @@ -18,9 +18,8 @@ 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: - - "--namespace=slo-1" - "--label-selector=podgroup=deployment-churn" - "--max-concurrent-reconciles=100" ports: 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/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 new file mode 100755 index 0000000000..ad085f0d58 --- /dev/null +++ b/swiftv2kubeobjects/lib/nodepool.sh @@ -0,0 +1,155 @@ +#!/bin/bash + +# Nodepool helper library +# Depends on Azure CLI, jq, and common.sh for cancellation handling + +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() { + 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) + # Split space-separated labels into individual array elements + # shellcheck disable=SC2206 + nodepool_cmd+=($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 +}