ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/DBinterface.py
(Generate patch)

Comparing COMP/CRAB/python/DBinterface.py (file contents):
Revision 1.27 by farinafa, Tue May 20 16:50:18 2008 UTC vs.
Revision 1.69 by farinafa, Fri Feb 26 17:44:57 2010 UTC

# Line 1 | Line 1
1 from crab_logger import Logger
1   from crab_exceptions import *
2   from crab_util import *
3   import common
# Line 34 | Line 33 | class DBinterface:
33              raise CrabException('Istantiate DB Session : '+str(e))
34  
35          try:
36 <            common.bossSession.installDB('$CRABPRODCOMMONPYTHON/ProdCommon/BossLite/DbObjects/setupDatabase-sqlite.sql')    
36 >            common.bossSession.bossLiteDB.installDB('$CRABPRODCOMMONPYTHON/ProdCommon/BossLite/DbObjects/setupDatabase-sqlite.sql')
37          except Exception, e :
38              raise CrabException('DB Installation error : '+str(e))
39          return
# Line 56 | Line 55 | class DBinterface:
55          Return task with all/list of jobs
56          """
57          try:
58 <            task = common.bossSession.load(1,jobsList)[0]
58 >            task = common.bossSession.load(1,jobsList)
59          except Exception, e :
60 <            common.logger.debug(3, "Error while getting task : " +str(traceback.format_exc()))
60 >            common.logger.debug( "Error while getting task : " +str(traceback.format_exc()))
61              raise CrabException('Error while getting task '+str(e))
62          return task
63  
# Line 67 | Line 66 | class DBinterface:
66          Return a task with a single job
67          """
68          try:
69 <            task = common.bossSession.load(1,str(n))[0]
69 >            task = common.bossSession.load(1,str(n))
70          except Exception, e :
71 <            common.logger.debug(3, "Error while getting job : " +str(traceback.format_exc()))
71 >            common.logger.debug( "Error while getting job : " +str(traceback.format_exc()))
72              raise CrabException('Error while getting job '+str(e))
73          return task
74  
# Line 81 | Line 80 | class DBinterface:
80          """
81          opt={}
82          if optsToSave.get('server_mode',0) == 1: opt['serverName']=optsToSave['server_name']
83 <        opt['name']=common.work_space.taskName()  
83 >        opt['name']= getUserName()+ '_' + string.split(common.work_space.topDir(),'/')[-2]+'_'+common.work_space.task_uuid()
84          task = Task( opt )
85          try:
86              common.bossSession.saveTask( task )
87          except Exception, e :
89           # common.logger.debug(3, "Error creating task : " +str(traceback.format_exc()))
90           # raise CrabException('Error creating task '+str(e))
88              raise CrabException('Error creating task '+str(traceback.format_exc()))
89              
90          return
# Line 107 | Line 104 | class DBinterface:
104  
105          return
106  
107 <    def createJobs_(self, jobsL):
107 >    def createJobs_(self, jobsL, isNew=True):
108          """  
109          Fill crab DB with  the jobs filed
110          """
# Line 116 | Line 113 | class DBinterface:
113          jobs = []
114          for id in jobsL:
115              parameters = {}
116 <            parameters['jobId'] =  str(id)
116 >            parameters['jobId'] = int(id)
117 >            parameters['taskId'] = 1
118              parameters['name'] = task['name'] + '_' + 'job' + str(id)
119              job = Job(parameters)
120              jobs.append(job)
121              common.bossSession.getRunningInstance(job)
122              job.runningJob['status'] = 'C'
123 <        task.addJobs(jobs)
123 >        ## added to support second step creation
124 >        ## maybe it is not needed. TO CLARIFY
125 >        if isNew:
126 >            task.addJobs(jobs)
127 >        else:
128 >            task.appendJobs(jobs)
129          try:
130              common.bossSession.updateDB( task )
131          except Exception, e :
# Line 177 | Line 180 | class DBinterface:
180          """
181          task = self.getTask(jobs)
182  
180        Jobs = task.getJobs()
183          print "--------------------------"
184 <        for Job in Jobs:
184 >        for Job in task.jobs:
185              print "Id: ",Job['jobId']
186              print "Dest: ", Job['dlsDestination']
187              print "Output: ", Job['outputFiles']
188              print "Args: ",Job['arguments']
189 +            print "Service: ",Job.runningJob['service']
190              print "--------------------------"
191          return      
192  
# Line 192 | Line 195 | class DBinterface:
195              tmp_task = self.getTask()
196          return common.bossSession.serialize(tmp_task)  
197  
198 <    def queryID(self,server_mode=0):
198 >    def queryID(self,server_mode=0, jid=False):
199          '''
200          Return the taskId if serevr_mode =1
201          Return the joblistId if serevr_mode =0
# Line 201 | Line 204 | class DBinterface:
204          lines=[]
205          task = self.getTask()
206          if server_mode == 1:
207 <            header= "Task Id = %-40s " %(task['name'])
208 <        else:
207 >            # init client server params...
208 >            CliServerParams(self)      
209 >            headerTask = "Task Id = %-40s\n" %(task['name'])
210 >            headerTask+=  '--------------------------------------------------------------------------------------------\n'
211 >            displayReport(self,headerTask,lines)
212 >            common.logger.info(showWebMon(self.server_name))
213 >        if (jid ) or (server_mode == 0):
214              for job in task.jobs:
215                  toPrint=''
216                  common.bossSession.getRunningInstance(job)
217                  toPrint = "%-5s %-50s " % (job['jobId'],job.runningJob['schedulerId'])
218                  lines.append(toPrint)
219 <            header+= "%-5s %-50s " % ('Job:','ID' )
220 <        displayReport(self,header,lines)
219 >            header+= "%-5s %-50s\n " % ('Job:','ID' )
220 >            header+=  '--------------------------------------------------------------------------------------------\n'
221 >            displayReport(self,header,lines)
222          return  
223  
224      def queryTask(self,attr):
# Line 250 | Line 259 | class DBinterface:
259          try:
260              task = common.bossSession.loadJobDist( 1, attr )
261          except Exception, e :
262 <            common.logger.debug(3, "Error loading Jobs By distinct Attr : " +str(traceback.format_exc()))
262 >            common.logger.debug( "Error loading Jobs By distinct Attr : " +str(traceback.format_exc()))
263              raise CrabException('Error loading Jobs By distinct Attr '+str(e))
264  
265          for i in task: distAttr.append(i[attr])  
# Line 264 | Line 273 | class DBinterface:
273          try:
274              task = common.bossSession.loadJobDistAttr( 1, attr_1, attr_2, list )
275          except Exception, e :
276 <            common.logger.debug(3, "Error loading Jobs By distinct Attr : " +str(traceback.format_exc()))
276 >            common.logger.debug( "Error loading Jobs By distinct Attr : " +str(traceback.format_exc()))
277              raise CrabException('Error loading Jobs By distinct Attr '+str(e))
278  
279          for i in task: distAttr.append(i[attr_1])  
# Line 278 | Line 287 | class DBinterface:
287          try:
288              task = common.bossSession.loadJobsByAttr(attr )
289          except Exception, e :
290 <            common.logger.debug(3, "Error loading Jobs By Attr : " +str(traceback.format_exc()))
290 >            common.logger.debug( "Error loading Jobs By Attr : " +str(traceback.format_exc()))
291              raise CrabException('Error loading Jobs By Attr '+str(e))
292          for i in task:
293              matched.append(i[field])
# Line 293 | Line 302 | class DBinterface:
302          try:
303              task = common.bossSession.loadJobsByRunningAttr(attr)
304          except Exception, e :
305 <            common.logger.debug(3, "Error loading Jobs By Running Attr : " +str(traceback.format_exc()))
305 >            common.logger.debug( "Error loading Jobs By Running Attr : " +str(traceback.format_exc()))
306              raise CrabException('Error loading Jobs By Running Attr '+str(e))
307          for i in task:
308              matched.append(i.runningJob[field])
# Line 309 | Line 318 | class DBinterface:
318              common.bossSession.getNewRunningInstance(job)
319              job.runningJob['status'] = 'C'
320              job.runningJob['statusScheduler'] = 'Created'
321 +            job.runningJob['state'] = 'Created'
322          common.bossSession.updateDB(task)    
323          return        
324  
325      def deserXmlStatus(self, reportList):
326  
327          task = self.getTask()
328 <
328 >        if int(self.cfg_params.get('WMBS.automation',0)) == 1:
329 >            if len(reportList) ==0:
330 >                msg = 'You are using CRAB with WMBS the server is still creating your jobs.\n'
331 >                msg += '\tPlease wait...'
332 >                raise CrabException(msg)
333 >            newJobs =  len(reportList) - len(task.jobs)
334 >            if newJobs != 0:
335 >                isNew=True  
336 >                if len(task.jobs):isNew=False
337 >                jobL=[]  
338 >                for i in range(1,newJobs+1):
339 >                    jobL.append(len(task.jobs)+i)
340 >                self.createJobs_(jobL,isNew)
341 >
342          for job in task.jobs:
343              if not job.runningJob:
344                  raise CrabException( "Missing running object for job %s"%str(job['jobId']) )
345  
346              id = str(job.runningJob['jobId'])
324            # TODO linear search, probably it can be optized with binary search
347              rForJ = None
348 +            nj_list= []
349              for r in reportList:
350                  if r.getAttribute('id') in [ id, 'all']:
351                      rForJ = r
352                      break
353  
354 <            # Data alignment
355 <            jobStatus = str(job.runningJob['statusScheduler'])
356 <            if rForJ.getAttribute('status') not in ['Created', 'Submitting', 'Unknown'] and \
357 <                     job.runningJob['statusScheduler'] != 'Cleared':
358 <                job.runningJob['statusScheduler'] = str( rForJ.getAttribute('status') )
359 <                jobStatus = str(job.runningJob['statusScheduler'])
360 <                job.runningJob['status'] = str( rForJ.getAttribute('sched_status') )
354 >            # check if rForJ is None
355 >            if rForJ is None:
356 >                common.logger.debug( "Missing XML element for job %s, skip update status"%str(id) )
357 >                continue
358 >            
359 >            ## Check the submission number and create new running jobs on the client side
360 >            if rForJ.getAttribute('resubmit') != 'None' and (rForJ.getAttribute('status') not in ['Cleared','Killed','Done','Done (Failed)','Not Submitted', 'Cancelled by user']) :
361 >                if int(job.runningJob['submission']) < int(rForJ.getAttribute('resubmit')) + 1:
362 >                    nj_list.append(id)
363 >            if len(nj_list) > 0: self.newRunJobs(nj_list)
364  
365 <            job.runningJob['destination'] = str( rForJ.getAttribute('site') )
340 <            dest = str(job.runningJob['destination']).split(':')[0]
365 >        task_new = self.getTask()
366  
367 <            job.runningJob['applicationReturnCode'] = str( rForJ.getAttribute('exe_exit') )
368 <            exe_exit_code = str(job.runningJob['applicationReturnCode'])
369 <
370 <            job.runningJob['wrapperReturnCode'] = str( rForJ.getAttribute('job_exit') )
371 <            job_exit_code = str(job.runningJob['wrapperReturnCode'])
372 <
373 <            #if str( rForJ.getAttribute('resubmit') ).isdigit():
374 <            #    job['submissionNumber'] = int(rForJ.getAttribute('resubmit'))
375 <            #    job.runningJob['submission'] =  int(rForJ.getAttribute('resubmit'))
376 <
377 <            # TODO cleared='0' field, how should it be handled/mapped in BL? #Fabio
378 <
379 <        common.bossSession.updateDB( task )
367 >        for job in task_new.jobs:
368 >            id = str(job.runningJob['jobId'])
369 >            # TODO linear search, probably it can be optized with binary search
370 >            rForJ = None
371 >            for r in reportList:
372 >                if r.getAttribute('id') in [ id, 'all']:
373 >                    rForJ = r
374 >                    break
375 >                  
376 >            # Data alignment
377 >            if rForJ.getAttribute('status') not in ['Unknown']: # ['Created', 'Unknown']:
378 >                   # update the status  
379 >                common.logger.debug("Updating DB status for job: " + str(id) + " @: " \
380 >                                      + str(rForJ.getAttribute('status')) )
381 >                job.runningJob['statusScheduler'] = str( rForJ.getAttribute('status') )
382 >                if (rForJ.getAttribute('status') == 'Done' or rForJ.getAttribute('status') == 'Done (Failed)')\
383 >                  and rForJ.getAttribute('sched_status') == 'E' :
384 >                    job.runningJob['status'] = 'SD'
385 >                else:
386 >                    job.runningJob['status'] = str( rForJ.getAttribute('sched_status') )
387 >          
388 >                job.runningJob['schedulerId'] = str( rForJ.getAttribute('sched_id') )
389 >
390 >                job.runningJob['destination'] = str( rForJ.getAttribute('site') )
391 >                dest = str(job.runningJob['destination']).split(':')[0]
392 >              
393 >                job.runningJob['applicationReturnCode'] = str( rForJ.getAttribute('exe_exit') )
394 >                exe_exit_code = str(job.runningJob['applicationReturnCode'])
395 >              
396 >                job.runningJob['wrapperReturnCode'] = str( rForJ.getAttribute('job_exit') )
397 >                job_exit_code = str(job.runningJob['wrapperReturnCode'])
398 >
399 >                job['closed'] = str( rForJ.getAttribute('ended') )
400 >
401 >                job.runningJob['state'] = str( rForJ.getAttribute('action') )
402 >          
403 >                # Needed for unique naming of the output.
404 >                # GIVES PROBLEMS. FIX in >=2_7_2    
405 >                #job.runningJob['submission'] =  str(rForJ.getAttribute('submission'))
406 >          
407 >        common.bossSession.updateDB( task_new )
408          return
409  
410      # FIXME temporary method to verify what kind of submission to perform towards the server
411      def checkIfNeverSubmittedBefore(self):
412          for j in self.getTask().jobs:
413 <            if j.runningJob['submission'] > 1 or j.runningJob['status'] != 'C':
413 >            if j.runningJob['submission'] > 1 or j.runningJob['state'] != 'Created':
414                  return False
415          return True
416  
417 +    # Method to update arguments w.r.t. resubmission number in order to grant unique output
418 +    def updateResubAttribs(self, jobsL):
419 +        task = self.getTask(jobsL)
420 +        for j in task.jobs:
421 +            common.bossSession.getRunningInstance(j)
422 +            newArgs = "%d %d"%(j.runningJob['jobId'], j.runningJob['submission'])
423 +            j['arguments'] = newArgs
424 +            
425 +        common.bossSession.updateDB(task)
426 +        return
427 +
428  

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines