ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/Submitter.py
Revision: 1.141
Committed: Mon Feb 16 17:46:02 2009 UTC (16 years, 2 months ago) by spiga
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_5_0_pre5, CRAB_2_5_0_pre4
Changes since 1.140: +1 -0 lines
Log Message:
specify also the submission type (direct)

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