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
66 changes: 61 additions & 5 deletions modules/python/clients/kubernetes_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -377,18 +377,18 @@ def wait_for_job_completed(self, job_name, namespace="default", timeout=300):
:param job_name: The name of the job to wait for.
:param namespace: The namespace where the job is located (default: "default").
:param timeout: The timeout in seconds to wait for the job to complete (default: 300 seconds).
:return: None
:return: The job name if completed successfully.
"""
start_time = time.time()
while time.time() - start_time < timeout:
try:
job = self.batch.read_namespaced_job(name=job_name, namespace=namespace)
if job.status.succeeded is not None and job.status.succeeded > 0:
if self._is_job_condition_met(job, "complete"):
logger.info(
f"Job '{job_name}' in namespace '{namespace}' has completed successfully."
)
return job.metadata.name
if job.status.failed is not None and job.status.failed > 0:
if self._is_job_condition_met(job, "failed"):
raise Exception(
f"Job '{job_name}' in namespace '{namespace}' has failed."
)
Expand Down Expand Up @@ -977,6 +977,8 @@ def wait_for_condition(self, resource_type: str, wait_condition_type: str, names
'deployments': ['available', 'progressing', 'replicafailure', 'ready'],
'statefulset': ['ready'],
'statefulsets': ['ready'],
'job': ['complete', 'failed'],
'jobs': ['complete', 'failed'],
}

# Validate wait_condition_type format and type
Expand Down Expand Up @@ -1053,6 +1055,9 @@ def _check_resource_condition(self, resource_type: str, resource_name: str, cond
if resource_type_lower in ['statefulset', 'statefulsets']:
return self._check_statefulset_condition(resource_name, namespace, wait_all)

if resource_type_lower in ['job', 'jobs']:
return self._check_job_condition(resource_name, condition_type, namespace, wait_all)

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

Expand All @@ -1079,7 +1084,6 @@ def _check_deployment_condition(self, resource_name: str, condition_type: str, n

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

Expand All @@ -1100,7 +1104,6 @@ def _check_statefulset_condition(self, resource_name: str, namespace: str, wait_

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

Expand All @@ -1114,6 +1117,47 @@ def _is_statefulset_ready(self, statefulset) -> bool:
and status.ready_replicas == spec_replicas
)

def _check_job_condition(self, resource_name: str, condition_type: str, namespace: str, wait_all: bool) -> bool:
"""Check job condition (e.g., 'complete', 'failed')."""
try:
if wait_all or not resource_name:
jobs = self.batch.list_namespaced_job(namespace=namespace).items
else:
job = self.batch.read_namespaced_job(name=resource_name, namespace=namespace)
jobs = [job]

for job in jobs:
if not self._is_job_condition_met(job, condition_type):
return False

return True

except client.rest.ApiException as e:
if e.status == 404:
return False
raise e

def _is_job_condition_met(self, job, condition_type: str) -> bool:
"""Check if a job meets the specified condition."""
if not job.status:
return False

condition_type_lower = condition_type.lower()

# Check job conditions
if job.status.conditions:
for condition in job.status.conditions:
if condition.type.lower() == condition_type_lower and condition.status == "True":
return True

# Fallback: infer completion from success counters when conditions are absent
if condition_type_lower == 'complete':
spec_completions = job.spec.completions or 1
return (job.status.succeeded is not None and
job.status.succeeded >= spec_completions)

return False

Comment thread
diamondpowell marked this conversation as resolved.
Resolved
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 Expand Up @@ -1194,6 +1238,8 @@ def _apply_single_manifest(self, manifest, namespace=None):
self.app.create_namespaced_daemon_set(namespace=namespace, body=manifest)
elif kind == "StatefulSet":
self.app.create_namespaced_stateful_set(namespace=namespace, body=manifest)
elif kind == "Job":
self.batch.create_namespaced_job(namespace=namespace, body=manifest)
elif kind == "Service":
self.api.create_namespaced_service(namespace=namespace, body=manifest)
elif kind == "ConfigMap":
Expand Down Expand Up @@ -1348,6 +1394,11 @@ def _update_single_manifest(self, manifest, namespace=None):
self.app.patch_namespaced_stateful_set(name=name, namespace=namespace, body=manifest)
else:
raise ValueError("StatefulSet requires a namespace")
elif kind == "Job":
if namespace:
self.batch.patch_namespaced_job(name=name, namespace=namespace, body=manifest)
else:
raise ValueError("Job requires a namespace")
elif kind == "Service":
if namespace:
self.api.patch_namespaced_service(name=name, namespace=namespace, body=manifest)
Expand Down Expand Up @@ -1529,6 +1580,11 @@ def _delete_single_manifest(self, manifest, ignore_not_found: bool = True, names
self.app.delete_namespaced_stateful_set(name=resource_name, namespace=namespace, body=delete_options)
else:
raise ValueError("StatefulSet requires a namespace")
elif kind == "Job":
if namespace:
self.batch.delete_namespaced_job(name=resource_name, namespace=namespace, body=delete_options)
else:
raise ValueError("Job requires a namespace")
elif kind == "Service":
if namespace:
self.api.delete_namespaced_service(name=resource_name, namespace=namespace, body=delete_options)
Expand Down
59 changes: 56 additions & 3 deletions modules/python/crud/azure/node_pool_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,13 @@
"wait_condition": "ready",
"verify_pods_ready": True,
},
"job": {
"template_file": "job.yml",
"count_key": "JOB_COMPLETIONS",
"resource_type": "job",
"wait_condition": "complete",
"verify_pods_ready": False, # Job pods terminate after completion
},
}

class NodePoolCRUD:
Expand Down Expand Up @@ -356,6 +363,39 @@ def create_statefulset(
namespace=namespace
)

def create_job(
self,
node_pool_name,
completions=1,
manifest_dir=None,
number_of_jobs=1,
label_selector="app=nginx-container",
namespace="default"
):
"""
Create Kubernetes Jobs after node pool operations.

Args:
node_pool_name: Name of the node pool to target
completions: Number of job completions (default: 1)
manifest_dir: Directory containing Kubernetes manifest files
number_of_jobs: Number of Jobs to create (default: 1)
label_selector: Label selector for pods (default: "app=nginx-container")
namespace: Kubernetes namespace (default: "default")

Returns:
True if all Job creations were successful, False otherwise
"""
return self._create_workloads(
workload_type="job",
node_pool_name=node_pool_name,
count=completions,
number_of_workloads=number_of_jobs,
manifest_dir=manifest_dir,
label_selector=label_selector,
namespace=namespace
)

def _create_workloads(
self,
workload_type,
Expand All @@ -369,9 +409,9 @@ def _create_workloads(
"""Unified helper to create multiple workload instances.

Args:
workload_type: Type of workload ("deployment" or "statefulset")
workload_type: Type of workload ("deployment", "statefulset", or "job")
node_pool_name: Name of the target node pool
count: Number of replicas per workload instance
count: Number of replicas/completions 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")
Expand Down Expand Up @@ -431,7 +471,7 @@ def _apply_workload(

Args:
k8s_client: Kubernetes client instance
workload_type: Type of workload ("deployment" or "statefulset")
workload_type: Type of workload ("deployment", "statefulset", or "job")
node_pool_name: Name of the target node pool
index: Workload instance index (1-based)
count: Number of replicas/completions
Expand Down Expand Up @@ -472,6 +512,19 @@ def _apply_workload(
}
)

# For Jobs, delete any existing job first to avoid reusing completed jobs
if workload_type == "job":
try:
k8s_client.batch.delete_namespaced_job(
name=resource_name,
namespace=namespace,
propagation_policy="Background"
)
logger.info("Deleted existing job %s before recreating", resource_name)
except Exception:
# Job doesn't exist, which is fine
pass

# Apply each document in the rendered multi-doc template
for doc in yaml.safe_load_all(rendered_template):
if doc:
Expand Down
31 changes: 30 additions & 1 deletion modules/python/crud/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,7 @@ def handle_node_pool_operation(node_pool_crud, args):
return 1

def handle_workload_operations(node_pool_crud, args):
"""Handle workload operations (deployment, statefulset) based on the command"""
"""Handle workload operations (deployment, statefulset, job) based on the command"""
command = args.command
result = None

Expand Down Expand Up @@ -197,6 +197,21 @@ def handle_workload_operations(node_pool_crud, args):
}

result = node_pool_crud.create_statefulset(**statefulset_kwargs)
elif command == "job":
if not hasattr(node_pool_crud, 'create_job'):
logger.error("Cloud provider does not support job workload operations")
return 1

# Prepare job arguments
job_kwargs = {
"node_pool_name": args.node_pool_name,
"completions": args.completions,
"manifest_dir": args.manifest_dir,
"number_of_jobs": args.count,
"label_selector": args.label_selector,
}

result = node_pool_crud.create_job(**job_kwargs)
else:
logger.error("Unknown workload command: '%s'", command)
return 1
Expand Down Expand Up @@ -531,6 +546,20 @@ def main():
)
statefulset_parser.set_defaults(func=handle_workload_operations)

# Job command
job_parser = subparsers.add_parser(
"job",
parents=[common_parser, workload_common_parser],
help="create jobs"
)
job_parser.add_argument(
"--completions",
type=int,
default=1,
help="Number of completions per job (default: 1)"
)
job_parser.set_defaults(func=handle_workload_operations)

Comment thread
diamondpowell marked this conversation as resolved.
Resolved
# Create-machine command (AKS Machine API)
_add_create_machine_subparser(subparsers, common_parser)

Expand Down
20 changes: 20 additions & 0 deletions modules/python/crud/workload_templates/job.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
apiVersion: batch/v1
kind: Job
metadata:
name: myapp-{{NODE_POOL_NAME}}-{{INDEX}}
Comment thread
diamondpowell marked this conversation as resolved.
Resolved
labels:
app: {{LABEL_VALUE}}
spec:
completions: {{JOB_COMPLETIONS}}
template:
metadata:
labels:
app: {{LABEL_VALUE}}
spec:
restartPolicy: Never
containers:
- name: {{LABEL_VALUE}}
image: mcr.microsoft.com/oss/nginx/nginx:1.21.6
command: ["nginx", "-t"]
ports:
- containerPort: 80
Loading
Loading