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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Empty file.
76 changes: 76 additions & 0 deletions modules/python/machine/data_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
"""Data classes for the Machine API perf test.

Differences from ado-telescope's k8s/data_classes.py:
- OperationNames is an Enum (not @dataclass(frozen=True)).
- cloud_data typed as Optional[Dict] (truthful).
- Dropped dead types: BaseConfig, MachineRequestBase, CreateMachineRequest, DeleteMachineRequest.
- Dropped unused fields: api_response, time, feature_name.
"""
from dataclasses import dataclass, field
from enum import Enum
from typing import Any, Dict, List, Optional


class OperationNames(str, Enum):
"""String enum of supported Machine API CRUD operations."""
CREATE_MACHINE = "create_machine"
SCALE_MACHINE = "scale_machine"


# Disable too-many-instance-attributes: this is a flat configuration record that
# mirrors CLI flags 1:1. Splitting it would just reintroduce wrappers.
@dataclass
class MachineConfig: # pylint: disable=too-many-instance-attributes
"""Top-level run configuration for a Machine API perf invocation."""
cloud: str
cluster_name: str
resource_group: str
agentpool_name: str
vm_size: str
timeout: int
result_dir: str
readiness_wait_timeout: int = 1200
region: Optional[str] = None
operation: Optional[str] = None
tags: Optional[Dict[str, str]] = None
machine_name: Optional[str] = None
scale_machine_count: int = 0
use_batch_api: bool = False
machine_workers: int = 1


# Disable too-many-instance-attributes: 10 fields all map to ARM Machine PUT body
# inputs; bundling them would just shift the noise.
@dataclass
class ScaleMachineRequest: # pylint: disable=too-many-instance-attributes
"""Request payload for scaling an agent pool by creating N Machine resources."""
cluster_name: str
resource_group: str
agentpool_name: str
vm_size: str
scale_machine_count: int
use_batch_api: bool
machine_workers: int
timeout: int = 300
readiness_wait_timeout: int = 1200
tags: Optional[Dict[str, str]] = None
machine_name: Optional[str] = None


# Disable too-many-instance-attributes: this dataclass is the on-disk JSON
# schema; reducing fields would silently drop telemetry columns.
@dataclass
class MachineOperationResponse: # pylint: disable=too-many-instance-attributes
"""Per-operation response written to disk and aggregated by collect.py."""
operation_name: str
succeeded: bool = False
start_time: Optional[str] = None
end_time: Optional[str] = None
error: str = ""
command_execution_time: float = 0
node_readiness_time: float = 0
successful_machines: List[str] = field(default_factory=list)
percentile_node_readiness_times: Dict[str, Dict[str, Any]] = field(default_factory=dict)
batch_command_execution_times: Dict[str, float] = field(default_factory=dict)
cloud_data: Optional[Dict] = None
warning_message: Optional[str] = None
55 changes: 55 additions & 0 deletions modules/python/machine/result_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
"""Persist per-operation results to JSON.

Differences from ado-telescope's k8s/result_handler.py:
- Output is a NESTED dict {"config": ..., "response": ...}
(not flat **-spread that overwrites overlapping keys).
- UTC timestamp in filename.
- Uses utils.common.save_info_to_file when feasible.
"""
import functools
import os
from dataclasses import asdict, is_dataclass
from datetime import datetime, timezone

from utils.common import save_info_to_file
from utils.logger_config import get_logger

logger = get_logger(__name__)


def _serialize(obj):
"""Convert dataclasses to dicts; pass everything else through unchanged."""
if is_dataclass(obj):
return asdict(obj)
return obj


def save_test_result(func):
"""Decorator that writes the wrapped method's response to a JSON file.

The file path is derived from ``self.config`` (cloud / cluster_name /
machine_name|agentpool_name) plus a UTC unix timestamp. Persistence
failures are logged but never propagated, so test orchestration is
insulated from disk errors.
"""
@functools.wraps(func)
def wrapper(self, *args, **kwargs):
response = func(self, *args, **kwargs)
try:
config = self.config
op_name = response.operation_name
suffix = config.machine_name or config.agentpool_name
timestamp = int(datetime.now(timezone.utc).timestamp())
filename = f"{op_name}-{config.cloud}-{config.cluster_name}-{suffix}-{timestamp}.json"
path = os.path.join(config.result_dir, filename)
Comment on lines +40 to +44
os.makedirs(config.result_dir, exist_ok=True)
Comment on lines +41 to +45
payload = {
"config": _serialize(config),
"response": _serialize(response),
}
save_info_to_file(payload, path)
logger.info("Wrote result to %s", path)
except Exception as exc: # pylint: disable=broad-except
logger.warning("Failed to save result: %s", exc)
Comment on lines +50 to +53
return response
return wrapper
41 changes: 41 additions & 0 deletions modules/python/tests/test_machine_data_classes.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
from machine.data_classes import (
MachineConfig, ScaleMachineRequest, MachineOperationResponse, OperationNames,
)

def test_operation_names_is_enum_with_required_values():
assert OperationNames.CREATE_MACHINE.value == "create_machine"
assert OperationNames.SCALE_MACHINE.value == "scale_machine"

def test_machine_config_defaults():
cfg = MachineConfig(
cloud="azure", cluster_name="c", resource_group="rg",
agentpool_name="ap", vm_size="Standard_D2_v3",
timeout=600, result_dir="/tmp/x",
)
assert cfg.scale_machine_count == 0
assert cfg.use_batch_api is False
assert cfg.machine_workers == 1
assert cfg.region is None
assert cfg.operation is None
assert cfg.tags is None
assert cfg.machine_name is None

def test_machine_operation_response_defaults_have_correct_types():
r = MachineOperationResponse(operation_name="scale_machine")
assert r.succeeded is False
assert r.successful_machines == []
assert r.percentile_node_readiness_times == {}
assert r.batch_command_execution_times == {}
assert r.command_execution_time == 0
assert r.node_readiness_time == 0
assert r.cloud_data is None # dict | None, not str

def test_scale_machine_request_required_fields():
req = ScaleMachineRequest(
cluster_name="c", resource_group="rg", agentpool_name="ap",
vm_size="Standard_D2_v3", scale_machine_count=5,
use_batch_api=False, machine_workers=2,
)
assert req.timeout == 300
assert req.tags is None
assert req.machine_name is None
78 changes: 78 additions & 0 deletions modules/python/tests/test_machine_result_handler.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
import json
import logging
import os
import glob
from unittest.mock import patch

from machine.data_classes import MachineConfig, MachineOperationResponse
from machine.result_handler import save_test_result


class _FakeMgr:
"""Minimal stand-in for MachineManager exposing only ``config``."""
def __init__(self, config):
self.config = config


def test_save_test_result_writes_nested_dict(tmp_path):
cfg = MachineConfig(
cloud="azure", cluster_name="cl", resource_group="rg",
agentpool_name="ap", vm_size="Standard_D2_v3",
timeout=600, result_dir=str(tmp_path),
machine_name="m1",
)

@save_test_result
def fake_op(self): # pylint: disable=unused-argument
return MachineOperationResponse(
operation_name="scale_machine",
succeeded=True,
command_execution_time=12.5,
)

fake_op(_FakeMgr(cfg))
files = glob.glob(str(tmp_path / "scale_machine-*.json"))
assert len(files) == 1
with open(files[0], encoding="utf-8") as fh:
payload = json.loads(fh.read())
# Nested, not flat-merged. Distinct keys preserved.
assert "config" in payload and "response" in payload
assert payload["config"]["cloud"] == "azure"
assert payload["response"]["operation_name"] == "scale_machine"
assert payload["response"]["succeeded"] is True
# Filename includes operation, cloud, cluster, machine_name.
assert "scale_machine-azure-cl-m1-" in os.path.basename(files[0])


def test_save_test_result_uses_agentpool_when_no_machine_name(tmp_path):
cfg = MachineConfig(
cloud="azure", cluster_name="cl", resource_group="rg",
agentpool_name="apool", vm_size="x", timeout=1, result_dir=str(tmp_path),
)

@save_test_result
def fake(self): # pylint: disable=unused-argument
return MachineOperationResponse(operation_name="create_machine", succeeded=True)

fake(_FakeMgr(cfg))
fs = glob.glob(str(tmp_path / "create_machine-*.json"))
assert any("create_machine-azure-cl-apool-" in os.path.basename(f) for f in fs)


def test_save_test_result_swallows_write_errors(tmp_path, caplog):
cfg = MachineConfig(
cloud="azure", cluster_name="cl", resource_group="rg",
agentpool_name="ap", vm_size="x", timeout=1, result_dir=str(tmp_path),
machine_name="m1",
)

@save_test_result
def fake(self): # pylint: disable=unused-argument
return MachineOperationResponse(operation_name="scale_machine", succeeded=True)

with patch("machine.result_handler.save_info_to_file", side_effect=OSError("disk full")):
with caplog.at_level(logging.WARNING, logger="machine.result_handler"):
response = fake(_FakeMgr(cfg))

assert response.operation_name == "scale_machine"
assert any("Failed to save result" in rec.message for rec in caplog.records)
Loading