JobStatusReceiver.py 6.5 KB
Newer Older
jtchilders's avatar
jtchilders committed
1
2
3
4
5
6
7
8
import logging,sys,multiprocessing,time,os
logger = logging.getLogger(__name__)

from django.db import connections,DEFAULT_DB_ALIAS
from django.db.utils import load_backend
from django.conf import settings

from common import MessageReceiver
9
10
11
from balsam.argo import QueueMessage
from balsam.argo.models import ArgoJob,ArgoSubJob,BALSAM_JOB_TO_SUBJOB_STATE_MAP
from balsam.service import BalsamJobStatus,models
jtchilders's avatar
jtchilders committed
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37

class JobStatusReceiver(MessageReceiver.MessageReceiver):
   ''' subscribes to the balsam job status queue and updates a job state '''

   def __init__(self,process_queue):
      super(JobStatusReceiver,self).__init__(
            settings.RABBITMQ_BALSAM_JOB_STATUS_QUEUE,
            settings.RABBITMQ_BALSAM_JOB_STATUS_ROUTING_KEY,
            settings.RABBITMQ_SERVER_NAME,
            settings.RABBITMQ_SERVER_PORT,
            settings.RABBITMQ_BALSAM_EXCHANGE_NAME,
            settings.RABBITMQ_SSL_CERT,
            settings.RABBITMQ_SSL_KEY,
            settings.RABBITMQ_SSL_CA_CERTS
           )
      self.process_queue = process_queue

   # This is where the real processing of incoming messages happens
   def consume_msg(self,channel,method_frame,header_frame,body):
      logger.debug(' in consume_msg ')
      try:
         if body is not None:

            # convert body text to BalsamJobStatusMessage
            statusMsg = BalsamJobStatus.BalsamJobStatus()
            statusMsg.deserialize(body)
38
            logger.info(' received status message for job ' + str(statusMsg.job_id) + ', message: ' + str(statusMsg.message))
jtchilders's avatar
jtchilders committed
39
40
            
            # create unique DB connection string
41
            db_connection_id = 'db_con_%08i' % statusMsg.job_id
jtchilders's avatar
jtchilders committed
42
43
44
45
46
47
            db_backend = load_backend(connections.databases[DEFAULT_DB_ALIAS]['ENGINE'])
            db_conn = db_backend.DatabaseWrapper(connections.databases[DEFAULT_DB_ALIAS], db_connection_id)
            connections[db_connection_id] = db_conn
            
            # get the subjob for this message
            try:
48
               subjob = ArgoSubJob.objects.get(job_id=statusMsg.job_id)
49
            except Exception as e:
50
               logger.error(' exception received while retreiving ArgoSubJob with id = ' + str(statusMsg.job_id) + ': ' + str(e))
jtchilders's avatar
jtchilders committed
51
52
53
54
               # acknoledge message
               channel.basic_ack(method_frame.delivery_tag)
               del connections[db_connection_id]
               # send message to balsam_service about completion
55
               self.process_queue.put(QueueMessage.QueueMessage(statusMsg.job_id,
jtchilders's avatar
jtchilders committed
56
57
58
59
60
                              QueueMessage.JobStatusReceiverRetrieveArgoSubJobFailed))
               return

            # get the argo job for this subjob
            try:
Michael Salim's avatar
Michael Salim committed
61
               argojob = ArgoJob.objects.get(job_id=subjob.job_id) # BUG !
62
            except Exception as e:
63
               logger.error(' exception received while retrieving ArgoJob with id = ' + str(subjob.job_id + ': ' + str(e)))
jtchilders's avatar
jtchilders committed
64
65
66
67
               # acknoledge message
               channel.basic_ack(method_frame.delivery_tag)
               del connections[db_connection_id]
               # send message to balsam_service about completion
68
               self.process_queue.put(QueueMessage.QueueMessage(subjob.job_id,
jtchilders's avatar
jtchilders committed
69
70
71
72
73
                              QueueMessage.JobStatusReceiverRetrieveArgoJobFailed))
               return

            # get the deserialized balsam job
            try:
74
               balsam_job = models.BalsamJob()
Michael Salim's avatar
Michael Salim committed
75
               statusMsg.get_job(balsam_job) # statusMsg.serialzed_job gets loaded into balsam_job
jtchilders's avatar
jtchilders committed
76
               logger.debug('balsam_job = ' + str(balsam_job))
Michael Salim's avatar
Michael Salim committed
77
            except BalsamJobStatus.DeserializeFailed as e:
78
               logger.error('Failed to deserialize BalsamJob for BalsamJobStatus message for argojob: ' + str(argojob.job_id) + ' subjob_id: ' + str(subjob.job_id))
jtchilders's avatar
jtchilders committed
79
80
81
82
               # acknoledge message
               channel.basic_ack(method_frame.delivery_tag)
               del connections[db_connection_id]
               # send message to balsam_service about completion
83
               self.process_queue.put(QueueMessage.QueueMessage(subjob.job_id,
jtchilders's avatar
jtchilders committed
84
85
86
                              QueueMessage.JobStatusReceiverRetrieveArgoJobFailed))
               return

Michael Salim's avatar
Michael Salim committed
87
88
            # parse balsam_job (just received from balsam, new status) into
            # subjob and argojob (need to be synced)
jtchilders's avatar
jtchilders committed
89
90
91
92
93
94
95
96
97
98
99
100
101
            if balsam_job is not None:

               # copy scheduler id to subjob
               subjob.scheduler_id  = balsam_job.scheduler_id
               # copy current job state to subjob
               subjob.state         = balsam_job.state
               # save subjob
               subjob.save(update_fields=['state','scheduler_id'],using=db_connection_id)
               
               # map subjob state to argo job state
               try:
                  argojob.state = BALSAM_JOB_TO_SUBJOB_STATE_MAP[balsam_job.state].name
                  logger.debug(' receieved subjob state = ' + subjob.state + ' setting argo job state to ' + argojob.state)
Michael Salim's avatar
Michael Salim committed
102
               except KeyError as e:
103
                  logger.error(' could not map balsam_job state: ' + str(balsam_job.state) + ' to an ArgoJob state for job id: ' + str(argojob.job_id))
jtchilders's avatar
jtchilders committed
104
105
106
107
                  # acknoledge message
                  channel.basic_ack(method_frame.delivery_tag)
                  del connections[db_connection_id]
                  # send message to balsam_service about completion
108
                  self.process_queue.put(QueueMessage.QueueMessage(argojob.job_id,
jtchilders's avatar
jtchilders committed
109
110
111
112
113
114
115
116
                                 QueueMessage.JobStatusReceiverBalsamStateMapFailure))
                  return
            
               # save argojob
               argojob.save(update_fields=['state'],using=db_connection_id)

            else:
               logger.error('received no balsam_job from BalsamJobStatus')
117
            self.process_queue.put(QueueMessage.QueueMessage(argojob.job_id,
jtchilders's avatar
jtchilders committed
118
119
120
121
122
123
124
125
126
127
                           QueueMessage.JobStatusReceiverCompleted))
            # acknoledge message
            channel.basic_ack(method_frame.delivery_tag)

            del connections[db_connection_id]



         else:
            logger.debug(' consume_msg called, but body is None ')
128
            self.process_queue.put(QueueMessage.QueueMessage(argojob.job_id,
jtchilders's avatar
jtchilders committed
129
130
                           QueueMessage.JobStatusReceiverMessageNoBody))
      
131
      except Exception as e:
jtchilders's avatar
jtchilders committed
132
133
134
135
136
137
         logger.exception("Error consuming status message: " + str(e))
         self.process_queue.put(QueueMessage.QueueMessage(0,
                        QueueMessage.JobStatusReceiverFailed))
      
      logger.debug(' leaving consume_msg ' )