1717from kubernetes import client , watch
1818from reana_commons .config import REANA_RUNTIME_KUBERNETES_NAMESPACE
1919from reana_commons .k8s .api_client import current_k8s_corev1_api_client
20- from reana_db .database import Session
21- from reana_db .models import Job , JobStatus
20+ from reana_db .models import JobStatus
2221
2322from reana_job_controller .config import (
2423 COMPUTE_BACKENDS ,
3231 C4P_SSH_TIMEOUT ,
3332 C4P_SSH_BANNER_TIMEOUT ,
3433 C4P_SSH_AUTH_TIMEOUT ,
34+ KUEUE_ENABLED ,
3535)
3636
3737from reana_job_controller .job_db import JOB_DB , store_job_logs , update_job_status
38- from reana_job_controller .kubernetes_job_manager import KubernetesJobManager
3938from reana_job_controller .utils import (
4039 SSHClient ,
4140 singleton ,
@@ -104,7 +103,8 @@ def get_reana_job_id(self, backend_job_id: str) -> str:
104103 remaining_jobs = self ._get_remaining_jobs ()
105104 return remaining_jobs [backend_job_id ]
106105
107- def get_backend_job_id (self , job_pod ):
106+ @staticmethod
107+ def get_backend_job_id (job_pod ):
108108 """Get the backend job id for the backend object.
109109
110110 :param job_pod: Compute backend job object (Kubernetes V1Pod
@@ -115,7 +115,7 @@ def get_backend_job_id(self, job_pod):
115115 """
116116 return job_pod .metadata .labels ["job-name" ]
117117
118- def should_process_job (self , job_pod ) -> bool :
118+ def should_process_job_pod (self , job_pod ) -> bool :
119119 """Decide whether the job should be processed or not.
120120
121121 Each job is processed only once, when it reaches a final state (either `failed` or `finished`).
@@ -141,6 +141,27 @@ def should_process_job(self, job_pod) -> bool:
141141
142142 return is_job_in_remaining_jobs and is_job_completed
143143
144+ def should_process_job (self , job ) -> bool :
145+ """Decide whether the job should be processed or not.
146+
147+ Each job is processed only once, when it reaches a final state (either `failed` or `finished`).
148+
149+ :param job: Compute backend job object (Kubernetes V1Job
150+ https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Job.md)
151+ """
152+ remaining_jobs = self ._get_remaining_jobs (
153+ statuses_to_skip = [
154+ JobStatus .finished .name ,
155+ JobStatus .failed .name ,
156+ JobStatus .stopped .name ,
157+ ]
158+ )
159+
160+ is_job_in_remaining_jobs = job .metadata .name in remaining_jobs
161+ is_job_completed = job .status .succeeded and not job .status .active
162+
163+ return is_job_in_remaining_jobs and is_job_completed
164+
144165 @staticmethod
145166 def _get_job_container_statuses (job_pod ):
146167 return (job_pod .status .container_statuses or []) + (
@@ -230,13 +251,65 @@ def get_job_status(self, job_pod) -> Optional[str]:
230251
231252 return status
232253
233- def watch_jobs (self , job_db , app = None ):
234- """Open stream connection to k8s apiserver to watch all jobs status.
235-
236- :param job_db: Dictionary which contains all current jobs.
237- """
254+ def watch_job_event_stream (self ):
238255 while True :
239256 logging .info ("Starting a new stream request to watch Jobs" )
257+
258+ try :
259+ w = watch .Watch ()
260+ for event in w .stream (
261+ client .BatchV1Api ().list_namespaced_job ,
262+ namespace = REANA_RUNTIME_KUBERNETES_NAMESPACE ,
263+ label_selector = f"reana-run-job-workflow-uuid={ self .workflow_uuid } " ,
264+ ):
265+ logging .info (f"New Job event received: { event ["type" ]} " )
266+
267+ job = event ["object" ]
268+ job_id = job .metadata .name
269+ job_finished = (
270+ job .status .succeeded
271+ and not job .status .active
272+ and not job .status .failed
273+ )
274+ job_status = (
275+ JobStatus .finished .name
276+ if job_finished
277+ else (
278+ JobStatus .failed .name
279+ if job .status .failed
280+ else JobStatus .running .name
281+ )
282+ )
283+
284+ if self .should_process_job (job ):
285+ reana_job_id = self .get_reana_job_id (job_id )
286+
287+ if job_status == JobStatus .failed .name :
288+ self .log_disruption (
289+ event ["object" ].status .conditions , job_id
290+ )
291+
292+ # TODO: Fetch logs from the remote job pod on the remote worker when MultiKueue supports this
293+ logs = self .job_manager_cls .get_logs (job_id )
294+ if logs is not None :
295+ store_job_logs (reana_job_id , logs )
296+
297+ update_job_status (
298+ reana_job_id ,
299+ job_status ,
300+ )
301+
302+ if JobStatus .should_cleanup_job (job_status ):
303+ self .clean_job (job_id )
304+
305+ except client .rest .ApiException as e :
306+ logging .exception (f"Error from Kubernetes API while watching jobs: { e } " )
307+ except Exception as e :
308+ logging .error (traceback .format_exc ())
309+ logging .error ("Unexpected error: {}" .format (e ))
310+
311+ def watch_pod_event_stream (self ):
312+ while True :
240313 try :
241314 w = watch .Watch ()
242315 for event in w .stream (
@@ -249,7 +322,7 @@ def watch_jobs(self, job_db, app=None):
249322
250323 # Each job is processed once, when reaching a final state
251324 # (either successfully or not)
252- if self .should_process_job (job_pod ):
325+ if self .should_process_job_pod (job_pod ):
253326 job_status = self .get_job_status (job_pod )
254327 backend_job_id = self .get_backend_job_id (job_pod )
255328 reana_job_id = self .get_reana_job_id (backend_job_id )
@@ -276,7 +349,20 @@ def watch_jobs(self, job_db, app=None):
276349 logging .error (traceback .format_exc ())
277350 logging .error ("Unexpected error: {}" .format (e ))
278351
279- def log_disruption (self , conditions , backend_job_id ):
352+ def watch_jobs (self , job_db , app = None ):
353+ """Open stream connection to k8s apiserver to watch all jobs status.
354+
355+ :param job_db: Dictionary which contains all current jobs.
356+ """
357+ # If using MultiKueue, watch jobs instead of pods since worker pods could be
358+ # running on a remote cluster that we can't directly monitor
359+ if KUEUE_ENABLED :
360+ self .watch_job_event_stream ()
361+ else :
362+ self .watch_pod_event_stream ()
363+
364+ @staticmethod
365+ def log_disruption (conditions , backend_job_id ):
280366 """Log disruption message from Kubernetes event conditions.
281367
282368 Usually it is pod eviction but can be any of https://kubernetes.io/docs/concepts/workloads/pods/disruptions/#pod-disruption-conditions.
0 commit comments