ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/Submitter.py
Revision: 1.165
Committed: Sat Oct 17 14:57:46 2009 UTC (15 years, 6 months ago) by spiga
Content type: text/x-python
Branch: MAIN
Changes since 1.164: +22 -11 lines
Log Message:
add support for WMBS

File Contents

# User Rev Content
1 nsmirnov 1.1 from Actor import *
2 nsmirnov 1.6 from crab_util import *
3 nsmirnov 1.2 import common
4 corvo 1.9 from ApmonIf import ApmonIf
5 slacapra 1.60 #from random import random
6 corvo 1.30 import time
7 ewv 1.128 import sha
8 ewv 1.139 import socket
9 ewv 1.140 import Scram
10 slacapra 1.60 from ProgressBar import ProgressBar
11     from TerminalController import TerminalController
12 nsmirnov 1.1
13     class Submitter(Actor):
14 slacapra 1.84 def __init__(self, cfg_params, parsed_range, val):
15 nsmirnov 1.1 self.cfg_params = cfg_params
16 ewv 1.161 self.limitJobs = True
17 slacapra 1.84 # get user request
18 spiga 1.156 self.nsjobs = -1
19     self.chosenJobsList = None
20 slacapra 1.84 if val:
21 slacapra 1.91 if val=='range': # for Resubmitter
22 spiga 1.156 self.chosenJobsList = parsed_range
23 ewv 1.92 elif val=='all':
24 slacapra 1.84 pass
25     elif (type(eval(val)) is int) and eval(val) > 0:
26     # positive number
27 spiga 1.156 self.nsjobs = eval(val)
28 slacapra 1.84 elif (type(eval(val)) is tuple)or( type(eval(val)) is int and eval(val)<0 ) :
29 spiga 1.156 self.chosenJobsList = parsed_range
30 farinafa 1.158 self.nsjobs = len(self.chosenJobsList)
31 slacapra 1.84 else:
32     msg = 'Bad submission option <'+str(val)+'>\n'
33     msg += ' Must be an integer or "all"'
34     msg += ' Generic range is not allowed"'
35     raise CrabException(msg)
36     pass
37 spiga 1.165 self.cmdline_nsjobs = self.nsjobs
38     #wmbs
39     self.cmdline_nsjobs = self.nsjobs
40 spiga 1.156 self.seWhiteList = cfg_params.get('GRID.se_white_list',[])
41     self.seBlackList = cfg_params.get('GRID.se_black_list',[])
42 ewv 1.157 self.datasetPath=self.cfg_params['CMSSW.datasetpath']
43     if string.lower(self.datasetPath)=='none':
44     self.datasetPath = None
45 spiga 1.156 self.scram = Scram.Scram(cfg_params)
46     return
47    
48 spiga 1.165 #wmbs
49     def BuildJobList(self,type=0):
50 slacapra 1.84 # total jobs
51     nj_list = []
52 spiga 1.165 if type==1: # and job_list non c'e'
53     self.nj_list = [1,2,3]
54     return
55 spiga 1.156 # build job list
56     from WMCore.SiteScreening.BlackWhiteListParser import SEBlackWhiteListParser
57     self.blackWhiteListParser = SEBlackWhiteListParser(self.seWhiteList, self.seBlackList, common.logger())
58     common.logger.debug('nsjobs '+str(self.nsjobs))
59 slacapra 1.84 # get the first not already submitted
60 spiga 1.115 self.complete_List = common._db.nJobs('list')
61 spiga 1.145 common.logger.debug('Total jobs '+str(len(self.complete_List)))
62 ewv 1.161
63 slacapra 1.84 jobSetForSubmission = 0
64     jobSkippedInSubmission = []
65 spiga 1.115 tmp_jList = self.complete_List
66 spiga 1.156 if self.chosenJobsList != None:
67     tmp_jList = self.chosenJobsList
68 spiga 1.134 for job in common._db.getTask(tmp_jList).jobs:
69 ewv 1.135 cleanedBlackWhiteList = self.blackWhiteListParser.cleanForBlackWhiteList(job['dlsDestination'])
70 ewv 1.157 if (cleanedBlackWhiteList != '') or (self.datasetPath == None):
71 slacapra 1.155 #if ( job.runningJob['status'] in ['C','RC'] and job.runningJob['statusScheduler'] in ['Created',None]):
72     if ( job.runningJob['state'] in ['Created']):
73 slacapra 1.84 jobSetForSubmission +=1
74 ewv 1.135 nj_list.append(job['id'])
75 ewv 1.92 else:
76 slacapra 1.84 continue
77     else :
78 spiga 1.134 jobSkippedInSubmission.append( job['id'] )
79 spiga 1.156 if self.nsjobs >0 and self.nsjobs == jobSetForSubmission:
80 slacapra 1.84 break
81     pass
82 spiga 1.156 if self.nsjobs>jobSetForSubmission:
83     common.logger.info('asking to submit '+str(self.nsjobs)+' jobs, but only '+\
84 spiga 1.134 str(jobSetForSubmission)+' left: submitting those')
85 slacapra 1.84 if len(jobSkippedInSubmission) > 0 :
86     mess =""
87     for jobs in jobSkippedInSubmission:
88     mess += str(jobs) + ","
89 spiga 1.156 common.logger.info("Jobs: " +str(mess) + "\n\tskipped because no sites are hosting this data\n")
90 slacapra 1.89 self.submissionError()
91     pass
92 slacapra 1.84 # submit N from last submitted job
93 spiga 1.145 common.logger.debug('nj_list '+str(nj_list))
94 slacapra 1.84 self.nj_list = nj_list
95 ewv 1.161 if self.limitJobs and len(self.nj_list) > 500:
96     msg = "The CRAB client will not submit more than 500 jobs.\n"
97     msg += "Use the server mode or submit your jobs in smaller groups"
98     raise CrabException(msg)
99 nsmirnov 1.1 return
100 ewv 1.92
101 nsmirnov 1.1 def run(self):
102 nsmirnov 1.2 """
103 slacapra 1.53 The main method of the class: submit jobs in range self.nj_list
104 nsmirnov 1.2 """
105 spiga 1.145 common.logger.debug("Submitter::run() called")
106 slacapra 1.24
107 spiga 1.112 start = time.time()
108    
109 spiga 1.156 self.BuildJobList()
110    
111 ewv 1.128 check = self.checkIfCreate()
112    
113 spiga 1.112 if check == 0 :
114     self.SendMLpre()
115 ewv 1.128
116     list_matched , task = self.performMatch()
117     njs = self.perfromSubmission(list_matched, task)
118    
119 spiga 1.112 stop = time.time()
120 spiga 1.145 common.logger.debug("Submission Time: "+str(stop - start))
121 ewv 1.128
122 spiga 1.149 msg = 'Total of %d jobs submitted'%njs
123 spiga 1.112 if njs != len(self.nj_list) :
124     msg += ' (from %d requested).'%(len(self.nj_list))
125     else:
126     msg += '.'
127 spiga 1.145 common.logger.info(msg)
128 ewv 1.128
129 spiga 1.112 if (njs < len(self.nj_list) or len(self.nj_list)==0):
130     self.submissionError()
131    
132 spiga 1.165 #wmbs
133     def checkIfCreate(self,type=0):
134 spiga 1.112 """
135     """
136     code = 0
137 spiga 1.134 task=common._db.getTask()
138 spiga 1.165 if type == 1 and len(task.jobs)==0:
139     if task['jobType']=='Submitted':
140     common.logger.info("No Request to be submitted: first create it.\n")
141     code=1
142     else:
143     totalCreatedJobs = 0
144     for job in task.jobs:
145     if job.runningJob['state'] == 'Created': totalCreatedJobs +=1
146    
147     if (totalCreatedJobs==0):
148     common.logger.info("No jobs to be submitted: first create them")
149     code = 1
150 ewv 1.128 return code
151 ewv 1.92
152 gutsche 1.70
153 ewv 1.128 def performMatch(self):
154     """
155 spiga 1.113 """
156 spiga 1.145 common.logger.info("Checking available resources...")
157 ewv 1.128 ### define here the list of distinct destinations sites list
158 spiga 1.94 distinct_dests = common._db.queryDistJob_Attr('dlsDestination', 'jobId' ,self.nj_list)
159    
160    
161     ### define here the list of jobs Id for each distinct list of sites
162 spiga 1.112 self.sub_jobs =[] # list of jobs Id list to submit
163 spiga 1.95 jobs_to_match =[] # list of jobs Id to match
164 ewv 1.128 all_jobs=[]
165 spiga 1.94 count=0
166 ewv 1.128 for distDest in distinct_dests:
167 spiga 1.94 all_jobs.append(common._db.queryAttrJob({'dlsDestination':distDest},'jobId'))
168     sub_jobs_temp=[]
169     for i in self.nj_list:
170 ewv 1.128 if i in all_jobs[count]: sub_jobs_temp.append(i)
171 spiga 1.94 if len(sub_jobs_temp)>0:
172 ewv 1.128 self.sub_jobs.append(sub_jobs_temp)
173 spiga 1.112 jobs_to_match.append(self.sub_jobs[count][0])
174 spiga 1.103 count +=1
175 spiga 1.94 sel=0
176 ewv 1.128 matched=[]
177 spiga 1.95
178     task=common._db.getTask()
179     for id_job in jobs_to_match :
180 spiga 1.121 match = common.scheduler.listMatch(distinct_dests[sel], False)
181 slacapra 1.111 if len(match)>0:
182 spiga 1.145 common.logger.info("Found compatible site(s) for job "+str(id_job))
183 slacapra 1.110 matched.append(sel)
184 spiga 1.77 else:
185 spiga 1.145 common.logger.info("No compatible site found, will not submit jobs "+str(self.sub_jobs[sel]))
186 slacapra 1.110 self.submissionError()
187 spiga 1.94 sel += 1
188 ewv 1.92
189 ewv 1.128 return matched , task
190 spiga 1.112
191     def perfromSubmission(self,matched,task):
192    
193 ewv 1.128 njs=0
194    
195 spiga 1.94 ### Progress Bar indicator, deactivate for debug
196 spiga 1.147 if common.debugLevel == 0 :
197 slacapra 1.110 term = TerminalController()
198 ewv 1.128
199     if len(matched)>0:
200 spiga 1.145 common.logger.info(str(len(matched))+" blocks of jobs will be submitted")
201 spiga 1.159 common.logger.debug("Delegating proxy ")
202     try:
203     common.scheduler.delegateProxy()
204     except CrabException:
205 farinafa 1.163 common.logger.debug("Proxy delegation failed ")
206 spiga 1.159
207 ewv 1.128 for ii in matched:
208 spiga 1.145 common.logger.debug('Submitting jobs '+str(self.sub_jobs[ii]))
209 spiga 1.112
210 slacapra 1.110 try:
211 spiga 1.112 common.scheduler.submit(self.sub_jobs[ii],task)
212 slacapra 1.110 except CrabException:
213     raise CrabException("Job not submitted")
214    
215 spiga 1.150 if common.debugLevel == 0 :
216 spiga 1.112 try: pbar = ProgressBar(term, 'Submitting '+str(len(self.sub_jobs[ii]))+' jobs')
217 corvo 1.74 except: pbar = None
218 spiga 1.150 if common.debugLevel == 0:
219 spiga 1.94 if pbar :
220 spiga 1.112 pbar.update(float(ii+1)/float(len(self.sub_jobs)),'please wait')
221 ewv 1.128 ### check the if the submission succeded Maybe not needed or at least simplified
222 spiga 1.112 sched_Id = common._db.queryRunJob('schedulerId', self.sub_jobs[ii])
223 spiga 1.95 listId=[]
224 spiga 1.94 run_jobToSave = {'status' :'S'}
225 spiga 1.108 listRunField = []
226 ewv 1.128 for j in range(len(self.sub_jobs[ii])):
227     if str(sched_Id[j]) != '':
228     listId.append(self.sub_jobs[ii][j])
229     listRunField.append(run_jobToSave)
230 spiga 1.145 common.logger.debug("Submitted job # "+ str(self.sub_jobs[ii][j]))
231 spiga 1.94 njs += 1
232 ewv 1.128 common._db.updateRunJob_(listId, listRunField)
233 mcinquil 1.144 self.stateChange(listId,"SubSuccess")
234 spiga 1.112 self.SendMLpost(self.sub_jobs[ii])
235 spiga 1.94 else:
236 spiga 1.145 common.logger.info("The whole task doesn't found compatible site ")
237 ewv 1.92
238 spiga 1.112 return njs
239 spiga 1.99
240     def submissionError(self):
241     ## add some more verbose message in case submission is not complete
242     msg = 'Submission performed using the Requirements: \n'
243     ### TODO_ DS--BL
244     #msg += common.taskDB.dict("jobtype")+' version: '+common.taskDB.dict("codeVersion")+'\n'
245     #msg += '(Hint: please check if '+common.taskDB.dict("jobtype")+' is available at the Sites)\n'
246 spiga 1.146 if self.cfg_params.has_key('GRID.se_white_list'):
247     msg += '\tSE White List: '+self.cfg_params['GRID.se_white_list']+'\n'
248     if self.cfg_params.has_key('GRID.se_black_list'):
249     msg += '\tSE Black List: '+self.cfg_params['GRID.se_black_list']+'\n'
250     if self.cfg_params.has_key('GRID.ce_white_list'):
251     msg += '\tCE White List: '+self.cfg_params['GRID.ce_white_list']+'\n'
252     if self.cfg_params.has_key('GRID.ce_black_list'):
253     msg += '\tCE Black List: '+self.cfg_params['GRID.ce_black_list']+'\n'
254     removeDefBL = self.cfg_params.get('GRID.remove_default_blacklist',0)
255 spiga 1.137 if removeDefBL == '0':
256     msg += '\tNote: All CMS T1s are BlackListed by default \n'
257 spiga 1.136 msg += '\t(Hint: By whitelisting you force the job to run at this particular site(s).\n'
258     msg += '\tPlease check if :\n'
259     msg += '\t\t -- the dataset is available at this site!\n'
260     msg += '\t\t -- the CMSSW version is available at this site!)\n'
261 spiga 1.145 common.logger.info(msg)
262 spiga 1.112
263     return
264 spiga 1.99
265 spiga 1.112 def collect_MLInfo(self):
266     """
267 ewv 1.129 Prepare DashBoard information
268 spiga 1.112 """
269 ewv 1.92
270 spiga 1.142 taskId = common._db.queryTask('name')
271 spiga 1.112 gridName = string.strip(common.scheduler.userName())
272 spiga 1.151 common.logger.debug("GRIDNAME: %s "%gridName)
273 spiga 1.112 taskType = 'analysis'
274 ewv 1.128
275 spiga 1.112 self.executable = self.cfg_params.get('CMSSW.executable','cmsRun')
276 spiga 1.146 VO = self.cfg_params.get('GRID.virtual_organization','cms')
277 spiga 1.112
278 ewv 1.129 params = {'tool': common.prog_name,
279 ewv 1.157 'SubmissionType':'direct',
280 ewv 1.129 'JSToolVersion': common.prog_version_str,
281     'tool_ui': os.environ.get('HOSTNAME',''),
282     'scheduler': common.scheduler.name(),
283     'GridName': gridName,
284 ewv 1.140 'ApplicationVersion': self.scram.getSWVersion(),
285 ewv 1.129 'taskType': taskType,
286     'vo': VO,
287 spiga 1.142 'CMSUser': getUserName(),
288     'user': getUserName(),
289 spiga 1.143 'taskId': str(taskId),
290 ewv 1.129 'datasetFull': self.datasetPath,
291 ewv 1.128 'exe': self.executable }
292 spiga 1.112
293     return params
294 ewv 1.128
295 spiga 1.112 def SendMLpre(self):
296     """
297 ewv 1.128 Send Pre info to ML
298 spiga 1.112 """
299     params = self.collect_MLInfo()
300 ewv 1.128
301 spiga 1.112 params['jobId'] ='TaskMeta'
302 ewv 1.128
303 spiga 1.112 common.apmon.sendToML(params)
304 ewv 1.128
305 spiga 1.151 common.logger.debug('Submission DashBoard Pre-Submission report: %s'%str(params))
306 ewv 1.128
307 spiga 1.112 return
308 ewv 1.92
309 spiga 1.112 def SendMLpost(self,allList):
310     """
311 ewv 1.128 Send post-submission info to ML
312     """
313     task = common._db.getTask(allList)
314 spiga 1.112
315     params = {}
316     for k,v in self.collect_MLInfo().iteritems():
317     params[k] = v
318 ewv 1.128
319 ewv 1.157 msg = ''
320 spiga 1.112 Sub_Type = 'Direct'
321     for job in task.jobs:
322 ewv 1.128 jj = job['jobId']
323 spiga 1.112 jobId = ''
324     localId = ''
325 ewv 1.128 jid = str(job.runningJob['schedulerId'])
326 ewv 1.162 if common.scheduler.name().upper() in ['CONDOR_G']:
327 spiga 1.112 rb = 'OSG'
328 ewv 1.128 taskHash = sha.new(common._db.queryTask('name')).hexdigest()
329 ewv 1.130 jobId = str(jj) + '_https://' + common.scheduler.name() + '/' + taskHash + '/' + str(jj)
330 spiga 1.151 msg += ('JobID for ML monitoring is created for CONDOR_G scheduler: %s \n'%str(jobId))
331 ewv 1.162 elif common.scheduler.name().upper() in ['GLIDEIN']:
332     rb = common.scheduler.name()
333     jobId = str(jj) + '_https://' + str(jid)
334     msg += ('JobID for ML monitoring is created for GLIDEIN scheduler: %s \n'%str(jobId))
335 mcinquil 1.164 elif common.scheduler.name().upper() in ['LSF', 'CAF', 'PBS']:
336 spiga 1.138 jobId= str(jj) + "_https://"+common.scheduler.name()+":/"+jid+"-"+string.replace(str(task['name']),"_","-")
337 mcinquil 1.164 msg += ('JobID for ML monitoring is created for %s scheduler: %s\n'%(common.scheduler.name().upper(), str(jobId)) )
338 spiga 1.112 rb = common.scheduler.name()
339     localId = jid
340 ewv 1.139 elif common.scheduler.name().upper() in ['CONDOR']:
341     taskHash = sha.new(common._db.queryTask('name')).hexdigest()
342     jobId = str(jj) + '_https://' + socket.gethostname() + '/' + taskHash + '/' + str(jj)
343 ewv 1.162 rb = common.scheduler.name()
344 spiga 1.151 msg += ('JobID for ML monitoring is created for CONDOR scheduler: %s\n'%str(jobId))
345 edelmann 1.154 elif common.scheduler.name().upper() in ['ARC']:
346     taskHash = sha.new(common._db.queryTask('name')).hexdigest()
347 edelmann 1.160 jobId = str(jj) + '_https://' + common.scheduler.name() + '/' + taskHash + '/' + str(jj)
348 edelmann 1.154 msg += ('JobID for ML monitoring is created for ARC scheduler: %s\n'%str(jobId))
349     rb = 'ARC'
350 spiga 1.112 else:
351     jobId = str(jj) + '_' + str(jid)
352 spiga 1.151 msg += ('JobID for ML monitoring is created for gLite scheduler %s\n'%str(jobId))
353 spiga 1.112 rb = str(job.runningJob['service'])
354 ewv 1.128
355     dlsDest = job['dlsDestination']
356 spiga 1.125 if len(dlsDest) == 1 :
357     T_SE=str(dlsDest[0])
358     elif len(dlsDest) == 2 :
359     T_SE=str(dlsDest[0])+','+str(dlsDest[1])
360 ewv 1.128 else :
361 spiga 1.112 T_SE=str(len(dlsDest))+'_Selected_SE'
362    
363    
364     infos = { 'jobId': jobId, \
365     'sid': jid, \
366     'broker': rb, \
367     'bossId': jj, \
368     'SubmissionType': Sub_Type, \
369     'TargetSE': T_SE, \
370     'localId' : localId}
371    
372     for k,v in infos.iteritems():
373     params[k] = v
374    
375 spiga 1.151 msg +=('Submission DashBoard report: %s\n'%str(params))
376 spiga 1.112 common.apmon.sendToML(params)
377 spiga 1.151 common.logger.log(10-1,msg)
378 nsmirnov 1.1 return
379 spiga 1.112
380