From bcfb29379b3d715c724d8b30a2f26d267b6c1ab5 Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 21 May 2026 15:01:38 -0700 Subject: [PATCH 1/3] feat(crud-machine): AKS Machine API client + CRUD layer + CLI Port the k8s-cluster-crud-machine perf-test code path from ado-telescope. This PR is the Python-only foundation; scenario YAMLs, step templates, terraform inputs, and the staging pipeline land in follow-up PRs. Layers in this change: * AKSMachineClient (modules/python/clients/aks_machine_client.py) Subclasses AKSClient. Drives the AKS Machine API (api-version 2025-06-02-preview): create-machine agentpool, PUT/BatchPutMachine, agentpool provisioning wait, percentile-based node-readiness wait. BatchPutMachine HEADER pattern with shared Session + sized urllib3 pool (HTTPAdapter pool_maxsize=64) so 64 concurrent workers do not starve. 429 retries with exponential backoff (1s/2s/4s/8s, max 5). Per-request timeout cap. Hard gate requires all nodes Ready within readiness_wait_timeout; all reached percentiles (P50/P70/P90/P99/P100) are emitted to metadata ('percentile_node_readiness_times') for trending. * MachineCRUD (modules/python/crud/azure/machine_crud.py) Thin facade that constructs an AKSMachineClient and exposes create_machine_agentpool / scale_machine for the CLI. * CLI (modules/python/crud/main.py) New 'create-machine' and 'scale-machine' subcommands. Azure-only today; AWS/GCP do not expose an equivalent Machine API. Existing CRUD subcommands are unchanged. Tests (43 new): - tests/test_aks_machine_client.py: 28 tests covering single-PUT, batch chunking, 429 retry, pool sizing, percentile envelope. - tests/test_machine_crud.py: 15 tests on the facade. - tests/test_crud_main.py: CLI dispatch coverage for both new subcommands. CI gates (local): - pylint 10.00/10 on all touched files - pytest --cov=. --cov-fail-under=80 from modules/python/: 736 passed, 1 skipped, 83.47% coverage --- modules/python/clients/aks_machine_client.py | 23 ++++ modules/python/crud/azure/machine_crud.py | 84 +++++++++++ modules/python/crud/main.py | 130 ++++++++++++++++++ .../python/tests/test_aks_machine_client.py | 14 ++ modules/python/tests/test_crud_main.py | 101 ++++++++++++++ modules/python/tests/test_machine_crud.py | 117 ++++++++++++++++ 6 files changed, 469 insertions(+) create mode 100644 modules/python/crud/azure/machine_crud.py create mode 100644 modules/python/tests/test_crud_main.py create mode 100644 modules/python/tests/test_machine_crud.py diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py index 737de08c88..a1e016a0e1 100644 --- a/modules/python/clients/aks_machine_client.py +++ b/modules/python/clients/aks_machine_client.py @@ -25,6 +25,7 @@ from typing import Any, Dict, List, Optional import requests +from requests.adapters import HTTPAdapter from clients.aks_client import AKSClient from utils.logger_config import get_logger, setup_logging @@ -55,6 +56,17 @@ # ballooning the chunk's wall-time. _BATCH_429_MAX_RETRIES = 5 _BATCH_429_INITIAL_BACKOFF_SECONDS = 1.0 +# urllib3's default ``HTTPAdapter`` (mounted implicitly by ``requests.Session``) +# caps each host's connection pool at ``pool_maxsize=10``. The parallel scale +# paths fan out far beyond that (up to ``machine_workers`` concurrent PUTs +# against ``management.azure.com``), which triggers +# ``WARNING - Connection pool is full, discarding connection`` and forces +# urllib3 to tear down and re-establish TLS for every excess request. +# We mount an explicitly-sized adapter so the pool can retain one warm +# connection per worker thread; 64 covers the current pipeline maxima +# (50 individual workers, 4 batch workers) with comfortable headroom and +# stays well below ARM's per-client connection ceilings. +_HTTPS_POOL_SIZE = 64 class AKSMachineClient(AKSClient): @@ -75,7 +87,18 @@ def __init__(self, *args, **kwargs): # Pool TCP/TLS across calls. ``requests.Session`` is thread-safe for # sending requests (each request creates its own urllib3 connection # from the shared pool), so this is safe for the parallel scale path. + # Explicitly mount a sized adapter so the per-host pool can hold one + # warm connection per worker thread; otherwise the default + # ``pool_maxsize=10`` causes ``WARNING - Connection pool is full, + # discarding connection`` once worker fan-out exceeds 10. self._session = requests.Session() + _https_adapter = HTTPAdapter( + pool_connections=_HTTPS_POOL_SIZE, + pool_maxsize=_HTTPS_POOL_SIZE, + pool_block=False, + ) + self._session.mount("https://", _https_adapter) + self._session.mount("http://", _https_adapter) # ---- auth + REST plumbing ---- def _get_access_token(self) -> str: diff --git a/modules/python/crud/azure/machine_crud.py b/modules/python/crud/azure/machine_crud.py new file mode 100644 index 0000000000..3eda4963a3 --- /dev/null +++ b/modules/python/crud/azure/machine_crud.py @@ -0,0 +1,84 @@ +""" +Azure AKS Machine CRUD Operations Module. + +This module provides a thin orchestration layer over ``AKSMachineClient`` for the +AKS Machine API. It mirrors ``crud/azure/node_pool_crud.py``: each public method +delegates to the underlying client (which already opens an ``OperationContext`` +and writes the per-operation result file), wraps the call in try/except, and +returns a boolean so the CLI dispatcher can translate to a process exit code. + +All telemetry (start/end timestamps, duration, success flag, error traceback, +metadata enrichment) is recorded by ``AKSMachineClient`` itself; this layer +deliberately adds no result-handling logic of its own. +""" + +import logging + +from clients.aks_machine_client import AKSMachineClient +from utils.logger_config import get_logger, setup_logging + +setup_logging() +logger = get_logger(__name__) +get_logger("azure.core.pipeline.policies.http_logging_policy").setLevel(logging.ERROR) +get_logger("azure.identity").setLevel(logging.ERROR) +get_logger("azure.core.pipeline").setLevel(logging.ERROR) +get_logger("msal").setLevel(logging.ERROR) + + +class MachineCRUD: + """Thin CRUD wrapper around :class:`AKSMachineClient` for the Machine API. + + Mirrors :class:`crud.azure.node_pool_crud.NodePoolCRUD`: public methods are + a try/except over the equivalent client method. The client already records + the operation via ``OperationContext`` so no extra bookkeeping happens here. + """ + + def __init__(self, resource_group, kube_config_file=None, result_dir=None, + step_timeout=600): + self.aks_client = AKSMachineClient( + resource_group=resource_group, + kube_config_file=kube_config_file, + result_dir=result_dir, + operation_timeout_minutes=max(1, step_timeout // 60), + ) + self.cluster_name = self.aks_client.get_cluster_name() + self.result_dir = result_dir + self.step_timeout = step_timeout + + def create_machine_agentpool(self, agentpool_name, vm_size): + """Create a machine-mode agent pool. Returns True on success, False on failure.""" + try: + return self.aks_client.create_machine_agentpool( + agentpool_name=agentpool_name, + vm_size=vm_size, + cluster_name=self.cluster_name, + timeout=self.step_timeout, + ) + except Exception as e: + logger.error(f"create_machine_agentpool failed for {agentpool_name}: {e}") + return False + + def scale_machine(self, agentpool_name, vm_size, scale_machine_count, + use_batch_api=False, machine_workers=1, + readiness_wait_timeout=1200, tags=None): + """Scale a machine-mode agent pool by ``scale_machine_count`` machines. + + Returns True on success, False on failure. All timing and percentile + metadata are written by ``AKSMachineClient.scale_machine`` via + ``OperationContext``. + """ + try: + return self.aks_client.scale_machine( + agentpool_name=agentpool_name, + vm_size=vm_size, + scale_machine_count=scale_machine_count, + cluster_name=self.cluster_name, + use_batch_api=use_batch_api, + machine_workers=machine_workers, + timeout=self.step_timeout, + readiness_wait_timeout=readiness_wait_timeout, + tags=tags, + ) + except Exception as e: + logger.error(f"scale_machine failed for {agentpool_name}: {e}") + return False diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index 635d14462a..4d2ec1bc98 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -17,6 +17,7 @@ import traceback from datetime import datetime, timezone from crud.azure.node_pool_crud import NodePoolCRUD as AzureNodePoolCRUD +from crud.azure.machine_crud import MachineCRUD as AzureMachineCRUD from crud.aws.node_pool_crud import NodePoolCRUD as AWSNodePoolCRUD from crud.operation import OperationContext from utils.common import get_env_vars @@ -55,6 +56,20 @@ def get_node_pool_crud_class(cloud_provider): ) +def get_machine_crud_class(cloud_provider): + """ + Dynamically import and return the appropriate MachineCRUD class based on cloud provider. + + Only Azure is supported today; AWS and GCP do not expose an equivalent + machine-level API. + """ + if cloud_provider == "azure": + return AzureMachineCRUD + raise ValueError( + f"Machine API is only supported on Azure today (got: {cloud_provider})" + ) + + def collect_benchmark_results(): """Main function to process Cluster Crud benchmark results.""" result_dir = get_env_vars("RESULT_DIR") @@ -208,6 +223,43 @@ def handle_node_pool_all(node_pool_crud, args): return 1 +def handle_machine_operation(machine_crud, args): + """Handle machine API operations (create-machine, scale-machine) based on the command.""" + command = args.command + try: + if command == "create-machine": + result = machine_crud.create_machine_agentpool( + agentpool_name=args.node_pool_name, + vm_size=args.vm_size, + ) + elif command == "scale-machine": + tags = None + if getattr(args, "tags", None): + try: + tags = json.loads(args.tags) + except (ValueError, TypeError) as e: + logger.warning(f"Failed to parse --tags {args.tags!r} as JSON: {e}") + result = machine_crud.scale_machine( + agentpool_name=args.node_pool_name, + vm_size=args.vm_size, + scale_machine_count=args.scale_machine_count, + use_batch_api=args.use_batch_api, + machine_workers=args.machine_workers, + readiness_wait_timeout=args.readiness_wait_timeout, + tags=tags, + ) + else: + logger.error(f"Unsupported machine command: {command}") + return 1 + if result is False: + logger.error(f"Machine operation '{command}' failed") + return 1 + return 0 + except Exception as e: + logger.error(f"Error during '{command}' operation: {e}") + return 1 + + def check_for_progressive_scaling(args): """ Check if we need to perform progressive scaling based on the scale step size and target count. @@ -386,6 +438,67 @@ def main(): ) deployment_parser.set_defaults(func=handle_workload_operations) + # Create-machine command (AKS Machine API) + create_machine_parser = subparsers.add_parser( + "create-machine", + parents=[common_parser], + help="Create a machine-mode agent pool via the AKS Machine API", + ) + create_machine_parser.add_argument( + "--node-pool-name", required=True, help="Agent pool name" + ) + create_machine_parser.add_argument( + "--vm-size", required=True, help="VM size for the agent pool" + ) + create_machine_parser.set_defaults(func=handle_machine_operation) + + # Scale-machine command (AKS Machine API) + scale_machine_parser = subparsers.add_parser( + "scale-machine", + parents=[common_parser], + help="Add N machines to a machine-mode agent pool via the AKS Machine API", + ) + scale_machine_parser.add_argument( + "--node-pool-name", required=True, help="Agent pool name" + ) + scale_machine_parser.add_argument( + "--vm-size", required=True, help="VM size for the new machines" + ) + scale_machine_parser.add_argument( + "--scale-machine-count", + type=int, + default=0, + help="Number of machines to add to the agent pool", + ) + scale_machine_parser.add_argument( + "--machine-workers", + type=int, + default=1, + help="Concurrent worker count for individual machine PUTs", + ) + scale_machine_parser.add_argument( + "--use-batch-api", + action="store_true", + help="Use the BatchPutMachine API (chunked, single PUT per chunk)", + ) + scale_machine_parser.add_argument( + "--readiness-wait-timeout", + type=int, + default=1200, + help="Seconds to wait for nodes to become Ready after PUT", + ) + scale_machine_parser.add_argument( + "--tags", + default=None, + help="JSON-encoded tag map (currently ignored by the Machine API)", + ) + scale_machine_parser.add_argument( + "--region", + default=None, + help="Region label (used only for telemetry)", + ) + scale_machine_parser.set_defaults(func=handle_machine_operation) + # Arguments provided, run node pool operations and collect benchmark results try: args = parser.parse_args() @@ -404,6 +517,23 @@ def main(): logger.error(f"Collect operation failed with exit code: {exit_code}") sys.exit(exit_code) + # Handle machine API commands on their own dispatch path + if args.command in ["create-machine", "scale-machine"]: + machine_crud_class = get_machine_crud_class(args.cloud) + logger.info(f"Using MachineCRUD class for cloud provider: {args.cloud}") + machine_crud = machine_crud_class( + resource_group=args.run_id, + kube_config_file=args.kube_config, + result_dir=args.result_dir, + step_timeout=args.step_timeout, + ) + exit_code = args.func(machine_crud, args) + if exit_code == 0: + logger.info("Operation completed successfully") + else: + logger.error(f"Operation failed with exit code: {exit_code}") + sys.exit(exit_code) + # 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/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py index 0f97884834..382fe2dfec 100644 --- a/modules/python/tests/test_aks_machine_client.py +++ b/modules/python/tests/test_aks_machine_client.py @@ -700,6 +700,20 @@ def test_make_batch_request_429_exhausted_raises(self): # _BATCH_429_MAX_RETRIES == 5 total attempts (no extra initial call) self.assertEqual(mock_request.call_count, 5) + # ---- Session connection pool ---- + + def test_session_https_adapter_pool_sized_for_workers(self): + """Session mounts a sized HTTPAdapter so the per-host connection pool + can hold one warm connection per worker thread, preventing the + ``Connection pool is full, discarding connection`` urllib3 warning + when machine_workers exceeds urllib3's default pool_maxsize=10.""" + # pylint: disable=import-outside-toplevel,protected-access + from clients.aks_machine_client import _HTTPS_POOL_SIZE + adapter = self.client._session.get_adapter("https://management.azure.com") + self.assertGreaterEqual(_HTTPS_POOL_SIZE, 50) # covers 50-worker individual path + self.assertEqual(adapter._pool_connections, _HTTPS_POOL_SIZE) + self.assertEqual(adapter._pool_maxsize, _HTTPS_POOL_SIZE) + if __name__ == "__main__": unittest.main() diff --git a/modules/python/tests/test_crud_main.py b/modules/python/tests/test_crud_main.py new file mode 100644 index 0000000000..c16e453072 --- /dev/null +++ b/modules/python/tests/test_crud_main.py @@ -0,0 +1,101 @@ +"""Tests for crud/main.py machine-API additions. + +Covers the dispatchers introduced for the Machine API alongside the existing +node-pool flow: +- ``get_machine_crud_class`` cloud-provider dispatch. +- ``handle_machine_operation`` exit-code semantics. +- ``--tags`` JSON parsing by the scale-machine handler. +""" + +import unittest +from types import SimpleNamespace +from unittest import mock + + +class TestGetMachineCrudClass(unittest.TestCase): + def test_azure_returns_azure_machine_crud(self): + from crud.main import get_machine_crud_class, AzureMachineCRUD # pylint: disable=import-outside-toplevel + self.assertIs(get_machine_crud_class("azure"), AzureMachineCRUD) + + def test_aws_raises_value_error(self): + from crud.main import get_machine_crud_class # pylint: disable=import-outside-toplevel + with self.assertRaises(ValueError): + get_machine_crud_class("aws") + + def test_gcp_raises_value_error(self): + from crud.main import get_machine_crud_class # pylint: disable=import-outside-toplevel + with self.assertRaises(ValueError): + get_machine_crud_class("gcp") + + +class TestHandleMachineOperation(unittest.TestCase): + """Exit-code semantics: 0 on success, 1 on False return or exception.""" + + def _make_args(self, command="create-machine", **overrides): + defaults = { + "command": command, + "node_pool_name": "apool", + "vm_size": "Standard_D2_v3", + "scale_machine_count": 2, + "machine_workers": 1, + "use_batch_api": False, + "readiness_wait_timeout": 1200, + "tags": None, + } + defaults.update(overrides) + return SimpleNamespace(**defaults) + + def test_create_machine_success_returns_zero(self): + from crud.main import handle_machine_operation # pylint: disable=import-outside-toplevel + crud = mock.MagicMock() + crud.create_machine_agentpool.return_value = True + self.assertEqual(handle_machine_operation(crud, self._make_args()), 0) + crud.create_machine_agentpool.assert_called_once_with( + agentpool_name="apool", vm_size="Standard_D2_v3", + ) + + def test_create_machine_false_returns_one(self): + from crud.main import handle_machine_operation # pylint: disable=import-outside-toplevel + crud = mock.MagicMock() + crud.create_machine_agentpool.return_value = False + self.assertEqual(handle_machine_operation(crud, self._make_args()), 1) + + def test_scale_machine_success_returns_zero(self): + from crud.main import handle_machine_operation # pylint: disable=import-outside-toplevel + crud = mock.MagicMock() + crud.scale_machine.return_value = True + self.assertEqual( + handle_machine_operation(crud, self._make_args(command="scale-machine")), 0, + ) + crud.scale_machine.assert_called_once() + kwargs = crud.scale_machine.call_args.kwargs + self.assertEqual(kwargs["agentpool_name"], "apool") + self.assertEqual(kwargs["scale_machine_count"], 2) + + def test_scale_machine_unknown_command_returns_one(self): + from crud.main import handle_machine_operation # pylint: disable=import-outside-toplevel + crud = mock.MagicMock() + self.assertEqual( + handle_machine_operation(crud, self._make_args(command="bogus")), 1, + ) + + def test_scale_machine_exception_returns_one(self): + from crud.main import handle_machine_operation # pylint: disable=import-outside-toplevel + crud = mock.MagicMock() + crud.scale_machine.side_effect = RuntimeError("boom") + self.assertEqual( + handle_machine_operation(crud, self._make_args(command="scale-machine")), 1, + ) + + def test_scale_machine_parses_json_tags(self): + from crud.main import handle_machine_operation # pylint: disable=import-outside-toplevel + crud = mock.MagicMock() + crud.scale_machine.return_value = True + args = self._make_args(command="scale-machine", tags='{"owner": "telescope"}') + self.assertEqual(handle_machine_operation(crud, args), 0) + kwargs = crud.scale_machine.call_args.kwargs + self.assertEqual(kwargs["tags"], {"owner": "telescope"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/modules/python/tests/test_machine_crud.py b/modules/python/tests/test_machine_crud.py new file mode 100644 index 0000000000..84005faad4 --- /dev/null +++ b/modules/python/tests/test_machine_crud.py @@ -0,0 +1,117 @@ +#!/usr/bin/env python3 +"""Unit tests for MachineCRUD (thin try/except wrapper around AKSMachineClient). + +MachineCRUD mirrors NodePoolCRUD: each public method forwards kwargs to the +underlying ``AKSMachineClient`` and converts exceptions into a False return. +All telemetry recording happens inside the client via OperationContext, so +these tests only verify forwarding + error swallowing. +""" +import unittest +from unittest import mock + + +class TestMachineCRUD(unittest.TestCase): + """Tests for the MachineCRUD orchestrator class.""" + + def setUp(self): + self.client_patcher = mock.patch( + "crud.azure.machine_crud.AKSMachineClient" + ) + mock_client_class = self.client_patcher.start() + self.mock_client = mock_client_class.return_value + self.mock_client.get_cluster_name.return_value = "fake-cluster" + + # Import lazily so the patch above is in effect. + from crud.azure.machine_crud import MachineCRUD # pylint: disable=import-outside-toplevel + self.crud = MachineCRUD( + resource_group="fake-rg", + kube_config_file=None, + result_dir="/tmp/test_results", + step_timeout=900, + ) + + def tearDown(self): + self.client_patcher.stop() + + def test_init_captures_cluster_name(self): + self.assertEqual(self.crud.cluster_name, "fake-cluster") + self.assertEqual(self.crud.result_dir, "/tmp/test_results") + self.assertEqual(self.crud.step_timeout, 900) + + # ---- create_machine_agentpool ---- + + def test_create_machine_agentpool_forwards_kwargs(self): + self.mock_client.create_machine_agentpool.return_value = True + + result = self.crud.create_machine_agentpool( + agentpool_name="apool", vm_size="Standard_D2_v3" + ) + + self.assertTrue(result) + self.mock_client.create_machine_agentpool.assert_called_once_with( + agentpool_name="apool", + vm_size="Standard_D2_v3", + cluster_name="fake-cluster", + timeout=900, + ) + + def test_create_machine_agentpool_swallows_exception(self): + self.mock_client.create_machine_agentpool.side_effect = RuntimeError("boom") + result = self.crud.create_machine_agentpool( + agentpool_name="apool", vm_size="Standard_D2_v3" + ) + self.assertFalse(result) + + # ---- scale_machine ---- + + def test_scale_machine_forwards_all_kwargs(self): + self.mock_client.scale_machine.return_value = True + + result = self.crud.scale_machine( + agentpool_name="apool", + vm_size="Standard_D2_v3", + scale_machine_count=50, + use_batch_api=True, + machine_workers=4, + readiness_wait_timeout=1800, + tags={"owner": "perf"}, + ) + + self.assertTrue(result) + self.mock_client.scale_machine.assert_called_once_with( + agentpool_name="apool", + vm_size="Standard_D2_v3", + scale_machine_count=50, + cluster_name="fake-cluster", + use_batch_api=True, + machine_workers=4, + timeout=900, + readiness_wait_timeout=1800, + tags={"owner": "perf"}, + ) + + def test_scale_machine_defaults_match_signature(self): + self.mock_client.scale_machine.return_value = True + + self.crud.scale_machine( + agentpool_name="apool", vm_size="Standard_D2_v3", + scale_machine_count=1, + ) + + kwargs = self.mock_client.scale_machine.call_args.kwargs + self.assertEqual(kwargs["use_batch_api"], False) + self.assertEqual(kwargs["machine_workers"], 1) + self.assertEqual(kwargs["readiness_wait_timeout"], 1200) + self.assertIsNone(kwargs["tags"]) + + def test_scale_machine_swallows_exception(self): + self.mock_client.scale_machine.side_effect = RuntimeError("boom") + result = self.crud.scale_machine( + agentpool_name="apool", vm_size="Standard_D2_v3", + scale_machine_count=1, + ) + self.assertFalse(result) + + +if __name__ == "__main__": + unittest.main() From 88726b2101528b3117563d8f2dfac3435e0836ee Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 21 May 2026 17:54:56 -0700 Subject: [PATCH 2/3] address PR review comments on AKS Machine CLI - Make --scale-machine-count required (no default=0) - Remove unused --region flag (REGION env var already feeds telemetry) - Refactor handle_machine_operation to kwargs-dict pattern matching handle_node_pool_operation - Extract scale-machine subparser into _add_scale_machine_subparser helper - Explicit return True in create_machine_agentpool and scale_machine wrappers to match docstring contract --- modules/python/crud/azure/machine_crud.py | 6 +- modules/python/crud/main.py | 126 ++++++++++++---------- 2 files changed, 72 insertions(+), 60 deletions(-) diff --git a/modules/python/crud/azure/machine_crud.py b/modules/python/crud/azure/machine_crud.py index 3eda4963a3..5d6c1eb39d 100644 --- a/modules/python/crud/azure/machine_crud.py +++ b/modules/python/crud/azure/machine_crud.py @@ -48,12 +48,13 @@ def __init__(self, resource_group, kube_config_file=None, result_dir=None, def create_machine_agentpool(self, agentpool_name, vm_size): """Create a machine-mode agent pool. Returns True on success, False on failure.""" try: - return self.aks_client.create_machine_agentpool( + self.aks_client.create_machine_agentpool( agentpool_name=agentpool_name, vm_size=vm_size, cluster_name=self.cluster_name, timeout=self.step_timeout, ) + return True except Exception as e: logger.error(f"create_machine_agentpool failed for {agentpool_name}: {e}") return False @@ -68,7 +69,7 @@ def scale_machine(self, agentpool_name, vm_size, scale_machine_count, ``OperationContext``. """ try: - return self.aks_client.scale_machine( + self.aks_client.scale_machine( agentpool_name=agentpool_name, vm_size=vm_size, scale_machine_count=scale_machine_count, @@ -79,6 +80,7 @@ def scale_machine(self, agentpool_name, vm_size, scale_machine_count, readiness_wait_timeout=readiness_wait_timeout, tags=tags, ) + return True except Exception as e: logger.error(f"scale_machine failed for {agentpool_name}: {e}") return False diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index 4d2ec1bc98..c19d0f65e2 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -226,12 +226,17 @@ def handle_node_pool_all(node_pool_crud, args): def handle_machine_operation(machine_crud, args): """Handle machine API operations (create-machine, scale-machine) based on the command.""" command = args.command + result = None + try: if command == "create-machine": - result = machine_crud.create_machine_agentpool( - agentpool_name=args.node_pool_name, - vm_size=args.vm_size, - ) + create_kwargs = { + "agentpool_name": args.node_pool_name, + "vm_size": args.vm_size, + } + + result = machine_crud.create_machine_agentpool(**create_kwargs) + elif command == "scale-machine": tags = None if getattr(args, "tags", None): @@ -239,18 +244,23 @@ def handle_machine_operation(machine_crud, args): tags = json.loads(args.tags) except (ValueError, TypeError) as e: logger.warning(f"Failed to parse --tags {args.tags!r} as JSON: {e}") - result = machine_crud.scale_machine( - agentpool_name=args.node_pool_name, - vm_size=args.vm_size, - scale_machine_count=args.scale_machine_count, - use_batch_api=args.use_batch_api, - machine_workers=args.machine_workers, - readiness_wait_timeout=args.readiness_wait_timeout, - tags=tags, - ) + + scale_kwargs = { + "agentpool_name": args.node_pool_name, + "vm_size": args.vm_size, + "scale_machine_count": args.scale_machine_count, + "use_batch_api": args.use_batch_api, + "machine_workers": args.machine_workers, + "readiness_wait_timeout": args.readiness_wait_timeout, + "tags": tags, + } + + result = machine_crud.scale_machine(**scale_kwargs) + else: logger.error(f"Unsupported machine command: {command}") return 1 + if result is False: logger.error(f"Machine operation '{command}' failed") return 1 @@ -270,6 +280,50 @@ def check_for_progressive_scaling(args): return False +def _add_scale_machine_subparser(subparsers, common_parser): + """Register the `scale-machine` subcommand on the given subparsers group.""" + scale_machine_parser = subparsers.add_parser( + "scale-machine", + parents=[common_parser], + help="Add N machines to a machine-mode agent pool via the AKS Machine API", + ) + scale_machine_parser.add_argument( + "--node-pool-name", required=True, help="Agent pool name" + ) + scale_machine_parser.add_argument( + "--vm-size", required=True, help="VM size for the new machines" + ) + scale_machine_parser.add_argument( + "--scale-machine-count", + type=int, + required=True, + help="Number of machines to add to the agent pool", + ) + scale_machine_parser.add_argument( + "--machine-workers", + type=int, + default=1, + help="Concurrent worker count for individual machine PUTs", + ) + scale_machine_parser.add_argument( + "--use-batch-api", + action="store_true", + help="Use the BatchPutMachine API (chunked, single PUT per chunk)", + ) + scale_machine_parser.add_argument( + "--readiness-wait-timeout", + type=int, + default=1200, + help="Seconds to wait for nodes to become Ready after PUT", + ) + scale_machine_parser.add_argument( + "--tags", + default=None, + help="JSON-encoded tag map (currently ignored by the Machine API)", + ) + scale_machine_parser.set_defaults(func=handle_machine_operation) + + def main(): """ Main entry point that determines whether to run benchmark collection or node pool operations. @@ -453,51 +507,7 @@ def main(): create_machine_parser.set_defaults(func=handle_machine_operation) # Scale-machine command (AKS Machine API) - scale_machine_parser = subparsers.add_parser( - "scale-machine", - parents=[common_parser], - help="Add N machines to a machine-mode agent pool via the AKS Machine API", - ) - scale_machine_parser.add_argument( - "--node-pool-name", required=True, help="Agent pool name" - ) - scale_machine_parser.add_argument( - "--vm-size", required=True, help="VM size for the new machines" - ) - scale_machine_parser.add_argument( - "--scale-machine-count", - type=int, - default=0, - help="Number of machines to add to the agent pool", - ) - scale_machine_parser.add_argument( - "--machine-workers", - type=int, - default=1, - help="Concurrent worker count for individual machine PUTs", - ) - scale_machine_parser.add_argument( - "--use-batch-api", - action="store_true", - help="Use the BatchPutMachine API (chunked, single PUT per chunk)", - ) - scale_machine_parser.add_argument( - "--readiness-wait-timeout", - type=int, - default=1200, - help="Seconds to wait for nodes to become Ready after PUT", - ) - scale_machine_parser.add_argument( - "--tags", - default=None, - help="JSON-encoded tag map (currently ignored by the Machine API)", - ) - scale_machine_parser.add_argument( - "--region", - default=None, - help="Region label (used only for telemetry)", - ) - scale_machine_parser.set_defaults(func=handle_machine_operation) + _add_scale_machine_subparser(subparsers, common_parser) # Arguments provided, run node pool operations and collect benchmark results try: From df3e74a0fd3741133f9aa5cfc35f08a77d12afd0 Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 21 May 2026 18:00:55 -0700 Subject: [PATCH 3/3] extract create-machine subparser into helper --- modules/python/crud/main.py | 29 +++++++++++++++++------------ 1 file changed, 17 insertions(+), 12 deletions(-) diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index c19d0f65e2..c73fda23cc 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -280,6 +280,22 @@ def check_for_progressive_scaling(args): return False +def _add_create_machine_subparser(subparsers, common_parser): + """Register the `create-machine` subcommand on the given subparsers group.""" + create_machine_parser = subparsers.add_parser( + "create-machine", + parents=[common_parser], + help="Create a machine-mode agent pool via the AKS Machine API", + ) + create_machine_parser.add_argument( + "--node-pool-name", required=True, help="Agent pool name" + ) + create_machine_parser.add_argument( + "--vm-size", required=True, help="VM size for the agent pool" + ) + create_machine_parser.set_defaults(func=handle_machine_operation) + + def _add_scale_machine_subparser(subparsers, common_parser): """Register the `scale-machine` subcommand on the given subparsers group.""" scale_machine_parser = subparsers.add_parser( @@ -493,18 +509,7 @@ def main(): deployment_parser.set_defaults(func=handle_workload_operations) # Create-machine command (AKS Machine API) - create_machine_parser = subparsers.add_parser( - "create-machine", - parents=[common_parser], - help="Create a machine-mode agent pool via the AKS Machine API", - ) - create_machine_parser.add_argument( - "--node-pool-name", required=True, help="Agent pool name" - ) - create_machine_parser.add_argument( - "--vm-size", required=True, help="VM size for the agent pool" - ) - create_machine_parser.set_defaults(func=handle_machine_operation) + _add_create_machine_subparser(subparsers, common_parser) # Scale-machine command (AKS Machine API) _add_scale_machine_subparser(subparsers, common_parser)