diff --git a/modules/python/clients/kubernetes_client.py b/modules/python/clients/kubernetes_client.py index f6464ffd95..6f314398d5 100644 --- a/modules/python/clients/kubernetes_client.py +++ b/modules/python/clients/kubernetes_client.py @@ -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." ) @@ -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 @@ -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 @@ -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 @@ -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 @@ -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 + 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: @@ -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": @@ -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) @@ -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) diff --git a/modules/python/crud/azure/node_pool_crud.py b/modules/python/crud/azure/node_pool_crud.py index d475de9ca9..0b5865d07c 100644 --- a/modules/python/crud/azure/node_pool_crud.py +++ b/modules/python/crud/azure/node_pool_crud.py @@ -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: @@ -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, @@ -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") @@ -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 @@ -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: diff --git a/modules/python/crud/main.py b/modules/python/crud/main.py index 743a753d3b..16f5a58e12 100644 --- a/modules/python/crud/main.py +++ b/modules/python/crud/main.py @@ -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 @@ -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 @@ -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) + # Create-machine command (AKS Machine API) _add_create_machine_subparser(subparsers, common_parser) diff --git a/modules/python/crud/workload_templates/job.yml b/modules/python/crud/workload_templates/job.yml new file mode 100644 index 0000000000..4fc6642bff --- /dev/null +++ b/modules/python/crud/workload_templates/job.yml @@ -0,0 +1,20 @@ +apiVersion: batch/v1 +kind: Job +metadata: + name: myapp-{{NODE_POOL_NAME}}-{{INDEX}} + 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 diff --git a/modules/python/tests/clients/test_kubernetes_client.py b/modules/python/tests/clients/test_kubernetes_client.py index a67d52fef2..090f3406d9 100644 --- a/modules/python/tests/clients/test_kubernetes_client.py +++ b/modules/python/tests/clients/test_kubernetes_client.py @@ -1481,10 +1481,15 @@ def test_wait_for_job_completed_success(self, mock_read_job): mock_status = MagicMock() mock_status.succeeded = 1 mock_status.failed = 0 + mock_status.conditions = [] # No conditions, will use succeeded fallback + + mock_spec = MagicMock() + mock_spec.completions = 1 mock_job = MagicMock() mock_job.status = mock_status mock_job.metadata = mock_metadata + mock_job.spec = mock_spec mock_read_job.return_value = mock_job @@ -1497,11 +1502,20 @@ def test_wait_for_job_completed_failure(self, mock_read_namespaced_job): """Test waiting for job completion when job has failed.""" job_name = "test-job" namespace = "default" + + # Create a proper Failed condition + mock_condition = MagicMock() + mock_condition.type = "Failed" + mock_condition.status = "True" + mock_status = MagicMock() mock_status.succeeded = 0 mock_status.failed = 1 + mock_status.conditions = [mock_condition] + mock_job = MagicMock() mock_job.status = mock_status + mock_job.spec.completions = 1 mock_metadata = MagicMock() mock_metadata.name = job_name mock_job.metadata = mock_metadata @@ -1531,6 +1545,7 @@ def test_wait_for_job_completed_timeout( status=MagicMock(succeeded=0, failed=0, conditions=[]), metadata=MagicMock(name=job_name), ) + mock_read_namespaced_job.return_value.spec = MagicMock(completions=1) with self.assertRaises(Exception) as context: self.client.wait_for_job_completed(job_name, namespace, timeout) @@ -3478,6 +3493,104 @@ def test_wait_for_condition_statefulset_not_found(self, mock_time): self.assertFalse(result) + @patch('time.time') + def test_wait_for_condition_job_complete_success(self, mock_time): + """Test wait_for_condition for job - complete success case""" + mock_time.side_effect = [0, 0, 1, 2, 2] + + mock_job = MagicMock() + mock_job.status.conditions = [ + MagicMock(type="Complete", status="True") + ] + mock_job.status.succeeded = 1 + + with patch.object(self.client, 'batch') as mock_batch, \ + patch('time.sleep'): + mock_batch.read_namespaced_job.return_value = mock_job + + result = self.client.wait_for_condition( + resource_type="job", + resource_name="test-job", + wait_condition_type="complete", + namespace="test-namespace", + timeout_seconds=5 + ) + + self.assertTrue(result) + mock_batch.read_namespaced_job.assert_called_with( + name="test-job", + namespace="test-namespace" + ) + + @patch('time.time') + def test_wait_for_condition_job_failed(self, mock_time): + """Test wait_for_condition for job - failed condition""" + mock_time.side_effect = [0, 0, 1, 2, 2] + + mock_job = MagicMock() + mock_job.status.conditions = [ + MagicMock(type="Failed", status="True") + ] + mock_job.status.succeeded = None + + with patch.object(self.client, 'batch') as mock_batch, \ + patch('time.sleep'): + mock_batch.read_namespaced_job.return_value = mock_job + + result = self.client.wait_for_condition( + resource_type="job", + resource_name="test-job", + wait_condition_type="failed", + namespace="test-namespace", + timeout_seconds=5 + ) + + self.assertTrue(result) + + @patch('time.time') + def test_wait_for_condition_job_timeout(self, mock_time): + """Test wait_for_condition for job - timeout case""" + mock_time.side_effect = [0, 0, 2, 5, 6, 6] + + mock_job = MagicMock() + mock_job.status.conditions = None + mock_job.status.succeeded = 0 + + with patch.object(self.client, 'batch') as mock_batch, \ + patch('time.sleep'): + mock_batch.read_namespaced_job.return_value = mock_job + + result = self.client.wait_for_condition( + resource_type="job", + resource_name="test-job", + wait_condition_type="complete", + namespace="test-namespace", + timeout_seconds=1 + ) + + self.assertFalse(result) + + @patch('time.time') + def test_wait_for_condition_job_not_found(self, mock_time): + """Test wait_for_condition for job - not found case""" + mock_time.side_effect = [0, 0, 2, 5, 6, 6] + + api_exception = ApiException(status=404, reason="Not Found") + + with patch.object(self.client, 'batch') as mock_batch, \ + patch('time.sleep'): + mock_batch.read_namespaced_job.side_effect = api_exception + + result = self.client.wait_for_condition( + resource_type="job", + resource_name="nonexistent", + wait_condition_type="complete", + namespace="test-namespace", + timeout_seconds=1 + ) + + self.assertFalse(result) + # Tests for the enhanced apply_manifest_from_file method with folder support @patch('os.path.isdir') @patch('os.path.isfile') diff --git a/modules/python/tests/crud/test_azure_node_pool_crud.py b/modules/python/tests/crud/test_azure_node_pool_crud.py index 20ba49e558..5562a00f09 100644 --- a/modules/python/tests/crud/test_azure_node_pool_crud.py +++ b/modules/python/tests/crud/test_azure_node_pool_crud.py @@ -463,5 +463,75 @@ def test_create_statefulset_partial_success(self): # Verify create_template was called 3 times (attempted all statefulsets) self.assertEqual(mock_k8s_client.create_template.call_count, 3) + def test_create_job_success(self): + """Test successful job creation""" + # Setup + mock_k8s_client = mock.MagicMock() + self.mock_aks_client.k8s_client = mock_k8s_client + # Must return a real string - yaml.safe_load_all(MagicMock()) causes an infinite loop + mock_k8s_client.create_template.return_value = "apiVersion: batch/v1\nkind: Job\n" + mock_k8s_client.wait_for_condition.return_value = True + + # Execute + result = self.node_pool_crud.create_job(node_pool_name="test-pool") + + # Verify + self.assertTrue(result) + + def test_create_job_failure(self): + """Test job creation failure""" + # Setup + mock_k8s_client = mock.MagicMock() + self.mock_aks_client.k8s_client = mock_k8s_client + # Must return a real string - yaml.safe_load_all(MagicMock()) causes an infinite loop + mock_k8s_client.create_template.return_value = "apiVersion: batch/v1\nkind: Job\n" + mock_k8s_client.wait_for_condition.return_value = False + + # Execute + result = self.node_pool_crud.create_job(node_pool_name="test-pool") + + # Verify + self.assertFalse(result) + + def test_create_job_no_client(self): + """Test job creation with no Kubernetes client""" + # Setup + self.mock_aks_client.k8s_client = None + + # Execute + result = self.node_pool_crud.create_job(node_pool_name="test-pool") + + # Verify + self.assertFalse(result) + + def test_create_job_partial_success(self): + """Test job creation when some jobs succeed and others fail""" + # Setup + mock_k8s_client = mock.MagicMock() + self.mock_aks_client.k8s_client = mock_k8s_client + + # Must return a real string - yaml.safe_load_all(MagicMock()) causes an infinite loop + mock_k8s_client.create_template.return_value = "apiVersion: batch/v1\nkind: Job\n" + + # Simulate: Job 1 succeeds, Job 2 fails, Job 3 succeeds + # wait_for_condition returns True/False for each Job + mock_k8s_client.wait_for_condition.side_effect = [True, False, True] + + # Execute - request 3 Jobs + result = self.node_pool_crud.create_job( + node_pool_name="test-pool", + number_of_jobs=3, + completions=1 + ) + + # Verify - should return False (not all jobs succeeded) + self.assertFalse(result) + + # Verify wait_for_condition was called 3 times (once per job) + self.assertEqual(mock_k8s_client.wait_for_condition.call_count, 3) + + # Verify create_template was called 3 times (attempted all jobs) + self.assertEqual(mock_k8s_client.create_template.call_count, 3) + if __name__ == "__main__": unittest.main() diff --git a/pipelines/perf-eval/GPU Benchmark/k8s-gpu-cluster-crud.yml b/pipelines/perf-eval/GPU Benchmark/k8s-gpu-cluster-crud.yml index 99647445bf..aa46640b94 100644 --- a/pipelines/perf-eval/GPU Benchmark/k8s-gpu-cluster-crud.yml +++ b/pipelines/perf-eval/GPU Benchmark/k8s-gpu-cluster-crud.yml @@ -45,6 +45,7 @@ stages: step_wait_time: 30 count: 1 replicas: 10 + completions: 1 manifest_dir: "" max_parallel: 1 credential_type: service_connection @@ -78,6 +79,7 @@ stages: step_wait_time: 30 count: 1 replicas: 10 + completions: 1 manifest_dir: "" max_parallel: 1 credential_type: service_connection diff --git a/steps/engine/crud/k8s/execute.yml b/steps/engine/crud/k8s/execute.yml index e84e3a1f7b..c0a6c9bf23 100644 --- a/steps/engine/crud/k8s/execute.yml +++ b/steps/engine/crud/k8s/execute.yml @@ -101,6 +101,33 @@ steps: REPLICAS: $(REPLICAS) MANIFEST_DIR: $(MANIFEST_DIR) + - script: | + set -eo pipefail + + # Deploy Jobs + PYTHONPATH=$PYTHONPATH:$(pwd) python3 "$PYTHON_SCRIPT_FILE" job \ + --cloud "$CLOUD" \ + --run-id "$RUN_ID" \ + --result-dir "$RESULT_DIR" \ + --node-pool-name "$POOL_NAME" \ + --count "$COUNT" \ + --completions "$COMPLETIONS" \ + ${MANIFEST_DIR:+--manifest-dir "$MANIFEST_DIR"} \ + --step-timeout "$STEP_TIME_OUT" \ + ${GPU_NODE_POOL:+--gpu-node-pool} + displayName: 'Execute K8s Job operations for ${{ parameters.cloud }}' + workingDirectory: modules/python + env: + PYTHON_SCRIPT_FILE: $(Pipeline.Workspace)/s/modules/python/crud/main.py + POOL_NAME: $(POOL_NAME) + CLOUD: ${{ parameters.cloud }} + STEP_TIME_OUT: $(STEP_TIME_OUT) + RESULT_DIR: $(System.DefaultWorkingDirectory)/$(RUN_ID) + GPU_NODE_POOL: $(GPU_NODE_POOL) + COUNT: $(COUNT) + COMPLETIONS: $(COMPLETIONS) + MANIFEST_DIR: $(MANIFEST_DIR) + - script: | set -eo pipefail