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,77 @@ 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.
254+ def watch_job_event_stream (self ):
255+ """
256+ Watch job events from the Kubernetes API.
235257
236- :param job_db: Dictionary which contains all current jobs.
258+ This method is used when MultiKueue is enabled, since in that case we can't
259+ directly monitor the worker pods as they are remote.
237260 """
238261 while True :
239262 logging .info ("Starting a new stream request to watch Jobs" )
263+
264+ try :
265+ w = watch .Watch ()
266+ for event in w .stream (
267+ client .BatchV1Api ().list_namespaced_job ,
268+ namespace = REANA_RUNTIME_KUBERNETES_NAMESPACE ,
269+ label_selector = f"reana-run-job-workflow-uuid={ self .workflow_uuid } " ,
270+ ):
271+ logging .info (f"New Job event received: { event ["type" ]} " )
272+
273+ job = event ["object" ]
274+ job_id = job .metadata .name
275+ job_finished = (
276+ job .status .succeeded
277+ and not job .status .active
278+ and not job .status .failed
279+ )
280+ job_status = (
281+ JobStatus .finished .name
282+ if job_finished
283+ else (
284+ JobStatus .failed .name
285+ if job .status .failed
286+ else JobStatus .running .name
287+ )
288+ )
289+
290+ if self .should_process_job (job ):
291+ reana_job_id = self .get_reana_job_id (job_id )
292+
293+ if job_status == JobStatus .failed .name :
294+ self .log_disruption (
295+ event ["object" ].status .conditions , job_id
296+ )
297+
298+ # TODO: Fetch logs from the remote job pod on the remote worker when MultiKueue supports this
299+ logs = self .job_manager_cls .get_logs (job_id )
300+ if logs is not None :
301+ store_job_logs (reana_job_id , logs )
302+
303+ update_job_status (
304+ reana_job_id ,
305+ job_status ,
306+ )
307+
308+ if JobStatus .should_cleanup_job (job_status ):
309+ self .clean_job (job_id )
310+
311+ except client .rest .ApiException as e :
312+ logging .exception (f"Error from Kubernetes API while watching jobs: { e } " )
313+ except Exception as e :
314+ logging .error (traceback .format_exc ())
315+ logging .error ("Unexpected error: {}" .format (e ))
316+
317+ def watch_pod_event_stream (self ):
318+ """
319+ Watch pod events from the Kubernetes API.
320+
321+ This method is used when MultiKueue is not enabled, since in that case we can
322+ directly monitor the worker pods as they are running on the local cluster.
323+ """
324+ while True :
240325 try :
241326 w = watch .Watch ()
242327 for event in w .stream (
@@ -249,7 +334,7 @@ def watch_jobs(self, job_db, app=None):
249334
250335 # Each job is processed once, when reaching a final state
251336 # (either successfully or not)
252- if self .should_process_job (job_pod ):
337+ if self .should_process_job_pod (job_pod ):
253338 job_status = self .get_job_status (job_pod )
254339 backend_job_id = self .get_backend_job_id (job_pod )
255340 reana_job_id = self .get_reana_job_id (backend_job_id )
@@ -276,7 +361,20 @@ def watch_jobs(self, job_db, app=None):
276361 logging .error (traceback .format_exc ())
277362 logging .error ("Unexpected error: {}" .format (e ))
278363
279- def log_disruption (self , conditions , backend_job_id ):
364+ def watch_jobs (self , job_db , app = None ):
365+ """Open stream connection to k8s apiserver to watch all jobs status.
366+
367+ :param job_db: Dictionary which contains all current jobs.
368+ """
369+ # If using MultiKueue, watch jobs instead of pods since worker pods could be
370+ # running on a remote cluster that we can't directly monitor
371+ if KUEUE_ENABLED :
372+ self .watch_job_event_stream ()
373+ else :
374+ self .watch_pod_event_stream ()
375+
376+ @staticmethod
377+ def log_disruption (conditions , backend_job_id ):
280378 """Log disruption message from Kubernetes event conditions.
281379
282380 Usually it is pod eviction but can be any of https://kubernetes.io/docs/concepts/workloads/pods/disruptions/#pod-disruption-conditions.
0 commit comments