Skip to content
Draft
31 changes: 31 additions & 0 deletions docs/verify.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,4 +81,35 @@ deactivate

## Verify End-to-End

### Attach/detach timeout and cleanup

The Azure CSI attach/detach engine accepts `engine_input.execution_timeout_minutes`.
The default is `0` (no process timeout); the QAD stage uses `60` minutes.
A process timeout fails the workload step instead of waiting for the whole job
to time out, leaving time for resource deletion.

On failure or timeout, the Azure workload step requests deletion of
`statefulset-local` and all PVCs in that execution's recorded test namespace.
It preserves the workload's failing exit code and reports Kubernetes cleanup
errors. Before allowing the step to finish, it waits up to 15 minutes for the
StatefulSet, pods, PVCs, namespace-associated PVs, and their VolumeAttachments
to disappear. It tracks PV names before deleting PVCs so attachment checks
remain scoped to this test, not other workloads. PV deletion relies on the
storage class reclaim policy and CSI finalizers for underlying disk deletion;
it is not a separate Azure disk-inventory check. Retained PVs or stuck
attachments cause an explicit cleanup error at the deadline, after which
cluster deletion runs as a fallback. Kubernetes requests have 30-second
timeouts and can extend the polling deadline slightly. This does not produce
successful detachment measurements. A forced agent termination can prevent
the cleanup trap from running.

Competitive jobs allow a 60-minute cancellation cleanup window. Terraform destroy
and Azure resource-group deletion run after failure or cancellation when their
setup variables are available, unless resource management or deletion was
explicitly skipped. Validate this behavior by running a short workload timeout
in a disposable pipeline run and confirming that both the cluster resource group
and AKS node resource group are deleted. Agent loss or exhaustion of the
cancellation window can still prevent cleanup; inspect Azure for remaining
resources in those cases.

To verify end-to-end functionality, you can run the E2E tests as described in the [E2E Testing Guide](e2e-testing.md). This will ensure that all components work together as expected across different cloud providers.
14 changes: 14 additions & 0 deletions jobs/competitive-test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,9 @@ parameters:
- name: ssh_key_enabled
type: boolean
default: true
- name: qad_enabled
type: boolean
default: false

jobs:
- job: ${{ parameters.cloud }}
Expand All @@ -56,6 +59,7 @@ jobs:
matrix:
${{ parameters.matrix }}
timeoutInMinutes: ${{ parameters.timeout_in_minutes }}
cancelTimeoutInMinutes: 60
condition: or(eq(variables['Build.Reason'], 'Manual'), and(eq(variables['Build.Reason'], 'Schedule'), eq(variables['Build.SourceBranchName'], 'main')))
steps:
- template: /steps/setup-tests.yml
Expand All @@ -67,6 +71,8 @@ jobs:
retry_attempt_count: ${{ parameters.retry_attempt_count }}
credential_type: ${{ parameters.credential_type }}
ssh_key_enabled: ${{ parameters.ssh_key_enabled }}
- ${{ if eq(parameters.qad_enabled, true) }}:
- template: /steps/cloud/azure/register-qad-features.yml
- template: /steps/provision-resources.yml
parameters:
cloud: ${{ parameters.cloud }}
Expand All @@ -76,6 +82,10 @@ jobs:
terraform_arguments: ${{ parameters.terraform_arguments }}
terraform_input_varibles: ${{ parameters.terraform_input_varibles }}
retry_attempt_count: ${{ parameters.retry_attempt_count }}
- ${{ if eq(parameters.qad_enabled, true) }}:
- template: /steps/cloud/azure/configure-and-validate-qad.yml
parameters:
region: ${{ parameters.regions[0] }}
- template: /steps/validate-resources.yml
parameters:
cloud: ${{ parameters.cloud }}
Expand All @@ -97,6 +107,10 @@ jobs:
regions: ${{ parameters.regions }}
engine_input: ${{ parameters.engine_input }}
credential_type: ${{ parameters.credential_type }}
- ${{ if eq(parameters.qad_enabled, true) }}:
- template: /steps/cloud/azure/cleanup-qad-role-assignment.yml
parameters:
region: ${{ parameters.regions[0] }}
- template: /steps/cleanup-resources.yml
parameters:
cloud: ${{ parameters.cloud }}
Expand Down
5 changes: 5 additions & 0 deletions modules/python/csi/csi.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,6 +131,11 @@ def execute_attach_detach(disk_number, storage_class, wait_time, result_dir):
namespace_obj = KUBERNETERS_CLIENT.create_namespace(namespace)
print(f"Created namespace {namespace_obj.metadata.name}")

namespace_file = os.environ.get("CSI_NAMESPACE_FILE")
if namespace_file:
with open(namespace_file, "w", encoding="utf-8") as file:
file.write(namespace)

# Start the timer
creation_start_time = datetime.now()

Expand Down
145 changes: 145 additions & 0 deletions modules/python/tests/test_attach_cleanup.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
"""Exercise the Azure attach step without contacting Kubernetes."""

import os
from pathlib import Path
import subprocess
import tempfile
import unittest

import yaml


class TestAttachCleanup(unittest.TestCase):
def run_step(self, status, namespace="test-12345", cleanup_status=0,
terminate=False, progress="complete"):
root = Path(__file__).resolve().parents[3]
step = yaml.safe_load(
(root / "steps/engine/attach/execute-azure.yml").read_text(encoding="utf-8")
)["steps"][0]["script"]
with tempfile.TemporaryDirectory() as directory:
marker = Path(directory) / "namespace"
mocks = """
mktemp() { printf '%s\\n' "$MOCK_MARKER"; }
timeout() {
printf '%s' "$MOCK_NAMESPACE" > "$CSI_NAMESPACE_FILE"
if [[ "$MOCK_TERMINATE" == "true" ]]; then
kill -TERM "$$"
fi
return "$MOCK_STATUS"
}
kubectl() {
if [[ "$1" == "delete" ]]; then
printf 'KUBECTL:%s\\n' "$*"
return "$MOCK_CLEANUP_STATUS"
fi
printf 'QUERY:%s\\n' "$*" >&2
if [[ "$MOCK_PROGRESS" == "query-error" && "$1 $2" == "get volumeattachments" ]]; then
return 1
fi
if [[ "$1 $2" == "get pv" &&
( "$MOCK_ROUND" -eq 0 || "$MOCK_PROGRESS" == "stuck-pv" ) ]]; then
printf '%s\\n' '{"items":[{"metadata":{"name":"test-pv"},"spec":{"claimRef":{"namespace":"test-12345"}}}]}'
elif [[ "$1 $2" == "get statefulsets,pods,pvc" &&
"$MOCK_ROUND" -eq 0 && "$MOCK_PROGRESS" == "delayed" ]]; then
printf '%s\\n' '{"items":[{"kind":"Pod","metadata":{"name":"statefulset-local-0"}}]}'
elif [[ "$1 $2" == "get volumeattachments" &&
( "$MOCK_PROGRESS" == "stuck-attachment" ||
( "$MOCK_PROGRESS" == "delayed" && "$MOCK_ROUND" -eq 0 ) ) ]]; then
printf '%s\\n' '{"items":[{"metadata":{"name":"test-attachment"},"spec":{"source":{"persistentVolumeName":"test-pv"}}}]}'
elif [[ "$1 $2" == "get volumeattachments" ]]; then
printf '%s\\n' '{"items":[{"metadata":{"name":"other-attachment"},"spec":{"source":{"persistentVolumeName":"other-pv"}}}]}'
else
printf '%s\\n' '{"items":[]}'
fi
}
MOCK_ROUND=0
sleep() {
printf 'POLL_WAIT\\n'
MOCK_ROUND=$((MOCK_ROUND + 1))
if [[ "$MOCK_PROGRESS" == stuck-* ]]; then
SECONDS=$((SECONDS + 901))
fi
}
"""
result = subprocess.run(
["bash"], input=mocks + step, text=True, capture_output=True,
check=False,
env={
**os.environ,
"MOCK_MARKER": str(marker),
"MOCK_NAMESPACE": namespace,
"MOCK_STATUS": str(status),
"MOCK_CLEANUP_STATUS": str(cleanup_status),
"MOCK_TERMINATE": str(terminate).lower(),
"MOCK_PROGRESS": progress,
"EXECUTION_TIMEOUT_MINUTES": "60",
"PYTHON_SCRIPT_FILE": "mock.py",
"DISK_NUMBER": "200",
"STORAGE_CLASS": "default",
"WAIT_TIME": "300",
"RESULT_DIR": directory,
},
)
self.assertFalse(marker.exists())
return result

def test_failure_and_timeout_delete_only_test_workload(self):
for status in (1, 124, 137):
with self.subTest(status=status):
result = self.run_step(status)
self.assertEqual(result.returncode, status, result.stderr)
self.assertIn(
"KUBECTL:delete statefulset statefulset-local --namespace test-12345",
result.stdout,
)
self.assertIn("KUBECTL:delete pvc --all --namespace test-12345", result.stdout)

def test_success_does_not_repeat_cleanup(self):
result = self.run_step(0)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertNotIn("KUBECTL:", result.stdout)

def test_missing_or_invalid_namespace_cannot_delete_other_workloads(self):
for namespace in ("", "default"):
with self.subTest(namespace=namespace):
result = self.run_step(1, namespace=namespace)
self.assertEqual(result.returncode, 1, result.stderr)
self.assertNotIn("KUBECTL:", result.stdout)

def test_cleanup_errors_are_reported_and_original_failure_is_preserved(self):
result = self.run_step(124, cleanup_status=1)
self.assertEqual(result.returncode, 124, result.stderr)
self.assertIn("Failed to delete StatefulSet", result.stdout)
self.assertIn("Failed to delete PVCs", result.stdout)

def test_termination_requests_cleanup(self):
result = self.run_step(0, terminate=True)
self.assertEqual(result.returncode, 143, result.stderr)
self.assertIn("KUBECTL:delete statefulset", result.stdout)
self.assertIn("KUBECTL:delete pvc", result.stdout)

def test_waits_for_pods_volumes_and_attachments(self):
result = self.run_step(124, progress="delayed")
self.assertEqual(result.returncode, 124, result.stderr)
self.assertIn("--cascade=foreground", result.stdout)
self.assertIn("Remaining PVs: [\"test-pv\"]", result.stdout)
self.assertIn('VolumeAttachments: ["test-attachment"]', result.stdout)
self.assertLess(
result.stdout.index("POLL_WAIT"),
result.stdout.index("have been removed."),
)
self.assertNotIn("exceeded 15 minutes", result.stdout)

def test_stuck_volumes_or_attachments_hit_cleanup_deadline(self):
for progress in ("stuck-pv", "stuck-attachment"):
with self.subTest(progress=progress):
result = self.run_step(124, progress=progress)
self.assertEqual(result.returncode, 124, result.stderr)
self.assertIn("exceeded 15 minutes", result.stdout)
self.assertNotIn("have been removed.", result.stdout)

def test_query_error_is_not_reported_as_successful_deletion(self):
result = self.run_step(124, progress="query-error")
self.assertEqual(result.returncode, 124, result.stderr)
self.assertIn("Failed to query workload deletion progress", result.stdout)
self.assertNotIn("have been removed.", result.stdout)
15 changes: 14 additions & 1 deletion modules/python/tests/test_csi.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,11 +23,24 @@
# Now import the module where the global KUBERNETERS_CLIENT is defined
from csi.csi import (
wait_for_condition, calculate_percentiles, log_duration,
create_statefulset, collect_attach_detach
create_statefulset, collect_attach_detach, execute_attach_detach
)

class TestCSI(unittest.TestCase):

@patch.dict("os.environ", {"CSI_NAMESPACE_FILE": "/tmp/csi-namespace"})
@patch("csi.csi.os.path.exists", return_value=True)
@patch("csi.csi.time.time_ns", return_value=12345)
@patch("csi.csi.KUBERNETERS_CLIENT")
@patch("csi.csi.create_statefulset", side_effect=RuntimeError("creation failed"))
@patch("builtins.open", new_callable=mock_open)
def test_records_namespace_before_statefulset_creation(
self, mock_file, _mock_create, _mock_client, _mock_time, _mock_exists):
with self.assertRaisesRegex(RuntimeError, "creation failed"):
execute_attach_detach(200, "default", 300, "/tmp/results")
mock_file.assert_called_once_with("/tmp/csi-namespace", "w", encoding="utf-8")
mock_file().write.assert_called_once_with("test-12345")

def test_calculate_percentiles(self):
disk_numbers = [300, 1000]
expected_percentiles = {
Expand Down
16 changes: 15 additions & 1 deletion modules/terraform/azure/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ locals {

azapi_config_map = { for c in var.azapi_config_list : c.aks_name => c }

qad_config_map = { for c in var.qad_config_list : c.role => c }

key_vault_config_map = { for kv in var.key_vault_config_list : kv.name => kv }

vm_config_map = { for vm in var.vm_config_list : vm.role => vm }
Expand Down Expand Up @@ -276,6 +278,18 @@ module "azapi" {
depends_on = [module.route_table, module.virtual_network, module.disk_encryption_set]
}

module "qad" {
for_each = local.qad_config_map

source = "./qad"
resource_group_name = local.run_id
location = local.region
qad_config = each.value
tags = local.tags

depends_on = [module.route_table, module.virtual_network, module.disk_encryption_set]
}

module "aks-cli" {
for_each = local.aks_cli_config_map

Expand Down Expand Up @@ -318,5 +332,5 @@ module "virtual_machine" {
nics_map = local.all_nics

# Ensure AKS cluster is created before VM tries to look it up for RBAC
depends_on = [module.aks, module.aks-cli, module.azapi]
depends_on = [module.aks, module.aks-cli, module.azapi, module.qad]
}
Loading
Loading