ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/Submitter.py
Revision: 1.176
Committed: Thu Feb 4 16:32:38 2010 UTC (15 years, 2 months ago) by ewv
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_7_2_p1, CRAB_2_7_1_branch_firstMERGE, CRAB_2_7_2, CRAB_2_7_2_pre4, CRAB_2_7_2_pre3, CRAB_2_7_2_pre2, CRAB_2_7_2_pre1, CRAB_2_7_1, fede_170310, CRAB_2_7_1_pre12, CRAB_2_7_1_pre11, CRAB_2_7_1_pre10, CRAB_2_7_1_pre9, CRAB_LumiMask, CRAB_2_7_lumi, from_LimiMask, CRAB_2_7_1_pre8, CRAB_2_7_1_pre6, CRAB_2_7_1_pre5
Branch point for: CRAB_multiout, CRAB_2_7_1_branch
Changes since 1.175: +9 -8 lines
Log Message:
Note on CAF's in Submitter, clarify

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