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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions modules/python/clients/aks_machine_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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):
Expand All @@ -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:
Expand Down
86 changes: 86 additions & 0 deletions modules/python/crud/azure/machine_crud.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,86 @@
"""
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),
Comment thread
karenychen marked this conversation as resolved.
Resolved
)
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:
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

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:
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,
)
Comment thread
karenychen marked this conversation as resolved.
Resolved
return True
except Exception as e:
logger.error(f"scale_machine failed for {agentpool_name}: {e}")
return False
145 changes: 145 additions & 0 deletions modules/python/crud/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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")
Expand Down Expand Up @@ -208,6 +223,53 @@ def handle_node_pool_all(node_pool_crud, args):
return 1


def handle_machine_operation(machine_crud, args):
Comment thread
karenychen marked this conversation as resolved.
Resolved
"""Handle machine API operations (create-machine, scale-machine) based on the command."""
command = args.command
result = None

try:
if command == "create-machine":
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):
try:
tags = json.loads(args.tags)
except (ValueError, TypeError) as e:
logger.warning(f"Failed to parse --tags {args.tags!r} as JSON: {e}")

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
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.
Expand All @@ -218,6 +280,66 @@ 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(
"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.
Expand Down Expand Up @@ -386,6 +508,12 @@ def main():
)
deployment_parser.set_defaults(func=handle_workload_operations)

# Create-machine command (AKS Machine API)
_add_create_machine_subparser(subparsers, common_parser)

# Scale-machine command (AKS Machine API)
_add_scale_machine_subparser(subparsers, common_parser)

Comment thread
karenychen marked this conversation as resolved.
Resolved
# Arguments provided, run node pool operations and collect benchmark results
try:
args = parser.parse_args()
Expand All @@ -404,6 +532,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"
Expand Down
14 changes: 14 additions & 0 deletions modules/python/tests/test_aks_machine_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading
Loading