From 39297dfb40901d8ef368e3a1eb74b21a2ab84522 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+engineeredcurlz@users.noreply.github.com> Date: Mon, 4 May 2026 16:51:53 -0400 Subject: [PATCH 01/19] feat: add statefulset workload to CRUD module MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add create_statefulset() to NodePoolCRUD that deploys K8s StatefulSets onto node pools after provisioning. Follows the same pattern as create_deployment — multi-doc YAML manifest parsing, configurable replica count, and per-statefulset readiness validation via wait_for_condition. - Add 'statefulset' subcommand to handle_workload_operations() in main.py with --number-of-statefulsets and --replicas args - Add statefulset.yml workload template with configurable replicas and node affinity via label_selector - Add _is_statefulset_ready and _check_statefulset_condition to kubernetes_client.py for readiness polling --- modules/python/clients/kubernetes_client.py | 38 +++++- modules/python/crud/azure/node_pool_crud.py | 118 ++++++++++++++++++ modules/python/crud/main.py | 33 +++++ .../crud/workload_templates/statefulset.yml | 34 +++++ 4 files changed, 222 insertions(+), 1 deletion(-) create mode 100644 modules/python/crud/workload_templates/statefulset.yml diff --git a/modules/python/clients/kubernetes_client.py b/modules/python/clients/kubernetes_client.py index 60838d2ce4..2785dbfd17 100644 --- a/modules/python/clients/kubernetes_client.py +++ b/modules/python/clients/kubernetes_client.py @@ -975,7 +975,8 @@ def wait_for_condition(self, resource_type: str, wait_condition_type: str, names valid_conditions = { 'deployment': ['available', 'progressing', 'replicafailure', 'ready'], 'deployments': ['available', 'progressing', 'replicafailure', 'ready'], - # Add more resource types as needed + 'statefulset': ['ready'], + 'statefulsets': ['ready'], } # Validate wait_condition_type format and type @@ -1049,6 +1050,9 @@ def _check_resource_condition(self, resource_type: str, resource_name: str, cond if resource_type_lower in ['deployment', 'deployments']: return self._check_deployment_condition(resource_name, condition_type, namespace, wait_all) + if resource_type_lower in ['statefulset', 'statefulsets']: + return self._check_statefulset_condition(resource_name, namespace, wait_all) + logger.warning(f"Unsupported resource type for condition checking: {resource_type}") return False @@ -1079,6 +1083,38 @@ def _check_deployment_condition(self, resource_name: str, condition_type: str, n return False raise e + def _check_statefulset_condition(self, resource_name: str, namespace: str, wait_all: bool) -> bool: + """Check statefulset condition (e.g., 'ready').""" + try: + if wait_all or not resource_name: + statefulsets = self.app.list_namespaced_stateful_set(namespace=namespace).items + else: + statefulset = self.app.read_namespaced_stateful_set(name=resource_name, namespace=namespace) + statefulsets = [statefulset] + + for statefulset in statefulsets: + if not self._is_statefulset_ready(statefulset): + return False + + return True + + except client.rest.ApiException as e: + if e.status == 404: + logger.debug("StatefulSet not found, waiting...") + return False + raise e + + def _is_statefulset_ready(self, statefulset) -> bool: + """Check if a statefulset has all replicas ready.""" + status = statefulset.status + spec_replicas = statefulset.spec.replicas or 0 + return ( + status is not None + and status.ready_replicas is not None + and status.ready_replicas == spec_replicas + and spec_replicas > 0 + ) + def _is_deployment_condition_met(self, deployment, condition_type: str) -> bool: """Check if a deployment meets the specified condition.""" if not deployment.status or not deployment.status.conditions: diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 208589d3d7..8ff4e6e07a 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -409,3 +409,121 @@ def create_deployment( return True logger.warning("Created %d/%d deployment(s)", successful_deployments, number_of_deployments) return False + + def create_statefulset( + self, + node_pool_name, + replicas=10, + manifest_dir=None, + number_of_statefulsets=1, + label_selector="app=nginx-container", + namespace="default" + ): + """ + Create Kubernetes StatefulSets after node pool operations. + + Args: + node_pool_name: Name of the node pool to target + namespace: Kubernetes namespace (default: "default") + replicas: Number of replicas for the StatefulSet (default: 10) + manifest_dir: Directory containing Kubernetes manifest files + number_of_statefulsets: Number of StatefulSets to create (default: 1) + label_selector: Label selector for pods (default: "app=nginx-container") + + Returns: + True if all StatefulSet creations were successful, False otherwise + """ + logger.info("Creating %d StatefulSet(s)", number_of_statefulsets) + logger.info("Target node pool: %s", node_pool_name) + logger.info("Replicas per StatefulSet: %d", replicas) + logger.info("Using manifest directory: %s", manifest_dir) + + try: + # Get Kubernetes client from AKS client + k8s_client = self.aks_client.k8s_client + + if not k8s_client: + logger.error("Kubernetes client not available") + return False + + successful_statefulsets = 0 + + # Loop through number of StatefulSets + for statefulset_index in range(1, number_of_statefulsets + 1): + logger.info("Creating StatefulSet %d/%d", statefulset_index, number_of_statefulsets) + + try: + if manifest_dir: + # Use the template path from manifest_dir + template_path = f"{manifest_dir}/statefulset.yml" + else: + # Use default template path + template_path = "modules/python/crud/workload_templates/statefulset.yml" + + # Generate StatefulSet name + statefulset_name = f"myapp-{node_pool_name}-{statefulset_index}" + + # Create StatefulSet template using k8s_client.create_template + statefulset_template = k8s_client.create_template( + template_path, + { + "STATEFULSET_REPLICAS": replicas, + "NODE_POOL_NAME": node_pool_name, + "INDEX": statefulset_index, + "LABEL_VALUE": label_selector.split("=", 1)[-1], + } + ) + + # Apply each document in the rendered multi-doc template + for doc in yaml.safe_load_all(statefulset_template): + if doc: + k8s_client.apply_manifest_from_file(manifest_dict=doc) + + logger.info("Applied manifest for StatefulSet %s", statefulset_name) + + # Wait for statefulset to be ready (successful statefulset verification) + logger.info("Waiting for StatefulSet %s to become ready...", statefulset_name) + statefulset_ready = k8s_client.wait_for_condition( + resource_type="statefulset", + wait_condition_type="ready", + resource_name=statefulset_name, + namespace=namespace, + timeout_seconds=self.step_timeout + ) + + if statefulset_ready: + logger.info("StatefulSet %s is successfully ready", statefulset_name) + + # Additionally wait for pods to be ready + logger.info("Waiting for pods of StatefulSet %s to be ready...", statefulset_name) + k8s_client.wait_for_pods_ready( + operation_timeout_in_minutes=5, + namespace=namespace, + pod_count=replicas, + label_selector=label_selector + ) + + logger.info("Successfully created and verified StatefulSet %d", statefulset_index) + successful_statefulsets += 1 + else: + logger.error("StatefulSet %s failed to become ready within timeout", statefulset_name) + continue + + except Exception as e: + logger.error("Failed to create StatefulSet %d: %s", statefulset_index, e) + # Continue with next StatefulSet instead of failing completely + continue + + # Check if all StatefulSets were successful + if successful_statefulsets == number_of_statefulsets: + logger.info("Successfully created all %d StatefulSet(s)", number_of_statefulsets) + return True + if successful_statefulsets > 0: + logger.warning("Created %d/%d StatefulSet(s)", successful_statefulsets, number_of_statefulsets) + return False + logger.error("Failed to create any StatefulSets") + return False + + except Exception as e: + logger.error("Failed to create StatefulSets: %s", e) + return False diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index 635d14462a..a03b9e1571 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -167,6 +167,15 @@ def handle_workload_operations(node_pool_crud, args): } result = node_pool_crud.create_deployment(**deploy_kwargs) + elif command == "statefulset": + # Prepare statefulset arguments + statefulset_kwargs = { + "node_pool_name": args.node_pool_name, + "replicas": args.replicas, + "manifest_dir": args.manifest_dir, + "number_of_statefulsets": args.number_of_statefulsets, + } + result = node_pool_crud.create_statefulset(**statefulset_kwargs) else: logger.error("Unknown workload command: '%s'", command) return 1 @@ -386,6 +395,30 @@ def main(): ) deployment_parser.set_defaults(func=handle_workload_operations) + # StatefulSet command - add after the "deployment" command parser + statefulset_parser = subparsers.add_parser( + "statefulset", parents=[common_parser], help="create statefulsets" + ) + statefulset_parser.add_argument("--node-pool-name", required=True, help="Node pool name") + statefulset_parser.add_argument( + "--number-of-statefulsets", + type=int, + default=1, + help="Number of statefulsets" + ) + statefulset_parser.add_argument( + "--replicas", + type=int, + default=10, + help="Number of statefulset replicas" + ) + statefulset_parser.add_argument( + "--manifest-dir", + required=True, + help="Directory containing Kubernetes manifest files for the statefulset" + ) + statefulset_parser.set_defaults(func=handle_workload_operations) + # Arguments provided, run node pool operations and collect benchmark results try: args = parser.parse_args() diff --git a/modules/python/crud/workload_templates/statefulset.yml b/modules/python/crud/workload_templates/statefulset.yml new file mode 100644 index 0000000000..c85725316c --- /dev/null +++ b/modules/python/crud/workload_templates/statefulset.yml @@ -0,0 +1,34 @@ +apiVersion: apps/v1 +kind: StatefulSet +metadata: + name: myapp-{{NODE_POOL_NAME}}-{{INDEX}} + labels: + app: {{LABEL_VALUE}} +spec: + serviceName: myapp-{{NODE_POOL_NAME}}-{{INDEX}} + replicas: {{STATEFULSET_REPLICAS}} + selector: + matchLabels: + app: {{LABEL_VALUE}} + template: + metadata: + labels: + app: {{LABEL_VALUE}} + spec: + containers: + - name: {{LABEL_VALUE}} + image: mcr.microsoft.com/oss/nginx/nginx:1.21.6 + ports: + - containerPort: 80 +--- +apiVersion: v1 +kind: Service +metadata: + name: myapp-{{NODE_POOL_NAME}}-{{INDEX}} +spec: + ports: + - port: 80 + name: myapp + clusterIP: None + selector: + app: {{LABEL_VALUE}} From 896d146f9abf43e018809f831cb1f7fd057ba2b5 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+engineeredcurlz@users.noreply.github.com> Date: Mon, 4 May 2026 16:52:04 -0400 Subject: [PATCH 02/19] feat: wire statefulset through pipeline topology MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Add statefulset execution step to the k8s CRUD engine pipeline between deployment and scale-down. Parameters (number_of_statefulsets, replicas) flow from pipeline matrix → topology → engine step → main.py. - Add statefulset script block to steps/engine/crud/k8s/execute.yml - Pass number_of_statefulsets through topology execute-crud.yml --- steps/engine/crud/k8s/execute.yml | 28 ++++++++++++++++++++ steps/topology/k8s-crud-gpu/execute-crud.yml | 1 + 2 files changed, 29 insertions(+) diff --git a/steps/engine/crud/k8s/execute.yml b/steps/engine/crud/k8s/execute.yml index bd3fbef2e3..6f92dcae81 100644 --- a/steps/engine/crud/k8s/execute.yml +++ b/steps/engine/crud/k8s/execute.yml @@ -10,6 +10,7 @@ parameters: step_wait_time: 30 gpu_node_pool: false count: 1 + number_of_statefulsets: 1 replicas: 10 manifest_dir: "" @@ -86,6 +87,33 @@ steps: REPLICAS: ${{ parameters.replicas }} MANIFEST_DIR: ${{ parameters.manifest_dir }} +- script: | + set -eo pipefail + + # Deploy StatefulSets + PYTHONPATH=$PYTHONPATH:$(pwd) python3 "$PYTHON_SCRIPT_FILE" statefulset \ + --cloud "$CLOUD" \ + --run-id "$RUN_ID" \ + --result-dir "$RESULT_DIR" \ + --node-pool-name "$POOL_NAME" \ + --number-of-statefulsets "$NUMBER_OF_STATEFULSETS" \ + --replicas "$REPLICAS" \ + --manifest-dir "$MANIFEST_DIR" \ + --step-timeout "$STEP_TIME_OUT" \ + ${GPU_NODE_POOL:+--gpu-node-pool} + displayName: 'Execute K8s StatefulSet operations for ${{ parameters.cloud }}' + workingDirectory: modules/python + env: + PYTHON_SCRIPT_FILE: $(Pipeline.Workspace)/s/modules/python/crud/main.py + POOL_NAME: ${{ parameters.pool_name }} + CLOUD: ${{ parameters.cloud }} + STEP_TIME_OUT: ${{ parameters.step_time_out }} + RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) + GPU_NODE_POOL: ${{ parameters.gpu_node_pool }} + NUMBER_OF_STATEFULSETS: ${{ parameters.number_of_statefulsets }} + REPLICAS: ${{ parameters.replicas }} + MANIFEST_DIR: ${{ parameters.manifest_dir }} + - script: | set -eo pipefail diff --git a/steps/topology/k8s-crud-gpu/execute-crud.yml b/steps/topology/k8s-crud-gpu/execute-crud.yml index 1c2b02d9c6..90e6afec54 100644 --- a/steps/topology/k8s-crud-gpu/execute-crud.yml +++ b/steps/topology/k8s-crud-gpu/execute-crud.yml @@ -23,5 +23,6 @@ steps: gpu_node_pool: $(GPU_NODE_POOL) step_wait_time: $(STEP_WAIT_TIME) count: $(COUNT) + number_of_statefulsets: $(NUMBER_OF_STATEFULSETS) replicas: $(REPLICAS) manifest_dir: $(MANIFEST_DIR) From fad0343153904a2feef4415dba8ba3186b296e6b Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+engineeredcurlz@users.noreply.github.com> Date: Mon, 4 May 2026 16:52:37 -0400 Subject: [PATCH 03/19] test: add unit tests for statefulset CRUD operations Add test coverage for create_statefulset and statefulset wait_for_condition: - test_create_statefulset_success: single statefulset with readiness check - test_create_statefulset_failure: statefulset fails to become ready - test_create_statefulset_partial_success: continues on individual failures - test_create_statefulset_no_client: returns early when k8s client unavailable - test_statefulset_wait_for_condition: validates _is_statefulset_ready and _check_statefulset_condition polling logic --- .../tests/clients/test_kubernetes_client.py | 71 +++++++++++++++++++ .../tests/crud/test_azure_node_pool_crud.py | 70 ++++++++++++++++++ 2 files changed, 141 insertions(+) diff --git a/modules/python/tests/clients/test_kubernetes_client.py b/modules/python/tests/clients/test_kubernetes_client.py index 8190789361..a67d52fef2 100644 --- a/modules/python/tests/clients/test_kubernetes_client.py +++ b/modules/python/tests/clients/test_kubernetes_client.py @@ -3407,6 +3407,77 @@ def test_wait_for_condition_case_insensitive(self): ) self.assertTrue(result) + @patch('time.time') + def test_wait_for_condition_statefulset_success(self, mock_time): + """Test wait_for_condition for statefulset - success case""" + mock_time.side_effect = [0, 0, 1, 2, 2] + + mock_statefulset = MagicMock() + mock_statefulset.spec.replicas = 3 + mock_statefulset.status.ready_replicas = 3 + + with patch.object(self.client, 'app') as mock_app, \ + patch('time.sleep'): + mock_app.read_namespaced_stateful_set.return_value = mock_statefulset + + result = self.client.wait_for_condition( + resource_type="statefulset", + resource_name="test-statefulset", + wait_condition_type="ready", + namespace="test-namespace", + timeout_seconds=5 + ) + + self.assertTrue(result) + mock_app.read_namespaced_stateful_set.assert_called_with( + name="test-statefulset", + namespace="test-namespace" + ) + + @patch('time.time') + def test_wait_for_condition_statefulset_timeout(self, mock_time): + """Test wait_for_condition for statefulset - timeout case""" + mock_time.side_effect = [0, 0, 2, 5, 6, 6] + + mock_statefulset = MagicMock() + mock_statefulset.spec.replicas = 3 + mock_statefulset.status.ready_replicas = 1 + + with patch.object(self.client, 'app') as mock_app, \ + patch('time.sleep'): + mock_app.read_namespaced_stateful_set.return_value = mock_statefulset + + result = self.client.wait_for_condition( + resource_type="statefulset", + resource_name="test-statefulset", + wait_condition_type="ready", + namespace="test-namespace", + timeout_seconds=1 + ) + + self.assertFalse(result) + + @patch('time.time') + def test_wait_for_condition_statefulset_not_found(self, mock_time): + """Test wait_for_condition for statefulset - not found case""" + mock_time.side_effect = [0, 0, 2, 5, 6, 6] + + api_exception = ApiException(status=404, reason="Not Found") + + with patch.object(self.client, 'app') as mock_app, \ + patch('time.sleep'): + mock_app.read_namespaced_stateful_set.side_effect = api_exception + + result = self.client.wait_for_condition( + resource_type="statefulset", + resource_name="nonexistent", + wait_condition_type="ready", + namespace="test-namespace", + timeout_seconds=1 + ) + + self.assertFalse(result) + # Tests for the enhanced apply_manifest_from_file method with folder support @patch('os.path.isdir') @patch('os.path.isfile') 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 9064a5af4a..c683d017fa 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -393,5 +393,75 @@ 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) + def test_create_statefulset_success(self): + """Test successful statefulset creation""" + # Setup + mock_k8s_client = mock.MagicMock() + self.mock_aks_client.k8s_client = mock_k8s_client + # Must return a real string - yaml.safe_load_all(MagicMock()) causes an infinite loop + mock_k8s_client.create_template.return_value = "apiVersion: apps/v1\nkind: StatefulSet\n" + mock_k8s_client.wait_for_condition.return_value = True + + # Execute + result = self.node_pool_crud.create_statefulset(node_pool_name="test-pool") + + # Verify + self.assertTrue(result) + + def test_create_statefulset_failure(self): + """Test statefulset creation failure""" + # Setup + mock_k8s_client = mock.MagicMock() + self.mock_aks_client.k8s_client = mock_k8s_client + # Must return a real string - yaml.safe_load_all(MagicMock()) causes an infinite loop + mock_k8s_client.create_template.return_value = "apiVersion: apps/v1\nkind: StatefulSet\n" + mock_k8s_client.wait_for_condition.return_value = False + + # Execute + result = self.node_pool_crud.create_statefulset(node_pool_name="test-pool") + + # Verify + self.assertFalse(result) + + def test_create_statefulset_no_client(self): + """Test statefulset creation with no Kubernetes client""" + # Setup + self.mock_aks_client.k8s_client = None + + # Execute + result = self.node_pool_crud.create_statefulset(node_pool_name="test-pool") + + # Verify + self.assertFalse(result) + + def test_create_statefulset_partial_success(self): + """Test Statefulset creation when some Statefulsets succeed and others fail""" + # Setup + mock_k8s_client = mock.MagicMock() + self.mock_aks_client.k8s_client = mock_k8s_client + + # Must return a real string - yaml.safe_load_all(MagicMock()) causes an infinite loop + mock_k8s_client.create_template.return_value = "apiVersion: apps/v1\nkind: StatefulSet\n" + + # Simulate: StatefulSet 1 succeeds, StatefulSet 2 fails, StatefulSet 3 succeeds + # wait_for_condition returns True/False for each StatefulSet + mock_k8s_client.wait_for_condition.side_effect = [True, False, True] + + # Execute - request 3 StatefulSets + result = self.node_pool_crud.create_statefulset( + node_pool_name="test-pool", + number_of_statefulsets=3, + replicas=5 + ) + + # Verify - should return False (not all statefulsets succeeded) + self.assertFalse(result) + + # Verify wait_for_condition was called 3 times (once per statefulset) + self.assertEqual(mock_k8s_client.wait_for_condition.call_count, 3) + + # Verify create_template was called 3 times (attempted all statefulsets) + self.assertEqual(mock_k8s_client.create_template.call_count, 3) + if __name__ == "__main__": unittest.main() From aac5e7faf12e1f461a853f44a0a29b16a2db8cf6 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+engineeredcurlz@users.noreply.github.com> Date: Tue, 5 May 2026 13:12:00 -0400 Subject: [PATCH 04/19] test: configure pipeline for statefulset workload validation --- modules/python/crud/azure/node_pool_crud.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 8ff4e6e07a..f04813231a 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -416,7 +416,7 @@ def create_statefulset( replicas=10, manifest_dir=None, number_of_statefulsets=1, - label_selector="app=nginx-container", + label_selector="app=nginx-statefulset", namespace="default" ): """ From aa1dd053f68d6615aeda13b9ecfd696624b5b2e3 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 14 May 2026 12:19:14 -0400 Subject: [PATCH 05/19] refactor: align statefulset with deployment patterns from merged PR - Extract _apply_statefulset helper (matches _apply_deployment pattern) - Use os.path for default template path instead of hardcoded string - Use per-statefulset labels to avoid selector collision - Remove redundant outer try/except - Use workload_common_parser for shared args (--count, --replicas, etc.) - Add hasattr guard for cloud provider compatibility - Use args.count instead of args.number_of_statefulsets - Update pipeline YAML to use count parameter --- modules/python/crud/azure/node_pool_crud.py | 205 ++++++++++--------- modules/python/crud/main.py | 32 +-- steps/engine/crud/k8s/execute.yml | 5 +- steps/topology/k8s-crud-gpu/execute-crud.yml | 1 - 4 files changed, 125 insertions(+), 118 deletions(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index f04813231a..f25fd98b3f 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -410,14 +410,87 @@ def create_deployment( logger.warning("Created %d/%d deployment(s)", successful_deployments, number_of_deployments) return False + def _apply_statefulset( + self, + k8s_client, + node_pool_name, + statefulset_index, + replicas, + manifest_dir, + label_selector, + namespace + ): + """Helper for create_statefulset — applies and verifies a single StatefulSet.""" + if manifest_dir: + # Use the template path from manifest_dir + template_path = f"{manifest_dir}/statefulset.yml" + else: + # Use default template path (relative to workingDirectory: modules/python) + template_path = os.path.join( + os.path.dirname(os.path.abspath(__file__)), + "..", "workload_templates", "statefulset.yml" + ) + + # Generate StatefulSet name + statefulset_name = f"myapp-{node_pool_name}-{statefulset_index}" + + # Use per-statefulset label to avoid selector collision + statefulset_label = f"{label_selector.split('=', 1)[-1]}-{statefulset_index}" + + # Create StatefulSet template using k8s_client.create_template + statefulset_template = k8s_client.create_template( + template_path, + { + "STATEFULSET_REPLICAS": replicas, + "NODE_POOL_NAME": node_pool_name, + "INDEX": statefulset_index, + "LABEL_VALUE": statefulset_label, + } + ) + + # Apply each document in the rendered multi-doc template + for doc in yaml.safe_load_all(statefulset_template): + if doc: + k8s_client.apply_manifest_from_file(manifest_dict=doc, namespace=namespace) + + logger.info("Applied manifest for StatefulSet %s", statefulset_name) + + # Wait for statefulset to be ready (successful statefulset verification) + logger.info("Waiting for StatefulSet %s to become ready...", statefulset_name) + statefulset_ready = k8s_client.wait_for_condition( + resource_type="statefulset", + wait_condition_type="ready", + resource_name=statefulset_name, + namespace=namespace, + timeout_seconds=self.step_timeout + ) + + if not statefulset_ready: + raise TimeoutError( + f"StatefulSet {statefulset_name} failed to become ready within timeout" + ) + + logger.info("StatefulSet %s is successfully ready", statefulset_name) + + # Additionally wait for pods to be ready + logger.info("Waiting for pods of StatefulSet %s to be ready...", statefulset_name) + k8s_client.wait_for_pods_ready( + operation_timeout_in_minutes=5, + namespace=namespace, + pod_count=replicas, + label_selector=f"app={statefulset_label}" + ) + + logger.info("Successfully created and verified StatefulSet %d", statefulset_index) + def create_statefulset( - self, - node_pool_name, - replicas=10, - manifest_dir=None, - number_of_statefulsets=1, - label_selector="app=nginx-statefulset", - namespace="default" + self, + node_pool_name, + replicas=10, + manifest_dir=None, + number_of_statefulsets=1, + label_selector="app=nginx-container", + namespace="default" ): """ Create Kubernetes StatefulSets after node pool operations. @@ -438,92 +511,38 @@ def create_statefulset( logger.info("Replicas per StatefulSet: %d", replicas) logger.info("Using manifest directory: %s", manifest_dir) - try: - # Get Kubernetes client from AKS client - k8s_client = self.aks_client.k8s_client - - if not k8s_client: - logger.error("Kubernetes client not available") - return False + # Get Kubernetes client from AKS client + k8s_client = self.aks_client.k8s_client - successful_statefulsets = 0 - - # Loop through number of StatefulSets - for statefulset_index in range(1, number_of_statefulsets + 1): - logger.info("Creating StatefulSet %d/%d", statefulset_index, number_of_statefulsets) - - try: - if manifest_dir: - # Use the template path from manifest_dir - template_path = f"{manifest_dir}/statefulset.yml" - else: - # Use default template path - template_path = "modules/python/crud/workload_templates/statefulset.yml" - - # Generate StatefulSet name - statefulset_name = f"myapp-{node_pool_name}-{statefulset_index}" - - # Create StatefulSet template using k8s_client.create_template - statefulset_template = k8s_client.create_template( - template_path, - { - "STATEFULSET_REPLICAS": replicas, - "NODE_POOL_NAME": node_pool_name, - "INDEX": statefulset_index, - "LABEL_VALUE": label_selector.split("=", 1)[-1], - } - ) - - # Apply each document in the rendered multi-doc template - for doc in yaml.safe_load_all(statefulset_template): - if doc: - k8s_client.apply_manifest_from_file(manifest_dict=doc) - - logger.info("Applied manifest for StatefulSet %s", statefulset_name) - - # Wait for statefulset to be ready (successful statefulset verification) - logger.info("Waiting for StatefulSet %s to become ready...", statefulset_name) - statefulset_ready = k8s_client.wait_for_condition( - resource_type="statefulset", - wait_condition_type="ready", - resource_name=statefulset_name, - namespace=namespace, - timeout_seconds=self.step_timeout - ) - - if statefulset_ready: - logger.info("StatefulSet %s is successfully ready", statefulset_name) - - # Additionally wait for pods to be ready - logger.info("Waiting for pods of StatefulSet %s to be ready...", statefulset_name) - k8s_client.wait_for_pods_ready( - operation_timeout_in_minutes=5, - namespace=namespace, - pod_count=replicas, - label_selector=label_selector - ) - - logger.info("Successfully created and verified StatefulSet %d", statefulset_index) - successful_statefulsets += 1 - else: - logger.error("StatefulSet %s failed to become ready within timeout", statefulset_name) - continue - - except Exception as e: - logger.error("Failed to create StatefulSet %d: %s", statefulset_index, e) - # Continue with next StatefulSet instead of failing completely - continue - - # Check if all StatefulSets were successful - if successful_statefulsets == number_of_statefulsets: - logger.info("Successfully created all %d StatefulSet(s)", number_of_statefulsets) - return True - if successful_statefulsets > 0: - logger.warning("Created %d/%d StatefulSet(s)", successful_statefulsets, number_of_statefulsets) - return False - logger.error("Failed to create any StatefulSets") + if not k8s_client: + logger.error("Kubernetes client not available") return False - except Exception as e: - logger.error("Failed to create StatefulSets: %s", e) - return False + successful_statefulsets = 0 + + # Loop through number of StatefulSets + for statefulset_index in range(1, number_of_statefulsets + 1): + logger.info("Creating StatefulSet %d/%d", statefulset_index, number_of_statefulsets) + + try: + self._apply_statefulset( + k8s_client=k8s_client, + node_pool_name=node_pool_name, + statefulset_index=statefulset_index, + replicas=replicas, + manifest_dir=manifest_dir, + label_selector=label_selector, + namespace=namespace + ) + successful_statefulsets += 1 + except Exception as e: + logger.error("Failed to create StatefulSet %d: %s", statefulset_index, e) + # Continue with next StatefulSet instead of failing completely + continue + + # Check if all StatefulSets were successful + if successful_statefulsets == number_of_statefulsets: + logger.info("Successfully created all %d StatefulSet(s)", number_of_statefulsets) + return True + logger.warning("Created %d/%d StatefulSet(s)", successful_statefulsets, number_of_statefulsets) + return False diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index a03b9e1571..b34389bcce 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -168,13 +168,19 @@ def handle_workload_operations(node_pool_crud, args): result = node_pool_crud.create_deployment(**deploy_kwargs) elif command == "statefulset": + if not hasattr(node_pool_crud, 'create_statefulset'): + logger.error("Cloud provider does not support statefulset workload operations") + return 1 + # Prepare statefulset arguments statefulset_kwargs = { "node_pool_name": args.node_pool_name, "replicas": args.replicas, "manifest_dir": args.manifest_dir, - "number_of_statefulsets": args.number_of_statefulsets, + "number_of_statefulsets": args.count, + "label_selector": args.label_selector, } + result = node_pool_crud.create_statefulset(**statefulset_kwargs) else: logger.error("Unknown workload command: '%s'", command) @@ -395,27 +401,11 @@ def main(): ) deployment_parser.set_defaults(func=handle_workload_operations) - # StatefulSet command - add after the "deployment" command parser + # StatefulSet command statefulset_parser = subparsers.add_parser( - "statefulset", parents=[common_parser], help="create statefulsets" - ) - statefulset_parser.add_argument("--node-pool-name", required=True, help="Node pool name") - statefulset_parser.add_argument( - "--number-of-statefulsets", - type=int, - default=1, - help="Number of statefulsets" - ) - statefulset_parser.add_argument( - "--replicas", - type=int, - default=10, - help="Number of statefulset replicas" - ) - statefulset_parser.add_argument( - "--manifest-dir", - required=True, - help="Directory containing Kubernetes manifest files for the statefulset" + "statefulset", + parents=[common_parser, workload_common_parser], + help="create statefulsets" ) statefulset_parser.set_defaults(func=handle_workload_operations) diff --git a/steps/engine/crud/k8s/execute.yml b/steps/engine/crud/k8s/execute.yml index 6f92dcae81..47b3deb3cf 100644 --- a/steps/engine/crud/k8s/execute.yml +++ b/steps/engine/crud/k8s/execute.yml @@ -10,7 +10,6 @@ parameters: step_wait_time: 30 gpu_node_pool: false count: 1 - number_of_statefulsets: 1 replicas: 10 manifest_dir: "" @@ -96,7 +95,7 @@ steps: --run-id "$RUN_ID" \ --result-dir "$RESULT_DIR" \ --node-pool-name "$POOL_NAME" \ - --number-of-statefulsets "$NUMBER_OF_STATEFULSETS" \ + --count "$COUNT" \ --replicas "$REPLICAS" \ --manifest-dir "$MANIFEST_DIR" \ --step-timeout "$STEP_TIME_OUT" \ @@ -110,7 +109,7 @@ steps: STEP_TIME_OUT: ${{ parameters.step_time_out }} RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) GPU_NODE_POOL: ${{ parameters.gpu_node_pool }} - NUMBER_OF_STATEFULSETS: ${{ parameters.number_of_statefulsets }} + COUNT: ${{ parameters.count }} REPLICAS: ${{ parameters.replicas }} MANIFEST_DIR: ${{ parameters.manifest_dir }} diff --git a/steps/topology/k8s-crud-gpu/execute-crud.yml b/steps/topology/k8s-crud-gpu/execute-crud.yml index 90e6afec54..1c2b02d9c6 100644 --- a/steps/topology/k8s-crud-gpu/execute-crud.yml +++ b/steps/topology/k8s-crud-gpu/execute-crud.yml @@ -23,6 +23,5 @@ steps: gpu_node_pool: $(GPU_NODE_POOL) step_wait_time: $(STEP_WAIT_TIME) count: $(COUNT) - number_of_statefulsets: $(NUMBER_OF_STATEFULSETS) replicas: $(REPLICAS) manifest_dir: $(MANIFEST_DIR) From b8c17b67cb7c2fc5bead7161b9cf6210a5220a60 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 14 May 2026 12:39:41 -0400 Subject: [PATCH 06/19] fix: gate statefulset step to Azure-only and use conditional manifest-dir - Wrap statefulset pipeline step inside Azure cloud gate (matches deployment) - Use ${MANIFEST_DIR:+--manifest-dir} conditional (matches deployment pattern) --- steps/engine/crud/k8s/execute.yml | 50 +++++++++++++++---------------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/steps/engine/crud/k8s/execute.yml b/steps/engine/crud/k8s/execute.yml index 47b3deb3cf..3191982a65 100644 --- a/steps/engine/crud/k8s/execute.yml +++ b/steps/engine/crud/k8s/execute.yml @@ -86,32 +86,32 @@ steps: REPLICAS: ${{ parameters.replicas }} MANIFEST_DIR: ${{ parameters.manifest_dir }} -- script: | - set -eo pipefail + - script: | + set -eo pipefail - # Deploy StatefulSets - PYTHONPATH=$PYTHONPATH:$(pwd) python3 "$PYTHON_SCRIPT_FILE" statefulset \ - --cloud "$CLOUD" \ - --run-id "$RUN_ID" \ - --result-dir "$RESULT_DIR" \ - --node-pool-name "$POOL_NAME" \ - --count "$COUNT" \ - --replicas "$REPLICAS" \ - --manifest-dir "$MANIFEST_DIR" \ - --step-timeout "$STEP_TIME_OUT" \ - ${GPU_NODE_POOL:+--gpu-node-pool} - displayName: 'Execute K8s StatefulSet operations for ${{ parameters.cloud }}' - workingDirectory: modules/python - env: - PYTHON_SCRIPT_FILE: $(Pipeline.Workspace)/s/modules/python/crud/main.py - POOL_NAME: ${{ parameters.pool_name }} - CLOUD: ${{ parameters.cloud }} - STEP_TIME_OUT: ${{ parameters.step_time_out }} - RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) - GPU_NODE_POOL: ${{ parameters.gpu_node_pool }} - COUNT: ${{ parameters.count }} - REPLICAS: ${{ parameters.replicas }} - MANIFEST_DIR: ${{ parameters.manifest_dir }} + # Deploy StatefulSets + PYTHONPATH=$PYTHONPATH:$(pwd) python3 "$PYTHON_SCRIPT_FILE" statefulset \ + --cloud "$CLOUD" \ + --run-id "$RUN_ID" \ + --result-dir "$RESULT_DIR" \ + --node-pool-name "$POOL_NAME" \ + --count "$COUNT" \ + --replicas "$REPLICAS" \ + ${MANIFEST_DIR:+--manifest-dir "$MANIFEST_DIR"} \ + --step-timeout "$STEP_TIME_OUT" \ + ${GPU_NODE_POOL:+--gpu-node-pool} + displayName: 'Execute K8s StatefulSet operations for ${{ parameters.cloud }}' + workingDirectory: modules/python + env: + PYTHON_SCRIPT_FILE: $(Pipeline.Workspace)/s/modules/python/crud/main.py + POOL_NAME: ${{ parameters.pool_name }} + CLOUD: ${{ parameters.cloud }} + STEP_TIME_OUT: ${{ parameters.step_time_out }} + RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) + GPU_NODE_POOL: ${{ parameters.gpu_node_pool }} + COUNT: ${{ parameters.count }} + REPLICAS: ${{ parameters.replicas }} + MANIFEST_DIR: ${{ parameters.manifest_dir }} - script: | set -eo pipefail From 2db2b319557eb51dc6ed9267f0c2450fc694e180 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 14 May 2026 12:45:22 -0400 Subject: [PATCH 07/19] fix: correct docstring to list supported workload types --- modules/python/crud/main.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index b34389bcce..23ff741fbf 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -147,7 +147,7 @@ def handle_node_pool_operation(node_pool_crud, args): return 1 def handle_workload_operations(node_pool_crud, args): - """Handle workload operations (deployment, statefulset, jobs) based on the command""" + """Handle workload operations (deployment, statefulset) based on the command""" command = args.command result = None From 8648753662654db9fb4a85b5e77d48d7a2fe4a8e Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 14 May 2026 14:53:43 -0400 Subject: [PATCH 08/19] fix: remove trailing whitespace in test file --- modules/python/tests/crud/test_azure_node_pool_crud.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 c683d017fa..20ba49e558 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -433,7 +433,7 @@ def test_create_statefulset_no_client(self): # Verify self.assertFalse(result) - + def test_create_statefulset_partial_success(self): """Test Statefulset creation when some Statefulsets succeed and others fail""" # Setup From 19e5aaa13b06304fe4c1b0d20027dd47a19e3af9 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 14 May 2026 14:54:10 -0400 Subject: [PATCH 09/19] test: populate pipeline test config for statefulset validation --- pipelines/system/new-pipeline-test.yml | 40 +++++++++++++++----------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 63d55f02d9..e9b9df788a 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -1,25 +1,33 @@ trigger: none variables: - SCENARIO_TYPE: - SCENARIO_NAME: + SCENARIO_TYPE: system + SCENARIO_NAME: k8s-crud-statefulset-test stages: - - stage: # format: [_]+ (e.g. azure_eastus2, aws_eastus_westus) + - stage: azure_australiaeast dependsOn: [] jobs: - - template: /jobs/competitive-test.yml # must keep as is + - template: /jobs/competitive-test.yml parameters: - cloud: # e.g. azure, aws - regions: # list of regions - - region1 # e.g. eastus2 - topology: # e.g. cluster-autoscaler - engine: # e.g. clusterloader2 - matrix: # list of test parameters to customize the provisioned resources - : - : - : - max_parallel: # required - credential_type: service_connection # required + cloud: azure + regions: + - australiaeast + topology: k8s-crud + engine: crud + matrix: + statefulset_crud: + pool_name: testpool + vm_size: Standard_D4s_v3 + create_node_count: 0 + scale_node_count: 3 + scale_step_size: 1 + step_time_out: 600 + step_wait_time: 30 + count: 1 + replicas: 10 + manifest_dir: "" + max_parallel: 1 + credential_type: service_connection ssh_key_enabled: false - timeout_in_minutes: 60 # if not specified, default is 60 + timeout_in_minutes: 120 From 6f54c8e37e45983080152381af9d6ed0be55820d Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 14 May 2026 15:04:27 -0400 Subject: [PATCH 10/19] fix: use k8s-crud-gpu topology (k8s-crud doesn't exist) --- pipelines/system/new-pipeline-test.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index e9b9df788a..22b4435c8a 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -13,7 +13,7 @@ stages: cloud: azure regions: - australiaeast - topology: k8s-crud + topology: k8s-crud-gpu engine: crud matrix: statefulset_crud: From 4e5c53d2734912ff325ce79800d1fa9a2f33408b Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Fri, 15 May 2026 10:25:33 -0400 Subject: [PATCH 11/19] fix: use existing perf-eval scenario for pipeline test The k8s-gpu-cluster-crud scenario already has terraform inputs. Custom scenario dirs will be reverted before merge. --- pipelines/system/new-pipeline-test.yml | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 22b4435c8a..268a7f82f0 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -1,8 +1,8 @@ trigger: none variables: - SCENARIO_TYPE: system - SCENARIO_NAME: k8s-crud-statefulset-test + SCENARIO_TYPE: perf-eval + SCENARIO_NAME: k8s-gpu-cluster-crud stages: - stage: azure_australiaeast From 3e09fe0e1799f7c569e72648ee287bbbf2563d23 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Fri, 15 May 2026 11:58:47 -0400 Subject: [PATCH 12/19] fix: add gpu_node_pool to test config and fix workload label collision - Add gpu_node_pool: '' to pipeline test matrix to prevent GPU driver installation on non-GPU VM (Standard_D4s_v3) - Include workload type in pod labels to prevent collision when both deployment and statefulset run in the same pipeline: - deployment: nginx-container-deployment-{index} - statefulset: nginx-container-statefulset-{index} Previously both used nginx-container-{index}, causing wait_for_pods_ready to see 20 pods when expecting 10 --- modules/python/crud/azure/node_pool_crud.py | 8 ++++---- pipelines/system/new-pipeline-test.yml | 1 + 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index f25fd98b3f..906bab5ffc 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -297,8 +297,8 @@ def _apply_deployment( # Generate deployment name deployment_name = f"myapp-{node_pool_name}-{deployment_index}" - # Use per-deployment label to avoid selector collision - deployment_label = f"{label_selector.split('=', 1)[-1]}-{deployment_index}" + # Use per-deployment label to avoid selector collision across workload types + deployment_label = f"{label_selector.split('=', 1)[-1]}-deployment-{deployment_index}" # Create deployment template using k8s_client.create_template deployment_template = k8s_client.create_template( @@ -434,8 +434,8 @@ def _apply_statefulset( # Generate StatefulSet name statefulset_name = f"myapp-{node_pool_name}-{statefulset_index}" - # Use per-statefulset label to avoid selector collision - statefulset_label = f"{label_selector.split('=', 1)[-1]}-{statefulset_index}" + # Use per-statefulset label to avoid selector collision across workload types + statefulset_label = f"{label_selector.split('=', 1)[-1]}-statefulset-{statefulset_index}" # Create StatefulSet template using k8s_client.create_template statefulset_template = k8s_client.create_template( diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 268a7f82f0..8fb87114ae 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -17,6 +17,7 @@ stages: engine: crud matrix: statefulset_crud: + gpu_node_pool: "" pool_name: testpool vm_size: Standard_D4s_v3 create_node_count: 0 From cd7bd005c0c5549add8a8a945cffb712b937f349 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Fri, 15 May 2026 12:38:13 -0400 Subject: [PATCH 13/19] revert: restore pipeline test placeholder before merge --- pipelines/system/new-pipeline-test.yml | 41 ++++++++++---------------- 1 file changed, 16 insertions(+), 25 deletions(-) diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 8fb87114ae..63d55f02d9 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -1,34 +1,25 @@ trigger: none variables: - SCENARIO_TYPE: perf-eval - SCENARIO_NAME: k8s-gpu-cluster-crud + SCENARIO_TYPE: + SCENARIO_NAME: stages: - - stage: azure_australiaeast + - stage: # format: [_]+ (e.g. azure_eastus2, aws_eastus_westus) dependsOn: [] jobs: - - template: /jobs/competitive-test.yml + - template: /jobs/competitive-test.yml # must keep as is parameters: - cloud: azure - regions: - - australiaeast - topology: k8s-crud-gpu - engine: crud - matrix: - statefulset_crud: - gpu_node_pool: "" - pool_name: testpool - vm_size: Standard_D4s_v3 - create_node_count: 0 - scale_node_count: 3 - scale_step_size: 1 - step_time_out: 600 - step_wait_time: 30 - count: 1 - replicas: 10 - manifest_dir: "" - max_parallel: 1 - credential_type: service_connection + cloud: # e.g. azure, aws + regions: # list of regions + - region1 # e.g. eastus2 + topology: # e.g. cluster-autoscaler + engine: # e.g. clusterloader2 + matrix: # list of test parameters to customize the provisioned resources + : + : + : + max_parallel: # required + credential_type: service_connection # required ssh_key_enabled: false - timeout_in_minutes: 120 + timeout_in_minutes: 60 # if not specified, default is 60 From db3d34ceddb38e90d3a42042ca2ead9f82ec0cce Mon Sep 17 00:00:00 2001 From: Diamond <32712461+diamondpowell@users.noreply.github.com> Date: Tue, 26 May 2026 11:56:17 -0400 Subject: [PATCH 14/19] dropping the > 0 guard so scale-to-zero workloads behave correctly. Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com> --- modules/python/clients/kubernetes_client.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/modules/python/clients/kubernetes_client.py b/modules/python/clients/kubernetes_client.py index 2785dbfd17..f6464ffd95 100644 --- a/modules/python/clients/kubernetes_client.py +++ b/modules/python/clients/kubernetes_client.py @@ -1105,14 +1105,13 @@ def _check_statefulset_condition(self, resource_name: str, namespace: str, wait_ raise e def _is_statefulset_ready(self, statefulset) -> bool: - """Check if a statefulset has all replicas ready.""" + """Check if a statefulset has all replicas ready, including scale-to-zero.""" status = statefulset.status spec_replicas = statefulset.spec.replicas or 0 return ( status is not None and status.ready_replicas is not None and status.ready_replicas == spec_replicas - and spec_replicas > 0 ) def _is_deployment_condition_met(self, deployment, condition_type: str) -> bool: From 54ec06cfb630070f04d1d0b19ac27cd1eeee64c3 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Tue, 26 May 2026 13:13:03 -0400 Subject: [PATCH 15/19] Simplify YAML parameters per reviewer feedback --- steps/engine/crud/k8s/execute.yml | 68 ++++++++------------ steps/topology/k8s-crud-gpu/execute-crud.yml | 12 ---- 2 files changed, 28 insertions(+), 52 deletions(-) diff --git a/steps/engine/crud/k8s/execute.yml b/steps/engine/crud/k8s/execute.yml index 3191982a65..e84e3a1f7b 100644 --- a/steps/engine/crud/k8s/execute.yml +++ b/steps/engine/crud/k8s/execute.yml @@ -1,17 +1,5 @@ parameters: - result_dir: "" - vm_size: "" - create_node_count: "" - scale_node_count: "" - scale_step_up_count: "" - pool_name: "" cloud: "" - step_time_out: 600 - step_wait_time: 30 - gpu_node_pool: false - count: 1 - replicas: 10 - manifest_dir: "" steps: - script: | @@ -45,16 +33,16 @@ steps: workingDirectory: modules/python env: PYTHON_SCRIPT_FILE: $(Pipeline.Workspace)/s/modules/python/crud/main.py - VM_SIZE: ${{ parameters.vm_size }} - CREATE_NODE_COUNT: ${{ parameters.create_node_count }} - SCALE_NODE_COUNT: ${{ parameters.scale_node_count }} - SCALE_STEP_SIZE: ${{ parameters.scale_step_up_count }} - POOL_NAME: ${{ parameters.pool_name }} + VM_SIZE: $(VM_SIZE) + CREATE_NODE_COUNT: $(CREATE_NODE_COUNT) + SCALE_NODE_COUNT: $(SCALE_NODE_COUNT) + SCALE_STEP_SIZE: $(SCALE_STEP_SIZE) + POOL_NAME: $(POOL_NAME) CLOUD: ${{ parameters.cloud }} - STEP_TIME_OUT: ${{ parameters.step_time_out }} + STEP_TIME_OUT: $(STEP_TIME_OUT) RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) - GPU_NODE_POOL: ${{ parameters.gpu_node_pool }} - STEP_WAIT_TIME: ${{ parameters.step_wait_time }} + GPU_NODE_POOL: $(GPU_NODE_POOL) + STEP_WAIT_TIME: $(STEP_WAIT_TIME) ${{ if eq(parameters.cloud, 'aws') }}: CAPACITY_TYPE: $(CAPACITY_TYPE) @@ -77,14 +65,14 @@ steps: workingDirectory: modules/python env: PYTHON_SCRIPT_FILE: $(Pipeline.Workspace)/s/modules/python/crud/main.py - POOL_NAME: ${{ parameters.pool_name }} + POOL_NAME: $(POOL_NAME) CLOUD: ${{ parameters.cloud }} - STEP_TIME_OUT: ${{ parameters.step_time_out }} + STEP_TIME_OUT: $(STEP_TIME_OUT) RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) - GPU_NODE_POOL: ${{ parameters.gpu_node_pool }} - COUNT: ${{ parameters.count }} - REPLICAS: ${{ parameters.replicas }} - MANIFEST_DIR: ${{ parameters.manifest_dir }} + GPU_NODE_POOL: $(GPU_NODE_POOL) + COUNT: $(COUNT) + REPLICAS: $(REPLICAS) + MANIFEST_DIR: $(MANIFEST_DIR) - script: | set -eo pipefail @@ -104,14 +92,14 @@ steps: workingDirectory: modules/python env: PYTHON_SCRIPT_FILE: $(Pipeline.Workspace)/s/modules/python/crud/main.py - POOL_NAME: ${{ parameters.pool_name }} + POOL_NAME: $(POOL_NAME) CLOUD: ${{ parameters.cloud }} - STEP_TIME_OUT: ${{ parameters.step_time_out }} + STEP_TIME_OUT: $(STEP_TIME_OUT) RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) - GPU_NODE_POOL: ${{ parameters.gpu_node_pool }} - COUNT: ${{ parameters.count }} - REPLICAS: ${{ parameters.replicas }} - MANIFEST_DIR: ${{ parameters.manifest_dir }} + GPU_NODE_POOL: $(GPU_NODE_POOL) + COUNT: $(COUNT) + REPLICAS: $(REPLICAS) + MANIFEST_DIR: $(MANIFEST_DIR) - script: | set -eo pipefail @@ -140,15 +128,15 @@ steps: workingDirectory: modules/python env: PYTHON_SCRIPT_FILE: $(Pipeline.Workspace)/s/modules/python/crud/main.py - VM_SIZE: ${{ parameters.vm_size }} - CREATE_NODE_COUNT: ${{ parameters.create_node_count }} - SCALE_NODE_COUNT: ${{ parameters.scale_node_count }} - SCALE_STEP_SIZE: ${{ parameters.scale_step_up_count }} - POOL_NAME: ${{ parameters.pool_name }} + VM_SIZE: $(VM_SIZE) + CREATE_NODE_COUNT: $(CREATE_NODE_COUNT) + SCALE_NODE_COUNT: $(SCALE_NODE_COUNT) + SCALE_STEP_SIZE: $(SCALE_STEP_SIZE) + POOL_NAME: $(POOL_NAME) CLOUD: ${{ parameters.cloud }} - STEP_TIME_OUT: ${{ parameters.step_time_out }} + STEP_TIME_OUT: $(STEP_TIME_OUT) RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) - GPU_NODE_POOL: ${{ parameters.gpu_node_pool }} - STEP_WAIT_TIME: ${{ parameters.step_wait_time }} + GPU_NODE_POOL: $(GPU_NODE_POOL) + STEP_WAIT_TIME: $(STEP_WAIT_TIME) ${{ if eq(parameters.cloud, 'aws') }}: CAPACITY_TYPE: $(CAPACITY_TYPE) diff --git a/steps/topology/k8s-crud-gpu/execute-crud.yml b/steps/topology/k8s-crud-gpu/execute-crud.yml index 1c2b02d9c6..1b585b617e 100644 --- a/steps/topology/k8s-crud-gpu/execute-crud.yml +++ b/steps/topology/k8s-crud-gpu/execute-crud.yml @@ -13,15 +13,3 @@ steps: - template: /steps/engine/crud/k8s/execute.yml parameters: cloud: ${{ parameters.cloud }} - vm_size: $(VM_SIZE) - create_node_count: $(CREATE_NODE_COUNT) - scale_node_count: $(SCALE_NODE_COUNT) - scale_step_up_count: $(SCALE_STEP_SIZE) - pool_name: $(POOL_NAME) - step_time_out: $(STEP_TIME_OUT) - result_dir: $(System.DefaultWorkingDirectory)/$(RUN_ID) - gpu_node_pool: $(GPU_NODE_POOL) - step_wait_time: $(STEP_WAIT_TIME) - count: $(COUNT) - replicas: $(REPLICAS) - manifest_dir: $(MANIFEST_DIR) From fc7adf93de8d31923b042c76ec10e8daebe3c36d Mon Sep 17 00:00:00 2001 From: Praneel Seth Date: Wed, 27 May 2026 14:46:40 +0000 Subject: [PATCH 16/19] Add WORKLOAD_CONFIG for unified workload helper --- modules/python/crud/azure/node_pool_crud.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 906bab5ffc..2f9e0410ce 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -23,6 +23,24 @@ get_logger("azure.core.pipeline").setLevel(logging.ERROR) get_logger("msal").setLevel(logging.ERROR) +# Workload type configuration for unified _apply_workload helper +WORKLOAD_CONFIG = { + "deployment": { + "template_file": "deployment.yml", + "count_key": "DEPLOYMENT_REPLICAS", + "resource_type": "deployment", + "wait_condition": "available", + "verify_pods_ready": True, + }, + "statefulset": { + "template_file": "statefulset.yml", + "count_key": "STATEFULSET_REPLICAS", + "resource_type": "statefulset", + "wait_condition": "ready", + "verify_pods_ready": True, + }, + # jobs workload config will be added later +} class NodePoolCRUD: """Performs AKS node pool operations - metrics collection is handled directly by AKSClient""" From 9d841d9b26d52f3371eef12f168d592a4cdf2e89 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Wed, 27 May 2026 15:20:37 -0400 Subject: [PATCH 17/19] Refactor: add unified _apply_workload helper for deployment/statefulset --- modules/python/crud/azure/node_pool_crud.py | 206 ++++++++++---------- 1 file changed, 99 insertions(+), 107 deletions(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 2f9e0410ce..dc04f7e33f 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -39,7 +39,6 @@ "wait_condition": "ready", "verify_pods_ready": True, }, - # jobs workload config will be added later } class NodePoolCRUD: @@ -291,79 +290,123 @@ def all( errors.append(error_msg) return False - def _apply_deployment( + def _apply_workload( self, k8s_client, + workload_type, node_pool_name, - deployment_index, - replicas, + index, + count, manifest_dir, label_selector, namespace ): - """Helper for create_deployment — applies and verifies a single deployment.""" + """Unified helper to apply and verify a single workload instance. + + Args: + k8s_client: Kubernetes client instance + workload_type: Type of workload ("deployment" or "statefulset") + node_pool_name: Name of the target node pool + index: Workload instance index (1-based) + count: Number of replicas/completions + manifest_dir: Optional custom manifest directory + label_selector: Base label selector (e.g., "app=nginx-container") + namespace: Kubernetes namespace + + Raises: + ValueError: If workload_type is not in WORKLOAD_CONFIG + TimeoutError: If workload fails to reach ready state + """ + if workload_type not in WORKLOAD_CONFIG: + raise ValueError(f"Unknown workload type: {workload_type}") + + config = WORKLOAD_CONFIG[workload_type] + + # Resolve template path if manifest_dir: - # Use the template path from manifest_dir - template_path = f"{manifest_dir}/deployment.yml" + template_path = f"{manifest_dir}/{config['template_file']}" else: - # Use default template path (relative to workingDirectory: modules/python) template_path = os.path.join( os.path.dirname(os.path.abspath(__file__)), - "..", "workload_templates", "deployment.yml" + "..", "workload_templates", config["template_file"] ) - - # Generate deployment name - deployment_name = f"myapp-{node_pool_name}-{deployment_index}" - - # Use per-deployment label to avoid selector collision across workload types - deployment_label = f"{label_selector.split('=', 1)[-1]}-deployment-{deployment_index}" - - # Create deployment template using k8s_client.create_template - deployment_template = k8s_client.create_template( + + # Generate resource name and label + resource_name = f"myapp-{node_pool_name}-{index}" + workload_label = f"{label_selector.split('=', 1)[-1]}-{workload_type}-{index}" + + # Render template + rendered_template = k8s_client.create_template( template_path, { - "DEPLOYMENT_REPLICAS": replicas, + config["count_key"]: count, "NODE_POOL_NAME": node_pool_name, - "INDEX": deployment_index, - "LABEL_VALUE": deployment_label, + "INDEX": index, + "LABEL_VALUE": workload_label, } ) - + # Apply each document in the rendered multi-doc template - for doc in yaml.safe_load_all(deployment_template): + for doc in yaml.safe_load_all(rendered_template): if doc: k8s_client.apply_manifest_from_file(manifest_dict=doc, namespace=namespace) - - logger.info("Applied manifest for deployment %s", deployment_name) - - # Wait for deployment to be available (successful deployment verification) - logger.info("Waiting for deployment %s to become available...", deployment_name) - deployment_ready = k8s_client.wait_for_condition( - resource_type="deployment", - wait_condition_type="available", - resource_name=deployment_name, + + logger.info("Applied manifest for %s %s", workload_type, resource_name) + + # Wait for workload to reach target condition + logger.info("Waiting for %s %s to become %s...", + workload_type, resource_name, config["wait_condition"]) + ready = k8s_client.wait_for_condition( + resource_type=config["resource_type"], + wait_condition_type=config["wait_condition"], + resource_name=resource_name, namespace=namespace, timeout_seconds=self.step_timeout ) - - if not deployment_ready: + + if not ready: raise TimeoutError( - f"Deployment {deployment_name} failed to become available within timeout" + f"{workload_type.capitalize()} {resource_name} failed to become " + f"{config['wait_condition']} within timeout" ) + + logger.info("%s %s is successfully %s", + workload_type.capitalize(), resource_name, config["wait_condition"]) + + # Wait for pods if configured (skipped for Jobs) + if config["verify_pods_ready"]: + logger.info("Waiting for pods of %s %s to be ready...", workload_type, resource_name) + k8s_client.wait_for_pods_ready( + operation_timeout_in_minutes=5, + namespace=namespace, + pod_count=count, + label_selector=f"app={workload_label}" + ) + + logger.info("Successfully created and verified %s %d", workload_type, index) - logger.info("Deployment %s is successfully available", deployment_name) - - # Additionally wait for pods to be ready - logger.info("Waiting for pods of deployment %s to be ready...", deployment_name) - k8s_client.wait_for_pods_ready( - operation_timeout_in_minutes=5, - namespace=namespace, - pod_count=replicas, - label_selector=f"app={deployment_label}" + def _apply_deployment( + self, + k8s_client, + node_pool_name, + deployment_index, + replicas, + manifest_dir, + label_selector, + namespace + ): + """Helper for create_deployment - delegates to unified _apply_workload.""" + self._apply_workload( + k8s_client=k8s_client, + workload_type="deployment", + node_pool_name=node_pool_name, + index=deployment_index, + count=replicas, + manifest_dir=manifest_dir, + label_selector=label_selector, + namespace=namespace ) - logger.info("Successfully created and verified deployment %d", deployment_index) - def create_deployment( self, node_pool_name, @@ -438,69 +481,18 @@ def _apply_statefulset( label_selector, namespace ): - """Helper for create_statefulset — applies and verifies a single StatefulSet.""" - if manifest_dir: - # Use the template path from manifest_dir - template_path = f"{manifest_dir}/statefulset.yml" - else: - # Use default template path (relative to workingDirectory: modules/python) - template_path = os.path.join( - os.path.dirname(os.path.abspath(__file__)), - "..", "workload_templates", "statefulset.yml" - ) - - # Generate StatefulSet name - statefulset_name = f"myapp-{node_pool_name}-{statefulset_index}" - - # Use per-statefulset label to avoid selector collision across workload types - statefulset_label = f"{label_selector.split('=', 1)[-1]}-statefulset-{statefulset_index}" - - # Create StatefulSet template using k8s_client.create_template - statefulset_template = k8s_client.create_template( - template_path, - { - "STATEFULSET_REPLICAS": replicas, - "NODE_POOL_NAME": node_pool_name, - "INDEX": statefulset_index, - "LABEL_VALUE": statefulset_label, - } + """Helper for create_statefulset - delegates to unified _apply_workload.""" + self._apply_workload( + k8s_client=k8s_client, + workload_type="statefulset", + node_pool_name=node_pool_name, + index=statefulset_index, + count=replicas, + manifest_dir=manifest_dir, + label_selector=label_selector, + namespace=namespace ) - # Apply each document in the rendered multi-doc template - for doc in yaml.safe_load_all(statefulset_template): - if doc: - k8s_client.apply_manifest_from_file(manifest_dict=doc, namespace=namespace) - - logger.info("Applied manifest for StatefulSet %s", statefulset_name) - - # Wait for statefulset to be ready (successful statefulset verification) - logger.info("Waiting for StatefulSet %s to become ready...", statefulset_name) - statefulset_ready = k8s_client.wait_for_condition( - resource_type="statefulset", - wait_condition_type="ready", - resource_name=statefulset_name, - namespace=namespace, - timeout_seconds=self.step_timeout - ) - - if not statefulset_ready: - raise TimeoutError( - f"StatefulSet {statefulset_name} failed to become ready within timeout" - ) - - logger.info("StatefulSet %s is successfully ready", statefulset_name) - - # Additionally wait for pods to be ready - logger.info("Waiting for pods of StatefulSet %s to be ready...", statefulset_name) - k8s_client.wait_for_pods_ready( - operation_timeout_in_minutes=5, - namespace=namespace, - pod_count=replicas, - label_selector=f"app={statefulset_label}" - ) - - logger.info("Successfully created and verified StatefulSet %d", statefulset_index) - def create_statefulset( self, node_pool_name, From 3396ec1d8f8e94c014814dbbafd58ea6859c7241 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Wed, 27 May 2026 15:28:53 -0400 Subject: [PATCH 18/19] Refactor: add unified _create_workloads helper for deployment/statefulset --- modules/python/crud/azure/node_pool_crud.py | 170 +++++++------------- 1 file changed, 62 insertions(+), 108 deletions(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index dc04f7e33f..2ebc5f49f7 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -385,109 +385,94 @@ def _apply_workload( logger.info("Successfully created and verified %s %d", workload_type, index) - def _apply_deployment( + def _create_workloads( self, - k8s_client, + workload_type, node_pool_name, - deployment_index, - replicas, + count, + number_of_workloads, manifest_dir, label_selector, namespace ): - """Helper for create_deployment - delegates to unified _apply_workload.""" - self._apply_workload( - k8s_client=k8s_client, - workload_type="deployment", - node_pool_name=node_pool_name, - index=deployment_index, - count=replicas, - manifest_dir=manifest_dir, - label_selector=label_selector, - namespace=namespace - ) - - def create_deployment( - self, - node_pool_name, - replicas=10, - manifest_dir=None, - number_of_deployments=1, - label_selector="app=nginx-container", - namespace="default" - ): - """ - Create Kubernetes deployments after node pool operations. - + """Unified helper to create multiple workload instances. + Args: - node_pool_name: Name of the node pool to target - replicas: Number of deployment replicas per deployment (default: 10) - manifest_dir: Directory containing Kubernetes manifest files - number_of_deployments: Number of deployments to create (default: 1) - label_selector: Label selector used to target the deployment workload - namespace: Kubernetes namespace (default: "default") - + workload_type: Type of workload ("deployment" or "statefulset") + node_pool_name: Name of the target node pool + count: Number of replicas per workload instance + number_of_workloads: Total number of workload instances to create + manifest_dir: Optional custom manifest directory + label_selector: Base label selector (e.g., "app=nginx-container") + namespace: Kubernetes namespace + Returns: - True if all deployment creations were successful, False otherwise + True if all workloads created successfully, False otherwise """ - logger.info("Creating %d deployment(s)", number_of_deployments) + workload_type_display = workload_type.capitalize() + logger.info("Creating %d %s(s)", number_of_workloads, workload_type_display) logger.info("Target node pool: %s", node_pool_name) - logger.info("Replicas per deployment: %d", replicas) + logger.info("Replicas per %s: %d", workload_type, count) logger.info("Using manifest directory: %s", manifest_dir) - # Get Kubernetes client from AKS client k8s_client = self.aks_client.k8s_client - if not k8s_client: logger.error("Kubernetes client not available") return False - successful_deployments = 0 - - # Loop through number of deployments - for deployment_index in range(1, number_of_deployments + 1): - logger.info("Creating deployment %d/%d", deployment_index, number_of_deployments) - + 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_deployment( + self._apply_workload( k8s_client=k8s_client, + workload_type=workload_type, node_pool_name=node_pool_name, - deployment_index=deployment_index, - replicas=replicas, + index=index, + count=count, manifest_dir=manifest_dir, label_selector=label_selector, namespace=namespace ) - successful_deployments += 1 + successes += 1 except Exception as e: - logger.error("Failed to create deployment %d: %s", deployment_index, e) - # Continue with next deployment instead of failing completely + logger.error("Failed to create %s %d: %s", workload_type, index, e) continue - # Check if all deployments were successful - if successful_deployments == number_of_deployments: - logger.info("Successfully created all %d deployment(s)", number_of_deployments) + 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 deployment(s)", successful_deployments, number_of_deployments) + logger.warning("Created %d/%d %s(s)", successes, number_of_workloads, workload_type_display) return False - def _apply_statefulset( + def create_deployment( self, - k8s_client, node_pool_name, - statefulset_index, - replicas, - manifest_dir, - label_selector, - namespace + replicas=10, + manifest_dir=None, + number_of_deployments=1, + label_selector="app=nginx-container", + namespace="default" ): - """Helper for create_statefulset - delegates to unified _apply_workload.""" - self._apply_workload( - k8s_client=k8s_client, - workload_type="statefulset", + """ + Create Kubernetes deployments after node pool operations. + + Args: + node_pool_name: Name of the node pool to target + replicas: Number of deployment replicas per deployment (default: 10) + manifest_dir: Directory containing Kubernetes manifest files + number_of_deployments: Number of deployments to create (default: 1) + label_selector: Label selector used to target the deployment workload + namespace: Kubernetes namespace (default: "default") + + Returns: + True if all deployment creations were successful, False otherwise + """ + return self._create_workloads( + workload_type="deployment", node_pool_name=node_pool_name, - index=statefulset_index, count=replicas, + number_of_workloads=number_of_deployments, manifest_dir=manifest_dir, label_selector=label_selector, namespace=namespace @@ -516,43 +501,12 @@ def create_statefulset( Returns: True if all StatefulSet creations were successful, False otherwise """ - logger.info("Creating %d StatefulSet(s)", number_of_statefulsets) - logger.info("Target node pool: %s", node_pool_name) - logger.info("Replicas per StatefulSet: %d", replicas) - logger.info("Using manifest directory: %s", manifest_dir) - - # Get Kubernetes client from AKS client - k8s_client = self.aks_client.k8s_client - - if not k8s_client: - logger.error("Kubernetes client not available") - return False - - successful_statefulsets = 0 - - # Loop through number of StatefulSets - for statefulset_index in range(1, number_of_statefulsets + 1): - logger.info("Creating StatefulSet %d/%d", statefulset_index, number_of_statefulsets) - - try: - self._apply_statefulset( - k8s_client=k8s_client, - node_pool_name=node_pool_name, - statefulset_index=statefulset_index, - replicas=replicas, - manifest_dir=manifest_dir, - label_selector=label_selector, - namespace=namespace - ) - successful_statefulsets += 1 - except Exception as e: - logger.error("Failed to create StatefulSet %d: %s", statefulset_index, e) - # Continue with next StatefulSet instead of failing completely - continue - - # Check if all StatefulSets were successful - if successful_statefulsets == number_of_statefulsets: - logger.info("Successfully created all %d StatefulSet(s)", number_of_statefulsets) - return True - logger.warning("Created %d/%d StatefulSet(s)", successful_statefulsets, number_of_statefulsets) - return False + return self._create_workloads( + workload_type="statefulset", + node_pool_name=node_pool_name, + count=replicas, + number_of_workloads=number_of_statefulsets, + manifest_dir=manifest_dir, + label_selector=label_selector, + namespace=namespace + ) From f84cf84fe54a1dacfc1c1d246429be2152c81c58 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Wed, 27 May 2026 15:41:01 -0400 Subject: [PATCH 19/19] Refactor: reorder workload methods - public first, helpers last --- modules/python/crud/azure/node_pool_crud.py | 282 ++++++++++---------- 1 file changed, 141 insertions(+), 141 deletions(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 2ebc5f49f7..d475de9ca9 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -290,6 +290,132 @@ def all( errors.append(error_msg) return False + def create_deployment( + self, + node_pool_name, + replicas=10, + manifest_dir=None, + number_of_deployments=1, + label_selector="app=nginx-container", + namespace="default" + ): + """ + Create Kubernetes deployments after node pool operations. + + Args: + node_pool_name: Name of the node pool to target + replicas: Number of deployment replicas per deployment (default: 10) + manifest_dir: Directory containing Kubernetes manifest files + number_of_deployments: Number of deployments to create (default: 1) + label_selector: Label selector used to target the deployment workload + namespace: Kubernetes namespace (default: "default") + + Returns: + True if all deployment creations were successful, False otherwise + """ + return self._create_workloads( + workload_type="deployment", + node_pool_name=node_pool_name, + count=replicas, + number_of_workloads=number_of_deployments, + manifest_dir=manifest_dir, + label_selector=label_selector, + namespace=namespace + ) + + def create_statefulset( + self, + node_pool_name, + replicas=10, + manifest_dir=None, + number_of_statefulsets=1, + label_selector="app=nginx-container", + namespace="default" + ): + """ + Create Kubernetes StatefulSets after node pool operations. + + Args: + node_pool_name: Name of the node pool to target + namespace: Kubernetes namespace (default: "default") + replicas: Number of replicas for the StatefulSet (default: 10) + manifest_dir: Directory containing Kubernetes manifest files + number_of_statefulsets: Number of StatefulSets to create (default: 1) + label_selector: Label selector for pods (default: "app=nginx-container") + + Returns: + True if all StatefulSet creations were successful, False otherwise + """ + return self._create_workloads( + workload_type="statefulset", + node_pool_name=node_pool_name, + count=replicas, + number_of_workloads=number_of_statefulsets, + manifest_dir=manifest_dir, + label_selector=label_selector, + namespace=namespace + ) + + def _create_workloads( + self, + workload_type, + node_pool_name, + count, + number_of_workloads, + manifest_dir, + label_selector, + namespace + ): + """Unified helper to create multiple workload instances. + + Args: + workload_type: Type of workload ("deployment" or "statefulset") + node_pool_name: Name of the target node pool + count: Number of replicas per workload instance + number_of_workloads: Total number of workload instances to create + manifest_dir: Optional custom manifest directory + label_selector: Base label selector (e.g., "app=nginx-container") + namespace: Kubernetes namespace + + Returns: + True if all workloads created successfully, False otherwise + """ + workload_type_display = workload_type.capitalize() + logger.info("Creating %d %s(s)", number_of_workloads, workload_type_display) + logger.info("Target node pool: %s", node_pool_name) + 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 + + 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 + def _apply_workload( self, k8s_client, @@ -302,7 +428,7 @@ def _apply_workload( namespace ): """Unified helper to apply and verify a single workload instance. - + Args: k8s_client: Kubernetes client instance workload_type: Type of workload ("deployment" or "statefulset") @@ -312,16 +438,16 @@ def _apply_workload( manifest_dir: Optional custom manifest directory label_selector: Base label selector (e.g., "app=nginx-container") namespace: Kubernetes namespace - + Raises: ValueError: If workload_type is not in WORKLOAD_CONFIG TimeoutError: If workload fails to reach ready state """ if workload_type not in WORKLOAD_CONFIG: raise ValueError(f"Unknown workload type: {workload_type}") - + config = WORKLOAD_CONFIG[workload_type] - + # Resolve template path if manifest_dir: template_path = f"{manifest_dir}/{config['template_file']}" @@ -330,11 +456,11 @@ def _apply_workload( os.path.dirname(os.path.abspath(__file__)), "..", "workload_templates", config["template_file"] ) - + # Generate resource name and label resource_name = f"myapp-{node_pool_name}-{index}" workload_label = f"{label_selector.split('=', 1)[-1]}-{workload_type}-{index}" - + # Render template rendered_template = k8s_client.create_template( template_path, @@ -345,16 +471,16 @@ def _apply_workload( "LABEL_VALUE": workload_label, } ) - + # Apply each document in the rendered multi-doc template for doc in yaml.safe_load_all(rendered_template): if doc: k8s_client.apply_manifest_from_file(manifest_dict=doc, namespace=namespace) - + logger.info("Applied manifest for %s %s", workload_type, resource_name) - + # Wait for workload to reach target condition - logger.info("Waiting for %s %s to become %s...", + logger.info("Waiting for %s %s to become %s...", workload_type, resource_name, config["wait_condition"]) ready = k8s_client.wait_for_condition( resource_type=config["resource_type"], @@ -363,16 +489,16 @@ def _apply_workload( namespace=namespace, timeout_seconds=self.step_timeout ) - + if not ready: raise TimeoutError( f"{workload_type.capitalize()} {resource_name} failed to become " f"{config['wait_condition']} within timeout" ) - - logger.info("%s %s is successfully %s", + + logger.info("%s %s is successfully %s", workload_type.capitalize(), resource_name, config["wait_condition"]) - + # Wait for pods if configured (skipped for Jobs) if config["verify_pods_ready"]: logger.info("Waiting for pods of %s %s to be ready...", workload_type, resource_name) @@ -382,131 +508,5 @@ def _apply_workload( pod_count=count, label_selector=f"app={workload_label}" ) - - logger.info("Successfully created and verified %s %d", workload_type, index) - - def _create_workloads( - self, - workload_type, - node_pool_name, - count, - number_of_workloads, - manifest_dir, - label_selector, - namespace - ): - """Unified helper to create multiple workload instances. - - Args: - workload_type: Type of workload ("deployment" or "statefulset") - node_pool_name: Name of the target node pool - count: Number of replicas per workload instance - number_of_workloads: Total number of workload instances to create - manifest_dir: Optional custom manifest directory - label_selector: Base label selector (e.g., "app=nginx-container") - namespace: Kubernetes namespace - - Returns: - True if all workloads created successfully, False otherwise - """ - workload_type_display = workload_type.capitalize() - logger.info("Creating %d %s(s)", number_of_workloads, workload_type_display) - logger.info("Target node pool: %s", node_pool_name) - 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 - - 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 - - def create_deployment( - self, - node_pool_name, - replicas=10, - manifest_dir=None, - number_of_deployments=1, - label_selector="app=nginx-container", - namespace="default" - ): - """ - Create Kubernetes deployments after node pool operations. - - Args: - node_pool_name: Name of the node pool to target - replicas: Number of deployment replicas per deployment (default: 10) - manifest_dir: Directory containing Kubernetes manifest files - number_of_deployments: Number of deployments to create (default: 1) - label_selector: Label selector used to target the deployment workload - namespace: Kubernetes namespace (default: "default") - - Returns: - True if all deployment creations were successful, False otherwise - """ - return self._create_workloads( - workload_type="deployment", - node_pool_name=node_pool_name, - count=replicas, - number_of_workloads=number_of_deployments, - manifest_dir=manifest_dir, - label_selector=label_selector, - namespace=namespace - ) - - def create_statefulset( - self, - node_pool_name, - replicas=10, - manifest_dir=None, - number_of_statefulsets=1, - label_selector="app=nginx-container", - namespace="default" - ): - """ - Create Kubernetes StatefulSets after node pool operations. - - Args: - node_pool_name: Name of the node pool to target - namespace: Kubernetes namespace (default: "default") - replicas: Number of replicas for the StatefulSet (default: 10) - manifest_dir: Directory containing Kubernetes manifest files - number_of_statefulsets: Number of StatefulSets to create (default: 1) - label_selector: Label selector for pods (default: "app=nginx-container") - - Returns: - True if all StatefulSet creations were successful, False otherwise - """ - return self._create_workloads( - workload_type="statefulset", - node_pool_name=node_pool_name, - count=replicas, - number_of_workloads=number_of_statefulsets, - manifest_dir=manifest_dir, - label_selector=label_selector, - namespace=namespace - ) + logger.info("Successfully created and verified %s %d", workload_type, index)