From 50d53358e61f0f41c65dc1d2dba2aa9ab90ecc50 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Wed, 3 Jun 2026 13:15:59 -0400 Subject: [PATCH 01/12] Register crud module in pyproject.toml Add crud to packages list and telescope-crud entry point. Enables pip install telescope-benchmarks to include CRUD module. --- modules/python/pyproject.toml | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/modules/python/pyproject.toml b/modules/python/pyproject.toml index c03218cb95..8b7d2a4b56 100644 --- a/modules/python/pyproject.toml +++ b/modules/python/pyproject.toml @@ -28,7 +28,7 @@ Source = "https://github.com/Azure/telescope" Documentation = "https://github.com/Azure/telescope/tree/main/modules/python" [tool.setuptools] -packages = ["iperf3", "clients", "utils", "clusterloader2", "kwok", "gpu"] +packages = ["iperf3", "clients", "utils", "clusterloader2", "kwok", "gpu", "crud"] [tool.setuptools.dynamic] dependencies = {file = "requirements.txt"} @@ -38,3 +38,4 @@ telescope-iperf3 = "iperf3.iperf3_pod:main" telescope-cl2-autoscale = "clusterloader2.autoscale.autoscale:main" telescope-cl2-cri = "clusterloader2.cri.cri:main" telescope-kwok = "kwok.kwok:main" +telescope-crud = "crud.main:main" From a5b5d6e2b80a6a55396e9248d2ca678271de4960 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Wed, 5 Aug 2026 23:00:51 -0400 Subject: [PATCH 02/12] add exclude_managed_identity param for pipeline auth --- modules/python/crud/azure/node_pool_crud.py | 2 +- modules/python/tests/crud/test_azure_node_pool_crud.py | 4 +++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 03f3f36635..8f397d2724 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -62,7 +62,7 @@ def __init__( kube_config_file=kube_config_file, result_dir=result_dir, operation_timeout_minutes=step_timeout / 60, # Convert seconds to minutes - credential=configure_credential(), + credential=configure_credential(default_credential_exclude_mi=True), ) if not self.aks_client: 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 afa0734652..d0c7d6bc11 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -51,7 +51,9 @@ def tearDown(self): def test_init_injects_configured_credential(self): """Test that the configured credential is passed to AKSClient.""" - self.mock_configure_credential.assert_called_once_with() + self.mock_configure_credential.assert_called_once_with( + default_credential_exclude_mi=True + ) self.mock_aks_client_cls.assert_called_once_with( resource_group="fake-resource-group", kube_config_file=None, From 81d14875c126bede6f75797969c2cca758e67caf Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 6 Aug 2026 11:20:36 -0400 Subject: [PATCH 03/12] fix: add missing __init__.py and register crud sub-packages crud/azure was missing __init__.py, and crud.azure and crud.aws sub-packages were not listed in pyproject.toml packages. After pip install, imports like 'from crud.azure.node_pool_crud import NodePoolCRUD' would fail with ModuleNotFoundError. --- modules/python/crud/azure/__init__.py | 0 modules/python/pyproject.toml | 2 +- 2 files changed, 1 insertion(+), 1 deletion(-) create mode 100644 modules/python/crud/azure/__init__.py diff --git a/modules/python/crud/azure/__init__.py b/modules/python/crud/azure/__init__.py new file mode 100644 index 0000000000..e69de29bb2 diff --git a/modules/python/pyproject.toml b/modules/python/pyproject.toml index 8b7d2a4b56..26880dcd57 100644 --- a/modules/python/pyproject.toml +++ b/modules/python/pyproject.toml @@ -28,7 +28,7 @@ Source = "https://github.com/Azure/telescope" Documentation = "https://github.com/Azure/telescope/tree/main/modules/python" [tool.setuptools] -packages = ["iperf3", "clients", "utils", "clusterloader2", "kwok", "gpu", "crud"] +packages = ["iperf3", "clients", "utils", "clusterloader2", "kwok", "gpu", "crud", "crud.azure", "crud.aws"] [tool.setuptools.dynamic] dependencies = {file = "requirements.txt"} From e4edcbbcc49622e6c62f136888abb699937a0cdd Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Wed, 19 Aug 2026 16:34:39 -0400 Subject: [PATCH 04/12] fix: support installed CRUD pipeline execution --- modules/python/crud/azure/node_pool_crud.py | 13 +++++++-- modules/python/crud/main.py | 12 +++++++++ modules/python/pyproject.toml | 3 +++ .../tests/crud/test_azure_node_pool_crud.py | 27 ++++++++++++++++--- 4 files changed, 50 insertions(+), 5 deletions(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 8f397d2724..7ef8aa2e7e 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -53,16 +53,25 @@ class NodePoolCRUD: """Performs AKS node pool operations - metrics collection is handled directly by AKSClient""" def __init__( - self, resource_group, kube_config_file=None, result_dir=None, step_timeout=600 + self, + resource_group, + cluster_name=None, + kube_config_file=None, + result_dir=None, + step_timeout=600, + exclude_managed_identity=False, ): """Initialize with Azure resource identifiers""" self.resource_group = resource_group self.aks_client = AKSClient( resource_group=resource_group, + cluster_name=cluster_name, kube_config_file=kube_config_file, result_dir=result_dir, operation_timeout_minutes=step_timeout / 60, # Convert seconds to minutes - credential=configure_credential(default_credential_exclude_mi=True), + credential=configure_credential( + default_credential_exclude_mi=exclude_managed_identity + ), ) if not self.aks_client: diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index 1fad21a6a3..ec4e7040b1 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -412,6 +412,11 @@ def main(): help="Cloud provider should be Azure, Aws or GCP", ) common_parser.add_argument("--run-id", required=True, help="Unique run identifier") + common_parser.add_argument( + "--cluster-name", + default=None, + help="AKS cluster name; Azure discovers the first cluster when omitted", + ) common_parser.add_argument( "--result-dir", default=".", help="Directory to save results" ) @@ -449,6 +454,11 @@ def main(): default="ON_DEMAND", help="Capacity type for AWS/Azure node pool", ) + common_parser.add_argument( + "--exclude-managed-identity", + action="store_true", + help="Exclude managed identity from DefaultAzureCredential", + ) # Create command create_parser = subparsers.add_parser( @@ -667,9 +677,11 @@ def main(): if args.cloud == "azure": node_pool_crud = NodePoolCRUD( resource_group=args.run_id, + cluster_name=args.cluster_name, kube_config_file=args.kube_config, result_dir=args.result_dir, step_timeout=args.step_timeout, + exclude_managed_identity=args.exclude_managed_identity, ) elif args.cloud == "aws": node_pool_crud = NodePoolCRUD( diff --git a/modules/python/pyproject.toml b/modules/python/pyproject.toml index 26880dcd57..05d90a1ca5 100644 --- a/modules/python/pyproject.toml +++ b/modules/python/pyproject.toml @@ -30,6 +30,9 @@ Documentation = "https://github.com/Azure/telescope/tree/main/modules/python" [tool.setuptools] packages = ["iperf3", "clients", "utils", "clusterloader2", "kwok", "gpu", "crud", "crud.azure", "crud.aws"] +[tool.setuptools.package-data] +crud = ["workload_templates/*.yml"] + [tool.setuptools.dynamic] dependencies = {file = "requirements.txt"} 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 d0c7d6bc11..c2db4a3f2b 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -49,19 +49,40 @@ def tearDown(self): except OSError: pass - def test_init_injects_configured_credential(self): - """Test that the configured credential is passed to AKSClient.""" + def test_authentication_configuration(self): + """Credential configuration is injected with the requested MI behavior.""" self.mock_configure_credential.assert_called_once_with( - default_credential_exclude_mi=True + default_credential_exclude_mi=False ) self.mock_aks_client_cls.assert_called_once_with( resource_group="fake-resource-group", + cluster_name=None, kube_config_file=None, result_dir=self.test_result_dir, operation_timeout_minutes=10.0, credential=self.mock_credential, ) + self.mock_configure_credential.reset_mock() + self.mock_aks_client_cls.reset_mock() + NodePoolCRUD( + resource_group="fake-resource-group", + cluster_name="fake-cluster", + exclude_managed_identity=True, + ) + + self.mock_configure_credential.assert_called_once_with( + default_credential_exclude_mi=True + ) + self.mock_aks_client_cls.assert_called_once_with( + resource_group="fake-resource-group", + cluster_name="fake-cluster", + kube_config_file=None, + result_dir=None, + operation_timeout_minutes=10.0, + credential=self.mock_credential, + ) + def test_create_node_pool_success(self): """Test successful node pool creation""" # Setup From 2bc5c5885e8ba90b26659a9e047ddcc94e090293 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Wed, 19 Aug 2026 17:13:46 -0400 Subject: [PATCH 05/12] fix: preserve CRUD constructor compatibility --- modules/python/crud/azure/node_pool_crud.py | 2 +- .../tests/crud/test_azure_node_pool_crud.py | 20 +++++++++++++++++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 7ef8aa2e7e..cad61e91c4 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -55,10 +55,10 @@ class NodePoolCRUD: def __init__( self, resource_group, - cluster_name=None, kube_config_file=None, result_dir=None, step_timeout=600, + cluster_name=None, exclude_managed_identity=False, ): """Initialize with Azure resource identifiers""" 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 c2db4a3f2b..e838103d1a 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -83,6 +83,26 @@ def test_authentication_configuration(self): credential=self.mock_credential, ) + def test_existing_positional_arguments_remain_compatible(self): + """New options do not change the existing positional argument order.""" + self.mock_aks_client_cls.reset_mock() + + NodePoolCRUD( + "fake-resource-group", + "/tmp/fake-kubeconfig", + "/tmp/fake-results", + 300, + ) + + self.mock_aks_client_cls.assert_called_once_with( + resource_group="fake-resource-group", + cluster_name=None, + exclude_managed_identity=False, + kube_config_file="/tmp/fake-kubeconfig", + result_dir="/tmp/fake-results", + operation_timeout_minutes=5.0, + ) + def test_create_node_pool_success(self): """Test successful node pool creation""" # Setup From 3d1adc6b0e4cc04cacaef74db00a7aa66ac6078d Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 20 Aug 2026 14:29:06 -0400 Subject: [PATCH 06/12] fix: scope Azure CRUD CLI options --- modules/python/crud/main.py | 43 ++++++++++++++------- modules/python/tests/crud/test_main.py | 52 +++++++++++++++++++++++++- 2 files changed, 81 insertions(+), 14 deletions(-) diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index ec4e7040b1..98bb1dc53e 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -412,11 +412,6 @@ def main(): help="Cloud provider should be Azure, Aws or GCP", ) common_parser.add_argument("--run-id", required=True, help="Unique run identifier") - common_parser.add_argument( - "--cluster-name", - default=None, - help="AKS cluster name; Azure discovers the first cluster when omitted", - ) common_parser.add_argument( "--result-dir", default=".", help="Directory to save results" ) @@ -454,7 +449,14 @@ def main(): default="ON_DEMAND", help="Capacity type for AWS/Azure node pool", ) - common_parser.add_argument( + + azure_node_pool_parser = argparse.ArgumentParser(add_help=False) + azure_node_pool_parser.add_argument( + "--cluster-name", + default=None, + help="AKS cluster name; Azure discovers the first cluster when omitted", + ) + azure_node_pool_parser.add_argument( "--exclude-managed-identity", action="store_true", help="Exclude managed identity from DefaultAzureCredential", @@ -462,7 +464,9 @@ def main(): # Create command create_parser = subparsers.add_parser( - "create", parents=[common_parser], help="Create a node pool" + "create", + parents=[common_parser, azure_node_pool_parser], + help="Create a node pool", ) create_parser.add_argument("--node-pool-name", required=True, help="Node pool name") create_parser.add_argument( @@ -477,7 +481,9 @@ def main(): # Scale command scale_parser = subparsers.add_parser( - "scale", parents=[common_parser], help="Scale a node pool" + "scale", + parents=[common_parser, azure_node_pool_parser], + help="Scale a node pool", ) scale_parser.add_argument("--node-pool-name", required=True, help="Node pool name") scale_parser.add_argument( @@ -500,7 +506,9 @@ def main(): # Delete command delete_parser = subparsers.add_parser( - "delete", parents=[common_parser], help="Delete a node pool" + "delete", + parents=[common_parser, azure_node_pool_parser], + help="Delete a node pool", ) delete_parser.add_argument("--node-pool-name", required=True, help="Node pool name") delete_parser.set_defaults(func=handle_node_pool_operation) @@ -508,7 +516,7 @@ def main(): # All CRUD Operations command all_parser = subparsers.add_parser( "all", - parents=[common_parser], + parents=[common_parser, azure_node_pool_parser], help="Run full lifecycle: create, scale-up, scale-down, delete a node pool", ) all_parser.add_argument("--node-pool-name", required=True, help="Node pool name") @@ -575,7 +583,7 @@ def main(): # Deployment command deployment_parser = subparsers.add_parser( "deployment", - parents=[common_parser, workload_common_parser], + parents=[common_parser, azure_node_pool_parser, workload_common_parser], help="create deployments" ) deployment_parser.set_defaults(func=handle_workload_operations) @@ -583,7 +591,7 @@ def main(): # StatefulSet command statefulset_parser = subparsers.add_parser( "statefulset", - parents=[common_parser, workload_common_parser], + parents=[common_parser, azure_node_pool_parser, workload_common_parser], help="create statefulsets" ) statefulset_parser.set_defaults(func=handle_workload_operations) @@ -591,7 +599,7 @@ def main(): # Job command job_parser = subparsers.add_parser( "job", - parents=[common_parser, workload_common_parser], + parents=[common_parser, azure_node_pool_parser, workload_common_parser], help="create jobs" ) job_parser.add_argument( @@ -643,6 +651,15 @@ def main(): logger.error(f"Operation failed with exit code: {exit_code}") sys.exit(exit_code) + if args.cloud != "azure" and ( + getattr(args, "cluster_name", None) + or getattr(args, "exclude_managed_identity", False) + ): + parser.error( + "--cluster-name and --exclude-managed-identity are supported only " + "with --cloud azure" + ) + # Validate required arguments are present for node pool operations if args.command in ["create", "scale", "delete", "all"] and not hasattr( args, "node_pool_name" diff --git a/modules/python/tests/crud/test_main.py b/modules/python/tests/crud/test_main.py index ccbb189ba4..49c7987429 100644 --- a/modules/python/tests/crud/test_main.py +++ b/modules/python/tests/crud/test_main.py @@ -829,6 +829,9 @@ def test_main_complete_create_operation(self, mock_azure_crud_class): "azure", "--run-id", "test-run", + "--cluster-name", + "test-cluster", + "--exclude-managed-identity", "--node-pool-name", "test-pool", "--vm-size", @@ -841,9 +844,56 @@ def test_main_complete_create_operation(self, mock_azure_crud_class): main() # Use the imported main function # Verify - mock_azure_crud_class.assert_called_once() + call_kwargs = mock_azure_crud_class.call_args.kwargs + self.assertEqual(call_kwargs["cluster_name"], "test-cluster") + self.assertTrue(call_kwargs["exclude_managed_identity"]) mock_node_pool_crud.create_node_pool.assert_called_once() + def test_main_machine_command_rejects_node_pool_azure_options(self): + """Machine commands must not accept node-pool-only Azure options.""" + test_args = [ + "crud.py", + "create-machine", + "--cloud", + "azure", + "--run-id", + "test-run", + "--node-pool-name", + "test-pool", + "--vm-size", + "Standard_D2s_v3", + "--cluster-name", + "test-cluster", + ] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as context: + main() + + self.assertEqual(context.exception.code, 2) + + def test_main_aws_rejects_azure_only_options(self): + """AWS node-pool commands must reject Azure-only options.""" + test_args = [ + "crud.py", + "create", + "--cloud", + "aws", + "--run-id", + "test-run", + "--node-pool-name", + "test-pool", + "--vm-size", + "m6i.2xlarge", + "--exclude-managed-identity", + ] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as context: + main() + + self.assertEqual(context.exception.code, 2) + @mock.patch("crud.main.OperationContext") @mock.patch("crud.main.AzureNodePoolCRUD") def test_main_operation_returns_none( From 31e1edd820d78d5b72cdfd984c142d4663a88f6f Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 20 Aug 2026 15:04:28 -0400 Subject: [PATCH 07/12] fix: support Azure VirtualMachines node pools --- modules/python/clients/aks_client.py | 177 ++++++++++-------- modules/python/crud/azure/node_pool_crud.py | 8 + modules/python/crud/main.py | 44 +++-- .../python/tests/clients/test_aks_client.py | 103 +++++++++- .../tests/crud/test_azure_node_pool_crud.py | 5 + modules/python/tests/crud/test_main.py | 40 +++- modules/python/utils/azure_node_pool_cli.py | 120 ++++++++++++ .../utils/provisioning_instrumentation.py | 41 ++++ 8 files changed, 444 insertions(+), 94 deletions(-) create mode 100644 modules/python/utils/azure_node_pool_cli.py diff --git a/modules/python/clients/aks_client.py b/modules/python/clients/aks_client.py index e41c95df57..94dedd4797 100644 --- a/modules/python/clients/aks_client.py +++ b/modules/python/clients/aks_client.py @@ -13,8 +13,8 @@ import logging import os -import subprocess import time +from functools import partial from typing import Dict, Optional, Any # Third party imports @@ -26,9 +26,12 @@ # Local imports from utils.logger_config import get_logger, setup_logging from utils.common import get_env_vars +from utils.azure_node_pool_cli import ( + add_managed_gpu_node_pool as add_managed_gpu_node_pool_cli, + run_node_pool_cli, +) from utils.provisioning_instrumentation import ( - begin_create_or_update_with_retry, - instrument_nodepool_provisioning, + instrument_aks_nodepool_provisioning, ) from .kubernetes_client import KubernetesClient @@ -71,29 +74,20 @@ def _instrument_nodepool_provisioning( node_count: int, op, label: str = "", + arm_callable=None, ) -> list: - """ - Run ARM operation and K8s node readiness check concurrently using threads. - Delegates to provisioning_instrumentation.instrument_nodepool_provisioning. - """ - def arm_callable(): - return begin_create_or_update_with_retry( - self.aks_client, self.resource_group, - cluster_name, node_pool_name, parameters, label=label, - ) - - def k8s_wait_callable(): - return self.k8s_client.wait_for_nodes_ready( - node_count=node_count, - operation_timeout_in_minutes=self.operation_timeout_minutes, - label_selector=f"agentpool={node_pool_name}", - ) - - return instrument_nodepool_provisioning( + """Instrument ARM and Kubernetes node readiness for an AKS node pool.""" + return instrument_aks_nodepool_provisioning( + aks_sdk_client=self.aks_client, + resource_group=self.resource_group, + k8s_client=self.k8s_client, + operation_timeout_minutes=self.operation_timeout_minutes, node_pool_name=node_pool_name, + cluster_name=cluster_name, + parameters=parameters, + node_count=node_count, op=op, arm_callable=arm_callable, - k8s_wait_callable=k8s_wait_callable, label=label, ) @@ -294,55 +288,20 @@ def add_managed_gpu_node_pool( node_count: int, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, + node_pool_type: str = "VirtualMachineScaleSets", ) -> None: - """ - Create a fully managed GPU node pool via az CLI (aks-preview extension). - Used because the stable Python SDK doesn't expose gpuProfile.nvidia.managementMode. - """ - # Ensure aks-preview extension is installed/upgraded (required for --enable-managed-gpu) - subprocess.run( - ["az", "extension", "add", "--name", "aks-preview", "--upgrade", - "--allow-preview", "true", "--yes"], - capture_output=True, text=True, check=False, + """Create a fully managed GPU node pool through the aks-preview CLI.""" + add_managed_gpu_node_pool_cli( + resource_group=self.resource_group, + node_pool_name=node_pool_name, + cluster_name=cluster_name, + vm_size=vm_size, + node_count=node_count, + gpu_instance_profile=gpu_instance_profile, + gpu_mig_strategy=gpu_mig_strategy, + node_pool_type=node_pool_type, ) - cmd = [ - "az", "aks", "nodepool", "add", - "--resource-group", self.resource_group, - "--cluster-name", cluster_name, - "--name", node_pool_name, - "--node-count", str(node_count), - "--node-vm-size", vm_size, - "--mode", "User", - "--node-osdisk-type", "Managed", - "--labels", "gpu=true", - "--enable-managed-gpu", "true", - ] - if gpu_instance_profile: - cmd += ["--gpu-instance-profile", gpu_instance_profile] - if gpu_mig_strategy: - cmd += ["--gpu-mig-strategy", gpu_mig_strategy] - logger.info(f"Running: {' '.join(cmd)}") - retries = 10 - retry_wait = 30 - for attempt in range(retries): - result = subprocess.run(cmd, capture_output=True, text=True, check=False) - if result.returncode == 0: - break - detail = " | ".join( - line for line in (result.stdout + result.stderr).splitlines() if line.strip() - ) - if "OperationNotAllowed" in detail and attempt < retries - 1: - logger.warning( - f"Cluster has an in-progress operation, retrying in {retry_wait}s (attempt {attempt + 1}/{retries})" - ) - time.sleep(retry_wait) - else: - raise RuntimeError( - f"az aks nodepool add failed (rc={result.returncode}): {detail}" - ) - logger.info(f"az aks nodepool add succeeded for '{node_pool_name}'") - @staticmethod def _gpu_mode_metadata( gpu_node_pool: bool, @@ -417,6 +376,7 @@ def create_node_pool( enable_managed_gpu: bool = False, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, + node_pool_type: str = "VirtualMachineScaleSets", ) -> Any: """ Create a new node pool in the AKS cluster. @@ -452,6 +412,7 @@ def create_node_pool( "cluster_name": cluster_name, "vm_size": vm_size, "node_count": node_count, + "node_pool_type": node_pool_type, "gpu_node_pool": gpu_node_pool, **self._gpu_mode_metadata( gpu_node_pool, @@ -469,14 +430,21 @@ def create_node_pool( try: # Build parameters for node pool creation parameters = { - "count": node_count, - "vm_size": vm_size, "os_type": "Linux", "mode": "User", "os_disk_type": "Managed", "nodeLabels": {"gpu": "true"} if gpu_node_pool else {}, } + if node_pool_type == "VirtualMachines": + if gpu_node_pool: + raise ValueError( + "GPU node pools with type VirtualMachines are not supported" + ) + else: + parameters["count"] = node_count + parameters["vm_size"] = vm_size + if gpu_node_pool and not enable_managed_gpu: # Managed GPU (driver bootstrap only): driver install, no NVIDIA management parameters["gpu_profile"] = { @@ -495,6 +463,7 @@ def create_node_pool( cluster_name=cluster_name, vm_size=vm_size, node_count=node_count, + node_pool_type=node_pool_type, gpu_instance_profile=gpu_instance_profile, gpu_mig_strategy=gpu_mig_strategy, ) @@ -505,9 +474,30 @@ def create_node_pool( label_selector=label_selector, ) else: - # Run ARM and K8s readiness concurrently to capture both timings + arm_callable = None + if node_pool_type == "VirtualMachines": + cmd = [ + "az", "aks", "nodepool", "add", + "--resource-group", self.resource_group, + "--cluster-name", cluster_name, + "--name", node_pool_name, + "--node-count", str(node_count), + "--vm-sizes", vm_size, + "--vm-set-type", node_pool_type, + "--mode", "User", + "--node-osdisk-type", "Managed", + ] + + arm_callable = partial( + run_node_pool_cli, cmd, node_pool_name, "add" + ) ready_nodes = self._instrument_nodepool_provisioning( - node_pool_name, cluster_name, parameters, node_count, op + node_pool_name, + cluster_name, + parameters, + node_count, + op, + arm_callable=arm_callable, ) logger.info( @@ -567,6 +557,7 @@ def scale_node_pool( scale_step_size: int = 1, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, + node_pool_type: str = "VirtualMachineScaleSets", ) -> Any: """ Scale a node pool to the specified node count. @@ -597,6 +588,7 @@ def scale_node_pool( metadata = { "cluster_name": cluster_name, "node_count": node_count, + "node_pool_type": node_pool_type, "gpu_node_pool": gpu_node_pool, "progressive_scaling": progressive, "scale_step_size": scale_step_size, @@ -634,6 +626,7 @@ def scale_node_pool( gpu_node_pool=gpu_node_pool, enable_managed_gpu=enable_managed_gpu, node_pool=node_pool, + node_pool_type=node_pool_type, gpu_instance_profile=gpu_instance_profile, gpu_mig_strategy=gpu_mig_strategy, ) @@ -658,7 +651,21 @@ def scale_node_pool( ) # For direct scaling, update the node count - node_pool.count = node_count + if node_pool_type == "VirtualMachines": + cmd = [ + "az", "aks", "nodepool", "scale", + "--resource-group", self.resource_group, + "--cluster-name", cluster_name, + "--name", node_pool_name, + "--node-count", str(node_count), + ] + + arm_callable = partial( + run_node_pool_cli, cmd, node_pool_name, "scale" + ) + else: + node_pool.count = node_count + arm_callable = None logger.info(f"Scaling node pool {node_pool_name} to {node_count} nodes") @@ -668,7 +675,12 @@ def scale_node_pool( # Run ARM and K8s readiness concurrently to capture both timings ready_nodes = self._instrument_nodepool_provisioning( - node_pool_name, cluster_name, node_pool, node_count, op, + node_pool_name, + cluster_name, + node_pool, + node_count, + op, + arm_callable=arm_callable, ) logger.info( @@ -797,6 +809,7 @@ def _progressive_scale( node_pool: Optional[Any] = None, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, + node_pool_type: str = "VirtualMachineScaleSets", ) -> Any: """ Scale a node pool progressively with specified step size @@ -887,12 +900,26 @@ def _progressive_scale( op.add_metadata( "cluster_info", self.get_cluster_data(cluster_name) ) - node_pool.count = step # Update node count in the node pool object + if node_pool_type == "VirtualMachines": + cmd = [ + "az", "aks", "nodepool", "scale", + "--resource-group", self.resource_group, + "--cluster-name", cluster_name, + "--name", node_pool_name, + "--node-count", str(step), + ] + arm_callable = partial( + run_node_pool_cli, cmd, node_pool_name, "scale" + ) + else: + node_pool.count = step + arm_callable = None # Run ARM and K8s readiness concurrently to capture both timings ready_nodes = self._instrument_nodepool_provisioning( node_pool_name, cluster_name, node_pool, step, op, label=f"step {step} ", + arm_callable=arm_callable, ) logger.info(f"All {step} nodes in pool {node_pool_name} are ready") diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index cad61e91c4..75d541ba86 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -86,6 +86,7 @@ def __init__( def create_node_pool( self, node_pool_name, vm_size, node_count=1, gpu_node_pool=False, enable_managed_gpu=False, gpu_instance_profile=None, gpu_mig_strategy=None, + node_pool_type="VirtualMachineScaleSets", ): """ Create a new node pool @@ -109,6 +110,7 @@ def create_node_pool( node_pool_name=node_pool_name, vm_size=vm_size, node_count=node_count, + node_pool_type=node_pool_type, gpu_node_pool=gpu_node_pool, enable_managed_gpu=enable_managed_gpu, gpu_instance_profile=gpu_instance_profile, @@ -130,6 +132,7 @@ def scale_node_pool( enable_managed_gpu=False, gpu_instance_profile=None, gpu_mig_strategy=None, + node_pool_type="VirtualMachineScaleSets", ): """ Scale a node pool to specified count @@ -152,6 +155,7 @@ def scale_node_pool( result = self.aks_client.scale_node_pool( node_pool_name=node_pool_name, node_count=node_count, + node_pool_type=node_pool_type, gpu_node_pool=gpu_node_pool, enable_managed_gpu=enable_managed_gpu, progressive=progressive, @@ -204,6 +208,7 @@ def all( step_wait_time=30, gpu_instance_profile=None, gpu_mig_strategy=None, + node_pool_type="VirtualMachineScaleSets", ): """ Unified method to perform all node pool operations: create, scale-up, scale-down, delete @@ -238,6 +243,7 @@ def all( node_pool_name=node_pool_name, vm_size=vm_size, node_count=node_count, + node_pool_type=node_pool_type, gpu_node_pool=gpu_node_pool, enable_managed_gpu=enable_managed_gpu, gpu_instance_profile=gpu_instance_profile, @@ -261,6 +267,7 @@ def all( scale_up_result = self.scale_node_pool( node_pool_name=node_pool_name, node_count=target_count, + node_pool_type=node_pool_type, progressive=progressive, scale_step_size=scale_step_size, gpu_node_pool=gpu_node_pool, @@ -286,6 +293,7 @@ def all( scale_down_result = self.scale_node_pool( node_pool_name=node_pool_name, node_count=node_count, + node_pool_type=node_pool_type, progressive=progressive, scale_step_size=scale_step_size, gpu_node_pool=gpu_node_pool, diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index 98bb1dc53e..df2d056033 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -110,11 +110,12 @@ def handle_node_pool_operation(node_pool_crud, args): # gpu_instance_profile / gpu_mig_strategy are Azure-only MIG inputs. The AWS # CRUD does not accept these kwargs (and has no **kwargs), so passing them for # --cloud aws would raise TypeError. Only forward them on Azure. - azure_gpu_kwargs = {} + azure_kwargs = {} if args.cloud == "azure": - azure_gpu_kwargs = { + azure_kwargs = { "gpu_instance_profile": args.gpu_instance_profile, "gpu_mig_strategy": args.gpu_mig_strategy, + "node_pool_type": args.node_pool_type, } try: @@ -126,7 +127,7 @@ def handle_node_pool_operation(node_pool_crud, args): "node_count": args.node_count, "gpu_node_pool": args.gpu_node_pool, "enable_managed_gpu": args.enable_managed_gpu, - **azure_gpu_kwargs, + **azure_kwargs, } result = node_pool_crud.create_node_pool(**create_kwargs) @@ -140,7 +141,7 @@ def handle_node_pool_operation(node_pool_crud, args): "scale_step_size": args.scale_step_size, "gpu_node_pool": args.gpu_node_pool, "enable_managed_gpu": args.enable_managed_gpu, - **azure_gpu_kwargs, + **azure_kwargs, } result = node_pool_crud.scale_node_pool(**scale_kwargs) @@ -160,7 +161,7 @@ def handle_node_pool_operation(node_pool_crud, args): "gpu_node_pool": args.gpu_node_pool, "enable_managed_gpu": args.enable_managed_gpu, "step_wait_time": args.step_wait_time, - **azure_gpu_kwargs, + **azure_kwargs, } result = node_pool_crud.all(**all_kwargs) @@ -450,22 +451,29 @@ def main(): help="Capacity type for AWS/Azure node pool", ) - azure_node_pool_parser = argparse.ArgumentParser(add_help=False) - azure_node_pool_parser.add_argument( + azure_client_parser = argparse.ArgumentParser(add_help=False) + azure_client_parser.add_argument( "--cluster-name", default=None, help="AKS cluster name; Azure discovers the first cluster when omitted", ) - azure_node_pool_parser.add_argument( + azure_client_parser.add_argument( "--exclude-managed-identity", action="store_true", help="Exclude managed identity from DefaultAzureCredential", ) + azure_node_pool_parser = argparse.ArgumentParser(add_help=False) + azure_node_pool_parser.add_argument( + "--node-pool-type", + choices=["VirtualMachineScaleSets", "VirtualMachines"], + default="VirtualMachineScaleSets", + help="Azure node pool type (default: VirtualMachineScaleSets)", + ) # Create command create_parser = subparsers.add_parser( "create", - parents=[common_parser, azure_node_pool_parser], + parents=[common_parser, azure_client_parser, azure_node_pool_parser], help="Create a node pool", ) create_parser.add_argument("--node-pool-name", required=True, help="Node pool name") @@ -482,7 +490,7 @@ def main(): # Scale command scale_parser = subparsers.add_parser( "scale", - parents=[common_parser, azure_node_pool_parser], + parents=[common_parser, azure_client_parser, azure_node_pool_parser], help="Scale a node pool", ) scale_parser.add_argument("--node-pool-name", required=True, help="Node pool name") @@ -507,7 +515,7 @@ def main(): # Delete command delete_parser = subparsers.add_parser( "delete", - parents=[common_parser, azure_node_pool_parser], + parents=[common_parser, azure_client_parser], help="Delete a node pool", ) delete_parser.add_argument("--node-pool-name", required=True, help="Node pool name") @@ -516,7 +524,7 @@ def main(): # All CRUD Operations command all_parser = subparsers.add_parser( "all", - parents=[common_parser, azure_node_pool_parser], + parents=[common_parser, azure_client_parser, azure_node_pool_parser], help="Run full lifecycle: create, scale-up, scale-down, delete a node pool", ) all_parser.add_argument("--node-pool-name", required=True, help="Node pool name") @@ -583,7 +591,7 @@ def main(): # Deployment command deployment_parser = subparsers.add_parser( "deployment", - parents=[common_parser, azure_node_pool_parser, workload_common_parser], + parents=[common_parser, azure_client_parser, workload_common_parser], help="create deployments" ) deployment_parser.set_defaults(func=handle_workload_operations) @@ -591,7 +599,7 @@ def main(): # StatefulSet command statefulset_parser = subparsers.add_parser( "statefulset", - parents=[common_parser, azure_node_pool_parser, workload_common_parser], + parents=[common_parser, azure_client_parser, workload_common_parser], help="create statefulsets" ) statefulset_parser.set_defaults(func=handle_workload_operations) @@ -599,7 +607,7 @@ def main(): # Job command job_parser = subparsers.add_parser( "job", - parents=[common_parser, azure_node_pool_parser, workload_common_parser], + parents=[common_parser, azure_client_parser, workload_common_parser], help="create jobs" ) job_parser.add_argument( @@ -654,10 +662,12 @@ def main(): if args.cloud != "azure" and ( getattr(args, "cluster_name", None) or getattr(args, "exclude_managed_identity", False) + or getattr(args, "node_pool_type", "VirtualMachineScaleSets") + != "VirtualMachineScaleSets" ): parser.error( - "--cluster-name and --exclude-managed-identity are supported only " - "with --cloud azure" + "--cluster-name, --exclude-managed-identity, and non-default " + "--node-pool-type values are supported only with --cloud azure" ) # Validate required arguments are present for node pool operations diff --git a/modules/python/tests/clients/test_aks_client.py b/modules/python/tests/clients/test_aks_client.py index 8a12c5eaa0..fd0d330ef3 100644 --- a/modules/python/tests/clients/test_aks_client.py +++ b/modules/python/tests/clients/test_aks_client.py @@ -235,6 +235,53 @@ def mock_get_node_pool_side_effect(name, cluster=None): self.mock_operation.add_metadata.assert_any_call("node_readiness_time", 30) self.mock_operation.add_metadata.assert_any_call("command_execution_time", 50) + @mock.patch("utils.azure_node_pool_cli.subprocess.run") + @mock.patch.object(AKSClient, "_instrument_nodepool_provisioning") + def test_create_virtual_machines_node_pool( + self, mock_instrument, mock_subprocess_run + ): + """VirtualMachines pools are created with the explicit Azure CLI type.""" + mock_created_node_pool = mock.MagicMock() + mock_created_node_pool.as_dict.return_value = {"name": "test-pool"} + self.aks_client.get_node_pool = mock.MagicMock( + return_value=mock_created_node_pool + ) + mock_subprocess_run.return_value = mock.MagicMock( + returncode=0, stdout="", stderr="" + ) + + def run_arm_callable(*_args, **kwargs): + kwargs["arm_callable"]() + return [] + + mock_instrument.side_effect = run_arm_callable + + result = self.aks_client.create_node_pool( + node_pool_name="test-pool", + vm_size="Standard_D2s_v3", + node_count=2, + node_pool_type="VirtualMachines", + ) + + self.assertTrue(result) + mock_subprocess_run.assert_called_once_with( + [ + "az", "aks", "nodepool", "add", + "--resource-group", "fake-resource-group", + "--cluster-name", "fake-cluster", + "--name", "test-pool", + "--node-count", "2", + "--vm-sizes", "Standard_D2s_v3", + "--vm-set-type", "VirtualMachines", + "--mode", "User", + "--node-osdisk-type", "Managed", + ], + capture_output=True, + text=True, + check=False, + timeout=1800, + ) + @mock.patch("utils.provisioning_instrumentation.time") @mock.patch("clients.aks_client.time") def test_create_node_pool_retry_occurred_metadata(self, _mock_time, mock_instr_time): @@ -349,7 +396,7 @@ def mock_get_node_pool_side_effect(name, cluster=None): # Check that NVIDIA verification was performed self.mock_k8s.verify_nvidia_smi_on_node.assert_called_once_with(ready_nodes) - @mock.patch("clients.aks_client.subprocess.run") + @mock.patch("utils.azure_node_pool_cli.subprocess.run") @mock.patch("clients.aks_client.time") def test_create_node_pool_fully_managed_gpu(self, mock_time, mock_subprocess_run): """Test creating a fully managed GPU node pool uses az CLI, verifies systemd services and nvidia-smi""" @@ -448,6 +495,60 @@ def test_scale_node_pool_up(self, mock_time, mock_instr_time): self.mock_operation.add_metadata.assert_any_call("node_readiness_time", 30) self.mock_operation.add_metadata.assert_any_call("command_execution_time", 50) + @mock.patch("utils.azure_node_pool_cli.subprocess.run") + @mock.patch("clients.aks_client.time") + @mock.patch.object(AKSClient, "_instrument_nodepool_provisioning") + def test_progressive_scale_virtual_machines_node_pool( + self, mock_instrument, mock_time, mock_subprocess_run + ): + """VirtualMachines progressive scaling uses Azure CLI for each step.""" + mock_time.sleep = mock.MagicMock() + mock_subprocess_run.return_value = mock.MagicMock( + returncode=0, stdout="", stderr="" + ) + mock_node_pool = mock.MagicMock() + mock_node_pool.count = 1 + mock_node_pool.vm_size = None + mock_node_pool.as_dict.return_value = {"count": 1} + self.aks_client.get_node_pool = mock.MagicMock(return_value=mock_node_pool) + self.aks_client.get_cluster_data = mock.MagicMock( + return_value={"name": "fake-cluster"} + ) + def run_arm_callable(*_args, **kwargs): + kwargs["arm_callable"]() + return [] + + mock_instrument.side_effect = run_arm_callable + + result = self.aks_client.scale_node_pool( + node_pool_name="test-pool", + node_count=3, + progressive=True, + scale_step_size=1, + node_pool_type="VirtualMachines", + ) + + self.assertTrue(result) + self.assertEqual( + [call.args[0] for call in mock_subprocess_run.call_args_list], + [ + [ + "az", "aks", "nodepool", "scale", + "--resource-group", "fake-resource-group", + "--cluster-name", "fake-cluster", + "--name", "test-pool", + "--node-count", "2", + ], + [ + "az", "aks", "nodepool", "scale", + "--resource-group", "fake-resource-group", + "--cluster-name", "fake-cluster", + "--name", "test-pool", + "--node-count", "3", + ], + ], + ) + @mock.patch("clients.aks_client.time") def test_scale_node_pool_down(self, mock_time): """Test scaling a node pool down""" 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 e838103d1a..5bf71f2d63 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -117,6 +117,7 @@ def test_create_node_pool_success(self): node_pool_name=node_pool_name, vm_size=vm_size, node_count=node_count, + node_pool_type="VirtualMachineScaleSets", gpu_node_pool=False, ) @@ -126,6 +127,7 @@ def test_create_node_pool_success(self): node_pool_name=node_pool_name, vm_size=vm_size, node_count=node_count, + node_pool_type="VirtualMachineScaleSets", gpu_node_pool=False, enable_managed_gpu=False, gpu_instance_profile=None, @@ -171,6 +173,7 @@ def test_scale_node_pool_up(self): self.mock_aks_client.scale_node_pool.assert_called_once_with( node_pool_name=node_pool_name, node_count=node_count, + node_pool_type="VirtualMachineScaleSets", gpu_node_pool=False, enable_managed_gpu=False, progressive=False, @@ -201,6 +204,7 @@ def test_scale_node_pool_down(self): self.mock_aks_client.scale_node_pool.assert_called_once_with( node_pool_name=node_pool_name, node_count=node_count, + node_pool_type="VirtualMachineScaleSets", gpu_node_pool=False, enable_managed_gpu=False, progressive=False, @@ -266,6 +270,7 @@ def test_all_operations(self, mock_time): node_pool_name=node_pool_name, vm_size=vm_size, node_count=node_count, + node_pool_type="VirtualMachineScaleSets", gpu_node_pool=True, enable_managed_gpu=False, gpu_instance_profile=None, diff --git a/modules/python/tests/crud/test_main.py b/modules/python/tests/crud/test_main.py index 49c7987429..d94e2272a5 100644 --- a/modules/python/tests/crud/test_main.py +++ b/modules/python/tests/crud/test_main.py @@ -72,6 +72,7 @@ def test_handle_node_pool_operation_create(self, mock_azure_crud): mock_args.node_pool_name = "test-np" mock_args.vm_size = "Standard_D2s_v3" mock_args.node_count = 3 + mock_args.node_pool_type = "VirtualMachines" mock_args.gpu_node_pool = False mock_args.enable_managed_gpu = False @@ -87,6 +88,7 @@ def test_handle_node_pool_operation_create(self, mock_azure_crud): node_pool_name="test-np", vm_size="Standard_D2s_v3", node_count=3, + node_pool_type="VirtualMachines", gpu_node_pool=False, enable_managed_gpu=False, gpu_instance_profile=mock_args.gpu_instance_profile, @@ -102,6 +104,7 @@ def test_handle_node_pool_operation_scale(self, mock_azure_crud): mock_args.cloud = "azure" mock_args.node_pool_name = "test-np" mock_args.target_count = 5 + mock_args.node_pool_type = "VirtualMachines" mock_args.scale_step_size = ( 1 # scale_step_size != target_count, so progressive=True ) @@ -119,6 +122,7 @@ def test_handle_node_pool_operation_scale(self, mock_azure_crud): mock_azure_crud.scale_node_pool.assert_called_once_with( node_pool_name="test-np", node_count=5, + node_pool_type="VirtualMachines", progressive=True, # Should be True because scale_step_size != target_count scale_step_size=1, gpu_node_pool=False, @@ -136,6 +140,7 @@ def test_handle_node_pool_operation_scale_non_progressive(self, mock_azure_crud) mock_args.cloud = "azure" mock_args.node_pool_name = "test-np" mock_args.target_count = 3 + mock_args.node_pool_type = "VirtualMachineScaleSets" mock_args.scale_step_size = ( 3 # scale_step_size == target_count, so progressive=False ) @@ -153,6 +158,7 @@ def test_handle_node_pool_operation_scale_non_progressive(self, mock_azure_crud) mock_azure_crud.scale_node_pool.assert_called_once_with( node_pool_name="test-np", node_count=3, + node_pool_type="VirtualMachineScaleSets", progressive=False, # Should be False because scale_step_size == target_count scale_step_size=3, gpu_node_pool=False, @@ -178,6 +184,7 @@ def test_handle_node_pool_operation_scale_fails_returns_error( mock_args.cloud = "azure" mock_args.node_pool_name = "test-np" mock_args.target_count = 10 + mock_args.node_pool_type = "VirtualMachineScaleSets" mock_args.scale_step_size = 2 # Progressive scaling mock_args.gpu_node_pool = False mock_args.enable_managed_gpu = False @@ -193,6 +200,7 @@ def test_handle_node_pool_operation_scale_fails_returns_error( mock_azure_crud.scale_node_pool.assert_called_once_with( node_pool_name="test-np", node_count=10, + node_pool_type="VirtualMachineScaleSets", progressive=True, scale_step_size=2, gpu_node_pool=False, @@ -269,6 +277,7 @@ def test_handle_node_pool_operation_all(self, mock_azure_crud): mock_args.vm_size = "Standard_D2s_v3" mock_args.node_count = 1 mock_args.target_count = 3 + mock_args.node_pool_type = "VirtualMachines" mock_args.scale_step_size = 1 mock_args.gpu_node_pool = True mock_args.enable_managed_gpu = False @@ -287,6 +296,7 @@ def test_handle_node_pool_operation_all(self, mock_azure_crud): vm_size="Standard_D2s_v3", node_count=1, target_count=3, + node_pool_type="VirtualMachines", progressive=True, # Should be True because scale_step_size != target_count scale_step_size=1, gpu_node_pool=True, @@ -316,6 +326,8 @@ def test_handle_node_pool_operation_scale_aws_omits_mig_kwargs(self): call_kwargs = mock_crud.scale_node_pool.call_args.kwargs self.assertNotIn("gpu_instance_profile", call_kwargs) self.assertNotIn("gpu_mig_strategy", call_kwargs) + self.assertNotIn("node_pool_type", call_kwargs) + self.assertNotIn("vm_size", call_kwargs) @mock.patch("crud.main.AzureNodePoolCRUD") def test_handle_node_pool_operation_failure(self, mock_azure_crud): @@ -834,6 +846,8 @@ def test_main_complete_create_operation(self, mock_azure_crud_class): "--exclude-managed-identity", "--node-pool-name", "test-pool", + "--node-pool-type", + "VirtualMachines", "--vm-size", "Standard_D2s_v3", "--node-count", @@ -847,7 +861,8 @@ def test_main_complete_create_operation(self, mock_azure_crud_class): call_kwargs = mock_azure_crud_class.call_args.kwargs self.assertEqual(call_kwargs["cluster_name"], "test-cluster") self.assertTrue(call_kwargs["exclude_managed_identity"]) - mock_node_pool_crud.create_node_pool.assert_called_once() + create_kwargs = mock_node_pool_crud.create_node_pool.call_args.kwargs + self.assertEqual(create_kwargs["node_pool_type"], "VirtualMachines") def test_main_machine_command_rejects_node_pool_azure_options(self): """Machine commands must not accept node-pool-only Azure options.""" @@ -886,6 +901,29 @@ def test_main_aws_rejects_azure_only_options(self): "--vm-size", "m6i.2xlarge", "--exclude-managed-identity", + "--node-pool-type", + "VirtualMachines", + ] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as context: + main() + + self.assertEqual(context.exception.code, 2) + + def test_main_workload_rejects_node_pool_type(self): + """Workload commands must not accept node-pool shape options.""" + test_args = [ + "crud.py", + "deployment", + "--cloud", + "azure", + "--run-id", + "test-run", + "--node-pool-name", + "test-pool", + "--node-pool-type", + "VirtualMachines", ] with mock.patch("sys.argv", test_args): diff --git a/modules/python/utils/azure_node_pool_cli.py b/modules/python/utils/azure_node_pool_cli.py new file mode 100644 index 0000000000..a52c1911c2 --- /dev/null +++ b/modules/python/utils/azure_node_pool_cli.py @@ -0,0 +1,120 @@ +"""Azure CLI helpers for AKS node-pool operations.""" + +import subprocess +import time + +from utils.logger_config import get_logger + +logger = get_logger(__name__) + + +def run_node_pool_cli( + cmd, + node_pool_name, + action, + retries=10, + retry_wait=30, + timeout=1800, +): + """Run an az node-pool command with bounded retries for AKS conflicts.""" + retry_occurred = False + for attempt in range(retries): + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False, + timeout=timeout, + ) + if result.returncode == 0: + return retry_occurred + detail = " | ".join( + line + for line in (result.stdout + result.stderr).splitlines() + if line.strip() + ) + if ( + any(code in detail for code in ("OperationNotAllowed", "EtagMismatch")) + and attempt < retries - 1 + ): + retry_occurred = True + logger.warning( + "Cluster has an in-progress operation, retrying %s for %s in %ss " + "(attempt %s/%s)", + action, + node_pool_name, + retry_wait, + attempt + 1, + retries, + ) + time.sleep(retry_wait) + continue + raise RuntimeError( + f"az aks nodepool {action} failed for {node_pool_name} " + f"(rc={result.returncode}): {detail}" + ) + return retry_occurred + + +def add_managed_gpu_node_pool( + resource_group, + node_pool_name, + cluster_name, + vm_size, + node_count, + gpu_instance_profile=None, + gpu_mig_strategy=None, + node_pool_type="VirtualMachineScaleSets", +): + """Create a fully managed GPU node pool through the aks-preview CLI.""" + subprocess.run( + [ + "az", + "extension", + "add", + "--name", + "aks-preview", + "--upgrade", + "--allow-preview", + "true", + "--yes", + ], + capture_output=True, + text=True, + check=False, + ) + + cmd = [ + "az", + "aks", + "nodepool", + "add", + "--resource-group", + resource_group, + "--cluster-name", + cluster_name, + "--name", + node_pool_name, + "--node-count", + str(node_count), + "--node-vm-size", + vm_size, + "--vm-set-type", + node_pool_type, + "--mode", + "User", + "--node-osdisk-type", + "Managed", + "--labels", + "gpu=true", + "--enable-managed-gpu", + "true", + ] + if gpu_instance_profile: + cmd += ["--gpu-instance-profile", gpu_instance_profile] + if gpu_mig_strategy: + cmd += ["--gpu-mig-strategy", gpu_mig_strategy] + + logger.info("Running: %s", " ".join(cmd)) + run_node_pool_cli(cmd, node_pool_name, "add") + logger.info("az aks nodepool add succeeded for '%s'", node_pool_name) diff --git a/modules/python/utils/provisioning_instrumentation.py b/modules/python/utils/provisioning_instrumentation.py index f8e38a5e13..d149c5c8b4 100644 --- a/modules/python/utils/provisioning_instrumentation.py +++ b/modules/python/utils/provisioning_instrumentation.py @@ -83,6 +83,47 @@ def instrument_nodepool_provisioning( return ready_nodes +def instrument_aks_nodepool_provisioning( + aks_sdk_client, + resource_group, + k8s_client, + operation_timeout_minutes, + node_pool_name, + cluster_name, + parameters, + node_count, + op, + label="", + arm_callable=None, +): + """Build AKS callables and instrument ARM and Kubernetes readiness.""" + if arm_callable is None: + def arm_callable(): + return begin_create_or_update_with_retry( + aks_sdk_client, + resource_group, + cluster_name, + node_pool_name, + parameters, + label=label, + ) + + def k8s_wait_callable(): + return k8s_client.wait_for_nodes_ready( + node_count=node_count, + operation_timeout_in_minutes=operation_timeout_minutes, + label_selector=f"agentpool={node_pool_name}", + ) + + return instrument_nodepool_provisioning( + node_pool_name=node_pool_name, + op=op, + arm_callable=arm_callable, + k8s_wait_callable=k8s_wait_callable, + label=label, + ) + + def begin_create_or_update_with_retry( aks_sdk_client, resource_group, From 7d0efa17840dcd248e3496b5379e741d32985494 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 20 Aug 2026 16:35:13 -0400 Subject: [PATCH 08/12] fix: preserve delete and AWS CRUD dispatch --- modules/python/crud/main.py | 7 ++++++- modules/python/tests/crud/test_main.py | 29 ++++++++++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index df2d056033..861dba062f 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -115,7 +115,6 @@ def handle_node_pool_operation(node_pool_crud, args): azure_kwargs = { "gpu_instance_profile": args.gpu_instance_profile, "gpu_mig_strategy": args.gpu_mig_strategy, - "node_pool_type": args.node_pool_type, } try: @@ -129,6 +128,8 @@ def handle_node_pool_operation(node_pool_crud, args): "enable_managed_gpu": args.enable_managed_gpu, **azure_kwargs, } + if args.cloud == "azure": + create_kwargs["node_pool_type"] = args.node_pool_type result = node_pool_crud.create_node_pool(**create_kwargs) @@ -143,6 +144,8 @@ def handle_node_pool_operation(node_pool_crud, args): "enable_managed_gpu": args.enable_managed_gpu, **azure_kwargs, } + if args.cloud == "azure": + scale_kwargs["node_pool_type"] = args.node_pool_type result = node_pool_crud.scale_node_pool(**scale_kwargs) @@ -163,6 +166,8 @@ def handle_node_pool_operation(node_pool_crud, args): "step_wait_time": args.step_wait_time, **azure_kwargs, } + if args.cloud == "azure": + all_kwargs["node_pool_type"] = args.node_pool_type result = node_pool_crud.all(**all_kwargs) else: diff --git a/modules/python/tests/crud/test_main.py b/modules/python/tests/crud/test_main.py index d94e2272a5..7237bd8a22 100644 --- a/modules/python/tests/crud/test_main.py +++ b/modules/python/tests/crud/test_main.py @@ -887,6 +887,35 @@ def test_main_machine_command_rejects_node_pool_azure_options(self): self.assertEqual(context.exception.code, 2) + @mock.patch("crud.main.AzureNodePoolCRUD") + def test_main_delete_does_not_require_node_pool_type( + self, mock_azure_crud_class + ): + """Delete must run without create/scale-only node-pool arguments.""" + mock_node_pool_crud = mock.MagicMock() + mock_azure_crud_class.return_value = mock_node_pool_crud + mock_node_pool_crud.delete_node_pool.return_value = True + test_args = [ + "crud.py", + "delete", + "--cloud", + "azure", + "--run-id", + "test-run", + "--cluster-name", + "test-cluster", + "--exclude-managed-identity", + "--node-pool-name", + "test-pool", + ] + + with mock.patch("sys.argv", test_args): + main() + + mock_node_pool_crud.delete_node_pool.assert_called_once_with( + node_pool_name="test-pool" + ) + def test_main_aws_rejects_azure_only_options(self): """AWS node-pool commands must reject Azure-only options.""" test_args = [ From 085d2a12980123b25f94f0a9bb1e779af46c03b2 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 20 Aug 2026 17:19:16 -0400 Subject: [PATCH 09/12] fix: report VirtualMachines scale failures correctly --- modules/python/clients/aks_client.py | 53 ++++++----- modules/python/crud/main.py | 1 + .../python/tests/clients/test_aks_client.py | 11 ++- modules/python/tests/crud/test_main.py | 15 ++-- .../tests/utils/test_azure_node_pool_cli.py | 89 +++++++++++++++++++ modules/python/utils/azure_node_pool_cli.py | 50 +++++++++++ 6 files changed, 183 insertions(+), 36 deletions(-) create mode 100644 modules/python/tests/utils/test_azure_node_pool_cli.py diff --git a/modules/python/clients/aks_client.py b/modules/python/clients/aks_client.py index 94dedd4797..c488f03ccd 100644 --- a/modules/python/clients/aks_client.py +++ b/modules/python/clients/aks_client.py @@ -28,6 +28,9 @@ from utils.common import get_env_vars from utils.azure_node_pool_cli import ( add_managed_gpu_node_pool as add_managed_gpu_node_pool_cli, + build_add_virtual_machines_command, + build_scale_virtual_machines_command, + get_node_pool_scale_state, run_node_pool_cli, ) from utils.provisioning_instrumentation import ( @@ -476,17 +479,13 @@ def create_node_pool( else: arm_callable = None if node_pool_type == "VirtualMachines": - cmd = [ - "az", "aks", "nodepool", "add", - "--resource-group", self.resource_group, - "--cluster-name", cluster_name, - "--name", node_pool_name, - "--node-count", str(node_count), - "--vm-sizes", vm_size, - "--vm-set-type", node_pool_type, - "--mode", "User", - "--node-osdisk-type", "Managed", - ] + cmd = build_add_virtual_machines_command( + self.resource_group, + cluster_name, + node_pool_name, + node_count, + vm_size, + ) arm_callable = partial( run_node_pool_cli, cmd, node_pool_name, "add" @@ -602,7 +601,9 @@ def scale_node_pool( self._log_gpu_mode(metadata) node_pool = self.get_node_pool(node_pool_name, cluster_name) - current_count = node_pool.count + current_count, current_vm_size = get_node_pool_scale_state( + node_pool, node_pool_type + ) if node_count > current_count: operation_type = "scale_up" elif node_count < current_count: @@ -637,7 +638,7 @@ def scale_node_pool( ) as op: try: # Store VM size for metrics - self.vm_size = node_pool.vm_size + self.vm_size = current_vm_size op.name = operation_type op.add_metadata("vm_size", self.vm_size) op.add_metadata("current_count", current_count) @@ -652,13 +653,12 @@ def scale_node_pool( # For direct scaling, update the node count if node_pool_type == "VirtualMachines": - cmd = [ - "az", "aks", "nodepool", "scale", - "--resource-group", self.resource_group, - "--cluster-name", cluster_name, - "--name", node_pool_name, - "--node-count", str(node_count), - ] + cmd = build_scale_virtual_machines_command( + self.resource_group, + cluster_name, + node_pool_name, + node_count, + ) arm_callable = partial( run_node_pool_cli, cmd, node_pool_name, "scale" @@ -901,13 +901,12 @@ def _progressive_scale( "cluster_info", self.get_cluster_data(cluster_name) ) if node_pool_type == "VirtualMachines": - cmd = [ - "az", "aks", "nodepool", "scale", - "--resource-group", self.resource_group, - "--cluster-name", cluster_name, - "--name", node_pool_name, - "--node-count", str(step), - ] + cmd = build_scale_virtual_machines_command( + self.resource_group, + cluster_name, + node_pool_name, + step, + ) arm_callable = partial( run_node_pool_cli, cmd, node_pool_name, "scale" ) diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index 861dba062f..4e95f95a09 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -785,6 +785,7 @@ def main(): logger.info("Operation completed successfully") else: logger.error(f"Operation failed with exit code: {exit_code}") + sys.exit(exit_code) except ImportError as import_error: error_msg = f"Import Error: {import_error}" diff --git a/modules/python/tests/clients/test_aks_client.py b/modules/python/tests/clients/test_aks_client.py index fd0d330ef3..11ed55496e 100644 --- a/modules/python/tests/clients/test_aks_client.py +++ b/modules/python/tests/clients/test_aks_client.py @@ -507,9 +507,14 @@ def test_progressive_scale_virtual_machines_node_pool( returncode=0, stdout="", stderr="" ) mock_node_pool = mock.MagicMock() - mock_node_pool.count = 1 - mock_node_pool.vm_size = None - mock_node_pool.as_dict.return_value = {"count": 1} + mock_node_pool.virtual_machines_profile = { + "scale": { + "manual": [{"size": "Standard_D2s_v3", "count": 1}] + } + } + mock_node_pool.as_dict.return_value = { + "virtual_machines_profile": mock_node_pool.virtual_machines_profile + } self.aks_client.get_node_pool = mock.MagicMock(return_value=mock_node_pool) self.aks_client.get_cluster_data = mock.MagicMock( return_value={"name": "fake-cluster"} diff --git a/modules/python/tests/crud/test_main.py b/modules/python/tests/crud/test_main.py index 7237bd8a22..ea71d24de5 100644 --- a/modules/python/tests/crud/test_main.py +++ b/modules/python/tests/crud/test_main.py @@ -1021,9 +1021,10 @@ def test_main_operation_returns_boolean_false( ] with mock.patch("sys.argv", test_args): - main() # Use the imported main function + with self.assertRaises(SystemExit) as context: + main() - # Verify error is logged but sys.exit is not called + self.assertEqual(context.exception.code, 1) mock_logger.error.assert_called_with("Operation failed with exit code: 1") @mock.patch("sys.exit") @@ -1620,9 +1621,10 @@ def mock_handle_operation(crud, args): # pylint: disable=unused-argument with mock.patch( "crud.main.handle_node_pool_operation", mock_handle_operation ): - main() + with self.assertRaises(SystemExit) as context: + main() - # Should log error with the specific exit code but not call sys.exit + self.assertEqual(context.exception.code, 42) mock_logger.error.assert_called_with("Operation failed with exit code: 42") @mock.patch("crud.main.logger") @@ -1686,9 +1688,10 @@ def mock_handle_operation(crud, args): # pylint: disable=unused-argument with mock.patch( "crud.main.handle_node_pool_operation", mock_handle_operation ): - main() + with self.assertRaises(SystemExit) as context: + main() - # Should log error but not call sys.exit + self.assertEqual(context.exception.code, 1) mock_logger.error.assert_called_with("Operation failed with exit code: 1") diff --git a/modules/python/tests/utils/test_azure_node_pool_cli.py b/modules/python/tests/utils/test_azure_node_pool_cli.py new file mode 100644 index 0000000000..3a527046ac --- /dev/null +++ b/modules/python/tests/utils/test_azure_node_pool_cli.py @@ -0,0 +1,89 @@ +"""Tests for Azure node-pool CLI helpers.""" + +import unittest +from unittest import mock + +from azure.mgmt.containerservice.models import ( + ManualScaleProfile, + ScaleProfile, + VirtualMachinesProfile, +) + +from utils.azure_node_pool_cli import ( + build_add_virtual_machines_command, + build_scale_virtual_machines_command, + get_node_pool_scale_state, +) + + +class TestAzureNodePoolCLI(unittest.TestCase): + """Validate VirtualMachines readback and command contracts.""" + + def test_get_scale_state_from_sdk_model(self): + node_pool = mock.MagicMock() + node_pool.virtual_machines_profile = VirtualMachinesProfile( + scale=ScaleProfile( + manual=[ + ManualScaleProfile(size="Standard_D2s_v3", count=2), + ManualScaleProfile(size="Standard_D4s_v3", count=3), + ] + ) + ) + + count, vm_size = get_node_pool_scale_state(node_pool, "VirtualMachines") + + self.assertEqual(count, 5) + self.assertEqual(vm_size, "Standard_D2s_v3") + + def test_get_scale_state_from_dict(self): + node_pool = mock.MagicMock() + node_pool.virtual_machines_profile = { + "scale": { + "manual": [{"size": "Standard_D2s_v3", "count": 2}] + } + } + + count, vm_size = get_node_pool_scale_state(node_pool, "VirtualMachines") + + self.assertEqual(count, 2) + self.assertEqual(vm_size, "Standard_D2s_v3") + + def test_build_add_virtual_machines_command(self): + command = build_add_virtual_machines_command( + "test-rg", "test-cluster", "test-pool", 2, "Standard_D2s_v3" + ) + + self.assertEqual( + command, + [ + "az", "aks", "nodepool", "add", + "--resource-group", "test-rg", + "--cluster-name", "test-cluster", + "--name", "test-pool", + "--node-count", "2", + "--vm-sizes", "Standard_D2s_v3", + "--vm-set-type", "VirtualMachines", + "--mode", "User", + "--node-osdisk-type", "Managed", + ], + ) + + def test_build_scale_virtual_machines_command(self): + command = build_scale_virtual_machines_command( + "test-rg", "test-cluster", "test-pool", 3 + ) + + self.assertEqual( + command, + [ + "az", "aks", "nodepool", "scale", + "--resource-group", "test-rg", + "--cluster-name", "test-cluster", + "--name", "test-pool", + "--node-count", "3", + ], + ) + + +if __name__ == "__main__": + unittest.main() diff --git a/modules/python/utils/azure_node_pool_cli.py b/modules/python/utils/azure_node_pool_cli.py index a52c1911c2..278df49646 100644 --- a/modules/python/utils/azure_node_pool_cli.py +++ b/modules/python/utils/azure_node_pool_cli.py @@ -8,6 +8,56 @@ logger = get_logger(__name__) +def get_node_pool_scale_state(node_pool, node_pool_type): + """Return current node count and VM size for VMSS or VirtualMachines pools.""" + if node_pool_type != "VirtualMachines": + return node_pool.count, node_pool.vm_size + + profile = node_pool.virtual_machines_profile + scale = profile.get("scale") if isinstance(profile, dict) else profile.scale + manual = scale.get("manual") if isinstance(scale, dict) else scale.manual + if not manual: + raise ValueError("VirtualMachines node pool has no manual scale profile") + + def read(entry, field): + return entry.get(field) if isinstance(entry, dict) else getattr(entry, field) + + counts = [read(entry, "count") for entry in manual] + if any(count is None for count in counts): + raise ValueError("VirtualMachines manual scale profile has no node count") + return sum(counts), read(manual[0], "size") + + +def build_add_virtual_machines_command( + resource_group, cluster_name, node_pool_name, node_count, vm_size +): + """Build the Azure CLI command that creates a VirtualMachines node pool.""" + return [ + "az", "aks", "nodepool", "add", + "--resource-group", resource_group, + "--cluster-name", cluster_name, + "--name", node_pool_name, + "--node-count", str(node_count), + "--vm-sizes", vm_size, + "--vm-set-type", "VirtualMachines", + "--mode", "User", + "--node-osdisk-type", "Managed", + ] + + +def build_scale_virtual_machines_command( + resource_group, cluster_name, node_pool_name, node_count +): + """Build the Azure CLI command that scales a VirtualMachines node pool.""" + return [ + "az", "aks", "nodepool", "scale", + "--resource-group", resource_group, + "--cluster-name", cluster_name, + "--name", node_pool_name, + "--node-count", str(node_count), + ] + + def run_node_pool_cli( cmd, node_pool_name, From 23bd92f2d7003facb968e64c29ced876799b7355 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 20 Aug 2026 17:44:12 -0400 Subject: [PATCH 10/12] refactor: isolate Azure CRUD helpers and tests --- modules/python/clients/aks_client.py | 80 ++++------- .../python/tests/clients/test_aks_client.py | 106 -------------- .../test_aks_client_virtual_machines.py | 121 ++++++++++++++++ .../tests/crud/test_azure_node_pool_crud.py | 2 +- modules/python/tests/crud/test_main.py | 135 ------------------ .../tests/crud/test_main_azure_options.py | 93 ++++++++++++ .../tests/utils/test_azure_node_pool_cli.py | 60 ++++++++ modules/python/utils/azure_node_pool_cli.py | 69 +++++++++ 8 files changed, 372 insertions(+), 294 deletions(-) create mode 100644 modules/python/tests/clients/test_aks_client_virtual_machines.py create mode 100644 modules/python/tests/crud/test_main_azure_options.py diff --git a/modules/python/clients/aks_client.py b/modules/python/clients/aks_client.py index c488f03ccd..5c0cbe37f8 100644 --- a/modules/python/clients/aks_client.py +++ b/modules/python/clients/aks_client.py @@ -14,7 +14,6 @@ import logging import os import time -from functools import partial from typing import Dict, Optional, Any # Third party imports @@ -28,10 +27,9 @@ from utils.common import get_env_vars from utils.azure_node_pool_cli import ( add_managed_gpu_node_pool as add_managed_gpu_node_pool_cli, - build_add_virtual_machines_command, - build_scale_virtual_machines_command, get_node_pool_scale_state, - run_node_pool_cli, + prepare_create_operation, + prepare_scale_operation, ) from utils.provisioning_instrumentation import ( instrument_aks_nodepool_provisioning, @@ -439,14 +437,16 @@ def create_node_pool( "nodeLabels": {"gpu": "true"} if gpu_node_pool else {}, } - if node_pool_type == "VirtualMachines": - if gpu_node_pool: - raise ValueError( - "GPU node pools with type VirtualMachines are not supported" - ) - else: - parameters["count"] = node_count - parameters["vm_size"] = vm_size + arm_callable = prepare_create_operation( + parameters, + node_pool_type, + gpu_node_pool, + self.resource_group, + cluster_name, + node_pool_name, + node_count, + vm_size, + ) if gpu_node_pool and not enable_managed_gpu: # Managed GPU (driver bootstrap only): driver install, no NVIDIA management @@ -477,19 +477,6 @@ def create_node_pool( label_selector=label_selector, ) else: - arm_callable = None - if node_pool_type == "VirtualMachines": - cmd = build_add_virtual_machines_command( - self.resource_group, - cluster_name, - node_pool_name, - node_count, - vm_size, - ) - - arm_callable = partial( - run_node_pool_cli, cmd, node_pool_name, "add" - ) ready_nodes = self._instrument_nodepool_provisioning( node_pool_name, cluster_name, @@ -652,20 +639,14 @@ def scale_node_pool( ) # For direct scaling, update the node count - if node_pool_type == "VirtualMachines": - cmd = build_scale_virtual_machines_command( - self.resource_group, - cluster_name, - node_pool_name, - node_count, - ) - - arm_callable = partial( - run_node_pool_cli, cmd, node_pool_name, "scale" - ) - else: - node_pool.count = node_count - arm_callable = None + arm_callable = prepare_scale_operation( + node_pool, + node_pool_type, + self.resource_group, + cluster_name, + node_pool_name, + node_count, + ) logger.info(f"Scaling node pool {node_pool_name} to {node_count} nodes") @@ -900,19 +881,14 @@ def _progressive_scale( op.add_metadata( "cluster_info", self.get_cluster_data(cluster_name) ) - if node_pool_type == "VirtualMachines": - cmd = build_scale_virtual_machines_command( - self.resource_group, - cluster_name, - node_pool_name, - step, - ) - arm_callable = partial( - run_node_pool_cli, cmd, node_pool_name, "scale" - ) - else: - node_pool.count = step - arm_callable = None + arm_callable = prepare_scale_operation( + node_pool, + node_pool_type, + self.resource_group, + cluster_name, + node_pool_name, + step, + ) # Run ARM and K8s readiness concurrently to capture both timings ready_nodes = self._instrument_nodepool_provisioning( diff --git a/modules/python/tests/clients/test_aks_client.py b/modules/python/tests/clients/test_aks_client.py index 11ed55496e..08d78b6feb 100644 --- a/modules/python/tests/clients/test_aks_client.py +++ b/modules/python/tests/clients/test_aks_client.py @@ -235,53 +235,6 @@ def mock_get_node_pool_side_effect(name, cluster=None): self.mock_operation.add_metadata.assert_any_call("node_readiness_time", 30) self.mock_operation.add_metadata.assert_any_call("command_execution_time", 50) - @mock.patch("utils.azure_node_pool_cli.subprocess.run") - @mock.patch.object(AKSClient, "_instrument_nodepool_provisioning") - def test_create_virtual_machines_node_pool( - self, mock_instrument, mock_subprocess_run - ): - """VirtualMachines pools are created with the explicit Azure CLI type.""" - mock_created_node_pool = mock.MagicMock() - mock_created_node_pool.as_dict.return_value = {"name": "test-pool"} - self.aks_client.get_node_pool = mock.MagicMock( - return_value=mock_created_node_pool - ) - mock_subprocess_run.return_value = mock.MagicMock( - returncode=0, stdout="", stderr="" - ) - - def run_arm_callable(*_args, **kwargs): - kwargs["arm_callable"]() - return [] - - mock_instrument.side_effect = run_arm_callable - - result = self.aks_client.create_node_pool( - node_pool_name="test-pool", - vm_size="Standard_D2s_v3", - node_count=2, - node_pool_type="VirtualMachines", - ) - - self.assertTrue(result) - mock_subprocess_run.assert_called_once_with( - [ - "az", "aks", "nodepool", "add", - "--resource-group", "fake-resource-group", - "--cluster-name", "fake-cluster", - "--name", "test-pool", - "--node-count", "2", - "--vm-sizes", "Standard_D2s_v3", - "--vm-set-type", "VirtualMachines", - "--mode", "User", - "--node-osdisk-type", "Managed", - ], - capture_output=True, - text=True, - check=False, - timeout=1800, - ) - @mock.patch("utils.provisioning_instrumentation.time") @mock.patch("clients.aks_client.time") def test_create_node_pool_retry_occurred_metadata(self, _mock_time, mock_instr_time): @@ -495,65 +448,6 @@ def test_scale_node_pool_up(self, mock_time, mock_instr_time): self.mock_operation.add_metadata.assert_any_call("node_readiness_time", 30) self.mock_operation.add_metadata.assert_any_call("command_execution_time", 50) - @mock.patch("utils.azure_node_pool_cli.subprocess.run") - @mock.patch("clients.aks_client.time") - @mock.patch.object(AKSClient, "_instrument_nodepool_provisioning") - def test_progressive_scale_virtual_machines_node_pool( - self, mock_instrument, mock_time, mock_subprocess_run - ): - """VirtualMachines progressive scaling uses Azure CLI for each step.""" - mock_time.sleep = mock.MagicMock() - mock_subprocess_run.return_value = mock.MagicMock( - returncode=0, stdout="", stderr="" - ) - mock_node_pool = mock.MagicMock() - mock_node_pool.virtual_machines_profile = { - "scale": { - "manual": [{"size": "Standard_D2s_v3", "count": 1}] - } - } - mock_node_pool.as_dict.return_value = { - "virtual_machines_profile": mock_node_pool.virtual_machines_profile - } - self.aks_client.get_node_pool = mock.MagicMock(return_value=mock_node_pool) - self.aks_client.get_cluster_data = mock.MagicMock( - return_value={"name": "fake-cluster"} - ) - def run_arm_callable(*_args, **kwargs): - kwargs["arm_callable"]() - return [] - - mock_instrument.side_effect = run_arm_callable - - result = self.aks_client.scale_node_pool( - node_pool_name="test-pool", - node_count=3, - progressive=True, - scale_step_size=1, - node_pool_type="VirtualMachines", - ) - - self.assertTrue(result) - self.assertEqual( - [call.args[0] for call in mock_subprocess_run.call_args_list], - [ - [ - "az", "aks", "nodepool", "scale", - "--resource-group", "fake-resource-group", - "--cluster-name", "fake-cluster", - "--name", "test-pool", - "--node-count", "2", - ], - [ - "az", "aks", "nodepool", "scale", - "--resource-group", "fake-resource-group", - "--cluster-name", "fake-cluster", - "--name", "test-pool", - "--node-count", "3", - ], - ], - ) - @mock.patch("clients.aks_client.time") def test_scale_node_pool_down(self, mock_time): """Test scaling a node pool down""" diff --git a/modules/python/tests/clients/test_aks_client_virtual_machines.py b/modules/python/tests/clients/test_aks_client_virtual_machines.py new file mode 100644 index 0000000000..231829fcc8 --- /dev/null +++ b/modules/python/tests/clients/test_aks_client_virtual_machines.py @@ -0,0 +1,121 @@ +"""VirtualMachines node-pool tests for AKSClient.""" + +import unittest +from unittest import mock + +from clients.aks_client import AKSClient + + +class TestAKSClientVirtualMachines(unittest.TestCase): + """Validate VirtualMachines create and progressive scale orchestration.""" + + def setUp(self): + self.container_client_patcher = mock.patch( + "clients.aks_client.ContainerServiceClient" + ) + self.kubernetes_client_patcher = mock.patch( + "clients.aks_client.KubernetesClient" + ) + self.operation_context_patcher = mock.patch("crud.operation.OperationContext") + + mock_container_client = self.container_client_patcher.start() + self.kubernetes_client_patcher.start() + self.mock_operation_context = self.operation_context_patcher.start() + self.mock_credential = mock.MagicMock() + + self.mock_agent_pools = mock_container_client.return_value.agent_pools + self.mock_operation_context.return_value.__enter__.return_value = mock.MagicMock() + self.aks_client = AKSClient( + subscription_id="fake-subscription-id", + resource_group="fake-resource-group", + cluster_name="fake-cluster", + credential=self.mock_credential, + result_dir="/tmp/test-results", + ) + self.aks_client.get_cluster_data = mock.MagicMock( + return_value={"name": "fake-cluster"} + ) + + def tearDown(self): + self.operation_context_patcher.stop() + self.container_client_patcher.stop() + self.kubernetes_client_patcher.stop() + + @mock.patch("utils.azure_node_pool_cli.subprocess.run") + @mock.patch.object(AKSClient, "_instrument_nodepool_provisioning") + def test_create_virtual_machines_node_pool( + self, mock_instrument, mock_subprocess_run + ): + mock_created_node_pool = mock.MagicMock() + mock_created_node_pool.as_dict.return_value = {"name": "test-pool"} + self.aks_client.get_node_pool = mock.MagicMock( + return_value=mock_created_node_pool + ) + mock_subprocess_run.return_value = mock.MagicMock( + returncode=0, stdout="", stderr="" + ) + + def run_arm_callable(*_args, **kwargs): + kwargs["arm_callable"]() + return [] + + mock_instrument.side_effect = run_arm_callable + + result = self.aks_client.create_node_pool( + node_pool_name="test-pool", + vm_size="Standard_D2s_v3", + node_count=2, + node_pool_type="VirtualMachines", + ) + + self.assertTrue(result) + command = mock_subprocess_run.call_args.args[0] + self.assertIn("--vm-set-type", command) + self.assertIn("VirtualMachines", command) + self.assertIn("--vm-sizes", command) + self.assertIn("Standard_D2s_v3", command) + + @mock.patch("utils.azure_node_pool_cli.subprocess.run") + @mock.patch("clients.aks_client.time") + @mock.patch.object(AKSClient, "_instrument_nodepool_provisioning") + def test_progressive_scale_virtual_machines_node_pool( + self, mock_instrument, mock_time, mock_subprocess_run + ): + mock_time.sleep = mock.MagicMock() + mock_subprocess_run.return_value = mock.MagicMock( + returncode=0, stdout="", stderr="" + ) + mock_node_pool = mock.MagicMock() + mock_node_pool.virtual_machines_profile = { + "scale": { + "manual": [{"size": "Standard_D2s_v3", "count": 1}] + } + } + mock_node_pool.as_dict.return_value = { + "virtual_machines_profile": mock_node_pool.virtual_machines_profile + } + self.aks_client.get_node_pool = mock.MagicMock(return_value=mock_node_pool) + + def run_arm_callable(*_args, **kwargs): + kwargs["arm_callable"]() + return [] + + mock_instrument.side_effect = run_arm_callable + + result = self.aks_client.scale_node_pool( + node_pool_name="test-pool", + node_count=3, + progressive=True, + scale_step_size=1, + node_pool_type="VirtualMachines", + ) + + self.assertTrue(result) + self.assertEqual( + [call.args[0][-1] for call in mock_subprocess_run.call_args_list], + ["2", "3"], + ) + + +if __name__ == "__main__": + unittest.main() 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 5bf71f2d63..be1bddd4f7 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -97,10 +97,10 @@ def test_existing_positional_arguments_remain_compatible(self): self.mock_aks_client_cls.assert_called_once_with( resource_group="fake-resource-group", cluster_name=None, - exclude_managed_identity=False, kube_config_file="/tmp/fake-kubeconfig", result_dir="/tmp/fake-results", operation_timeout_minutes=5.0, + credential=self.mock_credential, ) def test_create_node_pool_success(self): diff --git a/modules/python/tests/crud/test_main.py b/modules/python/tests/crud/test_main.py index ea71d24de5..9ebfca98c2 100644 --- a/modules/python/tests/crud/test_main.py +++ b/modules/python/tests/crud/test_main.py @@ -826,141 +826,6 @@ def test_main_no_func_attribute(self, mock_print_help, mock_exit): # Verify it was called with exit code 1 at least once self.assertIn(mock.call(1), mock_exit.call_args_list) - @mock.patch("crud.main.AzureNodePoolCRUD") - def test_main_complete_create_operation(self, mock_azure_crud_class): - """Test complete create operation flow""" - # Setup - mock_node_pool_crud = mock.MagicMock() - mock_azure_crud_class.return_value = mock_node_pool_crud - mock_node_pool_crud.create_node_pool.return_value = True - - test_args = [ - "crud.py", - "create", - "--cloud", - "azure", - "--run-id", - "test-run", - "--cluster-name", - "test-cluster", - "--exclude-managed-identity", - "--node-pool-name", - "test-pool", - "--node-pool-type", - "VirtualMachines", - "--vm-size", - "Standard_D2s_v3", - "--node-count", - "2", - ] - - with mock.patch("sys.argv", test_args): - main() # Use the imported main function - - # Verify - call_kwargs = mock_azure_crud_class.call_args.kwargs - self.assertEqual(call_kwargs["cluster_name"], "test-cluster") - self.assertTrue(call_kwargs["exclude_managed_identity"]) - create_kwargs = mock_node_pool_crud.create_node_pool.call_args.kwargs - self.assertEqual(create_kwargs["node_pool_type"], "VirtualMachines") - - def test_main_machine_command_rejects_node_pool_azure_options(self): - """Machine commands must not accept node-pool-only Azure options.""" - test_args = [ - "crud.py", - "create-machine", - "--cloud", - "azure", - "--run-id", - "test-run", - "--node-pool-name", - "test-pool", - "--vm-size", - "Standard_D2s_v3", - "--cluster-name", - "test-cluster", - ] - - with mock.patch("sys.argv", test_args): - with self.assertRaises(SystemExit) as context: - main() - - self.assertEqual(context.exception.code, 2) - - @mock.patch("crud.main.AzureNodePoolCRUD") - def test_main_delete_does_not_require_node_pool_type( - self, mock_azure_crud_class - ): - """Delete must run without create/scale-only node-pool arguments.""" - mock_node_pool_crud = mock.MagicMock() - mock_azure_crud_class.return_value = mock_node_pool_crud - mock_node_pool_crud.delete_node_pool.return_value = True - test_args = [ - "crud.py", - "delete", - "--cloud", - "azure", - "--run-id", - "test-run", - "--cluster-name", - "test-cluster", - "--exclude-managed-identity", - "--node-pool-name", - "test-pool", - ] - - with mock.patch("sys.argv", test_args): - main() - - mock_node_pool_crud.delete_node_pool.assert_called_once_with( - node_pool_name="test-pool" - ) - - def test_main_aws_rejects_azure_only_options(self): - """AWS node-pool commands must reject Azure-only options.""" - test_args = [ - "crud.py", - "create", - "--cloud", - "aws", - "--run-id", - "test-run", - "--node-pool-name", - "test-pool", - "--vm-size", - "m6i.2xlarge", - "--exclude-managed-identity", - "--node-pool-type", - "VirtualMachines", - ] - - with mock.patch("sys.argv", test_args): - with self.assertRaises(SystemExit) as context: - main() - - self.assertEqual(context.exception.code, 2) - - def test_main_workload_rejects_node_pool_type(self): - """Workload commands must not accept node-pool shape options.""" - test_args = [ - "crud.py", - "deployment", - "--cloud", - "azure", - "--run-id", - "test-run", - "--node-pool-name", - "test-pool", - "--node-pool-type", - "VirtualMachines", - ] - - with mock.patch("sys.argv", test_args): - with self.assertRaises(SystemExit) as context: - main() - - self.assertEqual(context.exception.code, 2) - @mock.patch("crud.main.OperationContext") @mock.patch("crud.main.AzureNodePoolCRUD") def test_main_operation_returns_none( diff --git a/modules/python/tests/crud/test_main_azure_options.py b/modules/python/tests/crud/test_main_azure_options.py new file mode 100644 index 0000000000..e1a00e260b --- /dev/null +++ b/modules/python/tests/crud/test_main_azure_options.py @@ -0,0 +1,93 @@ +"""CLI integration tests for Azure-specific CRUD options.""" + +import unittest +from unittest import mock + +from crud.main import main + + +class TestMainAzureOptions(unittest.TestCase): + """Validate option ownership across CRUD and machine commands.""" + + @mock.patch("crud.main.AzureNodePoolCRUD") + def test_main_complete_create_operation(self, mock_azure_crud_class): + mock_node_pool_crud = mock.MagicMock() + mock_azure_crud_class.return_value = mock_node_pool_crud + mock_node_pool_crud.create_node_pool.return_value = True + test_args = [ + "crud.py", "create", "--cloud", "azure", "--run-id", "test-run", + "--cluster-name", "test-cluster", "--exclude-managed-identity", + "--node-pool-name", "test-pool", "--node-pool-type", + "VirtualMachines", "--vm-size", "Standard_D2s_v3", "--node-count", "2", + ] + + with mock.patch("sys.argv", test_args): + main() + + client_kwargs = mock_azure_crud_class.call_args.kwargs + self.assertEqual(client_kwargs["cluster_name"], "test-cluster") + self.assertTrue(client_kwargs["exclude_managed_identity"]) + create_kwargs = mock_node_pool_crud.create_node_pool.call_args.kwargs + self.assertEqual(create_kwargs["node_pool_type"], "VirtualMachines") + + def test_main_machine_command_rejects_node_pool_azure_options(self): + test_args = [ + "crud.py", "create-machine", "--cloud", "azure", "--run-id", "test-run", + "--node-pool-name", "test-pool", "--vm-size", "Standard_D2s_v3", + "--cluster-name", "test-cluster", + ] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as context: + main() + + self.assertEqual(context.exception.code, 2) + + @mock.patch("crud.main.AzureNodePoolCRUD") + def test_main_delete_does_not_require_node_pool_type( + self, mock_azure_crud_class + ): + mock_node_pool_crud = mock.MagicMock() + mock_azure_crud_class.return_value = mock_node_pool_crud + mock_node_pool_crud.delete_node_pool.return_value = True + test_args = [ + "crud.py", "delete", "--cloud", "azure", "--run-id", "test-run", + "--cluster-name", "test-cluster", "--exclude-managed-identity", + "--node-pool-name", "test-pool", + ] + + with mock.patch("sys.argv", test_args): + main() + + mock_node_pool_crud.delete_node_pool.assert_called_once_with( + node_pool_name="test-pool" + ) + + def test_main_aws_rejects_azure_only_options(self): + test_args = [ + "crud.py", "create", "--cloud", "aws", "--run-id", "test-run", + "--node-pool-name", "test-pool", "--vm-size", "m6i.2xlarge", + "--exclude-managed-identity", "--node-pool-type", "VirtualMachines", + ] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as context: + main() + + self.assertEqual(context.exception.code, 2) + + def test_main_workload_rejects_node_pool_type(self): + test_args = [ + "crud.py", "deployment", "--cloud", "azure", "--run-id", "test-run", + "--node-pool-name", "test-pool", "--node-pool-type", "VirtualMachines", + ] + + with mock.patch("sys.argv", test_args): + with self.assertRaises(SystemExit) as context: + main() + + self.assertEqual(context.exception.code, 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/modules/python/tests/utils/test_azure_node_pool_cli.py b/modules/python/tests/utils/test_azure_node_pool_cli.py index 3a527046ac..d32f5f063d 100644 --- a/modules/python/tests/utils/test_azure_node_pool_cli.py +++ b/modules/python/tests/utils/test_azure_node_pool_cli.py @@ -13,6 +13,8 @@ build_add_virtual_machines_command, build_scale_virtual_machines_command, get_node_pool_scale_state, + prepare_create_operation, + prepare_scale_operation, ) @@ -84,6 +86,64 @@ def test_build_scale_virtual_machines_command(self): ], ) + def test_prepare_create_operation_configures_vmss(self): + parameters = {} + + operation = prepare_create_operation( + parameters, + "VirtualMachineScaleSets", + False, + "test-rg", + "test-cluster", + "test-pool", + 2, + "Standard_D2s_v3", + ) + + self.assertIsNone(operation) + self.assertEqual(parameters, {"count": 2, "vm_size": "Standard_D2s_v3"}) + + def test_prepare_create_operation_returns_virtual_machines_callable(self): + operation = prepare_create_operation( + {}, + "VirtualMachines", + False, + "test-rg", + "test-cluster", + "test-pool", + 2, + "Standard_D2s_v3", + ) + + self.assertTrue(callable(operation)) + + def test_prepare_scale_operation_configures_vmss(self): + node_pool = mock.MagicMock() + + operation = prepare_scale_operation( + node_pool, + "VirtualMachineScaleSets", + "test-rg", + "test-cluster", + "test-pool", + 3, + ) + + self.assertIsNone(operation) + self.assertEqual(node_pool.count, 3) + + def test_prepare_scale_operation_returns_virtual_machines_callable(self): + operation = prepare_scale_operation( + mock.MagicMock(), + "VirtualMachines", + "test-rg", + "test-cluster", + "test-pool", + 3, + ) + + self.assertTrue(callable(operation)) + if __name__ == "__main__": unittest.main() diff --git a/modules/python/utils/azure_node_pool_cli.py b/modules/python/utils/azure_node_pool_cli.py index 278df49646..b97d1a210f 100644 --- a/modules/python/utils/azure_node_pool_cli.py +++ b/modules/python/utils/azure_node_pool_cli.py @@ -2,6 +2,7 @@ import subprocess import time +from functools import partial from utils.logger_config import get_logger @@ -106,6 +107,74 @@ def run_node_pool_cli( return retry_occurred +def create_virtual_machines_node_pool( + resource_group, cluster_name, node_pool_name, node_count, vm_size +): + """Create a VirtualMachines node pool and return whether a retry occurred.""" + command = build_add_virtual_machines_command( + resource_group, cluster_name, node_pool_name, node_count, vm_size + ) + return run_node_pool_cli(command, node_pool_name, "add") + + +def scale_virtual_machines_node_pool( + resource_group, cluster_name, node_pool_name, node_count +): + """Scale a VirtualMachines node pool and return whether a retry occurred.""" + command = build_scale_virtual_machines_command( + resource_group, cluster_name, node_pool_name, node_count + ) + return run_node_pool_cli(command, node_pool_name, "scale") + + +def prepare_create_operation( + parameters, + node_pool_type, + gpu_node_pool, + resource_group, + cluster_name, + node_pool_name, + node_count, + vm_size, +): + """Configure VMSS parameters or return a VirtualMachines create callable.""" + if node_pool_type != "VirtualMachines": + parameters["count"] = node_count + parameters["vm_size"] = vm_size + return None + if gpu_node_pool: + raise ValueError("GPU node pools with type VirtualMachines are not supported") + return partial( + create_virtual_machines_node_pool, + resource_group, + cluster_name, + node_pool_name, + node_count, + vm_size, + ) + + +def prepare_scale_operation( + node_pool, + node_pool_type, + resource_group, + cluster_name, + node_pool_name, + node_count, +): + """Configure VMSS count or return a VirtualMachines scale callable.""" + if node_pool_type != "VirtualMachines": + node_pool.count = node_count + return None + return partial( + scale_virtual_machines_node_pool, + resource_group, + cluster_name, + node_pool_name, + node_count, + ) + + def add_managed_gpu_node_pool( resource_group, node_pool_name, From d41f41bf3536a0c1c4145c3aea127c4d67e10c61 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Tue, 25 Aug 2026 23:51:40 -0400 Subject: [PATCH 11/12] refactor: simplify Azure node pool operations --- modules/python/clients/aks_client.py | 54 +++++++++---------- modules/python/crud/azure/node_pool_crud.py | 7 +-- modules/python/crud/main.py | 28 +++++----- .../python/tests/clients/test_aks_client.py | 12 ++++- .../tests/utils/test_azure_node_pool_cli.py | 26 +++++++-- modules/python/utils/azure_node_pool_cli.py | 47 ++++++++++++---- modules/python/utils/constants.py | 6 +++ .../utils/provisioning_instrumentation.py | 41 -------------- 8 files changed, 119 insertions(+), 102 deletions(-) diff --git a/modules/python/clients/aks_client.py b/modules/python/clients/aks_client.py index 5c0cbe37f8..b2347525b3 100644 --- a/modules/python/clients/aks_client.py +++ b/modules/python/clients/aks_client.py @@ -25,6 +25,7 @@ # Local imports from utils.logger_config import get_logger, setup_logging from utils.common import get_env_vars +from utils.constants import AzureNodePoolTypeConstants from utils.azure_node_pool_cli import ( add_managed_gpu_node_pool as add_managed_gpu_node_pool_cli, get_node_pool_scale_state, @@ -32,7 +33,7 @@ prepare_scale_operation, ) from utils.provisioning_instrumentation import ( - instrument_aks_nodepool_provisioning, + instrument_nodepool_provisioning, ) from .kubernetes_client import KubernetesClient @@ -70,25 +71,24 @@ def _get_operation_context(self): def _instrument_nodepool_provisioning( self, node_pool_name: str, - cluster_name: str, - parameters: Any, node_count: int, op, + arm_callable, label: str = "", - arm_callable=None, ) -> list: """Instrument ARM and Kubernetes node readiness for an AKS node pool.""" - return instrument_aks_nodepool_provisioning( - aks_sdk_client=self.aks_client, - resource_group=self.resource_group, - k8s_client=self.k8s_client, - operation_timeout_minutes=self.operation_timeout_minutes, + def k8s_wait_callable(): + return self.k8s_client.wait_for_nodes_ready( + node_count=node_count, + operation_timeout_in_minutes=self.operation_timeout_minutes, + label_selector=f"agentpool={node_pool_name}", + ) + + return instrument_nodepool_provisioning( node_pool_name=node_pool_name, - cluster_name=cluster_name, - parameters=parameters, - node_count=node_count, op=op, arm_callable=arm_callable, + k8s_wait_callable=k8s_wait_callable, label=label, ) @@ -289,7 +289,7 @@ def add_managed_gpu_node_pool( node_count: int, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, - node_pool_type: str = "VirtualMachineScaleSets", + node_pool_type: str = AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ) -> None: """Create a fully managed GPU node pool through the aks-preview CLI.""" add_managed_gpu_node_pool_cli( @@ -377,7 +377,7 @@ def create_node_pool( enable_managed_gpu: bool = False, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, - node_pool_type: str = "VirtualMachineScaleSets", + node_pool_type: str = AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ) -> Any: """ Create a new node pool in the AKS cluster. @@ -437,6 +437,12 @@ def create_node_pool( "nodeLabels": {"gpu": "true"} if gpu_node_pool else {}, } + if gpu_node_pool and not enable_managed_gpu: + # Managed GPU (driver bootstrap only): driver install, no NVIDIA management + parameters["gpu_profile"] = { + "driver": "Install", + } + arm_callable = prepare_create_operation( parameters, node_pool_type, @@ -446,14 +452,9 @@ def create_node_pool( node_pool_name, node_count, vm_size, + self.aks_client, ) - if gpu_node_pool and not enable_managed_gpu: - # Managed GPU (driver bootstrap only): driver install, no NVIDIA management - parameters["gpu_profile"] = { - "driver": "Install", - } - logger.info( f"Creating node pool {node_pool_name} in cluster {cluster_name}" ) @@ -479,8 +480,6 @@ def create_node_pool( else: ready_nodes = self._instrument_nodepool_provisioning( node_pool_name, - cluster_name, - parameters, node_count, op, arm_callable=arm_callable, @@ -543,7 +542,7 @@ def scale_node_pool( scale_step_size: int = 1, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, - node_pool_type: str = "VirtualMachineScaleSets", + node_pool_type: str = AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ) -> Any: """ Scale a node pool to the specified node count. @@ -646,6 +645,7 @@ def scale_node_pool( cluster_name, node_pool_name, node_count, + self.aks_client, ) logger.info(f"Scaling node pool {node_pool_name} to {node_count} nodes") @@ -657,8 +657,6 @@ def scale_node_pool( # Run ARM and K8s readiness concurrently to capture both timings ready_nodes = self._instrument_nodepool_provisioning( node_pool_name, - cluster_name, - node_pool, node_count, op, arm_callable=arm_callable, @@ -790,7 +788,7 @@ def _progressive_scale( node_pool: Optional[Any] = None, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, - node_pool_type: str = "VirtualMachineScaleSets", + node_pool_type: str = AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ) -> Any: """ Scale a node pool progressively with specified step size @@ -888,11 +886,13 @@ def _progressive_scale( cluster_name, node_pool_name, step, + self.aks_client, + label=f"step {step} ", ) # Run ARM and K8s readiness concurrently to capture both timings ready_nodes = self._instrument_nodepool_provisioning( - node_pool_name, cluster_name, node_pool, step, op, + node_pool_name, step, op, label=f"step {step} ", arm_callable=arm_callable, ) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 75d541ba86..07df0150fd 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 utils.constants import AzureNodePoolTypeConstants from utils.logger_config import get_logger, setup_logging from utils.azure_auth import configure_credential @@ -86,7 +87,7 @@ def __init__( def create_node_pool( self, node_pool_name, vm_size, node_count=1, gpu_node_pool=False, enable_managed_gpu=False, gpu_instance_profile=None, gpu_mig_strategy=None, - node_pool_type="VirtualMachineScaleSets", + node_pool_type=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ): """ Create a new node pool @@ -132,7 +133,7 @@ def scale_node_pool( enable_managed_gpu=False, gpu_instance_profile=None, gpu_mig_strategy=None, - node_pool_type="VirtualMachineScaleSets", + node_pool_type=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ): """ Scale a node pool to specified count @@ -208,7 +209,7 @@ def all( step_wait_time=30, gpu_instance_profile=None, gpu_mig_strategy=None, - node_pool_type="VirtualMachineScaleSets", + node_pool_type=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ): """ Unified method to perform all node pool operations: create, scale-up, scale-down, delete diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index 4e95f95a09..18493457e4 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -21,6 +21,7 @@ from crud.aws.node_pool_crud import NodePoolCRUD as AWSNodePoolCRUD from crud.operation import OperationContext from utils.common import get_env_vars +from utils.constants import AzureNodePoolTypeConstants from utils.logger_config import get_logger, setup_logging # Configure logging @@ -111,10 +112,11 @@ def handle_node_pool_operation(node_pool_crud, args): # CRUD does not accept these kwargs (and has no **kwargs), so passing them for # --cloud aws would raise TypeError. Only forward them on Azure. azure_kwargs = {} - if args.cloud == "azure": + if args.cloud == "azure" and command in ("create", "scale", "all"): azure_kwargs = { "gpu_instance_profile": args.gpu_instance_profile, "gpu_mig_strategy": args.gpu_mig_strategy, + "node_pool_type": args.node_pool_type, } try: @@ -128,9 +130,6 @@ def handle_node_pool_operation(node_pool_crud, args): "enable_managed_gpu": args.enable_managed_gpu, **azure_kwargs, } - if args.cloud == "azure": - create_kwargs["node_pool_type"] = args.node_pool_type - result = node_pool_crud.create_node_pool(**create_kwargs) elif command == "scale": @@ -144,9 +143,6 @@ def handle_node_pool_operation(node_pool_crud, args): "enable_managed_gpu": args.enable_managed_gpu, **azure_kwargs, } - if args.cloud == "azure": - scale_kwargs["node_pool_type"] = args.node_pool_type - result = node_pool_crud.scale_node_pool(**scale_kwargs) elif command == "delete": @@ -166,9 +162,6 @@ def handle_node_pool_operation(node_pool_crud, args): "step_wait_time": args.step_wait_time, **azure_kwargs, } - if args.cloud == "azure": - all_kwargs["node_pool_type"] = args.node_pool_type - result = node_pool_crud.all(**all_kwargs) else: logger.error(f"Unsupported command: {command}") @@ -470,8 +463,11 @@ def main(): azure_node_pool_parser = argparse.ArgumentParser(add_help=False) azure_node_pool_parser.add_argument( "--node-pool-type", - choices=["VirtualMachineScaleSets", "VirtualMachines"], - default="VirtualMachineScaleSets", + choices=[ + AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, + AzureNodePoolTypeConstants.VIRTUAL_MACHINES, + ], + default=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, help="Azure node pool type (default: VirtualMachineScaleSets)", ) @@ -667,8 +663,12 @@ def main(): if args.cloud != "azure" and ( getattr(args, "cluster_name", None) or getattr(args, "exclude_managed_identity", False) - or getattr(args, "node_pool_type", "VirtualMachineScaleSets") - != "VirtualMachineScaleSets" + or getattr( + args, + "node_pool_type", + AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, + ) + != AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS ): parser.error( "--cluster-name, --exclude-managed-identity, and non-default " diff --git a/modules/python/tests/clients/test_aks_client.py b/modules/python/tests/clients/test_aks_client.py index 08d78b6feb..ec4a7ca312 100644 --- a/modules/python/tests/clients/test_aks_client.py +++ b/modules/python/tests/clients/test_aks_client.py @@ -626,10 +626,19 @@ def test_scale_gpu_node_pool_up_progressive_final_step(self, mock_time): # Two operations for two scaling steps mock_operation1 = mock.MagicMock() mock_operation2 = mock.MagicMock() - self.mock_agent_pools.begin_create_or_update.side_effect = [ + mock_operations = [ mock_operation1, mock_operation2, ] + requested_counts = [] + + def record_requested_count(**kwargs): + requested_counts.append(kwargs["parameters"].count) + return mock_operations.pop(0) + + self.mock_agent_pools.begin_create_or_update.side_effect = ( + record_requested_count + ) # Create mock for each scaling step's nodes ready_nodes1 = [mock.MagicMock(), mock.MagicMock()] # First step to 2 nodes @@ -664,6 +673,7 @@ def test_scale_gpu_node_pool_up_progressive_final_step(self, mock_time): self.assertEqual( self.mock_agent_pools.begin_create_or_update.call_count, 2 ) + self.assertEqual(requested_counts, [2, 3]) # Check that NVIDIA verification was performed only once (on the final step) self.mock_k8s.verify_nvidia_smi_on_node.assert_called_once_with( diff --git a/modules/python/tests/utils/test_azure_node_pool_cli.py b/modules/python/tests/utils/test_azure_node_pool_cli.py index d32f5f063d..ba40d2e60d 100644 --- a/modules/python/tests/utils/test_azure_node_pool_cli.py +++ b/modules/python/tests/utils/test_azure_node_pool_cli.py @@ -86,8 +86,10 @@ def test_build_scale_virtual_machines_command(self): ], ) - def test_prepare_create_operation_configures_vmss(self): + def test_prepare_create_operation_returns_vmss_callable(self): parameters = {} + aks_sdk_client = mock.MagicMock() + aks_sdk_client.agent_pools.begin_create_or_update.return_value.done.return_value = True operation = prepare_create_operation( parameters, @@ -98,10 +100,17 @@ def test_prepare_create_operation_configures_vmss(self): "test-pool", 2, "Standard_D2s_v3", + aks_sdk_client, ) - self.assertIsNone(operation) - self.assertEqual(parameters, {"count": 2, "vm_size": "Standard_D2s_v3"}) + self.assertTrue(callable(operation)) + operation() + call_parameters = ( + aks_sdk_client.agent_pools.begin_create_or_update.call_args.kwargs[ + "parameters" + ] + ) + self.assertEqual(call_parameters, {"count": 2, "vm_size": "Standard_D2s_v3"}) def test_prepare_create_operation_returns_virtual_machines_callable(self): operation = prepare_create_operation( @@ -113,12 +122,15 @@ def test_prepare_create_operation_returns_virtual_machines_callable(self): "test-pool", 2, "Standard_D2s_v3", + mock.MagicMock(), ) self.assertTrue(callable(operation)) - def test_prepare_scale_operation_configures_vmss(self): + def test_prepare_scale_operation_returns_vmss_callable(self): node_pool = mock.MagicMock() + aks_sdk_client = mock.MagicMock() + aks_sdk_client.agent_pools.begin_create_or_update.return_value.done.return_value = True operation = prepare_scale_operation( node_pool, @@ -127,10 +139,13 @@ def test_prepare_scale_operation_configures_vmss(self): "test-cluster", "test-pool", 3, + aks_sdk_client, ) - self.assertIsNone(operation) + self.assertTrue(callable(operation)) self.assertEqual(node_pool.count, 3) + operation() + aks_sdk_client.agent_pools.begin_create_or_update.assert_called_once() def test_prepare_scale_operation_returns_virtual_machines_callable(self): operation = prepare_scale_operation( @@ -140,6 +155,7 @@ def test_prepare_scale_operation_returns_virtual_machines_callable(self): "test-cluster", "test-pool", 3, + mock.MagicMock(), ) self.assertTrue(callable(operation)) diff --git a/modules/python/utils/azure_node_pool_cli.py b/modules/python/utils/azure_node_pool_cli.py index b97d1a210f..b6cebdfc71 100644 --- a/modules/python/utils/azure_node_pool_cli.py +++ b/modules/python/utils/azure_node_pool_cli.py @@ -4,14 +4,16 @@ import time from functools import partial +from utils.constants import AzureNodePoolTypeConstants from utils.logger_config import get_logger +from utils.provisioning_instrumentation import begin_create_or_update_with_retry logger = get_logger(__name__) def get_node_pool_scale_state(node_pool, node_pool_type): """Return current node count and VM size for VMSS or VirtualMachines pools.""" - if node_pool_type != "VirtualMachines": + if node_pool_type != AzureNodePoolTypeConstants.VIRTUAL_MACHINES: return node_pool.count, node_pool.vm_size profile = node_pool.virtual_machines_profile @@ -40,7 +42,7 @@ def build_add_virtual_machines_command( "--name", node_pool_name, "--node-count", str(node_count), "--vm-sizes", vm_size, - "--vm-set-type", "VirtualMachines", + "--vm-set-type", AzureNodePoolTypeConstants.VIRTUAL_MACHINES, "--mode", "User", "--node-osdisk-type", "Managed", ] @@ -136,12 +138,25 @@ def prepare_create_operation( node_pool_name, node_count, vm_size, + aks_sdk_client, + label="", ): - """Configure VMSS parameters or return a VirtualMachines create callable.""" - if node_pool_type != "VirtualMachines": - parameters["count"] = node_count - parameters["vm_size"] = vm_size - return None + """Return a node-pool create callable for the requested pool type.""" + if node_pool_type != AzureNodePoolTypeConstants.VIRTUAL_MACHINES: + sdk_parameters = { + **parameters, + "count": node_count, + "vm_size": vm_size, + } + return partial( + begin_create_or_update_with_retry, + aks_sdk_client, + resource_group, + cluster_name, + node_pool_name, + sdk_parameters, + label=label, + ) if gpu_node_pool: raise ValueError("GPU node pools with type VirtualMachines are not supported") return partial( @@ -161,11 +176,21 @@ def prepare_scale_operation( cluster_name, node_pool_name, node_count, + aks_sdk_client, + label="", ): - """Configure VMSS count or return a VirtualMachines scale callable.""" - if node_pool_type != "VirtualMachines": + """Return a node-pool scale callable for the requested pool type.""" + if node_pool_type != AzureNodePoolTypeConstants.VIRTUAL_MACHINES: node_pool.count = node_count - return None + return partial( + begin_create_or_update_with_retry, + aks_sdk_client, + resource_group, + cluster_name, + node_pool_name, + node_pool, + label=label, + ) return partial( scale_virtual_machines_node_pool, resource_group, @@ -183,7 +208,7 @@ def add_managed_gpu_node_pool( node_count, gpu_instance_profile=None, gpu_mig_strategy=None, - node_pool_type="VirtualMachineScaleSets", + node_pool_type=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ): """Create a fully managed GPU node pool through the aks-preview CLI.""" subprocess.run( diff --git a/modules/python/utils/constants.py b/modules/python/utils/constants.py index 150bbcb95b..97e1f1b39e 100644 --- a/modules/python/utils/constants.py +++ b/modules/python/utils/constants.py @@ -22,3 +22,9 @@ class AzureSKUFamily: VM_SIZE_TO_SKU_FAMILY = { "Standard_ND96asr_v4": "ndv4" } + + +@dataclass(frozen=True) +class AzureNodePoolTypeConstants: + VIRTUAL_MACHINE_SCALE_SETS = "VirtualMachineScaleSets" + VIRTUAL_MACHINES = "VirtualMachines" diff --git a/modules/python/utils/provisioning_instrumentation.py b/modules/python/utils/provisioning_instrumentation.py index d149c5c8b4..f8e38a5e13 100644 --- a/modules/python/utils/provisioning_instrumentation.py +++ b/modules/python/utils/provisioning_instrumentation.py @@ -83,47 +83,6 @@ def instrument_nodepool_provisioning( return ready_nodes -def instrument_aks_nodepool_provisioning( - aks_sdk_client, - resource_group, - k8s_client, - operation_timeout_minutes, - node_pool_name, - cluster_name, - parameters, - node_count, - op, - label="", - arm_callable=None, -): - """Build AKS callables and instrument ARM and Kubernetes readiness.""" - if arm_callable is None: - def arm_callable(): - return begin_create_or_update_with_retry( - aks_sdk_client, - resource_group, - cluster_name, - node_pool_name, - parameters, - label=label, - ) - - def k8s_wait_callable(): - return k8s_client.wait_for_nodes_ready( - node_count=node_count, - operation_timeout_in_minutes=operation_timeout_minutes, - label_selector=f"agentpool={node_pool_name}", - ) - - return instrument_nodepool_provisioning( - node_pool_name=node_pool_name, - op=op, - arm_callable=arm_callable, - k8s_wait_callable=k8s_wait_callable, - label=label, - ) - - def begin_create_or_update_with_retry( aks_sdk_client, resource_group, From 92660bd78834fffeb0cfb471ce23ef455eb4c458 Mon Sep 17 00:00:00 2001 From: Diamond Powell <32712461+diamondpowell@users.noreply.github.com> Date: Thu, 3 Sep 2026 14:48:12 -0400 Subject: [PATCH 12/12] fix: preserve managed GPU node pool behavior --- modules/python/clients/aks_client.py | 3 - .../tests/utils/test_azure_node_pool_cli.py | 56 +++++++++++++++++-- modules/python/utils/azure_node_pool_cli.py | 44 ++++++++++++--- 3 files changed, 88 insertions(+), 15 deletions(-) diff --git a/modules/python/clients/aks_client.py b/modules/python/clients/aks_client.py index b2347525b3..64a9f7e85e 100644 --- a/modules/python/clients/aks_client.py +++ b/modules/python/clients/aks_client.py @@ -289,7 +289,6 @@ def add_managed_gpu_node_pool( node_count: int, gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, - node_pool_type: str = AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ) -> None: """Create a fully managed GPU node pool through the aks-preview CLI.""" add_managed_gpu_node_pool_cli( @@ -300,7 +299,6 @@ def add_managed_gpu_node_pool( node_count=node_count, gpu_instance_profile=gpu_instance_profile, gpu_mig_strategy=gpu_mig_strategy, - node_pool_type=node_pool_type, ) @staticmethod @@ -467,7 +465,6 @@ def create_node_pool( cluster_name=cluster_name, vm_size=vm_size, node_count=node_count, - node_pool_type=node_pool_type, gpu_instance_profile=gpu_instance_profile, gpu_mig_strategy=gpu_mig_strategy, ) diff --git a/modules/python/tests/utils/test_azure_node_pool_cli.py b/modules/python/tests/utils/test_azure_node_pool_cli.py index ba40d2e60d..07deb61c93 100644 --- a/modules/python/tests/utils/test_azure_node_pool_cli.py +++ b/modules/python/tests/utils/test_azure_node_pool_cli.py @@ -10,6 +10,7 @@ ) from utils.azure_node_pool_cli import ( + add_managed_gpu_node_pool, build_add_virtual_machines_command, build_scale_virtual_machines_command, get_node_pool_scale_state, @@ -21,7 +22,7 @@ class TestAzureNodePoolCLI(unittest.TestCase): """Validate VirtualMachines readback and command contracts.""" - def test_get_scale_state_from_sdk_model(self): + def test_get_scale_state_rejects_multiple_manual_profiles(self): node_pool = mock.MagicMock() node_pool.virtual_machines_profile = VirtualMachinesProfile( scale=ScaleProfile( @@ -32,10 +33,8 @@ def test_get_scale_state_from_sdk_model(self): ) ) - count, vm_size = get_node_pool_scale_state(node_pool, "VirtualMachines") - - self.assertEqual(count, 5) - self.assertEqual(vm_size, "Standard_D2s_v3") + with self.assertRaisesRegex(ValueError, "multiple manual scale profiles"): + get_node_pool_scale_state(node_pool, "VirtualMachines") def test_get_scale_state_from_dict(self): node_pool = mock.MagicMock() @@ -86,6 +85,53 @@ def test_build_scale_virtual_machines_command(self): ], ) + @mock.patch("utils.azure_node_pool_cli.subprocess.run") + def test_managed_gpu_command_does_not_set_vm_type(self, mock_subprocess_run): + mock_subprocess_run.return_value = mock.MagicMock( + returncode=0, stdout="", stderr="" + ) + + add_managed_gpu_node_pool( + "test-rg", "test-pool", "test-cluster", "Standard_NC6s_v3", 1 + ) + + command = mock_subprocess_run.call_args_list[1].args[0] + self.assertNotIn("--vm-set-type", command) + + @mock.patch("utils.azure_node_pool_cli.time.sleep") + @mock.patch("utils.azure_node_pool_cli.subprocess.run") + def test_managed_gpu_retries_operation_not_allowed( + self, mock_subprocess_run, mock_sleep + ): + mock_subprocess_run.side_effect = [ + mock.MagicMock(returncode=0, stdout="", stderr=""), + mock.MagicMock( + returncode=1, stdout="", stderr="OperationNotAllowed" + ), + mock.MagicMock(returncode=0, stdout="", stderr=""), + ] + + add_managed_gpu_node_pool( + "test-rg", "test-pool", "test-cluster", "Standard_NC6s_v3", 1 + ) + + self.assertEqual(mock_subprocess_run.call_count, 3) + mock_sleep.assert_called_once_with(30) + + @mock.patch("utils.azure_node_pool_cli.subprocess.run") + def test_managed_gpu_does_not_retry_etag_mismatch(self, mock_subprocess_run): + mock_subprocess_run.side_effect = [ + mock.MagicMock(returncode=0, stdout="", stderr=""), + mock.MagicMock(returncode=1, stdout="", stderr="EtagMismatch"), + ] + + with self.assertRaisesRegex(RuntimeError, "EtagMismatch"): + add_managed_gpu_node_pool( + "test-rg", "test-pool", "test-cluster", "Standard_NC6s_v3", 1 + ) + + self.assertEqual(mock_subprocess_run.call_count, 2) + def test_prepare_create_operation_returns_vmss_callable(self): parameters = {} aks_sdk_client = mock.MagicMock() diff --git a/modules/python/utils/azure_node_pool_cli.py b/modules/python/utils/azure_node_pool_cli.py index b6cebdfc71..a8be4e0152 100644 --- a/modules/python/utils/azure_node_pool_cli.py +++ b/modules/python/utils/azure_node_pool_cli.py @@ -21,14 +21,19 @@ def get_node_pool_scale_state(node_pool, node_pool_type): manual = scale.get("manual") if isinstance(scale, dict) else scale.manual if not manual: raise ValueError("VirtualMachines node pool has no manual scale profile") + if len(manual) != 1: + raise ValueError( + "VirtualMachines node pools with multiple manual scale profiles " + "are not supported" + ) def read(entry, field): return entry.get(field) if isinstance(entry, dict) else getattr(entry, field) - counts = [read(entry, "count") for entry in manual] - if any(count is None for count in counts): + count = read(manual[0], "count") + if count is None: raise ValueError("VirtualMachines manual scale profile has no node count") - return sum(counts), read(manual[0], "size") + return count, read(manual[0], "size") def build_add_virtual_machines_command( @@ -208,7 +213,6 @@ def add_managed_gpu_node_pool( node_count, gpu_instance_profile=None, gpu_mig_strategy=None, - node_pool_type=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ): """Create a fully managed GPU node pool through the aks-preview CLI.""" subprocess.run( @@ -243,8 +247,6 @@ def add_managed_gpu_node_pool( str(node_count), "--node-vm-size", vm_size, - "--vm-set-type", - node_pool_type, "--mode", "User", "--node-osdisk-type", @@ -260,5 +262,33 @@ def add_managed_gpu_node_pool( cmd += ["--gpu-mig-strategy", gpu_mig_strategy] logger.info("Running: %s", " ".join(cmd)) - run_node_pool_cli(cmd, node_pool_name, "add") + retries = 10 + retry_wait = 30 + for attempt in range(retries): + result = subprocess.run( + cmd, + capture_output=True, + text=True, + check=False, + ) + if result.returncode == 0: + break + detail = " | ".join( + line + for line in (result.stdout + result.stderr).splitlines() + if line.strip() + ) + if "OperationNotAllowed" in detail and attempt < retries - 1: + logger.warning( + "Cluster has an in-progress operation, retrying in %ss " + "(attempt %s/%s)", + retry_wait, + attempt + 1, + retries, + ) + time.sleep(retry_wait) + continue + raise RuntimeError( + f"az aks nodepool add failed (rc={result.returncode}): {detail}" + ) logger.info("az aks nodepool add succeeded for '%s'", node_pool_name)