Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
47a8919
Enable Entra authentication by default for Terraform AKS pipelines
LeonardCareer Nov 18, 2026
294ea09
Simplify Entra authentication changes following review
LeonardCareer Nov 18, 2026
2aaca1a
Limit Entra changes to authentication requirements
LeonardCareer Nov 18, 2026
1415209
Call existing kubelogin setup explicitly from Azure topologies
LeonardCareer Nov 18, 2026
732259d
Add opt-in in-cluster CL2 execution for the AzureLinux pilot
LeonardCareer Nov 19, 2026
e64bcb4
Preserve raw CL2 logs without UTF-8 decoding
LeonardCareer Nov 19, 2026
77ee4c9
Simplify CL2 pilot to a Job and preserve report collection
LeonardCareer Nov 19, 2026
42c3328
Use Azure Pipelines authentication for Docker-hosted CL2
LeonardCareer Nov 19, 2026
4e69d83
Pass Azure client ID to CL2 kubelogin at runtime
LeonardCareer Nov 19, 2026
6b7d0e8
Enable Azure Pipelines authentication for scheduling CL2 runs
LeonardCareer Nov 19, 2026
c1e62ed
Centralize Azure kubelogin setup in setup-kubeconfig template
LeonardCareer Nov 19, 2026
f4010a6
Run Azure ClusterLoader2 benchmarks as Kubernetes Jobs
LeonardCareer Nov 19, 2026
950a114
Unify kubeconfig setup template names across clouds
LeonardCareer Nov 19, 2026
50c301a
Keep original kubeconfig template names and simplify callers
LeonardCareer Nov 19, 2026
12f3408
Always disable AKS local accounts across provisioning paths
LeonardCareer Nov 19, 2026
10b374f
Simplify CL2 Job diagnostics and preserve config path formatting
LeonardCareer Nov 19, 2026
0b2c5de
Install AKS CLI tools with required system directory permissions
LeonardCareer Nov 19, 2026
401da89
Allow Azure CL2 Jobs on schedulable Linux nodes
LeonardCareer Nov 19, 2026
ba084f1
Fix Python lint issues in CL2 Job execution
LeonardCareer Nov 20, 2026
abcdf15
Address review feedback and run CL2 Jobs across providers
LeonardCareer Nov 20, 2026
87c05c4
Remove added CL2 in-cluster test file
LeonardCareer Nov 20, 2026
fa5a682
Improve readability of CL2 Job resource definitions
LeonardCareer Nov 20, 2026
bf3131e
Name CL2 script by its run and collection purpose
LeonardCareer Nov 20, 2026
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
230 changes: 230 additions & 0 deletions modules/python/clusterloader2/in_cluster.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,230 @@
import base64
Comment thread
wonderyl marked this conversation as resolved.
Resolved
from functools import partial
import json
from pathlib import Path
import subprocess
import time
import uuid


def _kubectl(kubeconfig, namespace, *args, check=True, stdout=subprocess.PIPE, stdin=None):
# A command can span multiple 30s API requests (e.g. wait for 90s or copy reports).
result = subprocess.run(
["kubectl", "--kubeconfig", kubeconfig, "--request-timeout=30s", "-n", namespace, *args],
input=stdin, stdout=stdout, stderr=subprocess.PIPE, timeout=120, check=False,
)
if check and result.returncode:
raise RuntimeError(f"kubectl {' '.join(args)}: {result.stderr.decode(errors='replace')}")
return result


def run_cl2_job(kubeconfig, image, config_dir, report_dir, arguments):
"""Keep reports available until copied; publish-results returns the saved exit status."""
report_dir = Path(report_dir).resolve()
report_dir.mkdir(parents=True, exist_ok=True)
name = f"cl2-driver-{uuid.uuid4().hex[:12]}"
status_file = report_dir / f"{name}.exit-code"
status_file.write_text("1", encoding="ascii")
exit_code, pod, created = 1, None, False

kubectl = partial(_kubectl, kubeconfig, name)
config_maps, sources = [], []
for path in sorted(Path(config_dir).rglob("*")):
if path.is_file():
content = path.read_bytes()
if len(content) > 1048576:
raise ValueError(f"CL2 config file exceeds the ConfigMap 1 MiB limit: {path}")
config_name = f"{name}-config-{len(config_maps)}"
config_maps.append({
"apiVersion": "v1",
"kind": "ConfigMap",
"metadata": {"name": config_name},
"binaryData": {"config": base64.b64encode(content).decode("ascii")},
})
sources.append({
"configMap": {
"name": config_name,
"items": [{
"key": "config",
"path": path.relative_to(config_dir).as_posix(),
}],
},
})
if not config_maps:
raise ValueError("CL2 configuration must be nonempty")

timeout = 86400
root = "/root/perf-tests/clusterloader2"
run_and_collect_script = '''./clusterloader2 "$@"
rc=$?
printf '%s\\n' "$rc" > /cl2-control/exit-code.tmp
mv /cl2-control/exit-code.tmp /cl2-control/exit-code || exit 1
for i in $(seq 1 300); do
test -f /cl2-control/reports-collected && exit "$rc"
sleep 2
done
echo "Report collection timed out" >&2
exit 124
'''
resources = [
{
"apiVersion": "v1",
"kind": "ServiceAccount",
"metadata": {"name": name},
},
# CL2 installs CRDs and Prometheus RBAC across this disposable test cluster.
{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRole",
"metadata": {"name": name},
"rules": [
{
"apiGroups": ["*"],
"resources": ["*"],
"verbs": ["*"],
},
{
"nonResourceURLs": ["/metrics"],
"verbs": ["get"],
},
],
},
{
"apiVersion": "rbac.authorization.k8s.io/v1",
"kind": "ClusterRoleBinding",
"metadata": {"name": name},
"roleRef": {
"apiGroup": "rbac.authorization.k8s.io",
"kind": "ClusterRole",
"name": name,
},
"subjects": [{
"kind": "ServiceAccount",
"name": name,
"namespace": name,
}],
},
*config_maps,
{
"apiVersion": "batch/v1",
"kind": "Job",
"metadata": {"name": name},
"spec": {
"backoffLimit": 0,
"activeDeadlineSeconds": timeout + 600,
"template": {
"spec": {
"serviceAccountName": name,
"restartPolicy": "Never",
"nodeSelector": {"kubernetes.io/os": "linux"},
"containers": [{
"name": "cl2",
"image": image,
"command": ["/bin/sh", "-c"],
"args": [run_and_collect_script, "cl2", *arguments],
"resources": {
"requests": {
"cpu": "1",
"memory": "2Gi",
},
},
"volumeMounts": [
{
"name": "config",
"mountPath": f"{root}/config",
"readOnly": True,
},
{
"name": "reports",
"mountPath": f"{root}/results",
},
{
"name": "control",
"mountPath": "/cl2-control",
},
],
}],
"volumes": [
{
"name": "config",
"projected": {"sources": sources},
},
{
"name": "reports",
"emptyDir": {},
},
{
"name": "control",
"emptyDir": {},
},
],
},
},
},
},
]
try:
kubectl("create", "namespace", name)
created = True
kubectl("create", "-f", "-", stdin=json.dumps(
{
"apiVersion": "v1",
"kind": "List",
"items": resources,
}).encode())
deadline = time.monotonic() + timeout
startup_deadline = time.monotonic() + 300
started = False
while time.monotonic() < deadline:
pods = json.loads(kubectl("get", "pods", "-l", f"job-name={name}", "-o", "json").stdout)["items"]
if pods:
pod = pods[0]["metadata"]["name"]
phase = pods[0].get("status", {}).get("phase")
if phase in ("Failed", "Succeeded"):
raise RuntimeError(f"CL2 Pod {pod} terminated before report collection")
if phase == "Pending":
kubectl("wait", "--for=condition=PodScheduled", f"pod/{pod}", "--timeout=90s")
if phase == "Running":
started = True
result = kubectl("exec", pod, "--", "cat", "/cl2-control/exit-code", check=False)
if result.returncode:
time.sleep(5)
continue
code = int(result.stdout)
if not 0 <= code <= 255:
raise ValueError(f"Invalid CL2 exit code: {code}")
kubectl("cp", f"{pod}:{root}/results/.", str(report_dir))
if code == 0:
kubectl("exec", pod, "--", "test", "-s", f"{root}/results/junit.xml")
kubectl("exec", pod, "--", "touch", "/cl2-control/reports-collected")
kubectl("wait", f"--for=jsonpath={{.status.containerStatuses[0].state.terminated.exitCode}}={code}",
f"pod/{pod}", "--timeout=60s")
exit_code = code
break
elif pod:
raise RuntimeError(f"CL2 Pod {pod} disappeared before report collection")
if not started and time.monotonic() >= startup_deadline:
raise TimeoutError("CL2 Pod did not start within five minutes")
time.sleep(5)
else:
exit_code = 124
raise TimeoutError("CL2 Job timed out")
finally:
if pod:
try:
with (report_dir / f"{name}.log").open("wb") as output:
result = kubectl("logs", pod, stdout=output, check=False)
if result.returncode:
print(f"Warning: CL2 log collection failed: {result.stderr.decode(errors='replace')}")
except (OSError, subprocess.TimeoutExpired) as error:
print(f"Warning: CL2 log collection failed: {error}")
if created:
try:
kubectl("delete", "namespace,clusterrole,clusterrolebinding", name,
"--ignore-not-found", "--wait=false")
except (OSError, RuntimeError, subprocess.TimeoutExpired) as error:
print(f"CL2 cleanup failed; cluster teardown is required: {error}")
exit_code = exit_code or 1
status_file.write_text(str(exit_code), encoding="ascii")
print(f"CL2 Job exited {exit_code}; reports and status saved to {report_dir}")
return exit_code
41 changes: 4 additions & 37 deletions modules/python/clusterloader2/utils.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
from xml.dom import minidom
import json
import os
import docker
from clients.docker_client import DockerClient
import shlex
from clusterloader2.in_cluster import run_cl2_job
from utils.logger_config import get_logger, setup_logging

setup_logging()
Expand All @@ -26,13 +26,10 @@
def run_cl2_command(kubeconfig, cl2_image, cl2_config_dir, cl2_report_dir, provider, cl2_config_file="config.yaml", overrides=False, enable_prometheus=False, tear_down_prometheus=True,
enable_exec_service=False, scrape_kubelets=False,
scrape_containerd=False, scrape_ksm=False, scrape_metrics_server=False):
docker_client = DockerClient()

command = f"""--provider={provider} --v=2
--enable-exec-service={enable_exec_service}
--enable-prometheus-server={enable_prometheus}
--prometheus-scrape-kubelets={scrape_kubelets}
--kubeconfig /root/.kube/config
--testconfig /root/perf-tests/clusterloader2/config/{cl2_config_file}
--report-dir /root/perf-tests/clusterloader2/results
--tear-down-prometheus-server={tear_down_prometheus}
Expand All @@ -45,38 +42,8 @@ def run_cl2_command(kubeconfig, cl2_image, cl2_config_dir, cl2_report_dir, provi
if overrides:
command += " --testoverrides=/root/perf-tests/clusterloader2/config/overrides.yaml"

volumes = {
kubeconfig: {'bind': '/root/.kube/config', 'mode': 'rw'},
cl2_config_dir: {'bind': '/root/perf-tests/clusterloader2/config', 'mode': 'rw'},
cl2_report_dir: {
'bind': '/root/perf-tests/clusterloader2/results', 'mode': 'rw'}
}

if provider == "aws":
aws_path = os.path.expanduser("~/.aws/credentials")
volumes[aws_path] = {'bind': '/root/.aws/credentials', 'mode': 'rw'}

if provider == "aks":
azure_path = os.path.expanduser("~/.azure")
volumes[azure_path] = {'bind': '/root/.azure', 'mode': 'rw'}

logger.info(
f"Running clusterloader2 with command: {command} and volumes: {volumes}")
try:
container = docker_client.run_container(
cl2_image, command, volumes, detach=True)
for log in container.logs(stream=True):
log_line = log.decode('utf-8').rstrip('\n')
if log_line:
logger.info(log_line)
result = container.wait()
exit_code = result['StatusCode']
if exit_code != 0:
logger.error(
f"clusterloader2 exited with a non-zero status code {exit_code}. Make sure to check the logs to confirm whether the error is expected!")
except docker.errors.ContainerError as e:
logger.error(
f"Container exited with a non-zero status code: {e.exit_status}\n{e.stderr.decode('utf-8')}")
return run_cl2_job(kubeconfig, cl2_image, cl2_config_dir, cl2_report_dir,
shlex.split(command) + ["--run-from-cluster=true"])


def get_measurement(file_path):
Expand Down
4 changes: 2 additions & 2 deletions modules/terraform/azure/aks-cli/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -149,11 +149,11 @@ locals {
aad_parameter = (
var.aks_aad_enabled == true ?
format(
"--enable-aad --enable-azure-rbac --aad-admin-group-object-ids %s --aad-tenant-id %s",
"--enable-aad --enable-azure-rbac --aad-admin-group-object-ids %s --aad-tenant-id %s --disable-local-accounts",
data.azurerm_client_config.current.object_id,
data.azurerm_client_config.current.tenant_id
)
: ""
: "--disable-local-accounts"
)

custom_configurations = (
Expand Down
3 changes: 1 addition & 2 deletions modules/terraform/azure/aks-cli/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ variable "disk_encryption_sets" {
variable "aks_aad_enabled" {
description = "Indicates whether Azure Active Directory integration is enabled for AKS"
type = bool
default = false
default = true
}

variable "acr_pull_scopes_map" {
Expand Down Expand Up @@ -118,4 +118,3 @@ variable "aks_cli_config" {
disk_encryption_set_name = optional(string, null) # Name of the Disk Encryption Set to use for OS disk encryption
})
}

1 change: 1 addition & 0 deletions modules/terraform/azure/aks/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ resource "azurerm_kubernetes_cluster" "aks" {
workload_identity_enabled = var.aks_config.workload_identity_enabled
kubernetes_version = var.aks_config.kubernetes_version
edge_zone = var.aks_config.edge_zone
local_account_disabled = true

dynamic "azure_active_directory_role_based_access_control" {
for_each = var.aks_aad_enabled == true ? [1] : []
Expand Down
2 changes: 1 addition & 1 deletion modules/terraform/azure/aks/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,7 @@ variable "network_dataplane" {
variable "aks_aad_enabled" {
description = "Indicates whether Azure Active Directory integration is enabled for AKS"
type = bool
default = false
default = true
}

variable "key_vaults" {
Expand Down
11 changes: 6 additions & 5 deletions modules/terraform/azure/azapi/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,12 @@ locals {

properties = {
for k, v in {
kubernetesVersion = var.azapi_config.kubernetes_version
dnsPrefix = var.azapi_config.dns_prefix
agentPoolProfiles = local.agent_pool_profiles
networkProfile = local.network_profile
enableRBAC = var.azapi_config.aad_enabled ? true : null
kubernetesVersion = var.azapi_config.kubernetes_version
dnsPrefix = var.azapi_config.dns_prefix
agentPoolProfiles = local.agent_pool_profiles
networkProfile = local.network_profile
enableRBAC = var.azapi_config.aad_enabled ? true : null
disableLocalAccounts = true
aadProfile = var.azapi_config.aad_enabled ? {
managed = true
enableAzureRBAC = true
Expand Down
4 changes: 2 additions & 2 deletions modules/terraform/azure/azapi/variables.tf
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,13 @@ variable "tags" {
}

variable "azapi_config" {
description = "Configuration for creating an AKS cluster via Azure REST API (AzAPI provider). aad_enabled opts into managed Microsoft Entra ID integration and Azure RBAC for Kubernetes authorization."
description = "Configuration for creating an AKS cluster via Azure REST API (AzAPI provider). aad_enabled defaults to managed Microsoft Entra ID integration and Azure RBAC for Kubernetes authorization."
type = object({
role = string
aks_name = string
dns_prefix = string
api_version = optional(string, "2025-10-01")
aad_enabled = optional(bool, false)
aad_enabled = optional(bool, true)
metrics_reader_enabled = optional(bool, false)

sku = optional(object({
Expand Down
2 changes: 1 addition & 1 deletion modules/terraform/azure/main.tf
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ locals {
aks_custom_headers = lookup(var.json_input, "aks_custom_headers", [])
k8s_machine_type = lookup(var.json_input, "k8s_machine_type", null)
k8s_os_disk_type = lookup(var.json_input, "k8s_os_disk_type", null)
aks_aad_enabled = lookup(var.json_input, "aks_aad_enabled", false)
aks_aad_enabled = lookup(var.json_input, "aks_aad_enabled", true)
enable_apiserver_vnet_integration = lookup(var.json_input, "enable_apiserver_vnet_integration", false)
public_key_path = lookup(var.json_input, "public_key_path", null)
ssh_public_key = local.public_key_path != null ? (fileexists(local.public_key_path) ? file(local.public_key_path) : null) : null
Expand Down
Loading
Loading