Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/azure-cli/azure/cli/command_modules/acs/_consts.py
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,9 @@
CONST_GPU_DRIVER_INSTALL = "Install"
CONST_GPU_DRIVER_NONE = "None"

# managed GPU
CONST_GPU_MANAGEMENT_MODE_MANAGED = "Managed"

# SSH Access Consts
CONST_SSH_ACCESS_LOCALUSER = "localuser"
CONST_SSH_ACCESS_DISABLED = "disabled"
Expand Down
6 changes: 6 additions & 0 deletions src/azure-cli/azure/cli/command_modules/acs/_help.py
Original file line number Diff line number Diff line change
Expand Up @@ -2254,6 +2254,10 @@
- name: --gpu-driver
type: string
short-summary: Whether to install driver for GPU node pool. Possible values are "Install" or "None". Default is "Install".
- name: --enable-managed-gpu
type: bool
short-summary: Enable AKS-managed NVIDIA GPU components on a new Linux GPU node pool.
long-summary: Requires GPU driver installation and cannot be combined with --gpu-driver None. Defaults to false. The GPU management mode cannot be changed after node pool creation.
- name: --gateway-prefix-size
type: int
short-summary: The size of Public IPPrefix attached to the Gateway-mode node pool. The node pool must be in Gateway mode.
Expand Down Expand Up @@ -2293,6 +2297,8 @@
text: az aks nodepool add -g MyResourceGroup -n MyNodePool --cluster-name MyMC --vm-set-type VirtualMachines --vm-sizes "VMSize1,VMSize2" --node-count 3
- name: Create a nodepool with KataVmIsolation enabled.
text: az aks nodepool add -g MyResourceGroup -n nodepool1 --cluster-name MyManagedCluster --os-sku AzureLinux --vm-size Standard_D4s_v3 --workload-runtime KataVmIsolation --node-count 1
- name: Create a GPU node pool with AKS-managed NVIDIA GPU components.
text: az aks nodepool add -g MyResourceGroup -n gpunp --cluster-name MyManagedCluster --node-vm-size Standard_NC4as_T4_v3 --node-count 1 --enable-managed-gpu
"""

helps["aks nodepool delete"] = """
Expand Down
1 change: 1 addition & 0 deletions src/azure-cli/azure/cli/command_modules/acs/_params.py
Original file line number Diff line number Diff line change
Expand Up @@ -1323,6 +1323,7 @@ def load_arguments(self, _):
c.argument("if_match")
c.argument("if_none_match")
c.argument('gpu_driver', arg_type=get_enum_type(gpu_driver_install_modes))
c.argument('enable_managed_gpu', arg_type=get_three_state_flag())
c.argument("gateway_prefix_size", type=int, validator=validate_gateway_prefix_size)
c.argument('localdns_config', help='Path to a JSON file to configure the local DNS profile for a new nodepool.')
c.argument('workload_runtime', arg_type=get_enum_type(workload_runtime_types), help="The workload runtime to use on the nodepool.")
Expand Down
55 changes: 48 additions & 7 deletions src/azure-cli/azure/cli/command_modules/acs/agentpool_decorator.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@
CONST_DEFAULT_WINDOWS_NODE_VM_SIZE,
CONST_DEFAULT_VMS_VM_SIZE,
CONST_DEFAULT_WINDOWS_VMS_VM_SIZE,
CONST_GPU_DRIVER_INSTALL,
CONST_GPU_DRIVER_NONE,
CONST_GPU_MANAGEMENT_MODE_MANAGED,
CONST_MANAGED_CLUSTER_SKU_NAME_AUTOMATIC,
CONST_NODEPOOL_MODE_SYSTEM,
CONST_NODEPOOL_MODE_USER,
Expand Down Expand Up @@ -1880,6 +1883,25 @@ def get_gpu_driver(self) -> Union[str, None]:
"""
return self._get_gpu_driver()

def get_enable_managed_gpu(self) -> Union[bool, None]:
"""Return Managed GPU enablement, preserving an attached profile during creation.

An omitted argument returns None unless the command supplies a default or the
attached creation profile already specifies a management mode.
"""
enable_managed_gpu = self.raw_param.get("enable_managed_gpu")
if (
self.decorator_mode == DecoratorMode.CREATE and
self.agentpool and
self.agentpool.gpu_profile and
self.agentpool.gpu_profile.nvidia and
self.agentpool.gpu_profile.nvidia.management_mode is not None
):
enable_managed_gpu = (
self.agentpool.gpu_profile.nvidia.management_mode == CONST_GPU_MANAGEMENT_MODE_MANAGED
)
return enable_managed_gpu

def get_gateway_prefix_size(self) -> Union[int, None]:
"""Obtain the value of gateway_prefix_size.

Expand Down Expand Up @@ -2403,19 +2425,36 @@ def set_up_agentpool_windows_profile(self, agentpool: AgentPool) -> AgentPool:
return agentpool

def set_up_gpu_profile(self, agentpool: AgentPool) -> AgentPool:
"""Set up gpu profile for the AgentPool object.
"""Configure GPU drivers and Managed GPU without replacing existing GPU settings.

Managed GPU requires AKS driver installation. Reject a conflicting driver option
before changing the profile.

:return: the AgentPool object
"""
self._ensure_agentpool(agentpool)

gpu_driver = self.context.get_gpu_driver()
enable_managed_gpu = self.context.get_enable_managed_gpu()

if enable_managed_gpu:
if gpu_driver is not None and gpu_driver.lower() == CONST_GPU_DRIVER_NONE.lower():
raise MutuallyExclusiveArgumentError(
"Managed GPU requires GPU driver installation. "
"Remove --gpu-driver None or set --enable-managed-gpu false."
)
gpu_driver = CONST_GPU_DRIVER_INSTALL

# Construct AgentPoolGPUProfile if one of the fields has been set
if gpu_driver:
agentpool.gpu_profile = self.models.GPUProfile()
if gpu_driver is not None:
if agentpool.gpu_profile is None:
agentpool.gpu_profile = self.models.GPUProfile()
agentpool.gpu_profile.driver = gpu_driver

if enable_managed_gpu:
if agentpool.gpu_profile.nvidia is None:
agentpool.gpu_profile.nvidia = self.models.NvidiaGPUProfile()
agentpool.gpu_profile.nvidia.management_mode = CONST_GPU_MANAGEMENT_MODE_MANAGED

return agentpool

def set_up_artifact_streaming(self, agentpool: AgentPool) -> AgentPool:
Expand Down Expand Up @@ -3014,13 +3053,15 @@ def update_ssh_access(self, agentpool: AgentPool) -> AgentPool:
return agentpool

def update_gpu_profile(self, agentpool: AgentPool) -> AgentPool:
"""Update the requested GPU driver setting and preserve the rest of the GPU profile."""
self._ensure_agentpool(agentpool)

gpu_driver = self.context.get_gpu_driver()

# Construct AgentPoolGPUProfile if one of the fields has been set
if gpu_driver:
agentpool.gpu_profile = self.models.GPUProfile()
if gpu_driver is not None:
# Replacing the profile would discard the immutable NVIDIA management mode.
if agentpool.gpu_profile is None:
agentpool.gpu_profile = self.models.GPUProfile()
agentpool.gpu_profile.driver = gpu_driver

return agentpool
Expand Down
1 change: 1 addition & 0 deletions src/azure-cli/azure/cli/command_modules/acs/custom.py
Original file line number Diff line number Diff line change
Expand Up @@ -3595,6 +3595,7 @@ def aks_agentpool_add(
if_none_match=None,
# gpu driver
gpu_driver=None,
enable_managed_gpu=False,
# static egress gateway - gateway-mode pool
gateway_prefix_size=None,
# local DNS
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11867,6 +11867,43 @@ def test_aks_nodepool_add_with_gpu_instance_profile(self, resource_group, resour
self.cmd(
'aks delete -g {resource_group} -n {name} --yes --no-wait', checks=[self.is_empty()])

@live_only()
@AllowLargeResponse()
@AKSCustomResourceGroupPreparer(random_name_length=17, name_prefix='clitest', location='westus3')
def test_aks_nodepool_add_with_managed_gpu(self, resource_group, resource_group_location):
self.kwargs.update({
'resource_group': resource_group,
'name': self.create_random_name('cliakstest', 16),
'node_pool_name': self.create_random_name('gpu', 6),
'ssh_key_value': self.generate_ssh_keys(),
})
self.cmd(
'aks create --resource-group {resource_group} --name {name} '
'--node-count 1 --ssh-key-value {ssh_key_value}',
checks=[self.check('provisioningState', 'Succeeded')],
)
self.cmd(
'aks nodepool add --resource-group {resource_group} --cluster-name {name} '
'--name {node_pool_name} --node-vm-size Standard_NC4as_T4_v3 '
'--node-count 1 --enable-managed-gpu',
checks=[
self.check('provisioningState', 'Succeeded'),
self.check('gpuProfile.driver', 'Install'),
self.check('gpuProfile.nvidia.managementMode', 'Managed'),
],
)
self.cmd(
'aks nodepool update --resource-group {resource_group} --cluster-name {name} '
'--name {node_pool_name} --tags purpose=managed-gpu-test',
checks=[
self.check('provisioningState', 'Succeeded'),
self.check('gpuProfile.driver', 'Install'),
self.check('gpuProfile.nvidia.managementMode', 'Managed'),
self.check('tags.purpose', 'managed-gpu-test'),
],
)
self.cmd('aks delete -g {resource_group} -n {name} --yes --no-wait', checks=[self.is_empty()])

@AllowLargeResponse()
@AKSCustomResourceGroupPreparer(random_name_length=17, name_prefix='clitest', location='westus2')
def test_aks_create_with_overlay_network_plugin_mode(self, resource_group, resource_group_location):
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,209 @@
# --------------------------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for license information.
# --------------------------------------------------------------------------------------------

import argparse
import copy
import unittest
from types import SimpleNamespace
from unittest.mock import Mock, patch

from azure.cli.command_modules.acs import ContainerServiceCommandsLoader
from azure.cli.command_modules.acs._consts import AgentPoolDecoratorMode, DecoratorMode
from azure.cli.command_modules.acs.agentpool_decorator import (
AKSAgentPoolAddDecorator,
AKSAgentPoolContext,
AKSAgentPoolModels,
AKSAgentPoolParamDict,
AKSAgentPoolUpdateDecorator,
)
from azure.cli.command_modules.acs.custom import aks_agentpool_add, aks_agentpool_update
from azure.cli.command_modules.acs.tests.latest.mocks import MockCLI, MockCmd
from azure.cli.core.azclierror import MutuallyExclusiveArgumentError
from azure.cli.core.mock import DummyCli
from azure.cli.core.profiles import ResourceType


class ManagedGPUArgumentTestCase(unittest.TestCase):
"""Check the core command registration without loading aks-preview."""

def _arguments(self, command_name):
cli_ctx = DummyCli()
cli_ctx.invocation = SimpleNamespace(
data={"command_string": command_name}, parser=argparse.ArgumentParser()
)
loader = ContainerServiceCommandsLoader(cli_ctx)
loader.load_command_table(command_name.split())
loader.command_table[command_name].load_arguments()
loader.load_arguments(command_name)
return loader.argument_registry.arguments.get(command_name, {})

def test_add_accepts_bare_true_false_and_omitted(self):
settings = self._arguments("aks nodepool add")["enable_managed_gpu"].settings
self.assertFalse(settings.get("is_preview", False))
parser = argparse.ArgumentParser()
parser.add_argument(
"--enable-managed-gpu",
**{key: settings[key] for key in ("action", "choices", "nargs", "default") if key in settings}
)
for arguments, expected in (
([], None),
(["--enable-managed-gpu"], True),
(["--enable-managed-gpu", "true"], True),
(["--enable-managed-gpu", "false"], False),
):
with self.subTest(arguments=arguments):
self.assertIs(parser.parse_args(arguments).enable_managed_gpu, expected)

def test_update_does_not_offer_management_mode_changes(self):
self.assertNotIn("enable_managed_gpu", self._arguments("aks nodepool update"))

def test_preview_only_gpu_options_are_not_promoted(self):
arguments = self._arguments("aks nodepool add")
for name in ("managed_gpu_driver_mode", "gpu_mig_strategy", "gpu_mig_profiles"):
with self.subTest(name=name):
self.assertNotIn(name, arguments)


class ManagedGPUProfileTestCase(unittest.TestCase):
"""Exercise the stable models and full command handlers with SDK calls mocked."""

def setUp(self):
self.cmd = MockCmd(MockCLI())
self.client = Mock()
self.resource_type = ResourceType.MGMT_CONTAINERSERVICE
self.models = AKSAgentPoolModels(
self.cmd, self.resource_type, AgentPoolDecoratorMode.STANDALONE
)
self.pool_list = patch(
"azure.cli.command_modules.acs.agentpool_decorator.cf_agent_pools",
return_value=Mock(list=Mock(return_value=[])),
)
self.pool_list.start()
self.addCleanup(self.pool_list.stop)

def _add(self, **kwargs):
self.client.reset_mock()
aks_agentpool_add(
self.cmd, self.client, "test-rg", "test-cluster", "gpunp",
node_vm_size="Standard_NC4as_T4_v3", no_wait=True, **kwargs
)
self.client.begin_create_or_update.assert_called_once()
return self.client.begin_create_or_update.call_args.args[3]

def test_add_serializes_managed_gpu_with_driver_install(self):
for driver in (None, "Install"):
with self.subTest(driver=driver):
pool = self._add(enable_managed_gpu=True, gpu_driver=driver)
self.assertEqual(pool.gpu_profile.as_dict(), {
"driver": "Install", "nvidia": {"managementMode": "Managed"}
})

def test_add_keeps_existing_defaults_and_driver_only_options(self):
for enable_args in ({}, {"enable_managed_gpu": False}, {"enable_managed_gpu": None}):
for driver in (None, "Install", "None"):
with self.subTest(enable_args=enable_args, driver=driver):
pool = self._add(gpu_driver=driver, **enable_args)
if driver is None:
self.assertIsNone(pool.gpu_profile)
else:
self.assertEqual(pool.gpu_profile.as_dict(), {"driver": driver})

def test_add_rejects_conflicting_driver_before_sdk_write(self):
for driver in ("None", "none", "NONE"):
with self.subTest(driver=driver):
self.client.reset_mock()
with self.assertRaisesRegex(MutuallyExclusiveArgumentError, "requires GPU driver installation"):
self._add(enable_managed_gpu=True, gpu_driver=driver)
self.client.begin_create_or_update.assert_not_called()

def test_creation_context_preserves_attached_management_mode(self):
for pool_mode in AgentPoolDecoratorMode:
models = AKSAgentPoolModels(self.cmd, self.resource_type, pool_mode)
for management_mode in ("Managed", "Unmanaged"):
with self.subTest(pool_mode=pool_mode, management_mode=management_mode):
context = AKSAgentPoolContext(
self.cmd, AKSAgentPoolParamDict({}), models, DecoratorMode.CREATE, pool_mode
)
self.assertIsNone(context.get_enable_managed_gpu())
pool = models.UnifiedAgentPoolModel(
gpu_profile=models.GPUProfile(
nvidia=models.NvidiaGPUProfile(management_mode=management_mode)
)
)
context.attach_agentpool(pool)
self.assertIs(context.get_enable_managed_gpu(), management_mode == "Managed")

def test_add_decorator_preserves_gpu_profile_and_unknown_fields(self):
for pool_mode in AgentPoolDecoratorMode:
with self.subTest(pool_mode=pool_mode):
models = AKSAgentPoolModels(self.cmd, self.resource_type, pool_mode)
profile = models.GPUProfile({
"driver": "Install",
"nvidia": {"managementMode": "Managed", "futureSetting": "keep"},
})
pool = models.UnifiedAgentPoolModel(gpu_profile=profile)
decorator = AKSAgentPoolAddDecorator(
self.cmd, self.client, {"gpu_driver": "Install"}, self.resource_type, pool_mode
)
decorator.context.attach_agentpool(pool)
before = copy.deepcopy(profile.as_dict())
result = decorator.set_up_gpu_profile(pool)
self.assertIs(result.gpu_profile, profile)
self.assertEqual(result.gpu_profile.as_dict(), before)

def test_update_driver_preserves_management_mode_and_unknown_fields(self):
for pool_mode in AgentPoolDecoratorMode:
for driver in (None, "Install"):
with self.subTest(pool_mode=pool_mode, driver=driver):
models = AKSAgentPoolModels(self.cmd, self.resource_type, pool_mode)
profile = models.GPUProfile({
"driver": "Install",
"nvidia": {"managementMode": "Managed", "futureSetting": "keep"},
})
pool = models.UnifiedAgentPoolModel(gpu_profile=profile)
decorator = AKSAgentPoolUpdateDecorator(
self.cmd, self.client, {"gpu_driver": driver}, self.resource_type, pool_mode
)
decorator.context.attach_agentpool(pool)
before = copy.deepcopy(profile.as_dict())
result = decorator.update_gpu_profile(pool)
self.assertIs(result.gpu_profile, profile)
self.assertEqual(result.gpu_profile.as_dict(), before)

def test_unrelated_updates_preserve_complete_gpu_profile(self):
changes = (
{},
{"enable_cluster_autoscaler": True, "min_count": 1, "max_count": 3},
{"update_cluster_autoscaler": True, "min_count": 2, "max_count": 5},
{"disable_cluster_autoscaler": True},
{"labels": {"team": "gpu"}},
{"tags": {"team": "gpu"}},
{"gpu_driver": "Install"},
)
for change in changes:
with self.subTest(change=change):
profile = self.models.GPUProfile({
"driver": "Install",
"nvidia": {"managementMode": "Managed", "futureSetting": "keep"},
})
pool = self.models.AgentPool(
name="gpunp", type="VirtualMachineScaleSets", mode="User",
count=2, enable_auto_scaling=not change.get("enable_cluster_autoscaler", False),
min_count=1, max_count=3,
gpu_profile=profile,
)
before = copy.deepcopy(profile.as_dict())
self.client.reset_mock()
self.client.get.return_value = pool
aks_agentpool_update(
self.cmd, self.client, "test-rg", "test-cluster", "gpunp", no_wait=True, **change
)
self.client.begin_create_or_update.assert_called_once()
submitted = self.client.begin_create_or_update.call_args.args[3]
self.assertEqual(submitted.gpu_profile.as_dict(), before)


if __name__ == "__main__":
unittest.main()
Loading