ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/Submitter.py
Revision: 1.155
Committed: Wed Jun 10 11:40:52 2009 UTC (15 years, 10 months ago) by slacapra
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_6_0_pre8
Changes since 1.154: +5 -14 lines
Log Message:
mods to use new filed "state" to check if action is allowed

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 spiga 1.145 common.logger.debug('nsjobs '+str(nsjobs))
39 slacapra 1.84 # total jobs
40     nj_list = []
41     # get the first not already submitted
42 spiga 1.115 self.complete_List = common._db.nJobs('list')
43 spiga 1.145 common.logger.debug('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 spiga 1.146 seWhiteList = cfg_params.get('GRID.se_white_list',[])
55     seBlackList = cfg_params.get('GRID.se_black_list',[])
56 slacapra 1.152 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 slacapra 1.155 #if ( job.runningJob['status'] in ['C','RC'] and job.runningJob['statusScheduler'] in ['Created',None]):
61     if ( job.runningJob['state'] in ['Created']):
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.145 common.logger.info('asking to submit '+str(nsjobs)+' jobs, but only '+\
73 spiga 1.134 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 spiga 1.145 common.logger.info("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 spiga 1.145 common.logger.debug('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 spiga 1.145 common.logger.debug("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 spiga 1.145 common.logger.debug("Submission Time: "+str(stop - start))
107 ewv 1.128
108 spiga 1.149 msg = 'Total of %d jobs submitted'%njs
109 spiga 1.112 if njs != len(self.nj_list) :
110     msg += ' (from %d requested).'%(len(self.nj_list))
111     else:
112     msg += '.'
113 spiga 1.145 common.logger.info(msg)
114 ewv 1.128
115 spiga 1.112 if (njs < len(self.nj_list) or len(self.nj_list)==0):
116     self.submissionError()
117    
118    
119 ewv 1.128 def checkIfCreate(self):
120 spiga 1.112 """
121     """
122     code = 0
123 spiga 1.94 totalCreatedJobs = 0
124 spiga 1.134 task=common._db.getTask()
125     for job in task.jobs:
126 slacapra 1.155 if job.runningJob['state'] == 'Created': totalCreatedJobs +=1
127 slacapra 1.24
128     if (totalCreatedJobs==0):
129 slacapra 1.155 common.logger.info("No jobs to be submitted: first create them")
130     code = 1
131 ewv 1.128 return code
132 ewv 1.92
133 gutsche 1.70
134 ewv 1.128 def performMatch(self):
135     """
136 spiga 1.113 """
137 spiga 1.145 common.logger.info("Checking available resources...")
138 ewv 1.128 ### define here the list of distinct destinations sites list
139 spiga 1.94 distinct_dests = common._db.queryDistJob_Attr('dlsDestination', 'jobId' ,self.nj_list)
140    
141    
142     ### define here the list of jobs Id for each distinct list of sites
143 spiga 1.112 self.sub_jobs =[] # list of jobs Id list to submit
144 spiga 1.95 jobs_to_match =[] # list of jobs Id to match
145 ewv 1.128 all_jobs=[]
146 spiga 1.94 count=0
147 ewv 1.128 for distDest in distinct_dests:
148 spiga 1.94 all_jobs.append(common._db.queryAttrJob({'dlsDestination':distDest},'jobId'))
149     sub_jobs_temp=[]
150     for i in self.nj_list:
151 ewv 1.128 if i in all_jobs[count]: sub_jobs_temp.append(i)
152 spiga 1.94 if len(sub_jobs_temp)>0:
153 ewv 1.128 self.sub_jobs.append(sub_jobs_temp)
154 spiga 1.112 jobs_to_match.append(self.sub_jobs[count][0])
155 spiga 1.103 count +=1
156 spiga 1.94 sel=0
157 ewv 1.128 matched=[]
158 spiga 1.95
159     task=common._db.getTask()
160    
161     for id_job in jobs_to_match :
162 spiga 1.121 match = common.scheduler.listMatch(distinct_dests[sel], False)
163 slacapra 1.111 if len(match)>0:
164 spiga 1.145 common.logger.info("Found compatible site(s) for job "+str(id_job))
165 slacapra 1.110 matched.append(sel)
166 spiga 1.77 else:
167 spiga 1.145 common.logger.info("No compatible site found, will not submit jobs "+str(self.sub_jobs[sel]))
168 slacapra 1.110 self.submissionError()
169 spiga 1.94 sel += 1
170 ewv 1.92
171 ewv 1.128 return matched , task
172 spiga 1.112
173     def perfromSubmission(self,matched,task):
174    
175 ewv 1.128 njs=0
176    
177 spiga 1.94 ### Progress Bar indicator, deactivate for debug
178 spiga 1.147 if common.debugLevel == 0 :
179 slacapra 1.110 term = TerminalController()
180 ewv 1.128
181     if len(matched)>0:
182 spiga 1.145 common.logger.info(str(len(matched))+" blocks of jobs will be submitted")
183 ewv 1.128 for ii in matched:
184 spiga 1.145 common.logger.debug('Submitting jobs '+str(self.sub_jobs[ii]))
185 spiga 1.112
186 slacapra 1.110 try:
187 spiga 1.112 common.scheduler.submit(self.sub_jobs[ii],task)
188 slacapra 1.110 except CrabException:
189     raise CrabException("Job not submitted")
190    
191 spiga 1.150 if common.debugLevel == 0 :
192 spiga 1.112 try: pbar = ProgressBar(term, 'Submitting '+str(len(self.sub_jobs[ii]))+' jobs')
193 corvo 1.74 except: pbar = None
194 spiga 1.150 if common.debugLevel == 0:
195 spiga 1.94 if pbar :
196 spiga 1.112 pbar.update(float(ii+1)/float(len(self.sub_jobs)),'please wait')
197 ewv 1.128 ### check the if the submission succeded Maybe not needed or at least simplified
198 spiga 1.112 sched_Id = common._db.queryRunJob('schedulerId', self.sub_jobs[ii])
199 spiga 1.95 listId=[]
200 spiga 1.94 run_jobToSave = {'status' :'S'}
201 spiga 1.108 listRunField = []
202 ewv 1.128 for j in range(len(self.sub_jobs[ii])):
203     if str(sched_Id[j]) != '':
204     listId.append(self.sub_jobs[ii][j])
205     listRunField.append(run_jobToSave)
206 spiga 1.145 common.logger.debug("Submitted job # "+ str(self.sub_jobs[ii][j]))
207 spiga 1.94 njs += 1
208 ewv 1.128 common._db.updateRunJob_(listId, listRunField)
209 mcinquil 1.144 self.stateChange(listId,"SubSuccess")
210 spiga 1.112 self.SendMLpost(self.sub_jobs[ii])
211    
212 spiga 1.94 else:
213 spiga 1.145 common.logger.info("The whole task doesn't found compatible site ")
214 ewv 1.92
215 spiga 1.112 return njs
216 spiga 1.99
217     def submissionError(self):
218     ## add some more verbose message in case submission is not complete
219     msg = 'Submission performed using the Requirements: \n'
220     ### TODO_ DS--BL
221     #msg += common.taskDB.dict("jobtype")+' version: '+common.taskDB.dict("codeVersion")+'\n'
222     #msg += '(Hint: please check if '+common.taskDB.dict("jobtype")+' is available at the Sites)\n'
223 spiga 1.146 if self.cfg_params.has_key('GRID.se_white_list'):
224     msg += '\tSE White List: '+self.cfg_params['GRID.se_white_list']+'\n'
225     if self.cfg_params.has_key('GRID.se_black_list'):
226     msg += '\tSE Black List: '+self.cfg_params['GRID.se_black_list']+'\n'
227     if self.cfg_params.has_key('GRID.ce_white_list'):
228     msg += '\tCE White List: '+self.cfg_params['GRID.ce_white_list']+'\n'
229     if self.cfg_params.has_key('GRID.ce_black_list'):
230     msg += '\tCE Black List: '+self.cfg_params['GRID.ce_black_list']+'\n'
231     removeDefBL = self.cfg_params.get('GRID.remove_default_blacklist',0)
232 spiga 1.137 if removeDefBL == '0':
233     msg += '\tNote: All CMS T1s are BlackListed by default \n'
234 spiga 1.136 msg += '\t(Hint: By whitelisting you force the job to run at this particular site(s).\n'
235     msg += '\tPlease check if :\n'
236     msg += '\t\t -- the dataset is available at this site!\n'
237     msg += '\t\t -- the CMSSW version is available at this site!)\n'
238 spiga 1.145 common.logger.info(msg)
239 spiga 1.112
240     return
241 spiga 1.99
242 spiga 1.112 def collect_MLInfo(self):
243     """
244 ewv 1.129 Prepare DashBoard information
245 spiga 1.112 """
246 ewv 1.92
247 spiga 1.142 taskId = common._db.queryTask('name')
248 spiga 1.112 gridName = string.strip(common.scheduler.userName())
249 spiga 1.151 common.logger.debug("GRIDNAME: %s "%gridName)
250 spiga 1.112 taskType = 'analysis'
251 ewv 1.128
252 spiga 1.112 self.datasetPath = self.cfg_params['CMSSW.datasetpath']
253     if string.lower(self.datasetPath)=='none':
254     self.datasetPath = None
255     self.executable = self.cfg_params.get('CMSSW.executable','cmsRun')
256 spiga 1.146 VO = self.cfg_params.get('GRID.virtual_organization','cms')
257 spiga 1.112
258 ewv 1.129 params = {'tool': common.prog_name,
259 spiga 1.141 'SubmissionType':'direct',
260 ewv 1.129 'JSToolVersion': common.prog_version_str,
261     'tool_ui': os.environ.get('HOSTNAME',''),
262     'scheduler': common.scheduler.name(),
263     'GridName': gridName,
264 ewv 1.140 'ApplicationVersion': self.scram.getSWVersion(),
265 ewv 1.129 'taskType': taskType,
266     'vo': VO,
267 spiga 1.142 'CMSUser': getUserName(),
268     'user': getUserName(),
269 spiga 1.143 'taskId': str(taskId),
270 ewv 1.129 'datasetFull': self.datasetPath,
271 ewv 1.128 'exe': self.executable }
272 spiga 1.112
273     return params
274 ewv 1.128
275 spiga 1.112 def SendMLpre(self):
276     """
277 ewv 1.128 Send Pre info to ML
278 spiga 1.112 """
279     params = self.collect_MLInfo()
280 ewv 1.128
281 spiga 1.112 params['jobId'] ='TaskMeta'
282 ewv 1.128
283 spiga 1.112 common.apmon.sendToML(params)
284 ewv 1.128
285 spiga 1.151 common.logger.debug('Submission DashBoard Pre-Submission report: %s'%str(params))
286 ewv 1.128
287 spiga 1.112 return
288 ewv 1.92
289 spiga 1.112 def SendMLpost(self,allList):
290     """
291 ewv 1.128 Send post-submission info to ML
292     """
293     task = common._db.getTask(allList)
294 spiga 1.112
295     params = {}
296     for k,v in self.collect_MLInfo().iteritems():
297     params[k] = v
298 ewv 1.128
299 spiga 1.151 msg = ''
300 spiga 1.112 Sub_Type = 'Direct'
301     for job in task.jobs:
302 ewv 1.128 jj = job['jobId']
303 spiga 1.112 jobId = ''
304     localId = ''
305 ewv 1.128 jid = str(job.runningJob['schedulerId'])
306 ewv 1.130 if common.scheduler.name().upper() in ['CONDOR_G','GLIDEIN']:
307 spiga 1.112 rb = 'OSG'
308 ewv 1.128 taskHash = sha.new(common._db.queryTask('name')).hexdigest()
309 ewv 1.130 jobId = str(jj) + '_https://' + common.scheduler.name() + '/' + taskHash + '/' + str(jj)
310 spiga 1.151 msg += ('JobID for ML monitoring is created for CONDOR_G scheduler: %s \n'%str(jobId))
311 ewv 1.128 elif common.scheduler.name().upper() in ['LSF', 'CAF']:
312 spiga 1.138 jobId= str(jj) + "_https://"+common.scheduler.name()+":/"+jid+"-"+string.replace(str(task['name']),"_","-")
313 spiga 1.151 msg += ('JobID for ML monitoring is created for LSF scheduler: %s\n'%str(jobId))
314 spiga 1.112 rb = common.scheduler.name()
315     localId = jid
316 ewv 1.139 elif common.scheduler.name().upper() in ['CONDOR']:
317     taskHash = sha.new(common._db.queryTask('name')).hexdigest()
318     jobId = str(jj) + '_https://' + socket.gethostname() + '/' + taskHash + '/' + str(jj)
319 spiga 1.151 msg += ('JobID for ML monitoring is created for CONDOR scheduler: %s\n'%str(jobId))
320 ewv 1.139 rb = common.scheduler.name()
321 edelmann 1.154 elif common.scheduler.name().upper() in ['ARC']:
322     taskHash = sha.new(common._db.queryTask('name')).hexdigest()
323     jobId = str(jj) + '_https://' + socket.gethostname() + '/' + taskHash + '/' + str(jj)
324     msg += ('JobID for ML monitoring is created for ARC scheduler: %s\n'%str(jobId))
325     rb = 'ARC'
326 spiga 1.112 else:
327     jobId = str(jj) + '_' + str(jid)
328 spiga 1.151 msg += ('JobID for ML monitoring is created for gLite scheduler %s\n'%str(jobId))
329 spiga 1.112 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 spiga 1.151 msg +=('Submission DashBoard report: %s\n'%str(params))
352 spiga 1.112 common.apmon.sendToML(params)
353 spiga 1.151 common.logger.log(10-1,msg)
354 nsmirnov 1.1 return
355 spiga 1.112
356