diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py index a1e016a0e1..8769ab0b2e 100644 --- a/modules/python/clients/aks_machine_client.py +++ b/modules/python/clients/aks_machine_client.py @@ -2,8 +2,9 @@ Subclasses ``AKSClient`` to inherit auth, ContainerServiceClient, KubernetesClient, ``get_cluster_name``, ``get_cluster_data``, and the existing -node-pool CRUD methods. Adds raw REST methods for the Machine API which is not -yet exposed in the Azure SDK. +node-pool CRUD methods. Uses Azure CLI for Machine API operations that have a +first-class CLI surface and keeps direct REST only for the BatchPutMachine path, +which is not exposed by Azure CLI. Public methods (``create_machine_agentpool``, ``scale_machine``) wrap their work in ``OperationContext``: the context is opened inside the client method, @@ -11,13 +12,14 @@ None, failures are logged and re-raised so ``OperationContext`` records them. ``MachineCRUD`` therefore stays a thin try/except wrapper. -This revision adds the non-batch scale path. The batch dispatch -(``use_batch_api=True``) still raises ``NotImplementedError`` and will land in a -follow-up PR. +The non-batch scale path shells out to ``az aks machine add`` per machine. +The batch dispatch (``use_batch_api=True``) still uses the private +``BatchPutMachine`` header contract directly. """ import json import logging import math +import subprocess import threading import time from concurrent.futures import ThreadPoolExecutor, as_completed @@ -56,6 +58,7 @@ # ballooning the chunk's wall-time. _BATCH_429_MAX_RETRIES = 5 _BATCH_429_INITIAL_BACKOFF_SECONDS = 1.0 +_BATCH_MAX_MACHINES_PER_REQUEST = 50 # 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 @@ -64,7 +67,7 @@ # 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 +# (50 individual workers, 10 batch workers) with comfortable headroom and # stays well below ARM's per-client connection ceilings. _HTTPS_POOL_SIZE = 64 @@ -137,6 +140,33 @@ def make_request( method, url, headers=headers, json=data, timeout=timeout ) + def _run_az_cli_command(self, command: List[str], timeout: int) -> None: + """Run an Azure CLI command and raise a compact RuntimeError on failure.""" + logger.info("Running Azure CLI command: %s", " ".join(command)) + try: + completed = subprocess.run( + command, + check=False, + capture_output=True, + text=True, + timeout=timeout, + ) + except FileNotFoundError as exc: + raise RuntimeError("Azure CLI executable 'az' was not found") from exc + except subprocess.TimeoutExpired as exc: + raise RuntimeError( + f"Azure CLI command timed out after {timeout}s: {' '.join(command)}" + ) from exc + + if completed.returncode != 0: + stdout = (completed.stdout or "").strip() + stderr = (completed.stderr or "").strip() + detail = stderr or stdout or "" + raise RuntimeError( + f"Azure CLI command failed with exit code {completed.returncode}: " + f"{' '.join(command)}; output={detail[:1000]}" + ) + # ---- Machine API: agent pool provisioning ---- def create_machine_agentpool( self, @@ -145,7 +175,7 @@ def create_machine_agentpool( cluster_name: Optional[str] = None, timeout: int = 300, ) -> None: - """Convert an existing agentpool to Machines mode via PUT. + """Create a machine-mode agentpool via Azure CLI. Opens an ``OperationContext`` here, enriches metadata, returns on success, re-raises on failure (so the context records ``success=False`` @@ -153,19 +183,17 @@ def create_machine_agentpool( Args: agentpool_name: Target agentpool name. - vm_size: VM SKU recorded in operation metadata. The PUT body itself - only sets ``mode: Machines``; the SKU is informational here so - downstream Kusto rows can attribute the agentpool to a SKU. + vm_size: VM SKU for the machine-mode agentpool and operation metadata. cluster_name: Parent AKS cluster name. Defaults to ``self.get_cluster_name()`` (matches ``create_node_pool``). timeout: Total wall-clock budget (seconds) for this operation. Used as the polling deadline for ``_wait_for_agentpool_provisioning``. The per-request HTTP timeout is capped at - ``_PER_REQUEST_TIMEOUT_CAP`` so a single slow PUT cannot consume - the whole budget before polling starts. + ``_PER_REQUEST_TIMEOUT_CAP`` so a single slow CLI process cannot + consume the whole budget before polling starts. Raises: - RuntimeError: PUT non-2xx, ARM-reported Failed state, or timeout. + RuntimeError: CLI failure, ARM-reported Failed state, or timeout. """ cluster_name = cluster_name or self.get_cluster_name() metadata = { @@ -177,24 +205,28 @@ def create_machine_agentpool( "create_machine_agentpool", "azure", metadata, result_dir=self.result_dir ) as op: try: - sub = self.subscription_id url = ( - f"{_ARM_BASE}/subscriptions/{sub}/resourceGroups/{self.resource_group}" + f"{_ARM_BASE}/subscriptions/{self.subscription_id}/resourceGroups/" + f"{self.resource_group}" f"/providers/Microsoft.ContainerService/managedClusters/{cluster_name}" f"/agentPools/{agentpool_name}?api-version={_AGENTPOOL_API_VERSION}" ) - body = {"properties": {"mode": "Machines"}} - # Cap the PUT timeout so the bulk of ``timeout`` is preserved - # for the polling loop below. - put_timeout = min(timeout, _PER_REQUEST_TIMEOUT_CAP) - resp = self.make_request("PUT", url, data=body, timeout=put_timeout) - # ARM async PUT acceptance returns 200/201/202; the agentpool - # provisioning poll below is the real completion gate. - if resp.status_code not in (200, 201, 202): - raise RuntimeError( - f"create_machine_agentpool PUT failed: " - f"{resp.status_code} {resp.text[:500]}" - ) + command = [ + "az", "aks", "nodepool", "add", + "--resource-group", self.resource_group, + "--cluster-name", cluster_name, + "--name", agentpool_name, + "--mode", "Machines", + "--node-vm-size", vm_size, + "--node-count", "0", + "--subscription", self.subscription_id, + "--no-wait", + "--only-show-errors", + ] + self._run_az_cli_command( + command, + timeout=min(timeout, _PER_REQUEST_TIMEOUT_CAP), + ) if not self._wait_for_agentpool_provisioning(url, timeout): raise RuntimeError( f"agentpool {agentpool_name} did not reach Succeeded within {timeout}s" @@ -406,16 +438,17 @@ def scale_machine( Flow: 1. Snapshot the current Ready+labeled node count in the agentpool (``baseline_count``) so the readiness watcher counts only NEW nodes. - 2. Submit machine PUTs -- individually by default, or sharded into - ``machine_workers`` chunks where each chunk is sent as a single - ``BatchPutMachine``-headered PUT when ``use_batch_api=True`` (per- - machine ARM polling is intentionally NOT performed in either path). + 2. Submit machine creates -- individually via ``az aks machine add`` by + default, or sharded into ``machine_workers`` chunks where each + chunk is sent as a single ``BatchPutMachine``-headered PUT when + ``use_batch_api=True`` (per-machine ARM polling is intentionally + NOT performed in either path). 3. Wait ONCE on the agentpool-level provisioningState. 4. Wait for nodes labeled ``agentpool=`` to surpass ``baseline_count`` by enough to satisfy P50/P70/P90/P99/P100 targets. - ``tags`` is currently unused (Machine API rejects top-level tags on the - machine PUT body; machines inherit tags from the parent agentpool). + ``tags`` is currently unused (machines inherit tags from the parent + agentpool). See ``_create_batch_machines`` for the batch chunking contract and the ``BatchPutMachine`` header schema. @@ -451,7 +484,7 @@ def scale_machine( "scale_machine", "azure", metadata, result_dir=self.result_dir ) as op: try: - # Snapshot baseline BEFORE any PUTs so the readiness watcher + # Snapshot baseline BEFORE any creates so the readiness watcher # counts only NEW nodes. kc = self.k8s_client baseline_count = 0 @@ -480,7 +513,7 @@ def scale_machine( else: successful = self._scale_machine_individually(request, names) op.add_metadata("command_execution_time", time.time() - command_t0) - op.add_metadata("successful_machines", successful) + op.add_metadata("successful_machines", len(successful)) # Fail fast on partial landing BEFORE waiting on the agentpool # or readiness against a reduced count -- otherwise the recorded @@ -552,14 +585,14 @@ def _get_machine_name_prefix(scale_machine_count: int) -> str: def _scale_machine_individually( self, request: SimpleNamespace, names: List[str], ) -> List[str]: - """Submit per-machine PUTs concurrently via ThreadPoolExecutor. + """Submit per-machine Azure CLI commands concurrently via ThreadPoolExecutor. - Each worker calls ``_create_single_machine(name, request)`` which PUTs - the machine and returns True on any 2xx response. Per-machine - provisioningState is intentionally NOT polled (see + Each worker calls ``_create_single_machine(name, request)`` which runs + ``az aks machine add --no-wait`` and returns True on a zero exit code. + Per-machine provisioningState is intentionally NOT polled (see ``_create_single_machine`` for why); the agentpool-level poll in ``scale_machine`` is the real completion signal. Returns the list of - names that reported True. Per-machine exceptions are logged and + names that reported True. Per-machine CLI failures are logged and treated as failure (name omitted from result). """ successful: List[str] = [] @@ -577,11 +610,10 @@ def _scale_machine_individually( return successful def _create_single_machine(self, name: str, request: SimpleNamespace) -> bool: - """PUT a single Machine resource. Returns True on any 2xx response. + """Create a single Machine resource via Azure CLI. - Body is ``{"properties": {"hardware": {"vmSize": ...}}}``. Tags are inherited - from the parent agentpool; the machine PUT body in api-version 2025-06-02-preview - does not accept a top-level ``tags`` field (rejected with UnmarshalError). + Tags are inherited from the parent agentpool; the Machine API rejected + top-level tags in earlier direct REST testing. Intentionally does NOT poll the per-machine ARM provisioningState. The AKS RP reports per-machine ``provisioningState='Succeeded'`` essentially @@ -589,21 +621,28 @@ def _create_single_machine(self, name: str, request: SimpleNamespace) -> bool: VM is created. Polling here therefore returns spuriously early and only adds N round-trips of latency without surfacing useful signal. The canonical completion signal is the agentpool-level provisioningState, - which ``scale_machine`` polls once after all PUTs return. + which ``scale_machine`` polls once after all create requests return. - Never raises on HTTP errors; logs and returns False on non-2xx responses. + Never raises to the caller on CLI errors; logs and returns False. """ - sub = self.subscription_id - url = ( - f"{_ARM_BASE}/subscriptions/{sub}/resourceGroups/{request.resource_group}" - f"/providers/Microsoft.ContainerService/managedClusters/{request.cluster_name}" - f"/agentPools/{request.agentpool_name}/machines/{name}" - f"?api-version={_MACHINE_API_VERSION}" - ) - body: Dict[str, Any] = {"properties": {"hardware": {"vmSize": request.vm_size}}} - resp = self.make_request("PUT", url, data=body, timeout=request.timeout) - if resp.status_code not in (200, 201, 202): - logger.error(f"PUT machine {name} -> {resp.status_code} {resp.text[:500]}") + command = [ + "az", "aks", "machine", "add", + "--resource-group", request.resource_group, + "--cluster-name", request.cluster_name, + "--nodepool-name", request.agentpool_name, + "--machine-name", name, + "--vm-size", request.vm_size, + "--subscription", self.subscription_id, + "--no-wait", + "--only-show-errors", + ] + try: + self._run_az_cli_command( + command, + timeout=min(request.timeout, _PER_REQUEST_TIMEOUT_CAP), + ) + except RuntimeError as exc: + logger.error("az aks machine add failed for %s: %s", name, exc) return False return True @@ -615,14 +654,14 @@ def _scale_machine_batch( ) -> List[str]: """Dispatch ``names`` across ``machine_workers`` worker slices via the Batch API. - Each worker submits exactly one ``BatchPutMachine``-headered PUT carrying a - contiguous slice of ``names``. Slices are computed by arithmetic from the - ``worker_id``. + Each worker submits exactly one ``BatchPutMachine``-headered PUT carrying + a contiguous slice of ``names``. Slices are computed by arithmetic from + the ``worker_id``. - ``scale_machine_count`` MUST be an exact multiple of ``machine_workers``; - ``ValueError`` is raised otherwise so the failure surfaces at the - ``MachineCRUD`` boundary instead of producing a short final chunk that - would skew per-chunk latency dashboards. + ``scale_machine_count`` MUST be an exact multiple of ``machine_workers`` + and the resulting per-worker batch size MUST be no larger than + ``_BATCH_MAX_MACHINES_PER_REQUEST``. ``ValueError`` is raised otherwise + so the failure surfaces before any partial batch submission reaches ARM. Per-worker exceptions are caught and logged; the worker's slice is excluded from the returned ``successful`` list. The input ``request`` @@ -639,6 +678,12 @@ def _scale_machine_batch( f"got remainder {n % workers}" ) per_worker = n // workers + if per_worker > _BATCH_MAX_MACHINES_PER_REQUEST: + raise ValueError( + f"calculated batch size ({per_worker}) exceeds " + f"BatchPutMachine limit ({_BATCH_MAX_MACHINES_PER_REQUEST}); " + f"increase machine_workers for scale_machine_count ({n})" + ) successful: List[str] = [] def run_worker(worker_id: int) -> List[str]: @@ -694,6 +739,12 @@ def _create_batch_machines( """ if not chunk: return [] + if len(chunk) > _BATCH_MAX_MACHINES_PER_REQUEST: + raise ValueError( + f"BatchPutMachine supports at most " + f"{_BATCH_MAX_MACHINES_PER_REQUEST} machines per request; " + f"got {len(chunk)}" + ) sub = self.subscription_id first_machine_name = chunk[0] url = ( diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py index 382fe2dfec..53cd0eeb01 100644 --- a/modules/python/tests/test_aks_machine_client.py +++ b/modules/python/tests/test_aks_machine_client.py @@ -7,8 +7,8 @@ the right keys - failure path raises (so the OperationContext records ``success=False``) -This revision adds tests for both scale paths (non-batch individual PUTs and -the BatchPutMachine-headered chunked path) plus the batch-path helpers +This revision adds tests for both scale paths (non-batch individual CLI calls +and the BatchPutMachine-headered chunked path) plus the batch-path helpers ``_scale_machine_batch``, ``_create_batch_machines``, and ``_make_batch_request``. """ @@ -85,34 +85,34 @@ def tearDown(self): @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", return_value=True) - @mock.patch.object(AKSMachineClient, "make_request") - def test_create_machine_agentpool_success(self, mock_make_request, _mock_wait): - """PUT 200 + Succeeded poll -> returns; metadata enriched.""" - mock_resp = mock.MagicMock() - mock_resp.status_code = 200 - mock_make_request.return_value = mock_resp + @mock.patch.object(AKSMachineClient, "_run_az_cli_command") + def test_create_machine_agentpool_success(self, mock_run_cli, _mock_wait): + """CLI command accepted + Succeeded poll -> returns; metadata enriched.""" self.client.create_machine_agentpool( agentpool_name="apool", vm_size="Standard_D2_v3" ) - mock_make_request.assert_called_once() - call_args = mock_make_request.call_args - self.assertEqual(call_args.args[0], "PUT") - self.assertEqual(call_args.kwargs["data"], {"properties": {"mode": "Machines"}}) + mock_run_cli.assert_called_once() + command = mock_run_cli.call_args.args[0] + self.assertEqual(command[:4], ["az", "aks", "nodepool", "add"]) + self.assertIn("--mode", command) + self.assertIn("Machines", command) + self.assertIn("--node-vm-size", command) + self.assertIn("Standard_D2_v3", command) + self.assertIn("--node-count", command) + self.assertIn("0", command) + self.assertIn("--no-wait", command) metadata_keys = { call.args[0] for call in self.mock_operation.add_metadata.call_args_list } self.assertIn("agentpool_info", metadata_keys) self.assertIn("cluster_info", metadata_keys) - @mock.patch.object(AKSMachineClient, "make_request") - def test_create_machine_agentpool_put_failure_raises(self, mock_make_request): - """PUT non-2xx -> RuntimeError propagates out of with-block.""" - mock_resp = mock.MagicMock() - mock_resp.status_code = 500 - mock_resp.text = "boom" - mock_make_request.return_value = mock_resp + @mock.patch.object(AKSMachineClient, "_run_az_cli_command", + side_effect=RuntimeError("boom")) + def test_create_machine_agentpool_cli_failure_raises(self, _mock_run_cli): + """CLI failure -> RuntimeError propagates out of with-block.""" with self.assertRaises(RuntimeError): self.client.create_machine_agentpool( @@ -121,14 +121,11 @@ def test_create_machine_agentpool_put_failure_raises(self, mock_make_request): @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", return_value=False) - @mock.patch.object(AKSMachineClient, "make_request") + @mock.patch.object(AKSMachineClient, "_run_az_cli_command") def test_create_machine_agentpool_provisioning_timeout_raises( - self, mock_make_request, _mock_wait + self, _mock_run_cli, _mock_wait ): - """PUT OK but provisioning never reaches Succeeded -> RuntimeError.""" - mock_resp = mock.MagicMock() - mock_resp.status_code = 200 - mock_make_request.return_value = mock_resp + """CLI succeeds but provisioning never reaches Succeeded -> RuntimeError.""" with self.assertRaises(RuntimeError): self.client.create_machine_agentpool( @@ -184,6 +181,7 @@ def test_scale_machine_non_batch_success( call.args[0] for call in self.mock_operation.add_metadata.call_args_list } self.assertIn("successful_machines", metadata_keys) + self.mock_operation.add_metadata.assert_any_call("successful_machines", 2) self.assertIn("percentile_node_readiness_times", metadata_keys) self.assertIn("node_readiness_time", metadata_keys) self.assertIn("cluster_info", metadata_keys) @@ -195,12 +193,12 @@ def test_scale_machine_non_batch_success( def test_scale_machine_partial_landing_raises( self, mock_create, mock_wait_ap, mock_wait_ready ): - """Non-batch path: if fewer machines land than requested, + """Non-batch path: if fewer machine CLI commands succeed than requested, scale_machine raises RuntimeError BEFORE waiting on agentpool provisioning or node readiness -- otherwise the recorded percentile envelope and node_readiness_time describe a smaller target than requested.""" - # Two PUTs requested, first lands, second fails. + # Two machine adds requested, first lands, second fails. mock_create.side_effect = [True, False] self.mock_k8s.get_ready_nodes.return_value = [] @@ -216,12 +214,14 @@ def test_scale_machine_partial_landing_raises( # have been reached. mock_wait_ap.assert_not_called() mock_wait_ready.assert_not_called() - # successful_machines metadata IS recorded so operators can see which - # PUTs landed; downstream readiness/cluster_info metadata is not. + # Machine names are intentionally not uploaded; only the successful count + # is recorded. Downstream readiness/cluster_info metadata is not recorded + # on partial landing. metadata_keys = { call.args[0] for call in self.mock_operation.add_metadata.call_args_list } self.assertIn("successful_machines", metadata_keys) + self.mock_operation.add_metadata.assert_any_call("successful_machines", 1) self.assertNotIn("percentile_node_readiness_times", metadata_keys) self.assertNotIn("node_readiness_time", metadata_keys) self.assertNotIn("cluster_info", metadata_keys) @@ -257,6 +257,47 @@ def test_scale_machine_passes_baseline_count_to_readiness( self.assertEqual(mock_wait_ready.call_args.kwargs["baseline_count"], 3) self.assertEqual(mock_wait_ready.call_args.kwargs["expected_count"], 1) + def test_scale_machine_consumes_timeout_budgets(self): + """scale_machine forwards the caller's timeout budgets to dispatch and waits.""" + names = ["scale2-machine-1", "scale2-machine-2"] + readiness_envelope = { + f"P{p}": { + "target_nodes": 2, + "elapsed_time_seconds": 10.0, + "percentage": p, + "success": True, + } + for p in (50, 70, 90, 99, 100) + } + with mock.patch.object( + AKSMachineClient, + "_scale_machine_individually", + return_value=names, + ) as mock_individual, mock.patch.object( + AKSMachineClient, + "_wait_for_agentpool_provisioning", + return_value=True, + ) as mock_wait_ap, mock.patch.object( + AKSMachineClient, + "_wait_for_machine_node_readiness", + return_value=readiness_envelope, + ) as mock_wait_ready: + self.mock_k8s.get_ready_nodes.return_value = [] + + self.client.scale_machine( + agentpool_name="apool", + vm_size="Standard_D2_v3", + scale_machine_count=2, + timeout=900, + readiness_wait_timeout=900, + ) + + request = mock_individual.call_args.args[0] + self.assertEqual(request.timeout, 900) + self.assertEqual(request.readiness_wait_timeout, 900) + self.assertEqual(mock_wait_ap.call_args.args[1], 900) + self.assertEqual(mock_wait_ready.call_args.kwargs["timeout"], 900) + def test_scale_machine_batch_path_dispatches_to_batch(self): """The use_batch_api=True branch calls _scale_machine_batch (not _individually) and records command_execution_time in operation metadata.""" @@ -300,9 +341,9 @@ def test_scale_machine_batch_path_dispatches_to_batch(self): # ---- _create_single_machine ---- - @mock.patch.object(AKSMachineClient, "make_request") - def test_create_single_machine_2xx_returns_true(self, mock_make_request): - """Any 200/201/202 response counts as a successful PUT.""" + @mock.patch.object(AKSMachineClient, "_run_az_cli_command") + def test_create_single_machine_cli_success_returns_true(self, mock_run_cli): + """A zero-exit Azure CLI command counts as a successful machine add.""" request = SimpleNamespace( agentpool_name="apool", cluster_name="fake-cluster", @@ -310,18 +351,20 @@ def test_create_single_machine_2xx_returns_true(self, mock_make_request): vm_size="Standard_D2_v3", timeout=60, ) - for code in (200, 201, 202): - with self.subTest(status=code): - mock_resp = mock.MagicMock() - mock_resp.status_code = code - mock_make_request.return_value = mock_resp - self.assertTrue( - self.client._create_single_machine("m1", request) - ) - - @mock.patch.object(AKSMachineClient, "make_request") - def test_create_single_machine_non_2xx_returns_false(self, mock_make_request): - """Non-2xx responses are logged and return False (never raise).""" + self.assertTrue(self.client._create_single_machine("m1", request)) + mock_run_cli.assert_called_once() + command = mock_run_cli.call_args.args[0] + self.assertEqual(command[:4], ["az", "aks", "machine", "add"]) + self.assertIn("--machine-name", command) + self.assertIn("m1", command) + self.assertIn("--vm-size", command) + self.assertIn("Standard_D2_v3", command) + self.assertIn("--no-wait", command) + + @mock.patch.object(AKSMachineClient, "_run_az_cli_command", + side_effect=RuntimeError("boom")) + def test_create_single_machine_cli_failure_returns_false(self, _mock_run_cli): + """CLI failures are logged and return False (never raise).""" request = SimpleNamespace( agentpool_name="apool", cluster_name="fake-cluster", @@ -329,10 +372,6 @@ def test_create_single_machine_non_2xx_returns_false(self, mock_make_request): vm_size="Standard_D2_v3", timeout=60, ) - mock_resp = mock.MagicMock() - mock_resp.status_code = 500 - mock_resp.text = "boom" - mock_make_request.return_value = mock_resp self.assertFalse(self.client._create_single_machine("m1", request)) # ---- _wait_for_machine_node_readiness ---- @@ -512,7 +551,7 @@ def test_wait_readiness_no_k8s_client_short_circuits(self): # ---- _scale_machine_batch ---- def test_scale_machine_batch_partitions_and_aggregates(self): - """Names sharded across machine_workers; all successful slices aggregated.""" + """Names sharded across workers; all successful slices aggregated.""" request = SimpleNamespace( agentpool_name="apool", cluster_name="fake-cluster", @@ -529,8 +568,11 @@ def test_scale_machine_batch_partitions_and_aggregates(self): ) as mock_create_batch: successful = self.client._scale_machine_batch(request, names) self.assertEqual(set(successful), set(names)) - # 2 workers, each handling per_worker = 4 // 2 = 2 names self.assertEqual(mock_create_batch.call_count, 2) + chunk_lengths = [ + len(call.args[1]) for call in mock_create_batch.call_args_list + ] + self.assertEqual(sorted(chunk_lengths), [2, 2]) def test_scale_machine_batch_per_worker_failure_isolated(self): """One worker raising does not poison the other worker's success list.""" @@ -571,6 +613,60 @@ def test_scale_machine_batch_rejects_non_exact_multiple(self): with self.assertRaises(ValueError): self.client._scale_machine_batch(request, names) + def test_scale_machine_batch_rejects_non_positive_workers(self): + """machine_workers must be positive.""" + request = SimpleNamespace( + agentpool_name="apool", + cluster_name="fake-cluster", + resource_group="fake-rg", + vm_size="Standard_D2_v3", + timeout=60, + machine_workers=0, + ) + with self.assertRaises(ValueError): + self.client._scale_machine_batch(request, ["m-1"]) + + def test_scale_machine_batch_rejects_calculated_batch_over_limit(self): + """Fail fast before ARM when calculated per-worker batch size exceeds 50.""" + request = SimpleNamespace( + agentpool_name="apool", + cluster_name="fake-cluster", + resource_group="fake-rg", + vm_size="Standard_D2_v3", + timeout=60, + machine_workers=10, + ) + names = [f"m-{i}" for i in range(1, 1001)] + with mock.patch.object( + AKSMachineClient, "_create_batch_machines" + ) as mock_create_batch: + with self.assertRaisesRegex(ValueError, "calculated batch size"): + self.client._scale_machine_batch(request, names) + mock_create_batch.assert_not_called() + + def test_scale_machine_batch_allows_calculated_batch_at_limit(self): + """A calculated per-worker batch size of exactly 50 is allowed.""" + request = SimpleNamespace( + agentpool_name="apool", + cluster_name="fake-cluster", + resource_group="fake-rg", + vm_size="Standard_D2_v3", + timeout=60, + machine_workers=20, + ) + names = [f"m-{i}" for i in range(1, 1001)] + with mock.patch.object( + AKSMachineClient, + "_create_batch_machines", + side_effect=lambda req, chunk, worker_id: list(chunk), + ) as mock_create_batch: + successful = self.client._scale_machine_batch(request, names) + self.assertEqual(set(successful), set(names)) + self.assertEqual(mock_create_batch.call_count, 20) + self.assertTrue( + all(len(call.args[1]) == 50 for call in mock_create_batch.call_args_list) + ) + # ---- _create_batch_machines ---- def test_create_batch_machines_empty_chunk_returns_empty(self): @@ -626,6 +722,23 @@ def test_create_batch_machines_header_shape(self): [{"machineName": "m-2"}, {"machineName": "m-3"}], ) + def test_create_batch_machines_rejects_oversized_chunk(self): + """BatchPutMachine rejects more than 50 machines per request client-side.""" + request = SimpleNamespace( + agentpool_name="apool", + cluster_name="fake-cluster", + resource_group="fake-rg", + vm_size="Standard_D2_v3", + timeout=60, + ) + names = [f"m-{i}" for i in range(1, 52)] + with mock.patch.object( + AKSMachineClient, "_make_batch_request" + ) as mock_make_batch: + with self.assertRaises(ValueError): + self.client._create_batch_machines(request, names, chunk_idx=0) + mock_make_batch.assert_not_called() + # ---- _make_batch_request ---- def test_make_batch_request_2xx_returns(self): diff --git a/pipelines/perf-eval/Autoscale Benchmark/k8s-cluster-crud-machine.yml b/pipelines/perf-eval/Autoscale Benchmark/k8s-cluster-crud-machine.yml new file mode 100644 index 0000000000..e324961da4 --- /dev/null +++ b/pipelines/perf-eval/Autoscale Benchmark/k8s-cluster-crud-machine.yml @@ -0,0 +1,38 @@ +trigger: none + +schedules: + - cron: "0 12 * * *" + displayName: "Daily 12:00 UTC" + branches: + include: + - main + always: true + +variables: + SCENARIO_TYPE: perf-eval + SCENARIO_NAME: k8s-cluster-crud-machine # matches ado-telescope: feeds Kusto table k8s_cluster_crud_machine_main + USE_LATEST_GA_K8S_VERSION: true + +stages: + - stage: azure_canadacentral_small_machine_pool + dependsOn: [] + jobs: + - template: /jobs/competitive-test.yml + parameters: + cloud: azure + regions: + - canadacentral + topology: k8s-cluster-crud-machine + engine: machine + matrix: + small_machine_pool: + vm_size: Standard_D2_v3 + pool_name: smallpool1 + scale_machine_count: 1 + machine_workers: 1 + use_batch_api: "false" + step_time_out: 600 + max_parallel: 1 + timeout_in_minutes: 180 + credential_type: service_connection + ssh_key_enabled: false diff --git a/pipelines/system/new-pipeline-test.yml b/pipelines/system/new-pipeline-test.yml index 63d55f02d9..6c01310600 100644 --- a/pipelines/system/new-pipeline-test.yml +++ b/pipelines/system/new-pipeline-test.yml @@ -1,25 +1,78 @@ trigger: none variables: - SCENARIO_TYPE: - SCENARIO_NAME: + SCENARIO_TYPE: perf-eval + SCENARIO_NAME: k8s-cluster-crud-machine + USE_LATEST_GA_K8S_VERSION: true stages: - - stage: # format: [_]+ (e.g. azure_eastus2, aws_eastus_westus) + - stage: azure_canadacentral_small_scale_10 dependsOn: [] jobs: - - template: /jobs/competitive-test.yml # must keep as is + - template: /jobs/competitive-test.yml parameters: - cloud: # e.g. azure, aws - regions: # list of regions - - region1 # e.g. eastus2 - topology: # e.g. cluster-autoscaler - engine: # e.g. clusterloader2 - matrix: # list of test parameters to customize the provisioned resources - : - : - : - max_parallel: # required - credential_type: service_connection # required + cloud: azure + regions: + - canadacentral + topology: k8s-cluster-crud-machine + engine: machine + matrix: + canadacentral-small-scale-10: + vm_size: Standard_D2_v3 + pool_name: smallpool1 + scale_machine_count: 10 + machine_workers: 5 + use_batch_api: "false" + step_time_out: 900 + max_parallel: 1 + timeout_in_minutes: 360 + credential_type: service_connection + ssh_key_enabled: false + + - stage: azure_canadacentral_medium_scale_500 + dependsOn: [] + jobs: + - template: /jobs/competitive-test.yml + parameters: + cloud: azure + regions: + - canadacentral + topology: k8s-cluster-crud-machine + engine: machine + matrix: + canadacentral-medium-scale-500: + vm_size: Standard_D2_v3 + pool_name: mediump1 + scale_machine_count: 500 + machine_workers: 10 + use_batch_api: "true" + step_time_out: 2400 + max_parallel: 1 + timeout_in_minutes: 360 + credential_type: service_connection + ssh_key_enabled: false + + - stage: azure_canadacentral_large_scale_1000 + dependsOn: + - azure_canadacentral_small_scale_10 + - azure_canadacentral_medium_scale_500 + jobs: + - template: /jobs/competitive-test.yml + parameters: + cloud: azure + regions: + - canadacentral + topology: k8s-cluster-crud-machine + engine: machine + matrix: + canadacentral-large-scale-1000: + vm_size: Standard_D2_v3 + pool_name: largep1 + scale_machine_count: 1000 + machine_workers: 20 + use_batch_api: "true" + step_time_out: 3600 + max_parallel: 1 + timeout_in_minutes: 360 + credential_type: service_connection ssh_key_enabled: false - timeout_in_minutes: 60 # if not specified, default is 60 diff --git a/scenarios/perf-eval/k8s-cluster-crud-machine/terraform-inputs/azure.tfvars b/scenarios/perf-eval/k8s-cluster-crud-machine/terraform-inputs/azure.tfvars new file mode 100644 index 0000000000..0688e5bf59 --- /dev/null +++ b/scenarios/perf-eval/k8s-cluster-crud-machine/terraform-inputs/azure.tfvars @@ -0,0 +1,32 @@ +scenario_type = "perf-eval" +scenario_name = "k8s-cluster-crud-machine" +deletion_delay = "4h" +owner = "aks" +aks_cli_config_list = [ + { + role = "client" + aks_name = "mchapi" + sku_tier = "standard" + use_aks_preview_cli_extension = true + default_node_pool = { + name = "default" + node_count = 2 + vm_size = "Standard_D2_v3" + } + + optional_parameters = [ + { + name = "network-plugin" + value = "azure" + }, + { + name = "network-plugin-mode" + value = "overlay" + }, + { + name = "pod-cidr" + value = "10.128.0.0/11" + } + ] + } +] diff --git a/scenarios/perf-eval/k8s-cluster-crud-machine/terraform-test-inputs/azure.json b/scenarios/perf-eval/k8s-cluster-crud-machine/terraform-test-inputs/azure.json new file mode 100644 index 0000000000..c0cd1ffe14 --- /dev/null +++ b/scenarios/perf-eval/k8s-cluster-crud-machine/terraform-test-inputs/azure.json @@ -0,0 +1,23 @@ +{ + "run_id" : "123456789", + "region" : "canadacentral", + "aks_cli_system_node_pool" : { + "name" : "default", + "node_count" : 1, + "vm_size" : "Standard_D2s_v3", + "vm_set_type" : "VirtualMachineScaleSets" + }, + "aks_cli_user_node_pool" : [{ + "name" : "pool1", + "node_count" : 1, + "vm_size" : "Standard_D2s_v3", + "vm_set_type" : "VirtualMachineScaleSets" + }, + { + "name" : "pool2", + "node_count" : 1, + "vm_size" : "Standard_D2s_v3", + "vm_set_type" : "VirtualMachineScaleSets" + }] + +} diff --git a/steps/engine/machine/k8s/collect.yml b/steps/engine/machine/k8s/collect.yml new file mode 100644 index 0000000000..09915ed478 --- /dev/null +++ b/steps/engine/machine/k8s/collect.yml @@ -0,0 +1,18 @@ +parameters: + - name: cloud + type: string + - name: region + type: string + +steps: + - bash: | + set -euo pipefail + python3 -m crud.main collect + workingDirectory: modules/python + displayName: "Collect Machine API results" + env: + PYTHONPATH: $(Pipeline.Workspace)/s/modules/python + RUN_ID: $(RUN_ID) + REGION: ${{ parameters.region }} + RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) + RUN_URL: $(System.TeamFoundationCollectionUri)$(System.TeamProject)/_build/results?buildId=$(Build.BuildId)&view=logs&j=$(System.JobId) diff --git a/steps/engine/machine/k8s/execute.yml b/steps/engine/machine/k8s/execute.yml new file mode 100644 index 0000000000..7b0bf3875c --- /dev/null +++ b/steps/engine/machine/k8s/execute.yml @@ -0,0 +1,60 @@ +parameters: + - name: cloud + type: string + - name: result_dir + type: string + - name: vm_size + type: string + - name: pool_name + type: string + - name: scale_machine_count + type: string # numeric matrix values resolve at runtime via $(VAR) + - name: machine_workers + type: string + - name: use_batch_api + type: string # 'true'|'false' as ADO doesn't have boolean type for matrix + - name: step_time_out + type: string + default: "600" + +steps: + - bash: | + set -euo pipefail + tags=$(jq -nc --arg run_id "$RUN_ID" \ + --arg deletion_due_time "$DELETION_DUE_TIME" \ + --arg creation_time "$(date -u +'%Y-%m-%dT%H:%M:%SZ')" \ + --arg scenario "$SCENARIO_TYPE-$SCENARIO_NAME" \ + --arg owner aks \ + '{run_id:$run_id, deletion_due_time:$deletion_due_time, creation_time:$creation_time, scenario:$scenario, owner:$owner}') + python3 -m crud.main create-machine \ + --cloud "${{ parameters.cloud }}" \ + --run-id "$RUN_ID" \ + --node-pool-name "${{ parameters.pool_name }}" \ + --vm-size "${{ parameters.vm_size }}" \ + --step-timeout "${{ parameters.step_time_out }}" \ + --result-dir "${{ parameters.result_dir }}" + USE_BATCH_FLAG="" + if [[ "${{ parameters.use_batch_api }}" == "true" ]]; then + USE_BATCH_FLAG="--use-batch-api" + fi + # shellcheck disable=SC2086 + python3 -m crud.main scale-machine \ + --cloud "${{ parameters.cloud }}" \ + --run-id "$RUN_ID" \ + --node-pool-name "${{ parameters.pool_name }}" \ + --vm-size "${{ parameters.vm_size }}" \ + --scale-machine-count "${{ parameters.scale_machine_count }}" \ + --machine-workers "${{ parameters.machine_workers }}" \ + $USE_BATCH_FLAG \ + --step-timeout "${{ parameters.step_time_out }}" \ + --readiness-wait-timeout "${{ parameters.step_time_out }}" \ + --result-dir "${{ parameters.result_dir }}" \ + --tags "$tags" + workingDirectory: modules/python + displayName: "Execute Machine API CRUD" + env: + PYTHONPATH: $(Pipeline.Workspace)/s/modules/python + RUN_ID: $(RUN_ID) + DELETION_DUE_TIME: $(DELETION_DUE_TIME) + SCENARIO_TYPE: $(SCENARIO_TYPE) + SCENARIO_NAME: $(SCENARIO_NAME) diff --git a/steps/topology/k8s-cluster-crud-machine/collect-machine.yml b/steps/topology/k8s-cluster-crud-machine/collect-machine.yml new file mode 100644 index 0000000000..4ebb07b663 --- /dev/null +++ b/steps/topology/k8s-cluster-crud-machine/collect-machine.yml @@ -0,0 +1,14 @@ +parameters: + - name: cloud + type: string + - name: regions + type: object + - name: engine_input + type: object + default: {} + +steps: + - template: /steps/engine/machine/k8s/collect.yml + parameters: + cloud: ${{ parameters.cloud }} + region: ${{ parameters.regions[0] }} diff --git a/steps/topology/k8s-cluster-crud-machine/execute-machine.yml b/steps/topology/k8s-cluster-crud-machine/execute-machine.yml new file mode 100644 index 0000000000..f088411869 --- /dev/null +++ b/steps/topology/k8s-cluster-crud-machine/execute-machine.yml @@ -0,0 +1,20 @@ +parameters: + - name: cloud + type: string + - name: regions + type: object + - name: engine_input + type: object + default: {} + +steps: + - template: /steps/engine/machine/k8s/execute.yml + parameters: + cloud: ${{ parameters.cloud }} + result_dir: $(System.DefaultWorkingDirectory)/$(RUN_ID) + vm_size: $(VM_SIZE) + pool_name: $(POOL_NAME) + scale_machine_count: $(SCALE_MACHINE_COUNT) + machine_workers: $(MACHINE_WORKERS) + use_batch_api: $(USE_BATCH_API) + step_time_out: $(STEP_TIME_OUT) diff --git a/steps/topology/k8s-cluster-crud-machine/validate-resources.yml b/steps/topology/k8s-cluster-crud-machine/validate-resources.yml new file mode 100644 index 0000000000..d861b4015e --- /dev/null +++ b/steps/topology/k8s-cluster-crud-machine/validate-resources.yml @@ -0,0 +1,13 @@ +parameters: + - name: cloud + type: string + - name: regions + type: object + - name: engine + type: string + +steps: + - template: /steps/cloud/${{ parameters.cloud }}/update-kubeconfig.yml + parameters: + role: client + region: ${{ parameters.regions[0] }}