ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/Submitter.py
Revision: 1.171
Committed: Wed Nov 25 14:06:34 2009 UTC (15 years, 5 months ago) by farinafa
Content type: text/x-python
Branch: MAIN
Changes since 1.170: +1 -1 lines
Log Message:
Change name of the field sent to dashboard to 'resubmitter' for bug #58044

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