diff --git a/modules/python/crud/README.md b/modules/python/crud/README.md index 38baf80e2b..fd46b614d3 100644 --- a/modules/python/crud/README.md +++ b/modules/python/crud/README.md @@ -14,6 +14,9 @@ The CRUD module provides comprehensive node pool management operations for Kuber * **scale**: Scale an existing node pool up or down * **delete**: Delete an existing node pool * **all**: Run complete lifecycle (create → scale up → scale down → delete) +* **deployment**: Create Deployments and record aggregate readiness time +* **statefulset**: Create StatefulSets and record aggregate readiness time +* **job**: Create Jobs and record aggregate completion time * **collect**: Collect and process benchmark results ## Define Variables @@ -22,7 +25,6 @@ The CRUD module provides comprehensive node pool management operations for Kuber ```bash pushd modules/python -PYTHON_SCRIPT_FILE=crud/main.py CREATE_NODE_COUNT=0 SCALE_NODE_COUNT=2 SCALE_STEP_SIZE=1 @@ -62,7 +64,7 @@ export AWS_DEFAULT_REGION="us-east-1" Create a new node pool in your Kubernetes cluster: ```bash -PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE create \ +python3 -m crud.main create \ --cloud $CLOUD \ --run-id $RUN_ID \ --result-dir "$RESULT_DIR" \ @@ -78,7 +80,7 @@ PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE create \ ```bash -PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE scale \ +python3 -m crud.main scale \ --cloud $CLOUD \ --run-id $RUN_ID \ --result-dir $RESULT_DIR \ @@ -93,7 +95,7 @@ PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE scale \ ## Scale Down Node Pool ```bash -PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE scale \ +python3 -m crud.main scale \ --cloud $CLOUD \ --run-id $RUN_ID \ --result-dir $RESULT_DIR \ @@ -110,7 +112,7 @@ PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE scale \ Delete an existing node pool: ```bash -PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE delete \ +python3 -m crud.main delete \ --cloud $CLOUD \ --run-id $RUN_ID \ --result-dir $RESULT_DIR \ @@ -124,7 +126,7 @@ Run the complete node pool lifecycle - create, scale up, scale down, and delete: ```bash -PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE all \ +python3 -m crud.main all \ --cloud $CLOUD \ --run-id $RUN_ID \ --result-dir $RESULT_DIR \ @@ -138,6 +140,41 @@ PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE all \ ${GPU_NODE_POOL:+--gpu-node-pool} ``` +## Workload Timing + +Each workload command writes one aggregate operation record to `RESULT_DIR`. +The duration covers all requested workload instances through their Available, +Ready, or Complete condition. + +```bash +python3 -m crud.main deployment \ + --cloud azure \ + --run-id "$RUN_ID" \ + --result-dir "$RESULT_DIR" \ + --node-pool-name "$NODE_POOL_NAME" \ + --count 1 \ + --replicas 10 \ + --step-timeout "$STEP_TIME_OUT" + +python3 -m crud.main statefulset \ + --cloud azure \ + --run-id "$RUN_ID" \ + --result-dir "$RESULT_DIR" \ + --node-pool-name "$NODE_POOL_NAME" \ + --count 1 \ + --replicas 10 \ + --step-timeout "$STEP_TIME_OUT" + +python3 -m crud.main job \ + --cloud azure \ + --run-id "$RUN_ID" \ + --result-dir "$RESULT_DIR" \ + --node-pool-name "$NODE_POOL_NAME" \ + --count 1 \ + --completions 1 \ + --step-timeout "$STEP_TIME_OUT" +``` + ## Collect Benchmark Results Collect and process benchmark results from JSON files: @@ -147,5 +184,5 @@ Collect and process benchmark results from JSON files: export RESULT_DIR=/tmp/${RUN_ID} export RUN_URL="https://example.com/pipeline/run" -PYTHONPATH=$PYTHONPATH:$(pwd) python3 $PYTHON_SCRIPT_FILE collect +python3 -m crud.main collect ``` diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 07df0150fd..9b78df98b0 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -12,6 +12,7 @@ import yaml from clients.aks_client import AKSClient +from crud.operation import OperationContext from utils.constants import AzureNodePoolTypeConstants from utils.logger_config import get_logger, setup_logging from utils.azure_auth import configure_credential @@ -50,6 +51,12 @@ }, } +WORKLOAD_OPERATION_NAMES = { + "deployment": "create_pods", + "statefulset": "create_statefulset", + "job": "create_jobs", +} + class NodePoolCRUD: """Performs AKS node pool operations - metrics collection is handled directly by AKSClient""" @@ -82,6 +89,7 @@ def __init__( # Get the cluster name when initializing self.cluster_name = self.aks_client.get_cluster_name() + self.result_dir = result_dir self.step_timeout = step_timeout def create_node_pool( @@ -470,35 +478,62 @@ def _create_workloads( logger.info("Replicas per %s: %d", workload_type, count) logger.info("Using manifest directory: %s", manifest_dir) - k8s_client = self.aks_client.k8s_client - if not k8s_client: - logger.error("Kubernetes client not available") - return False + metadata = { + "workload_type": workload_type, + "node_pool_name": node_pool_name, + "workload_count": number_of_workloads, + ( + "completions_per_instance" + if workload_type == "job" + else "replicas_per_instance" + ): count, + "namespace": namespace, + } + with OperationContext( + WORKLOAD_OPERATION_NAMES[workload_type], + "azure", + metadata, + result_dir=self.result_dir, + ) as operation: + k8s_client = self.aks_client.k8s_client + if not k8s_client: + error_message = "Kubernetes client not available" + logger.error(error_message) + operation.success = False + operation.error_message = error_message + operation.add_metadata("successful_workloads", 0) + return False - successes = 0 - for index in range(1, number_of_workloads + 1): - logger.info("Creating %s %d/%d", workload_type, index, number_of_workloads) - try: - self._apply_workload( - k8s_client=k8s_client, - workload_type=workload_type, - node_pool_name=node_pool_name, - index=index, - count=count, - manifest_dir=manifest_dir, - label_selector=label_selector, - namespace=namespace - ) - successes += 1 - except Exception as e: - logger.error("Failed to create %s %d: %s", workload_type, index, e) - continue - - if successes == number_of_workloads: - logger.info("Successfully created all %d %s(s)", number_of_workloads, workload_type_display) - return True - logger.warning("Created %d/%d %s(s)", successes, number_of_workloads, workload_type_display) - return False + successes = 0 + for index in range(1, number_of_workloads + 1): + logger.info("Creating %s %d/%d", workload_type, index, number_of_workloads) + try: + self._apply_workload( + k8s_client=k8s_client, + workload_type=workload_type, + node_pool_name=node_pool_name, + index=index, + count=count, + manifest_dir=manifest_dir, + label_selector=label_selector, + namespace=namespace + ) + successes += 1 + except Exception as e: + logger.error("Failed to create %s %d: %s", workload_type, index, e) + continue + + operation.add_metadata("successful_workloads", successes) + operation.success = successes == number_of_workloads + if operation.success: + logger.info("Successfully created all %d %s(s)", number_of_workloads, workload_type_display) + return True + + operation.error_message = ( + f"Created {successes}/{number_of_workloads} {workload_type_display}(s)" + ) + logger.warning(operation.error_message) + return False def _apply_workload( self, diff --git a/modules/python/crud/operation.py b/modules/python/crud/operation.py index a6ef4fa7ae..035d2ee30d 100644 --- a/modules/python/crud/operation.py +++ b/modules/python/crud/operation.py @@ -229,7 +229,7 @@ def __exit__(self, exc_type, exc_val, exc_tb) -> None: exc_val: The exception value if an exception occurred, None otherwise. exc_tb: The traceback if an exception occurred, None otherwise. """ - success = exc_type is None + success = self.operation.success if exc_type is None else False error = exc_val if exc_type is not None else None self.operation.end(success=success, error=error) diff --git a/modules/python/tests/crud/test_azure_node_pool_crud.py b/modules/python/tests/crud/test_azure_node_pool_crud.py index be1bddd4f7..1a1ce114e3 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -3,7 +3,10 @@ Unit tests for NodePoolCRUD class """ +import json import os +import shutil +import tempfile import unittest from unittest import mock from crud.azure.node_pool_crud import NodePoolCRUD @@ -28,8 +31,7 @@ def setUp(self): self.mock_configure_credential.return_value = self.mock_credential # Create test directory for result files - self.test_result_dir = "/tmp/test_results" - os.makedirs(self.test_result_dir, exist_ok=True) + self.test_result_dir = tempfile.mkdtemp() # Setup NodePoolCRUD client self.node_pool_crud = NodePoolCRUD( @@ -44,10 +46,17 @@ def tearDown(self): self.credential_patcher.stop() self.aks_client_patcher.stop() - try: - os.rmdir(self.test_result_dir) - except OSError: - pass + shutil.rmtree(self.test_result_dir) + + def _read_operation_info(self): + result_files = os.listdir(self.test_result_dir) + self.assertEqual(len(result_files), 1) + with open( + os.path.join(self.test_result_dir, result_files[0]), + "r", + encoding="utf-8", + ) as result_file: + return json.load(result_file)["operation_info"] def test_authentication_configuration(self): """Credential configuration is injected with the requested MI behavior.""" @@ -416,6 +425,24 @@ def test_create_deployment_success(self): # Verify self.assertTrue(result) + operation_info = self._read_operation_info() + self.assertEqual(operation_info["name"], "create_pods") + self.assertTrue(operation_info["success"]) + self.assertIsNotNone(operation_info["start_timestamp"]) + self.assertIsNotNone(operation_info["end_timestamp"]) + self.assertIsNotNone(operation_info["duration"]) + self.assertEqual(operation_info["unit"], "seconds") + self.assertEqual( + operation_info["metadata"], + { + "workload_type": "deployment", + "node_pool_name": "test-pool", + "workload_count": 1, + "replicas_per_instance": 10, + "namespace": "default", + "successful_workloads": 1, + }, + ) def test_create_deployment_failure(self): """Test deployment creation failure""" @@ -442,6 +469,9 @@ def test_create_deployment_no_client(self): # Verify self.assertFalse(result) + operation_info = self._read_operation_info() + self.assertFalse(operation_info["success"]) + self.assertEqual(operation_info["error_message"], "Kubernetes client not available") def test_create_deployment_partial_success(self): """Test deployment creation when some deployments succeed and others fail""" @@ -472,6 +502,11 @@ def test_create_deployment_partial_success(self): # Verify create_template was called 3 times (attempted all deployments) self.assertEqual(mock_k8s_client.create_template.call_count, 3) + operation_info = self._read_operation_info() + self.assertEqual(operation_info["name"], "create_pods") + self.assertFalse(operation_info["success"]) + self.assertEqual(operation_info["metadata"]["successful_workloads"], 2) + def test_create_statefulset_success(self): """Test successful statefulset creation""" # Setup @@ -486,6 +521,9 @@ def test_create_statefulset_success(self): # Verify self.assertTrue(result) + operation_info = self._read_operation_info() + self.assertEqual(operation_info["name"], "create_statefulset") + self.assertTrue(operation_info["success"]) def test_create_statefulset_failure(self): """Test statefulset creation failure""" @@ -556,6 +594,11 @@ def test_create_job_success(self): # Verify self.assertTrue(result) + operation_info = self._read_operation_info() + self.assertEqual(operation_info["name"], "create_jobs") + self.assertTrue(operation_info["success"]) + self.assertEqual(operation_info["metadata"]["completions_per_instance"], 1) + self.assertNotIn("replicas_per_instance", operation_info["metadata"]) def test_create_job_failure(self): """Test job creation failure""" diff --git a/modules/python/tests/crud/test_main.py b/modules/python/tests/crud/test_main.py index 9ebfca98c2..3265b9e56b 100644 --- a/modules/python/tests/crud/test_main.py +++ b/modules/python/tests/crud/test_main.py @@ -643,6 +643,55 @@ def test_collect_benchmark_results_success( lines = f.readlines() self.assertEqual(len(lines), 2) # Two result entries + @mock.patch("crud.main.get_env_vars") + def test_collect_benchmark_results_preserves_workload_operations( + self, mock_get_env_vars + ): + """Test aggregate workload records are collected as distinct rows.""" + env_vars = { + "RESULT_DIR": self.test_dir, + "RUN_URL": "https://example.com/run/123", + "RUN_ID": "test-run-123", + "REGION": "eastus", + } + mock_get_env_vars.side_effect = env_vars.get + + operation_names = ["create_pods", "create_statefulset", "create_jobs"] + for operation_name in operation_names: + operation_file = os.path.join(self.test_dir, f"{operation_name}.json") + with open(operation_file, "w", encoding="utf-8") as result_file: + json.dump( + { + "operation_info": { + "name": operation_name, + "cloud": "azure", + "duration": 10.0, + "success": True, + "metadata": {"workload_type": operation_name}, + "unit": "seconds", + } + }, + result_file, + ) + + result = collect_benchmark_results() + + self.assertEqual(result, 0) + with open( + os.path.join(self.test_dir, "results.json"), "r", encoding="utf-8" + ) as results_file: + rows = [json.loads(line) for line in results_file] + + self.assertEqual(len(rows), 3) + collected_names = { + json.loads(row["operation_info"])["name"] for row in rows + } + self.assertEqual(collected_names, set(operation_names)) + for row in rows: + self.assertEqual(row["region"], "eastus") + self.assertEqual(row["run_id"], "test-run-123") + self.assertEqual(row["run_url"], "https://example.com/run/123") + @mock.patch("crud.main.get_env_vars") @mock.patch("crud.main.glob.glob") def test_collect_benchmark_results_skip_results_json( diff --git a/modules/python/tests/crud/test_operation.py b/modules/python/tests/crud/test_operation.py index 1b22734d70..46eeca7f5b 100644 --- a/modules/python/tests/crud/test_operation.py +++ b/modules/python/tests/crud/test_operation.py @@ -413,6 +413,13 @@ def test_operation_context_success(self, mock_datetime): self.assertTrue(files[0].startswith("azure_test_operation_")) self.assertTrue(files[0].endswith(".json")) + def test_operation_context_preserves_explicit_failure(self): + """Test OperationContext preserves a failure without an exception.""" + with OperationContext("test_operation", "azure") as op: + op.success = False + + self.assertFalse(op.success) + @mock.patch("crud.operation.datetime") def test_operation_context_failure(self, mock_datetime): """Test OperationContext with failed operation"""