diff --git a/modules/python/clients/aks_client.py b/modules/python/clients/aks_client.py index e41c95df57..64a9f7e85e 100644 --- a/modules/python/clients/aks_client.py +++ b/modules/python/clients/aks_client.py @@ -13,7 +13,6 @@ import logging import os -import subprocess import time from typing import Dict, Optional, Any @@ -26,8 +25,14 @@ # 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, + prepare_create_operation, + prepare_scale_operation, +) from utils.provisioning_instrumentation import ( - begin_create_or_update_with_retry, instrument_nodepool_provisioning, ) from .kubernetes_client import KubernetesClient @@ -66,22 +71,12 @@ 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 = "", ) -> 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, - ) - + """Instrument ARM and Kubernetes node readiness for an AKS node pool.""" def k8s_wait_callable(): return self.k8s_client.wait_for_nodes_ready( node_count=node_count, @@ -295,54 +290,17 @@ def add_managed_gpu_node_pool( gpu_instance_profile: Optional[str] = None, gpu_mig_strategy: Optional[str] = None, ) -> 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, ) - 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 +375,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 = AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ) -> Any: """ Create a new node pool in the AKS cluster. @@ -452,6 +411,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,8 +429,6 @@ 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", @@ -483,6 +441,18 @@ def create_node_pool( "driver": "Install", } + arm_callable = prepare_create_operation( + parameters, + node_pool_type, + gpu_node_pool, + self.resource_group, + cluster_name, + node_pool_name, + node_count, + vm_size, + self.aks_client, + ) + logger.info( f"Creating node pool {node_pool_name} in cluster {cluster_name}" ) @@ -505,9 +475,11 @@ def create_node_pool( label_selector=label_selector, ) else: - # Run ARM and K8s readiness concurrently to capture both timings ready_nodes = self._instrument_nodepool_provisioning( - node_pool_name, cluster_name, parameters, node_count, op + node_pool_name, + node_count, + op, + arm_callable=arm_callable, ) logger.info( @@ -567,6 +539,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 = AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ) -> Any: """ Scale a node pool to the specified node count. @@ -597,6 +570,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, @@ -610,7 +584,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: @@ -634,6 +610,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, ) @@ -644,7 +621,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) @@ -658,7 +635,15 @@ def scale_node_pool( ) # For direct scaling, update the node count - node_pool.count = node_count + arm_callable = prepare_scale_operation( + node_pool, + node_pool_type, + self.resource_group, + cluster_name, + node_pool_name, + node_count, + self.aks_client, + ) logger.info(f"Scaling node pool {node_pool_name} to {node_count} nodes") @@ -668,7 +653,10 @@ 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, + node_count, + op, + arm_callable=arm_callable, ) logger.info( @@ -797,6 +785,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 = AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ) -> Any: """ Scale a node pool progressively with specified step size @@ -887,12 +876,22 @@ 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 + arm_callable = prepare_scale_operation( + node_pool, + node_pool_type, + self.resource_group, + 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, ) logger.info(f"All {step} nodes in pool {node_pool_name} are ready") 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/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index 03f3f36635..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 @@ -53,16 +54,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, + kube_config_file=None, + result_dir=None, + step_timeout=600, + cluster_name=None, + 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(), + credential=configure_credential( + default_credential_exclude_mi=exclude_managed_identity + ), ) if not self.aks_client: @@ -77,6 +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=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ): """ Create a new node pool @@ -100,6 +111,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, @@ -121,6 +133,7 @@ def scale_node_pool( enable_managed_gpu=False, gpu_instance_profile=None, gpu_mig_strategy=None, + node_pool_type=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ): """ Scale a node pool to specified count @@ -143,6 +156,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, @@ -195,6 +209,7 @@ def all( step_wait_time=30, gpu_instance_profile=None, gpu_mig_strategy=None, + node_pool_type=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, ): """ Unified method to perform all node pool operations: create, scale-up, scale-down, delete @@ -229,6 +244,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, @@ -252,6 +268,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, @@ -277,6 +294,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 1fad21a6a3..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 @@ -110,11 +111,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 = {} - if args.cloud == "azure": - azure_gpu_kwargs = { + azure_kwargs = {} + 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: @@ -126,9 +128,8 @@ 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) elif command == "scale": @@ -140,9 +141,8 @@ 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) elif command == "delete": @@ -160,9 +160,8 @@ 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) else: logger.error(f"Unsupported command: {command}") @@ -450,9 +449,33 @@ def main(): help="Capacity type for AWS/Azure node pool", ) + 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_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=[ + AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, + AzureNodePoolTypeConstants.VIRTUAL_MACHINES, + ], + default=AzureNodePoolTypeConstants.VIRTUAL_MACHINE_SCALE_SETS, + help="Azure node pool type (default: VirtualMachineScaleSets)", + ) + # Create command create_parser = subparsers.add_parser( - "create", parents=[common_parser], help="Create a node pool" + "create", + 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") create_parser.add_argument( @@ -467,7 +490,9 @@ def main(): # Scale command scale_parser = subparsers.add_parser( - "scale", parents=[common_parser], help="Scale a node pool" + "scale", + 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") scale_parser.add_argument( @@ -490,7 +515,9 @@ def main(): # Delete command delete_parser = subparsers.add_parser( - "delete", parents=[common_parser], help="Delete a node pool" + "delete", + parents=[common_parser, azure_client_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) @@ -498,7 +525,7 @@ def main(): # All CRUD Operations command all_parser = subparsers.add_parser( "all", - parents=[common_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") @@ -565,7 +592,7 @@ def main(): # Deployment command deployment_parser = subparsers.add_parser( "deployment", - parents=[common_parser, workload_common_parser], + parents=[common_parser, azure_client_parser, workload_common_parser], help="create deployments" ) deployment_parser.set_defaults(func=handle_workload_operations) @@ -573,7 +600,7 @@ def main(): # StatefulSet command statefulset_parser = subparsers.add_parser( "statefulset", - parents=[common_parser, workload_common_parser], + parents=[common_parser, azure_client_parser, workload_common_parser], help="create statefulsets" ) statefulset_parser.set_defaults(func=handle_workload_operations) @@ -581,7 +608,7 @@ def main(): # Job command job_parser = subparsers.add_parser( "job", - parents=[common_parser, workload_common_parser], + parents=[common_parser, azure_client_parser, workload_common_parser], help="create jobs" ) job_parser.add_argument( @@ -633,6 +660,21 @@ 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) + 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 " + "--node-pool-type values 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" @@ -667,9 +709,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( @@ -741,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/pyproject.toml b/modules/python/pyproject.toml index c03218cb95..05d90a1ca5 100644 --- a/modules/python/pyproject.toml +++ b/modules/python/pyproject.toml @@ -28,7 +28,10 @@ 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", "crud.azure", "crud.aws"] + +[tool.setuptools.package-data] +crud = ["workload_templates/*.yml"] [tool.setuptools.dynamic] dependencies = {file = "requirements.txt"} @@ -38,3 +41,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" diff --git a/modules/python/tests/clients/test_aks_client.py b/modules/python/tests/clients/test_aks_client.py index 8a12c5eaa0..ec4a7ca312 100644 --- a/modules/python/tests/clients/test_aks_client.py +++ b/modules/python/tests/clients/test_aks_client.py @@ -349,7 +349,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""" @@ -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/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 afa0734652..be1bddd4f7 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -49,17 +49,60 @@ def tearDown(self): except OSError: pass - def test_init_injects_configured_credential(self): - """Test that the configured credential is passed to AKSClient.""" - self.mock_configure_credential.assert_called_once_with() + 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=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_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, + 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): """Test successful node pool creation""" # Setup @@ -74,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, ) @@ -83,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, @@ -128,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, @@ -158,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, @@ -223,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 ccbb189ba4..9ebfca98c2 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): @@ -814,36 +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", - "--node-pool-name", - "test-pool", - "--vm-size", - "Standard_D2s_v3", - "--node-count", - "2", - ] - - with mock.patch("sys.argv", test_args): - main() # Use the imported main function - - # Verify - mock_azure_crud_class.assert_called_once() - mock_node_pool_crud.create_node_pool.assert_called_once() - @mock.patch("crud.main.OperationContext") @mock.patch("crud.main.AzureNodePoolCRUD") def test_main_operation_returns_none( @@ -904,9 +886,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") @@ -1503,9 +1486,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") @@ -1569,9 +1553,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/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 new file mode 100644 index 0000000000..07deb61c93 --- /dev/null +++ b/modules/python/tests/utils/test_azure_node_pool_cli.py @@ -0,0 +1,211 @@ +"""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 ( + add_managed_gpu_node_pool, + build_add_virtual_machines_command, + build_scale_virtual_machines_command, + get_node_pool_scale_state, + prepare_create_operation, + prepare_scale_operation, +) + + +class TestAzureNodePoolCLI(unittest.TestCase): + """Validate VirtualMachines readback and command contracts.""" + + def test_get_scale_state_rejects_multiple_manual_profiles(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), + ] + ) + ) + + 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() + 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", + ], + ) + + @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() + aks_sdk_client.agent_pools.begin_create_or_update.return_value.done.return_value = True + + operation = prepare_create_operation( + parameters, + "VirtualMachineScaleSets", + False, + "test-rg", + "test-cluster", + "test-pool", + 2, + "Standard_D2s_v3", + aks_sdk_client, + ) + + 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( + {}, + "VirtualMachines", + False, + "test-rg", + "test-cluster", + "test-pool", + 2, + "Standard_D2s_v3", + mock.MagicMock(), + ) + + self.assertTrue(callable(operation)) + + 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, + "VirtualMachineScaleSets", + "test-rg", + "test-cluster", + "test-pool", + 3, + aks_sdk_client, + ) + + 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( + mock.MagicMock(), + "VirtualMachines", + "test-rg", + "test-cluster", + "test-pool", + 3, + mock.MagicMock(), + ) + + 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 new file mode 100644 index 0000000000..a8be4e0152 --- /dev/null +++ b/modules/python/utils/azure_node_pool_cli.py @@ -0,0 +1,294 @@ +"""Azure CLI helpers for AKS node-pool operations.""" + +import subprocess +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 != AzureNodePoolTypeConstants.VIRTUAL_MACHINES: + 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") + 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) + + count = read(manual[0], "count") + if count is None: + raise ValueError("VirtualMachines manual scale profile has no node count") + return count, 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", AzureNodePoolTypeConstants.VIRTUAL_MACHINES, + "--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, + 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 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, + aks_sdk_client, + label="", +): + """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( + 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, + aks_sdk_client, + label="", +): + """Return a node-pool scale callable for the requested pool type.""" + if node_pool_type != AzureNodePoolTypeConstants.VIRTUAL_MACHINES: + node_pool.count = node_count + 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, + cluster_name, + node_pool_name, + node_count, + ) + + +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, +): + """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, + "--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)) + 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) 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"