Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
39297df
feat: add statefulset workload to CRUD module
diamondpowell May 4, 2026
896d146
feat: wire statefulset through pipeline topology
diamondpowell May 4, 2026
fad0343
test: add unit tests for statefulset CRUD operations
diamondpowell May 4, 2026
aac5e7f
test: configure pipeline for statefulset workload validation
diamondpowell May 5, 2026
aa1dd05
refactor: align statefulset with deployment patterns from merged PR
diamondpowell May 14, 2026
b8c17b6
fix: gate statefulset step to Azure-only and use conditional manifest…
diamondpowell May 14, 2026
2db2b31
fix: correct docstring to list supported workload types
diamondpowell May 14, 2026
8648753
fix: remove trailing whitespace in test file
diamondpowell May 14, 2026
19e5aaa
test: populate pipeline test config for statefulset validation
diamondpowell May 14, 2026
6f54c8e
fix: use k8s-crud-gpu topology (k8s-crud doesn't exist)
diamondpowell May 14, 2026
4e5c53d
fix: use existing perf-eval scenario for pipeline test
diamondpowell May 15, 2026
3e09fe0
fix: add gpu_node_pool to test config and fix workload label collision
diamondpowell May 15, 2026
cd7bd00
revert: restore pipeline test placeholder before merge
diamondpowell May 15, 2026
db3d34c
dropping the > 0 guard so scale-to-zero workloads behave correctly.
diamondpowell May 26, 2026
54ec06c
Simplify YAML parameters per reviewer feedback
diamondpowell May 26, 2026
033e18a
Merge main into dipowell/crud-statefulset
diamondpowell May 26, 2026
fc7adf9
Add WORKLOAD_CONFIG for unified workload helper
praneelseth May 27, 2026
9d841d9
Refactor: add unified _apply_workload helper for deployment/statefulset
diamondpowell May 27, 2026
3396ec1
Refactor: add unified _create_workloads helper for deployment/statefu…
diamondpowell May 27, 2026
f84cf84
Refactor: reorder workload methods - public first, helpers last
diamondpowell May 27, 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
37 changes: 36 additions & 1 deletion modules/python/clients/kubernetes_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -975,7 +975,8 @@ def wait_for_condition(self, resource_type: str, wait_condition_type: str, names
valid_conditions = {
'deployment': ['available', 'progressing', 'replicafailure', 'ready'],
'deployments': ['available', 'progressing', 'replicafailure', 'ready'],
# Add more resource types as needed
'statefulset': ['ready'],
'statefulsets': ['ready'],
}

# Validate wait_condition_type format and type
Expand Down Expand Up @@ -1049,6 +1050,9 @@ def _check_resource_condition(self, resource_type: str, resource_name: str, cond
if resource_type_lower in ['deployment', 'deployments']:
return self._check_deployment_condition(resource_name, condition_type, namespace, wait_all)

if resource_type_lower in ['statefulset', 'statefulsets']:
return self._check_statefulset_condition(resource_name, namespace, wait_all)

logger.warning(f"Unsupported resource type for condition checking: {resource_type}")
return False

Expand Down Expand Up @@ -1079,6 +1083,37 @@ def _check_deployment_condition(self, resource_name: str, condition_type: str, n
return False
raise e

def _check_statefulset_condition(self, resource_name: str, namespace: str, wait_all: bool) -> bool:
"""Check statefulset condition (e.g., 'ready')."""
try:
if wait_all or not resource_name:
statefulsets = self.app.list_namespaced_stateful_set(namespace=namespace).items
else:
statefulset = self.app.read_namespaced_stateful_set(name=resource_name, namespace=namespace)
statefulsets = [statefulset]

for statefulset in statefulsets:
if not self._is_statefulset_ready(statefulset):
return False

return True

except client.rest.ApiException as e:
if e.status == 404:
logger.debug("StatefulSet not found, waiting...")
return False
raise e

def _is_statefulset_ready(self, statefulset) -> bool:
"""Check if a statefulset has all replicas ready, including scale-to-zero."""
status = statefulset.status
spec_replicas = statefulset.spec.replicas or 0
return (
status is not None
and status.ready_replicas is not None
and status.ready_replicas == spec_replicas
)

def _is_deployment_condition_met(self, deployment, condition_type: str) -> bool:
"""Check if a deployment meets the specified condition."""
if not deployment.status or not deployment.status.conditions:
Expand Down
287 changes: 194 additions & 93 deletions modules/python/crud/azure/node_pool_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,23 @@
get_logger("azure.core.pipeline").setLevel(logging.ERROR)
get_logger("msal").setLevel(logging.ERROR)

# Workload type configuration for unified _apply_workload helper
WORKLOAD_CONFIG = {
"deployment": {
"template_file": "deployment.yml",
"count_key": "DEPLOYMENT_REPLICAS",
"resource_type": "deployment",
"wait_condition": "available",
"verify_pods_ready": True,
},
"statefulset": {
"template_file": "statefulset.yml",
"count_key": "STATEFULSET_REPLICAS",
"resource_type": "statefulset",
"wait_condition": "ready",
"verify_pods_ready": True,
},
}

class NodePoolCRUD:
"""Performs AKS node pool operations - metrics collection is handled directly by AKSClient"""
Expand Down Expand Up @@ -273,79 +290,6 @@ def all(
errors.append(error_msg)
return False

def _apply_deployment(
self,
k8s_client,
node_pool_name,
deployment_index,
replicas,
manifest_dir,
label_selector,
namespace
):
"""Helper for create_deployment — applies and verifies a single deployment."""
if manifest_dir:
# Use the template path from manifest_dir
template_path = f"{manifest_dir}/deployment.yml"
else:
# Use default template path (relative to workingDirectory: modules/python)
template_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"..", "workload_templates", "deployment.yml"
)

# Generate deployment name
deployment_name = f"myapp-{node_pool_name}-{deployment_index}"

# Use per-deployment label to avoid selector collision
deployment_label = f"{label_selector.split('=', 1)[-1]}-{deployment_index}"

# Create deployment template using k8s_client.create_template
deployment_template = k8s_client.create_template(
template_path,
{
"DEPLOYMENT_REPLICAS": replicas,
"NODE_POOL_NAME": node_pool_name,
"INDEX": deployment_index,
"LABEL_VALUE": deployment_label,
}
)

# Apply each document in the rendered multi-doc template
for doc in yaml.safe_load_all(deployment_template):
if doc:
k8s_client.apply_manifest_from_file(manifest_dict=doc, namespace=namespace)

logger.info("Applied manifest for deployment %s", deployment_name)

# Wait for deployment to be available (successful deployment verification)
logger.info("Waiting for deployment %s to become available...", deployment_name)
deployment_ready = k8s_client.wait_for_condition(
resource_type="deployment",
wait_condition_type="available",
resource_name=deployment_name,
namespace=namespace,
timeout_seconds=self.step_timeout
)

if not deployment_ready:
raise TimeoutError(
f"Deployment {deployment_name} failed to become available within timeout"
)

logger.info("Deployment %s is successfully available", deployment_name)

# Additionally wait for pods to be ready
logger.info("Waiting for pods of deployment %s to be ready...", deployment_name)
k8s_client.wait_for_pods_ready(
operation_timeout_in_minutes=5,
namespace=namespace,
pod_count=replicas,
label_selector=f"app={deployment_label}"
)

logger.info("Successfully created and verified deployment %d", deployment_index)

def create_deployment(
self,
node_pool_name,
Expand All @@ -369,43 +313,200 @@ def create_deployment(
Returns:
True if all deployment creations were successful, False otherwise
"""
logger.info("Creating %d deployment(s)", number_of_deployments)
return self._create_workloads(
workload_type="deployment",
node_pool_name=node_pool_name,
count=replicas,
number_of_workloads=number_of_deployments,
manifest_dir=manifest_dir,
label_selector=label_selector,
namespace=namespace
)

def create_statefulset(
self,
node_pool_name,
replicas=10,
manifest_dir=None,
number_of_statefulsets=1,
label_selector="app=nginx-container",
namespace="default"
):
"""
Create Kubernetes StatefulSets after node pool operations.

Args:
node_pool_name: Name of the node pool to target
namespace: Kubernetes namespace (default: "default")
replicas: Number of replicas for the StatefulSet (default: 10)
manifest_dir: Directory containing Kubernetes manifest files
number_of_statefulsets: Number of StatefulSets to create (default: 1)
label_selector: Label selector for pods (default: "app=nginx-container")

Returns:
True if all StatefulSet creations were successful, False otherwise
"""
return self._create_workloads(
workload_type="statefulset",
node_pool_name=node_pool_name,
count=replicas,
number_of_workloads=number_of_statefulsets,
manifest_dir=manifest_dir,
label_selector=label_selector,
namespace=namespace
)

def _create_workloads(
self,
workload_type,
node_pool_name,
count,
number_of_workloads,
manifest_dir,
label_selector,
namespace
):
"""Unified helper to create multiple workload instances.

Args:
workload_type: Type of workload ("deployment" or "statefulset")
node_pool_name: Name of the target node pool
count: Number of replicas per workload instance
number_of_workloads: Total number of workload instances to create
manifest_dir: Optional custom manifest directory
label_selector: Base label selector (e.g., "app=nginx-container")
namespace: Kubernetes namespace

Returns:
True if all workloads created successfully, False otherwise
"""
workload_type_display = workload_type.capitalize()
logger.info("Creating %d %s(s)", number_of_workloads, workload_type_display)
logger.info("Target node pool: %s", node_pool_name)
logger.info("Replicas per deployment: %d", replicas)
logger.info("Replicas per %s: %d", workload_type, count)
logger.info("Using manifest directory: %s", manifest_dir)

# Get Kubernetes client from AKS client
k8s_client = self.aks_client.k8s_client

if not k8s_client:
logger.error("Kubernetes client not available")
return False

successful_deployments = 0

# Loop through number of deployments
for deployment_index in range(1, number_of_deployments + 1):
logger.info("Creating deployment %d/%d", deployment_index, number_of_deployments)

successes = 0
for index in range(1, number_of_workloads + 1):
logger.info("Creating %s %d/%d", workload_type, index, number_of_workloads)
try:
self._apply_deployment(
self._apply_workload(
k8s_client=k8s_client,
workload_type=workload_type,
node_pool_name=node_pool_name,
deployment_index=deployment_index,
replicas=replicas,
index=index,
count=count,
manifest_dir=manifest_dir,
label_selector=label_selector,
namespace=namespace
)
successful_deployments += 1
successes += 1
except Exception as e:
logger.error("Failed to create deployment %d: %s", deployment_index, e)
# Continue with next deployment instead of failing completely
logger.error("Failed to create %s %d: %s", workload_type, index, e)
continue

# Check if all deployments were successful
if successful_deployments == number_of_deployments:
logger.info("Successfully created all %d deployment(s)", number_of_deployments)
if successes == number_of_workloads:
logger.info("Successfully created all %d %s(s)", number_of_workloads, workload_type_display)
return True
logger.warning("Created %d/%d deployment(s)", successful_deployments, number_of_deployments)
logger.warning("Created %d/%d %s(s)", successes, number_of_workloads, workload_type_display)
return False

def _apply_workload(
self,
k8s_client,
workload_type,
node_pool_name,
index,
count,
manifest_dir,
label_selector,
namespace
):
"""Unified helper to apply and verify a single workload instance.

Args:
k8s_client: Kubernetes client instance
workload_type: Type of workload ("deployment" or "statefulset")
node_pool_name: Name of the target node pool
index: Workload instance index (1-based)
count: Number of replicas/completions
manifest_dir: Optional custom manifest directory
label_selector: Base label selector (e.g., "app=nginx-container")
namespace: Kubernetes namespace

Raises:
ValueError: If workload_type is not in WORKLOAD_CONFIG
TimeoutError: If workload fails to reach ready state
"""
if workload_type not in WORKLOAD_CONFIG:
raise ValueError(f"Unknown workload type: {workload_type}")

config = WORKLOAD_CONFIG[workload_type]

# Resolve template path
if manifest_dir:
template_path = f"{manifest_dir}/{config['template_file']}"
else:
template_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"..", "workload_templates", config["template_file"]
)

# Generate resource name and label
resource_name = f"myapp-{node_pool_name}-{index}"
workload_label = f"{label_selector.split('=', 1)[-1]}-{workload_type}-{index}"

# Render template
rendered_template = k8s_client.create_template(
template_path,
{
config["count_key"]: count,
"NODE_POOL_NAME": node_pool_name,
"INDEX": index,
"LABEL_VALUE": workload_label,
}
)

# Apply each document in the rendered multi-doc template
for doc in yaml.safe_load_all(rendered_template):
if doc:
k8s_client.apply_manifest_from_file(manifest_dict=doc, namespace=namespace)

logger.info("Applied manifest for %s %s", workload_type, resource_name)

# Wait for workload to reach target condition
logger.info("Waiting for %s %s to become %s...",
workload_type, resource_name, config["wait_condition"])
ready = k8s_client.wait_for_condition(
resource_type=config["resource_type"],
wait_condition_type=config["wait_condition"],
resource_name=resource_name,
namespace=namespace,
timeout_seconds=self.step_timeout
)

if not ready:
raise TimeoutError(
f"{workload_type.capitalize()} {resource_name} failed to become "
f"{config['wait_condition']} within timeout"
)

logger.info("%s %s is successfully %s",
workload_type.capitalize(), resource_name, config["wait_condition"])

# Wait for pods if configured (skipped for Jobs)
if config["verify_pods_ready"]:
logger.info("Waiting for pods of %s %s to be ready...", workload_type, resource_name)
k8s_client.wait_for_pods_ready(
operation_timeout_in_minutes=5,
namespace=namespace,
pod_count=count,
label_selector=f"app={workload_label}"
)

logger.info("Successfully created and verified %s %d", workload_type, index)
Loading
Loading