From 74ba3b5ce56bee5f56ff732c293f6a0d226496a6 Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 14 May 2026 12:29:41 -0700 Subject: [PATCH 1/2] feat(crud): add AKSMachineClient subclass for AKS Machine API First slice of the AKS Machine API CRUD perf-test port from ado-telescope to gh-telescope. Adds a new `AKSMachineClient(AKSClient)` subclass that adds raw REST methods for the AKS Machine API (not yet exposed in the Azure SDK). Subsequent PRs will add the CRUD orchestrator (`crud/azure/machine_crud.py`), the CLI subcommands in `crud/main.py`, scenario terraform inputs, and the pipeline templates. ## What this PR adds - `modules/python/clients/aks_machine_client.py`: - `class AKSMachineClient(AKSClient)`: subclass to inherit auth, ContainerServiceClient, KubernetesClient, `get_cluster_name`, `get_cluster_data`, and the existing node-pool CRUD methods. - `create_machine_agentpool(agentpool_name, vm_size, cluster_name=None, timeout=300) -> bool`: converts an existing agentpool to Machines mode via PUT. - `scale_machine(agentpool_name, vm_size, scale_machine_count, ...) -> bool`: adds N machines to a machine-mode agentpool, supports both per-machine PUTs and the AKS BatchPutMachine header pattern. - Both methods wrap their work in `OperationContext` exactly like `AKSClient.create_node_pool` / `scale_node_pool`: opens context, enriches with `op.add_metadata` along the way, returns True on success, re-raises on failure so the context records the trace. - `_wait_for_machine_node_readiness`: baseline-aware percentile watcher returning ado-parity nested envelope keyed P50/P70/P90/P99/P100. Each entry carries `{target_nodes, elapsed_time_seconds, percentage, success}`. - `modules/python/tests/test_aks_machine_client.py`: 9 tests covering successful create/scale (batch and non-batch), PUT failure, agentpool provisioning timeout, partial machine landing (raises RuntimeError), baseline-count propagation to the readiness watcher, and the ado-compatible machine-name prefix generator. ## Schema for downstream Kusto consumers When `scale_machine` runs through `OperationContext`, the persisted metadata dict includes: `successful_machines`, `batch_command_execution_times` (when batch), `percentile_node_readiness_times` (nested envelope), `node_readiness_time` (= P100.elapsed_time_seconds), `cluster_info`. ## Verification - `pylint modules/python/clients/aks_machine_client.py modules/python/tests/test_aks_machine_client.py` -> 10.00/10. - `pytest modules/python/tests/test_aks_machine_client.py` -> 9 passed. - Full `modules/python/ pytest --cov=. --cov-fail-under=80` -> 702 passed, 81.24% coverage. ## Subsequent PRs 2. `feat(crud): add MachineCRUD orchestrator` 3. `feat(crud): add create-machine + scale-machine CLI subcommands` 4. `feat(crud-machine): scenario terraform inputs` 5. `feat(crud-machine): pipeline templates + production pipeline` --- modules/python/clients/aks_machine_client.py | 699 ++++++++++++++++++ .../python/tests/test_aks_machine_client.py | 248 +++++++ 2 files changed, 947 insertions(+) create mode 100644 modules/python/clients/aks_machine_client.py create mode 100644 modules/python/tests/test_aks_machine_client.py diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py new file mode 100644 index 0000000000..18d1f92d62 --- /dev/null +++ b/modules/python/clients/aks_machine_client.py @@ -0,0 +1,699 @@ +"""AKS Machine API client. + +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. + +Public methods (``create_machine_agentpool``, ``scale_machine``) wrap their work +in ``OperationContext`` exactly like ``AKSClient.create_node_pool`` / +``AKSClient.scale_node_pool``: the context is opened inside the client method, +metadata is enriched with ``op.add_metadata`` along the way, success returns +True, failures are logged and re-raised so ``OperationContext`` records them. +``MachineCRUD`` therefore stays a thin try/except wrapper, mirroring +``crud/azure/node_pool_crud.py``. + +Ported from ado-telescope/modules/python/k8s/cloud_providers/azure.py. +""" +import json +import logging +import threading +import time +from concurrent.futures import ThreadPoolExecutor, as_completed +from types import SimpleNamespace +from typing import Any, Dict, List, Optional, Tuple + +import requests + +from clients.aks_client import AKSClient +from utils.logger_config import get_logger, setup_logging + +# Configure logging (mirrors clients/aks_client.py / crud/azure/node_pool_crud.py). +setup_logging() +logger = get_logger(__name__) +# Suppress noisy Azure SDK logs (mirror clients/aks_client.py). +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) + +_ARM_BASE = "https://management.azure.com" +_ARM_SCOPE = "https://management.azure.com/.default" +_AGENTPOOL_API_VERSION = "2024-06-02-preview" # per ado azure.py — agentpool sub-resource +_MACHINE_API_VERSION = "2025-06-02-preview" # per ado azure.py — machines sub-resource +_POLL_INTERVAL_SECONDS = 10 +_PROVISIONING_NONE_STATE_LIMIT = 5 +_BATCH_429_MAX_RETRIES = 3 +_BATCH_429_INITIAL_BACKOFF_SECONDS = 1.0 + + +class AKSMachineClient(AKSClient): + """Extends ``AKSClient`` with Machine-API REST plumbing. + + Inherits ``credential``, ``subscription_id``, ``resource_group``, + ``k8s_client``, ``get_cluster_name``, ``get_cluster_data``, and the + existing ``create_node_pool`` / ``scale_node_pool`` / ``delete_node_pool`` + methods. Tests that require a baseline node pool can therefore call the + inherited methods directly without a separate client. + """ + + def __init__(self, *args, **kwargs): + super().__init__(*args, **kwargs) + self._token_cache_value: Optional[str] = None + self._token_cache_expiry: float = 0.0 # unix epoch seconds + self._token_lock = threading.Lock() + + # ---- auth + REST plumbing ---- + def _get_access_token(self) -> str: + """Cached token fetch. Re-uses token across worker threads with a 60s safety margin + before expiry. Avoids forking `az account get-access-token` per worker.""" + with self._token_lock: + if self._token_cache_value and time.time() < self._token_cache_expiry - 60: + return self._token_cache_value + tok = self.credential.get_token(_ARM_SCOPE) + self._token_cache_value = tok.token + self._token_cache_expiry = float(tok.expires_on) + return self._token_cache_value + + def make_request( + self, + method: str, + url: str, + data: Optional[Dict[str, Any]] = None, + timeout: int = 30, + ) -> requests.Response: + """Send an authenticated ARM REST request and return the raw Response. + + Callers are responsible for checking ``response.status_code`` (or + calling ``raise_for_status()``) — this method does NOT raise on HTTP + errors. Long-running Machine API operations return 200/202 with a + Location header that callers must follow. + """ + headers = { + "Authorization": f"Bearer {self._get_access_token()}", + "Content-Type": "application/json", + } + return requests.request(method, url, headers=headers, json=data, timeout=timeout) + + # ---- Machine API: agent pool provisioning ---- + def create_machine_agentpool( + self, + agentpool_name: str, + vm_size: str, + cluster_name: Optional[str] = None, + timeout: int = 300, + ) -> bool: + """Convert an existing agentpool to Machines mode via PUT. + + Mirrors ``AKSClient.create_node_pool`` convention: opens an + ``OperationContext`` here, enriches metadata, returns True on success, + re-raises on failure (so the context records ``success=False`` with + traceback before the exception propagates to ``MachineCRUD``). + + 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. + cluster_name: Parent AKS cluster name. Defaults to + ``self.get_cluster_name()`` (matches ``create_node_pool``). + timeout: Total budget (seconds) used as both the PUT HTTP timeout + AND the polling deadline for ``_wait_for_agentpool_provisioning``. + + Returns: + True iff the agentpool reaches provisioningState='Succeeded'. + + Raises: + RuntimeError: PUT non-2xx, ARM-reported Failed state, or timeout. + """ + cluster_name = cluster_name or self.get_cluster_name() + metadata = { + "cluster_name": cluster_name, + "agentpool_name": agentpool_name, + "vm_size": vm_size, + } + with self._get_operation_context()( + "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"/providers/Microsoft.ContainerService/managedClusters/{cluster_name}" + f"/agentPools/{agentpool_name}?api-version={_AGENTPOOL_API_VERSION}" + ) + body = {"properties": {"mode": "Machines"}} + resp = self.make_request("PUT", url, data=body, timeout=timeout) + if resp.status_code not in (200, 201): + raise RuntimeError( + f"create_machine_agentpool PUT failed: " + f"{resp.status_code} {resp.text[:500]}" + ) + if not self._wait_for_agentpool_provisioning(url, timeout): + raise RuntimeError( + f"agentpool {agentpool_name} did not reach Succeeded within {timeout}s" + ) + op.add_metadata("agentpool_info", self.get_node_pool( + agentpool_name, cluster_name).as_dict()) + op.add_metadata("cluster_info", self.get_cluster_data(cluster_name)) + return True + except Exception as e: + logger.error(f"Failed to create machine agentpool {agentpool_name}: {e}") + raise + + def _wait_for_agentpool_provisioning(self, url: str, timeout: int) -> bool: + """Poll the agentpool URL until provisioningState is terminal. + + Polls every ``_POLL_INTERVAL_SECONDS`` (10s) using a 30s per-request HTTP + timeout. Returns True on 'Succeeded'. Returns False on 'Failed' or when + ``timeout`` seconds have elapsed since invocation. Transient non-200 GETs + are logged and retried until the deadline. Also handles missing + provisioningState (treats absence for ``_PROVISIONING_NONE_STATE_LIMIT`` + consecutive polls as Failed). + """ + deadline = time.time() + timeout + none_count = 0 + while time.time() < deadline: + r = self.make_request("GET", url, timeout=30) + if r.status_code != 200: + logger.warning(f"agentpool GET {url} -> {r.status_code}") + time.sleep(_POLL_INTERVAL_SECONDS) + continue + try: + body = r.json() + except (ValueError, TypeError) as exc: + logger.warning(f"agentpool poll JSON parse failed: {exc}") + time.sleep(_POLL_INTERVAL_SECONDS) + continue + state = body.get("properties", {}).get("provisioningState") + if state == "Succeeded": + return True + if state == "Failed": + logger.error(f"agentpool provisioning failed: {body}") + return False + if state is None: + none_count += 1 + if none_count >= _PROVISIONING_NONE_STATE_LIMIT: + logger.warning( + f"agentpool provisioningState absent for {none_count} consecutive polls; " + f"treating as Failed." + ) + return False + else: + none_count = 0 + time.sleep(_POLL_INTERVAL_SECONDS) + logger.error(f"agentpool provisioning timed out after {timeout}s") + return False + + def _wait_for_machine_node_readiness( + self, + agentpool_name: str, + expected_count: int, + timeout: int, + baseline_count: int = 0, + ) -> Dict[str, Dict[str, Any]]: + """Wait for ``expected_count`` NEW Ready nodes; return ado-parity nested percentile dict. + + AKS Machine ARM resource names (e.g. ``scale100-machine-1``) are NOT the + same as the underlying k8s Node names (``aks---vmss``), so + we cannot look up Nodes by Machine name. Instead we poll Nodes labelled + ``agentpool=`` and record the wall-clock elapsed when each percentile + ready threshold is hit. + + ``baseline_count`` is the number of Ready+labeled nodes that already + existed BEFORE scale_machine ran. Percentile targets are computed against + ``baseline_count + expected_count`` and clamped to ``> baseline_count`` + so a target never fires on pre-existing nodes alone. Without this, an + agentpool that already has 1 Ready node and is being scaled by 1 more + would report P50/P70/P90/P99/P100 = ~0.7s (the first poll) even though the + new node had not yet provisioned. + + ``timeout`` is wall-clock seconds from invocation. Returns the nested + empty-state envelope (``elapsed_time_seconds=None``, ``success=False``) + if ``k8s_client`` is unavailable, ``expected_count`` <= 0, or no + percentile target is met within ``timeout``. Polling exceptions are + logged and treated as 0 ready this tick. Never raises. + """ + # ado-parity empty-state envelope: nested dict per P-key with + # `target_nodes`, `elapsed_time_seconds`, `percentage`, `success` so + # the Kusto schema sees consistent shape regardless of outcome. + empty_envelope: Dict[str, Dict[str, Any]] = { + f"P{p}": { + "target_nodes": 0, + "elapsed_time_seconds": None, + "percentage": p, + "success": False, + } + for p in (50, 70, 90, 99, 100) + } + kc = self.k8s_client + if kc is None: + logger.error( + "k8s_client is None on AKSClient; cannot wait for machine readiness" + ) + return empty_envelope + if expected_count <= 0: + return empty_envelope + label_selector = f"agentpool={agentpool_name}" + target_total = baseline_count + expected_count + # Each percentile target must be STRICTLY GREATER than baseline_count so + # we count only NEW nodes — pre-existing labeled Ready nodes alone must + # never satisfy any threshold. + targets = { + p: max(baseline_count + 1, int((p / 100.0) * target_total)) + for p in (50, 70, 90, 99, 100) + } + elapsed: Dict[int, float] = {} + start = time.time() + deadline = start + timeout + logger.info( + f"Waiting for nodes in agentpool {agentpool_name} (label {label_selector}) - " + f"targets {targets}, baseline={baseline_count}, expected={expected_count}, " + f"timeout {timeout}s" + ) + while time.time() < deadline and len(elapsed) < len(targets): + try: + ready = len(kc.get_ready_nodes(label_selector=label_selector)) + except Exception as e: + logger.warning(f"get_ready_nodes({label_selector}) failed: {e}") + ready = 0 + now_elapsed = time.time() - start + for p, target in targets.items(): + if p not in elapsed and ready >= target: + elapsed[p] = now_elapsed + logger.info( + f"P{p} hit: {ready}/{target_total} ready " + f"(target={target}, baseline={baseline_count}) at {now_elapsed:.2f}s" + ) + if len(elapsed) < len(targets): + time.sleep(2) + if not elapsed: + logger.warning( + f"No percentile target met within {timeout}s for agentpool {agentpool_name}" + ) + return { + f"P{p}": { + "target_nodes": targets[p], + "elapsed_time_seconds": None, + "percentage": p, + "success": False, + } + for p in (50, 70, 90, 99, 100) + } + result: Dict[str, Dict[str, Any]] = { + f"P{p}": { + "target_nodes": targets[p], + "elapsed_time_seconds": elapsed.get(p), + "percentage": p, + "success": p in elapsed, + } + for p in (50, 70, 90, 99, 100) + } + # ado-parity stdout logging: percentile summary including P100, which is + # the wall-clock elapsed until ALL target nodes are Ready. This matches + # ado's `response.node_readiness_time = percentile_times[100]` exactly. + logger.info(f"Node Readiness Percentile Summary for agentpool {agentpool_name}:") + for p in (50, 70, 90, 99, 100): + if p in elapsed: + logger.info(f" P{p} (target={targets[p]} nodes): {elapsed[p]:.2f} seconds") + else: + logger.info(f" P{p} (target={targets[p]} nodes): TIMEOUT") + max_elapsed = max(elapsed.values()) + logger.info( + f"All target nodes became ready in {max_elapsed:.2f} seconds " + f"in agent pool {agentpool_name}" + ) + logger.info(f"Percentile node readiness data: {json.dumps(result, indent=2)}") + return result + + def scale_machine( + self, + agentpool_name: str, + vm_size: str, + scale_machine_count: int, + cluster_name: Optional[str] = None, + use_batch_api: bool = False, + machine_workers: int = 1, + timeout: int = 600, + readiness_wait_timeout: int = 1200, + tags: Optional[Dict[str, str]] = None, # pylint: disable=unused-argument + ) -> bool: + """Scale a Machine-mode agentpool by creating ``scale_machine_count`` machines. + + Mirrors ``AKSClient.scale_node_pool`` convention: opens an + ``OperationContext`` here, enriches with successful machine names, + per-percentile readiness envelope, batch chunk timings, and the cluster + snapshot. Returns True iff every requested machine landed AND every + readiness percentile target was hit. Re-raises on failure so the + context records the trace. + + Flow (both batch and non-batch): + 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 or via the batch header pattern). + Per-machine ARM polling is intentionally NOT performed. + 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). + + Raises: + RuntimeError: fewer machines landed than requested. + """ + cluster_name = cluster_name or self.get_cluster_name() + metadata = { + "cluster_name": cluster_name, + "agentpool_name": agentpool_name, + "vm_size": vm_size, + "scale_machine_count": scale_machine_count, + "use_batch_api": use_batch_api, + "machine_workers": machine_workers, + } + # Bundle into a SimpleNamespace so the helpers retain the + # ``request.foo`` shape ported verbatim from ado-telescope without + # exposing yet another module-level data class. + request = SimpleNamespace( + agentpool_name=agentpool_name, + cluster_name=cluster_name, + resource_group=self.resource_group, + vm_size=vm_size, + scale_machine_count=scale_machine_count, + use_batch_api=use_batch_api, + machine_workers=machine_workers, + timeout=timeout, + readiness_wait_timeout=readiness_wait_timeout, + ) + with self._get_operation_context()( + "scale_machine", "azure", metadata, result_dir=self.result_dir + ) as op: + try: + # Snapshot baseline BEFORE any PUTs so the readiness watcher + # counts only NEW nodes. + kc = self.k8s_client + baseline_count = 0 + if kc is not None: + try: + baseline_count = len( + kc.get_ready_nodes( + label_selector=f"agentpool={agentpool_name}" + ) + ) + logger.info( + f"baseline ready nodes in agentpool {agentpool_name}: {baseline_count}" + ) + except Exception: + logger.warning( + "baseline node snapshot failed; readiness count may be inflated" + ) + + # Naming parity with ado-telescope. + prefix = self._get_machine_name_prefix(scale_machine_count) + names = [ + f"{prefix}-machine-{i + 1}" for i in range(scale_machine_count) + ] + if use_batch_api: + successful, batch_times = self._scale_machine_batch(request, names) + op.add_metadata("batch_command_execution_times", batch_times) + else: + successful = self._scale_machine_individually(request, names) + op.add_metadata("successful_machines", successful) + + # Single agentpool-level provisioning check. + agentpool_url = ( + f"{_ARM_BASE}/subscriptions/{self.subscription_id}/resourceGroups/" + f"{self.resource_group}/providers/Microsoft.ContainerService/" + f"managedClusters/{cluster_name}/agentPools/" + f"{agentpool_name}?api-version={_AGENTPOOL_API_VERSION}" + ) + agentpool_ok = self._wait_for_agentpool_provisioning( + agentpool_url, timeout + ) + logger.info( + f"agentpool {agentpool_name} provisioning " + f"{'Succeeded' if agentpool_ok else 'Failed/Timeout'}" + ) + + percentile_envelope = self._wait_for_machine_node_readiness( + agentpool_name=agentpool_name, + expected_count=len(successful), + timeout=readiness_wait_timeout, + baseline_count=baseline_count, + ) + op.add_metadata("percentile_node_readiness_times", percentile_envelope) + p100 = percentile_envelope.get("P100", {}) + op.add_metadata( + "node_readiness_time", p100.get("elapsed_time_seconds") or 0.0 + ) + op.add_metadata("cluster_info", self.get_cluster_data(cluster_name)) + + if len(successful) != scale_machine_count: + raise RuntimeError( + f"scale_machine landed {len(successful)}/{scale_machine_count} machines" + ) + return True + except Exception as e: + logger.error(f"Failed to scale machine agentpool {agentpool_name}: {e}") + raise + + + @staticmethod + def _get_machine_name_prefix(scale_machine_count: int) -> str: + """Generate the ado-compatible machine-name prefix for a given scale count. + + Mirrors ado-telescope ``azure.py::_get_machine_name_prefix`` exactly so + that the resulting machine ARM resource names match across repos and + cross-repo Kusto dashboards keyed on machine name continue to correlate. + + - ``scale1000`` -> ``scale1k`` (any multiple of 1000 >= 1000 collapses) + - ``scale500`` -> ``scale500`` + - ``scale1`` -> ``scale1`` + """ + if scale_machine_count >= 1000 and scale_machine_count % 1000 == 0: + return f"scale{scale_machine_count // 1000}k" + return f"scale{scale_machine_count}" + + def _scale_machine_individually( + self, request: SimpleNamespace, names: List[str], + ) -> List[str]: + """Submit per-machine PUTs concurrently via ThreadPoolExecutor. + + Each worker calls ``_create_single_machine(name, request)`` which PUTs + the machine and waits for its provisioning to terminate. Returns the + list of names that reported True. Per-machine exceptions are logged + and treated as failure (name omitted from result). + """ + successful: List[str] = [] + with ThreadPoolExecutor(max_workers=request.machine_workers) as ex: + futures = {ex.submit(self._create_single_machine, n, request): n for n in names} + for fut in as_completed(futures): + n = futures[fut] + try: + if fut.result(): + successful.append(n) + except Exception: + logger.exception(f"create_single_machine failed for {n}") + return successful + + def _create_single_machine(self, name: str, request: SimpleNamespace) -> bool: + """PUT a single Machine resource. Returns True on any 2xx response. + + 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). + + Intentionally does NOT poll the per-machine ARM provisioningState. The + AKS RP reports per-machine ``provisioningState='Succeeded'`` essentially + as soon as the agentpool admits the request — well before the underlying + 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. + + Never raises on HTTP errors; logs and returns False on non-2xx responses. + """ + 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]}") + return False + return True + + # ---- Machine API: batch scale path ---- + @staticmethod + def _array_split(items: List[str], n: int) -> List[List[str]]: + """Split ``items`` into ``n`` chunks of as-equal-as-possible size. + + Equivalent to ``numpy.array_split`` semantics with pure Python. ``n`` is + clamped to ``[1, len(items)]`` so empty/oversized worker counts degrade + gracefully. Returns at most ``len(items)`` chunks; never returns empty + chunks unless ``items`` itself is empty. + """ + if not items: + return [] + n = max(1, min(n, len(items))) + k, m = divmod(len(items), n) + return [items[i * k + min(i, m):(i + 1) * k + min(i + 1, m)] for i in range(n)] + + def _scale_machine_batch( + self, + request: SimpleNamespace, + names: List[str], + ) -> Tuple[List[str], Dict[str, float]]: + """Dispatch ``names`` across ``request.machine_workers`` chunks via the AKS Batch API. + + Splits ``names`` into up to ``request.machine_workers`` chunks + (``_array_split`` semantics) and submits each chunk to a + ``ThreadPoolExecutor``. Each worker calls ``_create_batch_machines``, + whose return value is the list of names that landed successfully in + that chunk. Per-chunk wall time is captured under ``chunk_`` + regardless of success/failure. Per-chunk worker exceptions are caught + and logged; the chunk's names are excluded from the returned + ``successful`` list. The input ``request`` is not mutated. + """ + chunks = self._array_split(names, request.machine_workers) + successful: List[str] = [] + batch_times: Dict[str, float] = {} + + def run_chunk(idx: int, chunk: List[str]): + t0 = time.time() + try: + created = self._create_batch_machines(request, chunk, idx) + except Exception: + logger.exception(f"batch chunk {idx} failed") + created = [] + elapsed = time.time() - t0 + return idx, created, elapsed + + with ThreadPoolExecutor(max_workers=max(1, request.machine_workers)) as ex: + futures = [ex.submit(run_chunk, i, chunk) for i, chunk in enumerate(chunks)] + for fut in as_completed(futures): + try: + idx, created, elapsed = fut.result() + except Exception: + # run_chunk already swallows; this is belt-and-suspenders. + logger.exception("unexpected error retrieving batch chunk result") + continue + batch_times[f"chunk_{idx}"] = elapsed + successful.extend(created) + return successful, batch_times + + def _create_batch_machines( + self, + request: SimpleNamespace, + chunk: List[str], + chunk_idx: int, + ) -> List[str]: + """Submit a batch-PUT request creating every machine in ``chunk``. + + Uses the AKS Machine API ``BatchPutMachine`` HEADER pattern (NOT the + non-existent ARM ``/$batch`` envelope): a single PUT to the first + machine name in ``chunk`` carrying a ``BatchPutMachine`` header whose + value is JSON containing ``vmSkus`` and ``batchMachines`` lists. + + Returns the list of machine names submitted on 2xx. Raises + ``RuntimeError`` (from ``_make_batch_request``) if the request exhausts + 429 retries or returns a non-2xx. Caller catches and excludes failed + chunks from the success list. + """ + if not chunk: + return [] + sub = self.subscription_id + first_machine_name = chunk[0] + url = ( + f"{_ARM_BASE}/subscriptions/{sub}/resourceGroups/{request.resource_group}" + f"/providers/Microsoft.ContainerService/managedClusters/{request.cluster_name}" + f"/agentPools/{request.agentpool_name}/machines/{first_machine_name}" + f"?api-version={_MACHINE_API_VERSION}" + ) + body: Dict[str, Any] = {"properties": {"hardware": {"vmSize": request.vm_size}}} + # ado-telescope verbatim envelope shape (azure.py:1268-1298). The Machine + # API expects: + # - batchMachines[].machineName (NOT "name") — using the wrong key + # causes the API to silently ignore the entries, creating only the + # URL-pointed machine. This was the root cause of build 66357 + # reporting succeeded=true but only 100/200 (== worker count) ready. + # - batchMachines lists ONLY the *additional* machines; the first one + # is created from the URL + body. + # - vmSkus is a {"value": []} envelope, not a flat list. + remaining_machines = chunk[1:] + batch_machines = [{"machineName": name} for name in remaining_machines] + vm_sku = { + "name": request.vm_size, + "resourceType": "virtualMachines", + "family": "standardDv3Family", + "locations": ["westus", "eastus", "westeurope"], + "capabilities": [ + {"name": "vCPUs", "value": "2"}, + {"name": "MemoryGB", "value": "8"}, + ], + "restrictions": [], + } + batch_header_value = json.dumps({ + "vmSkus": {"value": [vm_sku]}, + "batchMachines": batch_machines, + }) + logger.info( + f"chunk {chunk_idx}: submitting BatchPutMachine PUT for {len(chunk)} machines " + f"(target={first_machine_name})" + ) + self._make_batch_request( + "PUT", url, body, request.timeout, batch_header_value=batch_header_value, + ) + return list(chunk) + + def _make_batch_request( + self, + method: str, + url: str, + data: Dict[str, Any], + timeout: int, + batch_header_value: str, + ) -> None: + """Send a ``BatchPutMachine``-headered request with bounded 429 backoff. + + Sends the request directly (NOT via ``make_request``) so we can attach + the ``BatchPutMachine`` header alongside the standard auth/content-type + headers. Retries on HTTP 429 up to ``_BATCH_429_MAX_RETRIES`` attempts + with exponential backoff starting at + ``_BATCH_429_INITIAL_BACKOFF_SECONDS`` and doubling each attempt + (1s, 2s, 4s by default). All other non-2xx responses raise immediately. + """ + backoff = _BATCH_429_INITIAL_BACKOFF_SECONDS + last_resp: Optional[requests.Response] = None + for attempt in range(_BATCH_429_MAX_RETRIES): + headers = { + "Authorization": f"Bearer {self._get_access_token()}", + "Content-Type": "application/json", + "BatchPutMachine": batch_header_value, + } + resp = requests.request( + method, url, headers=headers, json=data, timeout=timeout, + ) + last_resp = resp + if resp.status_code in (200, 201, 202, 204): + return + if resp.status_code != 429: + raise RuntimeError( + f"batch request failed: {resp.status_code} {resp.text[:500]}" + ) + if attempt == _BATCH_429_MAX_RETRIES - 1: + break + logger.warning( + f"batch request 429; retrying in {backoff:.1f}s " + f"(attempt {attempt + 1}/{_BATCH_429_MAX_RETRIES})" + ) + time.sleep(backoff) + backoff *= 2 + text = last_resp.text[:500] if last_resp is not None else "" + raise RuntimeError( + f"batch request exceeded {_BATCH_429_MAX_RETRIES} 429 retries; last text={text}" + ) diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py new file mode 100644 index 0000000000..6a4e86c8c6 --- /dev/null +++ b/modules/python/tests/test_aks_machine_client.py @@ -0,0 +1,248 @@ +#!/usr/bin/env python3 +"""Unit tests for AKSMachineClient (subclass of AKSClient). + +Mirrors tests/clients/test_aks_client.py mocking patterns. All public methods +open an ``OperationContext`` (patched here) and write the result file via +``Operation.save_to_file`` on context exit. Tests verify: +- success path returns True and enriches ``op.add_metadata`` with the right keys +- failure path raises (so the OperationContext records ``success=False``) +- partial machine landing raises ``RuntimeError`` from ``scale_machine`` +""" +# pylint: disable=protected-access +# Several tests intentionally exercise the static helper ``_get_machine_name_prefix`` +# directly; the leading underscore is conventional rather than semantic privacy. +import os +import unittest +from unittest import mock + +from clients.aks_machine_client import AKSMachineClient + + +class TestAKSMachineClient(unittest.TestCase): + """Tests for the AKSMachineClient class.""" + + def setUp(self): + """Patch all upstream Azure SDK and OperationContext seams.""" + self.cs_client_patcher = mock.patch( + "clients.aks_client.ContainerServiceClient" + ) + self.mi_cred_patcher = mock.patch( + "clients.aks_client.ManagedIdentityCredential" + ) + self.k8s_client_patcher = mock.patch("clients.aks_client.KubernetesClient") + self.operation_context_patcher = mock.patch( + "crud.operation.OperationContext" + ) + + self.cs_client_patcher.start() + self.mi_cred_patcher.start() + mock_k8s_class = self.k8s_client_patcher.start() + self.mock_operation_context = self.operation_context_patcher.start() + + self.mock_k8s = mock_k8s_class.return_value + self.mock_operation = mock.MagicMock() + self.mock_operation_context.return_value.__enter__.return_value = ( + self.mock_operation + ) + self.mock_operation_context.return_value.__exit__.return_value = None + + self.test_result_dir = "/tmp/test_results" + os.makedirs(self.test_result_dir, exist_ok=True) + + self.client = AKSMachineClient( + subscription_id="fake-sub", + resource_group="fake-rg", + cluster_name="fake-cluster", + use_managed_identity=True, + result_dir=self.test_result_dir, + ) + + # Stub inherited helpers that the Machine methods enrich metadata with. + self.client.get_cluster_name = mock.MagicMock(return_value="fake-cluster") + self.client.get_cluster_data = mock.MagicMock( + return_value={"name": "fake-cluster"} + ) + fake_pool = mock.MagicMock() + fake_pool.as_dict.return_value = {"name": "fake-pool"} + self.client.get_node_pool = mock.MagicMock(return_value=fake_pool) + + def tearDown(self): + mock.patch.stopall() + + # ---- create_machine_agentpool ---- + + @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 \u2192 return True; metadata enriched.""" + mock_resp = mock.MagicMock() + mock_resp.status_code = 200 + mock_make_request.return_value = mock_resp + + result = self.client.create_machine_agentpool( + agentpool_name="apool", vm_size="Standard_D2_v3" + ) + + self.assertTrue(result) + 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"}}) + 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 \u2192 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 + + with self.assertRaises(RuntimeError): + self.client.create_machine_agentpool( + agentpool_name="apool", vm_size="Standard_D2_v3" + ) + + @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", + return_value=False) + @mock.patch.object(AKSMachineClient, "make_request") + def test_create_machine_agentpool_provisioning_timeout_raises( + self, mock_make_request, _mock_wait + ): + """PUT OK but provisioning never reaches Succeeded \u2192 RuntimeError.""" + mock_resp = mock.MagicMock() + mock_resp.status_code = 200 + mock_make_request.return_value = mock_resp + + with self.assertRaises(RuntimeError): + self.client.create_machine_agentpool( + agentpool_name="apool", vm_size="Standard_D2_v3" + ) + + # ---- scale_machine (non-batch path) ---- + + @mock.patch.object(AKSMachineClient, "_wait_for_machine_node_readiness") + @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", + return_value=True) + @mock.patch.object(AKSMachineClient, "_scale_machine_individually") + def test_scale_machine_non_batch_success( + self, mock_indiv, _mock_ap, mock_readiness + ): + """Non-batch: all machines land + percentiles met \u2192 True.""" + mock_indiv.return_value = ["scale2-machine-1", "scale2-machine-2"] + mock_readiness.return_value = { + "P100": {"target_nodes": 2, "elapsed_time_seconds": 42.0, + "percentage": 100, "success": True}, + } + + result = self.client.scale_machine( + agentpool_name="apool", vm_size="Standard_D2_v3", + scale_machine_count=2, + ) + + self.assertTrue(result) + metadata_keys = { + call.args[0] for call in self.mock_operation.add_metadata.call_args_list + } + self.assertIn("successful_machines", metadata_keys) + self.assertIn("percentile_node_readiness_times", metadata_keys) + self.assertIn("node_readiness_time", metadata_keys) + self.assertIn("cluster_info", metadata_keys) + self.assertNotIn("batch_command_execution_times", metadata_keys) + + @mock.patch.object(AKSMachineClient, "_wait_for_machine_node_readiness") + @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", + return_value=True) + @mock.patch.object(AKSMachineClient, "_scale_machine_individually") + def test_scale_machine_partial_landing_raises( + self, mock_indiv, _mock_ap, mock_readiness + ): + """Fewer machines landed than requested \u2192 RuntimeError.""" + mock_indiv.return_value = ["scale2-machine-1"] # only 1 of 2 + mock_readiness.return_value = { + "P100": {"target_nodes": 2, "elapsed_time_seconds": None, + "percentage": 100, "success": False}, + } + + with self.assertRaises(RuntimeError): + self.client.scale_machine( + agentpool_name="apool", vm_size="Standard_D2_v3", + scale_machine_count=2, + ) + + # ---- scale_machine (batch path) ---- + + @mock.patch.object(AKSMachineClient, "_wait_for_machine_node_readiness") + @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", + return_value=True) + @mock.patch.object(AKSMachineClient, "_scale_machine_batch") + def test_scale_machine_batch_success( + self, mock_batch, _mock_ap, mock_readiness + ): + """Batch: all chunks land + percentiles met \u2192 True + batch timings logged.""" + mock_batch.return_value = ( + ["scale2-machine-1", "scale2-machine-2"], + {"chunk_0": 1.5}, + ) + mock_readiness.return_value = { + "P100": {"target_nodes": 2, "elapsed_time_seconds": 99.0, + "percentage": 100, "success": True}, + } + + result = self.client.scale_machine( + agentpool_name="apool", vm_size="Standard_D2_v3", + scale_machine_count=2, use_batch_api=True, + ) + + self.assertTrue(result) + metadata_keys = { + call.args[0] for call in self.mock_operation.add_metadata.call_args_list + } + self.assertIn("batch_command_execution_times", metadata_keys) + + # ---- baseline behaviour ---- + + @mock.patch.object(AKSMachineClient, "_wait_for_machine_node_readiness") + @mock.patch.object(AKSMachineClient, "_wait_for_agentpool_provisioning", + return_value=True) + @mock.patch.object(AKSMachineClient, "_scale_machine_individually") + def test_scale_machine_passes_baseline_count_to_readiness( + self, mock_indiv, _mock_ap, mock_readiness + ): + """scale_machine snapshots baseline before PUT and forwards it to the watcher.""" + # Two pre-existing ready nodes already labelled with the agentpool. + self.mock_k8s.get_ready_nodes.return_value = [mock.MagicMock(), + mock.MagicMock()] + mock_indiv.return_value = ["scale1-machine-1"] + mock_readiness.return_value = { + "P100": {"target_nodes": 3, "elapsed_time_seconds": 1.0, + "percentage": 100, "success": True}, + } + + self.client.scale_machine( + agentpool_name="apool", vm_size="Standard_D2_v3", + scale_machine_count=1, + ) + + mock_readiness.assert_called_once() + self.assertEqual(mock_readiness.call_args.kwargs["baseline_count"], 2) + + # ---- _get_machine_name_prefix static helper ---- + + def test_machine_name_prefix_collapses_thousands(self): + self.assertEqual(AKSMachineClient._get_machine_name_prefix(1000), "scale1k") + self.assertEqual(AKSMachineClient._get_machine_name_prefix(3000), "scale3k") + + def test_machine_name_prefix_keeps_non_thousand_values(self): + self.assertEqual(AKSMachineClient._get_machine_name_prefix(1), "scale1") + self.assertEqual(AKSMachineClient._get_machine_name_prefix(500), "scale500") + self.assertEqual(AKSMachineClient._get_machine_name_prefix(1500), "scale1500") + + +if __name__ == "__main__": + unittest.main() From 806722e5443fc5f6cb0d2422d0e2e512a02fe1fd Mon Sep 17 00:00:00 2001 From: Karen Chen Date: Thu, 14 May 2026 13:12:08 -0700 Subject: [PATCH 2/2] address PR #1178 review comments Changes: - scale_machine: raise RuntimeError on !agentpool_ok or P100 success=False instead of silently returning True - PUT machine status check: accept 202 Accepted (ARM async semantics) in addition to 200/201 - _scale_machine_individually: clamp ThreadPoolExecutor workers to max(1, request.machine_workers) to prevent ValueError on <=0 - _scale_machine_individually docstring: clarify per-machine provisioningState is intentionally not polled (parity with batch path) - tests: replace hardcoded /tmp/test_results + os.makedirs with tempfile.TemporaryDirectory + tearDown cleanup - strip provenance/mirroring comments across both files; keep only WHY-rationale comments --- modules/python/clients/aks_machine_client.py | 82 ++++++++++--------- .../python/tests/test_aks_machine_client.py | 14 ++-- 2 files changed, 53 insertions(+), 43 deletions(-) diff --git a/modules/python/clients/aks_machine_client.py b/modules/python/clients/aks_machine_client.py index 18d1f92d62..bf27878e36 100644 --- a/modules/python/clients/aks_machine_client.py +++ b/modules/python/clients/aks_machine_client.py @@ -6,14 +6,10 @@ yet exposed in the Azure SDK. Public methods (``create_machine_agentpool``, ``scale_machine``) wrap their work -in ``OperationContext`` exactly like ``AKSClient.create_node_pool`` / -``AKSClient.scale_node_pool``: the context is opened inside the client method, +in ``OperationContext``: the context is opened inside the client method, metadata is enriched with ``op.add_metadata`` along the way, success returns True, failures are logged and re-raised so ``OperationContext`` records them. -``MachineCRUD`` therefore stays a thin try/except wrapper, mirroring -``crud/azure/node_pool_crud.py``. - -Ported from ado-telescope/modules/python/k8s/cloud_providers/azure.py. +``MachineCRUD`` therefore stays a thin try/except wrapper. """ import json import logging @@ -28,10 +24,10 @@ from clients.aks_client import AKSClient from utils.logger_config import get_logger, setup_logging -# Configure logging (mirrors clients/aks_client.py / crud/azure/node_pool_crud.py). +# Configure logging. setup_logging() logger = get_logger(__name__) -# Suppress noisy Azure SDK logs (mirror clients/aks_client.py). +# Suppress noisy Azure SDK logs. 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) @@ -39,8 +35,8 @@ _ARM_BASE = "https://management.azure.com" _ARM_SCOPE = "https://management.azure.com/.default" -_AGENTPOOL_API_VERSION = "2024-06-02-preview" # per ado azure.py — agentpool sub-resource -_MACHINE_API_VERSION = "2025-06-02-preview" # per ado azure.py — machines sub-resource +_AGENTPOOL_API_VERSION = "2024-06-02-preview" +_MACHINE_API_VERSION = "2025-06-02-preview" _POLL_INTERVAL_SECONDS = 10 _PROVISIONING_NONE_STATE_LIMIT = 5 _BATCH_429_MAX_RETRIES = 3 @@ -105,10 +101,9 @@ def create_machine_agentpool( ) -> bool: """Convert an existing agentpool to Machines mode via PUT. - Mirrors ``AKSClient.create_node_pool`` convention: opens an - ``OperationContext`` here, enriches metadata, returns True on success, - re-raises on failure (so the context records ``success=False`` with - traceback before the exception propagates to ``MachineCRUD``). + Opens an ``OperationContext`` here, enriches metadata, returns True on + success, re-raises on failure (so the context records ``success=False`` + with traceback before the exception propagates to ``MachineCRUD``). Args: agentpool_name: Target agentpool name. @@ -144,7 +139,9 @@ def create_machine_agentpool( ) body = {"properties": {"mode": "Machines"}} resp = self.make_request("PUT", url, data=body, timeout=timeout) - if resp.status_code not in (200, 201): + # 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]}" @@ -212,7 +209,7 @@ def _wait_for_machine_node_readiness( timeout: int, baseline_count: int = 0, ) -> Dict[str, Dict[str, Any]]: - """Wait for ``expected_count`` NEW Ready nodes; return ado-parity nested percentile dict. + """Wait for ``expected_count`` NEW Ready nodes; return nested percentile dict. AKS Machine ARM resource names (e.g. ``scale100-machine-1``) are NOT the same as the underlying k8s Node names (``aks---vmss``), so @@ -234,7 +231,7 @@ def _wait_for_machine_node_readiness( percentile target is met within ``timeout``. Polling exceptions are logged and treated as 0 ready this tick. Never raises. """ - # ado-parity empty-state envelope: nested dict per P-key with + # Empty-state envelope: nested dict per P-key with # `target_nodes`, `elapsed_time_seconds`, `percentage`, `success` so # the Kusto schema sees consistent shape regardless of outcome. empty_envelope: Dict[str, Dict[str, Any]] = { @@ -309,9 +306,8 @@ def _wait_for_machine_node_readiness( } for p in (50, 70, 90, 99, 100) } - # ado-parity stdout logging: percentile summary including P100, which is - # the wall-clock elapsed until ALL target nodes are Ready. This matches - # ado's `response.node_readiness_time = percentile_times[100]` exactly. + # Log percentile summary including P100, which is the wall-clock + # elapsed until ALL target nodes are Ready. logger.info(f"Node Readiness Percentile Summary for agentpool {agentpool_name}:") for p in (50, 70, 90, 99, 100): if p in elapsed: @@ -340,11 +336,10 @@ def scale_machine( ) -> bool: """Scale a Machine-mode agentpool by creating ``scale_machine_count`` machines. - Mirrors ``AKSClient.scale_node_pool`` convention: opens an - ``OperationContext`` here, enriches with successful machine names, - per-percentile readiness envelope, batch chunk timings, and the cluster - snapshot. Returns True iff every requested machine landed AND every - readiness percentile target was hit. Re-raises on failure so the + Opens an ``OperationContext`` here, enriches with successful machine + names, per-percentile readiness envelope, batch chunk timings, and the + cluster snapshot. Returns True iff every requested machine landed AND + every readiness percentile target was hit. Re-raises on failure so the context records the trace. Flow (both batch and non-batch): @@ -372,8 +367,7 @@ def scale_machine( "machine_workers": machine_workers, } # Bundle into a SimpleNamespace so the helpers retain the - # ``request.foo`` shape ported verbatim from ado-telescope without - # exposing yet another module-level data class. + # ``request.foo`` shape without exposing yet another module-level data class. request = SimpleNamespace( agentpool_name=agentpool_name, cluster_name=cluster_name, @@ -408,7 +402,6 @@ def scale_machine( "baseline node snapshot failed; readiness count may be inflated" ) - # Naming parity with ado-telescope. prefix = self._get_machine_name_prefix(scale_machine_count) names = [ f"{prefix}-machine-{i + 1}" for i in range(scale_machine_count) @@ -452,6 +445,17 @@ def scale_machine( raise RuntimeError( f"scale_machine landed {len(successful)}/{scale_machine_count} machines" ) + if not agentpool_ok: + raise RuntimeError( + f"agentpool {agentpool_name} did not reach Succeeded within {timeout}s" + ) + # P100 is the strictest readiness envelope (all target nodes + # Ready); if it succeeded, every lower percentile did too. + if not p100.get("success", False): + raise RuntimeError( + f"node readiness P100 did not complete within " + f"{readiness_wait_timeout}s for agentpool {agentpool_name}" + ) return True except Exception as e: logger.error(f"Failed to scale machine agentpool {agentpool_name}: {e}") @@ -460,11 +464,10 @@ def scale_machine( @staticmethod def _get_machine_name_prefix(scale_machine_count: int) -> str: - """Generate the ado-compatible machine-name prefix for a given scale count. + """Generate the machine-name prefix for a given scale count. - Mirrors ado-telescope ``azure.py::_get_machine_name_prefix`` exactly so - that the resulting machine ARM resource names match across repos and - cross-repo Kusto dashboards keyed on machine name continue to correlate. + The prefix is part of the machine ARM resource name; cross-repo Kusto + dashboards key on machine name, so this scheme is kept stable. - ``scale1000`` -> ``scale1k`` (any multiple of 1000 >= 1000 collapses) - ``scale500`` -> ``scale500`` @@ -480,12 +483,17 @@ def _scale_machine_individually( """Submit per-machine PUTs concurrently via ThreadPoolExecutor. Each worker calls ``_create_single_machine(name, request)`` which PUTs - the machine and waits for its provisioning to terminate. Returns the - list of names that reported True. Per-machine exceptions are logged - and treated as failure (name omitted from result). + the machine and returns True on any 2xx response. 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 + treated as failure (name omitted from result). """ successful: List[str] = [] - with ThreadPoolExecutor(max_workers=request.machine_workers) as ex: + # Clamp workers to >=1 so a misconfigured request (0 or negative) cannot + # crash ThreadPoolExecutor with ValueError. Matches the batch path. + with ThreadPoolExecutor(max_workers=max(1, request.machine_workers)) as ex: futures = {ex.submit(self._create_single_machine, n, request): n for n in names} for fut in as_completed(futures): n = futures[fut] @@ -615,7 +623,7 @@ def _create_batch_machines( f"?api-version={_MACHINE_API_VERSION}" ) body: Dict[str, Any] = {"properties": {"hardware": {"vmSize": request.vm_size}}} - # ado-telescope verbatim envelope shape (azure.py:1268-1298). The Machine + # AKS Batch Machine API envelope shape. The Machine # API expects: # - batchMachines[].machineName (NOT "name") — using the wrong key # causes the API to silently ignore the entries, creating only the diff --git a/modules/python/tests/test_aks_machine_client.py b/modules/python/tests/test_aks_machine_client.py index 6a4e86c8c6..998ab50d08 100644 --- a/modules/python/tests/test_aks_machine_client.py +++ b/modules/python/tests/test_aks_machine_client.py @@ -1,9 +1,8 @@ #!/usr/bin/env python3 """Unit tests for AKSMachineClient (subclass of AKSClient). -Mirrors tests/clients/test_aks_client.py mocking patterns. All public methods -open an ``OperationContext`` (patched here) and write the result file via -``Operation.save_to_file`` on context exit. Tests verify: +All public methods open an ``OperationContext`` (patched here) and write the +result file via ``Operation.save_to_file`` on context exit. Tests verify: - success path returns True and enriches ``op.add_metadata`` with the right keys - failure path raises (so the OperationContext records ``success=False``) - partial machine landing raises ``RuntimeError`` from ``scale_machine`` @@ -11,7 +10,7 @@ # pylint: disable=protected-access # Several tests intentionally exercise the static helper ``_get_machine_name_prefix`` # directly; the leading underscore is conventional rather than semantic privacy. -import os +import tempfile import unittest from unittest import mock @@ -46,8 +45,10 @@ def setUp(self): ) self.mock_operation_context.return_value.__exit__.return_value = None - self.test_result_dir = "/tmp/test_results" - os.makedirs(self.test_result_dir, exist_ok=True) + # Hermetic per-test temp dir avoids cross-platform /tmp assumptions + # and parallel-run collisions. + self._tmp_dir = tempfile.TemporaryDirectory() + self.test_result_dir = self._tmp_dir.name self.client = AKSMachineClient( subscription_id="fake-sub", @@ -68,6 +69,7 @@ def setUp(self): def tearDown(self): mock.patch.stopall() + self._tmp_dir.cleanup() # ---- create_machine_agentpool ----