ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/crab.py
Revision: 1.128
Committed: Wed Oct 3 09:24:34 2007 UTC (17 years, 7 months ago) by farinafa
Content type: text/x-python
Branch: MAIN
CVS Tags: CRAB_2_0_0_pre10
Changes since 1.127: +6 -17 lines
Log Message:
Fix to kill and submit ranges interactions

File Contents

# User Rev Content
1 elmer 1.65 #!/usr/bin/env python
2 nsmirnov 1.1 from crab_help import *
3     from crab_util import *
4     from crab_exceptions import *
5     from crab_logger import Logger
6     from WorkSpace import WorkSpace
7     from JobDB import JobDB
8 slacapra 1.77 from TaskDB import TaskDB
9 nsmirnov 1.3 from JobList import JobList
10 nsmirnov 1.1 from Creator import Creator
11     from Submitter import Submitter
12 slacapra 1.8 from Checker import Checker
13 slacapra 1.9 from PostMortem import PostMortem
14     from Status import Status
15 spiga 1.16 from StatusBoss import StatusBoss
16 corvo 1.42 from ApmonIf import ApmonIf
17 slacapra 1.36 from Cleaner import Cleaner
18 nsmirnov 1.1 import common
19 spiga 1.13 import Statistic
20 spiga 1.107 import commands
21 gutsche 1.121 from BlackWhiteListParser import BlackWhiteListParser
22 nsmirnov 1.1
23 spiga 1.98 from BossSession import *
24 corvo 1.93
25 spiga 1.107 #modified to support server mode
26 mcinquil 1.119 #from SubmitterServer import SubmitterServer
27     #from GetOutputServer import GetOutputServer
28     #from StatusServer import StatusServer
29     #from PostMortemServer import PostMortemServer
30     #from KillerServer import KillerServer
31     #from CleanerServer import CleanerServer
32 spiga 1.107
33 nsmirnov 1.1 import sys, os, time, string
34    
35     ###########################################################################
36     class Crab:
37 nsmirnov 1.3 def __init__(self, opts):
38 fanzago 1.76 ## test_tag
39 nsmirnov 1.1 # The order of main_actions is important !
40 fanzago 1.111 self.main_actions = [ '-create', '-submit' ]
41     ### FEDE new option "-publish" FOR DBS OUTPUT PUBLICATION
42 slacapra 1.70 self.aux_actions = [ '-list', '-kill', '-status', '-getoutput','-get',
43 slacapra 1.67 '-resubmit' , '-cancelAndResubmit', '-testJdl', '-postMortem', '-clean',
44 fanzago 1.111 '-printId', '-publish' ]
45 nsmirnov 1.1
46     # Dictionary of actions, e.g. '-create' -> object of class Creator
47     self.actions = {}
48 fanzago 1.76
49 nsmirnov 1.1 # Configuration file
50     self.cfg_fname = None
51     # Dictionary with configuration parameters
52     self.cfg_params = {}
53    
54     # Current working directory
55     self.cwd = os.getcwd()+'/'
56     # Current time in format 'yymmdd_hhmmss'
57     self.current_time = time.strftime('%y%m%d_%H%M%S',
58     time.localtime(time.time()))
59    
60 nsmirnov 1.3 # Session name (?) Do we need this ?
61 nsmirnov 1.1 self.name = '0'
62    
63     # Job type
64     self.job_type_name = None
65    
66     # Continuation flag
67     self.flag_continue = 0
68    
69     # quiet mode, i.e. no output on screen
70     self.flag_quiet = 0
71     # produce more output
72     self.debug_level = 0
73    
74    
75 nsmirnov 1.3 self.initialize_(opts)
76 nsmirnov 1.1
77     return
78    
79 nsmirnov 1.7 def version():
80 nsmirnov 1.1 return common.prog_version_str
81    
82 nsmirnov 1.7 version = staticmethod(version)
83    
84 nsmirnov 1.3 def initialize_(self, opts):
85 nsmirnov 1.1
86     # Process the '-continue' option first because
87     # in the case of continuation the CRAB configuration
88     # parameters are loaded from already existing Working Space.
89 nsmirnov 1.3 self.processContinueOption_(opts)
90 nsmirnov 1.1
91     # Process ini-file first, then command line options
92     # because they override ini-file settings.
93    
94 nsmirnov 1.3 self.processIniFile_(opts)
95 nsmirnov 1.1
96 nsmirnov 1.3 if self.flag_continue: opts = self.loadConfiguration_(opts)
97 nsmirnov 1.1
98 nsmirnov 1.3 self.processOptions_(opts)
99 nsmirnov 1.1
100 slacapra 1.77 common.taskDB = TaskDB()
101    
102 slacapra 1.101
103 nsmirnov 1.1 if not self.flag_continue:
104 nsmirnov 1.3 self.createWorkingSpace_()
105 slacapra 1.9 optsToBeSaved={}
106     for it in opts.keys():
107     if (it in self.main_actions) or (it in self.aux_actions) or (it == '-debug'):
108     pass
109     else:
110     optsToBeSaved[it]=opts[it]
111 slacapra 1.101 # store in taskDB the opts
112     common.taskDB.setDict(it[1:], optsToBeSaved[it])
113 slacapra 1.9 common.work_space.saveConfiguration(optsToBeSaved, self.cfg_fname)
114 nsmirnov 1.1 pass
115 slacapra 1.77 else:
116     common.taskDB.load()
117 nsmirnov 1.1
118     # At this point all configuration options have been read.
119    
120     args = string.join(sys.argv,' ')
121 slacapra 1.11
122 nsmirnov 1.3 self.updateHistory_(args)
123 slacapra 1.11
124 nsmirnov 1.3 self.createLogger_(args)
125 slacapra 1.11
126 nsmirnov 1.1 common.jobDB = JobDB()
127 corvo 1.51
128 gutsche 1.121 # init BlackWhiteListParser
129     self.blackWhiteListParser = BlackWhiteListParser(self.cfg_params)
130    
131 spiga 1.107 self.UseServer=0
132     try:
133     self.UseServer=int(self.cfg_params['CRAB.server_mode'])
134     except KeyError:
135     pass
136    
137    
138 corvo 1.63 if int(self.cfg_params['USER.activate_monalisa']): self.cfg_params['apmon'] = ApmonIf()
139    
140 nsmirnov 1.3 if self.flag_continue:
141 slacapra 1.12 try:
142     common.jobDB.load()
143 corvo 1.50 self.cfg_params['taskId'] = common.jobDB._jobs[0].taskId
144 slacapra 1.12 common.logger.debug(6, str(common.jobDB))
145     except DBException,e:
146     pass
147 nsmirnov 1.3 pass
148 slacapra 1.11
149 nsmirnov 1.3 self.createScheduler_()
150 slacapra 1.11
151 slacapra 1.106 common.logger.debug(6, 'Used properties:')
152     if (common.logger.debugLevel()<6 ):
153     common.logger.write('Used properties:')
154     keys = self.cfg_params.keys()
155     keys.sort()
156     for k in keys:
157     if self.cfg_params[k]:
158     common.logger.debug(6, ' '+k+' : '+str(self.cfg_params[k]))
159     if (common.logger.debugLevel()<6 ):
160     common.logger.write(' '+k+' : '+str(self.cfg_params[k]))
161     pass
162     else:
163     common.logger.debug(6, ' '+k+' : ')
164     if (common.logger.debugLevel()<6 ):
165     common.logger.write(' '+k+' : ')
166 nsmirnov 1.3 pass
167     pass
168 slacapra 1.106 common.logger.debug(6, 'End of used properties.\n')
169     if (common.logger.debugLevel()<6 ):
170     common.logger.write('End of used properties.\n')
171    
172 nsmirnov 1.3 self.initializeActions_(opts)
173 nsmirnov 1.1 return
174    
175 nsmirnov 1.3 def processContinueOption_(self,opts):
176 nsmirnov 1.1
177     continue_dir = None
178 nsmirnov 1.4
179     # Look for the '-continue' option.
180    
181 nsmirnov 1.1 for opt in opts.keys():
182     if ( opt in ('-continue','-c') ):
183     self.flag_continue = 1
184     val = opts[opt]
185     if val:
186     if val[0] == '/': continue_dir = val # abs path
187     else: continue_dir = self.cwd + val # rel path
188     pass
189 nsmirnov 1.4 break
190     pass
191    
192     # Look for actions which has sense only with '-continue'
193    
194     if not self.flag_continue:
195     for opt in opts.keys():
196 slacapra 1.102 if ( opt in (self.aux_actions)):
197 nsmirnov 1.4 self.flag_continue = 1
198     break
199 nsmirnov 1.1 pass
200     pass
201 slacapra 1.102 if ("-submit" in opts.keys() and "-create" not in opts.keys() ):
202     self.flag_continue = 1
203 nsmirnov 1.1
204     if not self.flag_continue: return
205    
206     if not continue_dir:
207     prefix = common.prog_name + '_' + self.name + '_'
208     continue_dir = findLastWorkDir(prefix)
209     pass
210    
211     if not continue_dir:
212     raise CrabException('Cannot find last working directory.')
213    
214     if not os.path.exists(continue_dir):
215     msg = 'Cannot continue because the working directory <'
216     msg += continue_dir
217     msg += '> does not exist.'
218     raise CrabException(msg)
219    
220     # Instantiate WorkSpace
221 fanzago 1.49 common.work_space = WorkSpace(continue_dir, self.cfg_params)
222 nsmirnov 1.1
223     return
224    
225 nsmirnov 1.3 def processIniFile_(self, opts):
226 nsmirnov 1.1 """
227     Processes a configuration INI-file.
228     """
229    
230     # Extract cfg-file name from the cmd-line options.
231    
232     for opt in opts.keys():
233     if ( opt == '-cfg' ):
234     if self.flag_continue:
235     raise CrabException('-continue and -cfg cannot coexist.')
236     if opts[opt] : self.cfg_fname = opts[opt]
237     else : usage()
238     pass
239    
240     elif ( opt == '-name' ):
241     self.name = opts[opt]
242     pass
243    
244     pass
245    
246     # Set default cfg-fname
247    
248     if self.cfg_fname == None:
249     if self.flag_continue:
250     self.cfg_fname = common.work_space.cfgFileName()
251     else:
252     self.cfg_fname = common.prog_name+'.cfg'
253     pass
254     pass
255    
256     # Load cfg-file
257    
258     if string.lower(self.cfg_fname) != 'none':
259     if os.path.exists(self.cfg_fname):
260     self.cfg_params = loadConfig(self.cfg_fname)
261 corvo 1.64 self.cfg_params['user'] = os.environ['USER']
262 nsmirnov 1.1 pass
263     else:
264     msg = 'cfg-file '+self.cfg_fname+' not found.'
265     raise CrabException(msg)
266     pass
267     pass
268    
269     # process the [CRAB] section
270    
271     lhp = len('CRAB.')
272     for k in self.cfg_params.keys():
273     if len(k) >= lhp and k[:lhp] == 'CRAB.':
274     opt = '-'+k[lhp:]
275     if len(opt) >= 3 and opt[:3] == '-__': continue
276     if opt not in opts.keys():
277     opts[opt] = self.cfg_params[k]
278     pass
279     pass
280     pass
281    
282     return
283    
284 nsmirnov 1.3 def processOptions_(self, opts):
285 nsmirnov 1.1 """
286     Processes the command-line options.
287     """
288    
289     for opt in opts.keys():
290     val = opts[opt]
291    
292 nsmirnov 1.3 # Skip actions, they are processed later in initializeActions_()
293     if opt in self.main_actions:
294     self.cfg_params['CRAB.'+opt[1:]] = val
295     continue
296     if opt in self.aux_actions:
297     self.cfg_params['CRAB.'+opt[1:]] = val
298     continue
299 nsmirnov 1.1
300 spiga 1.107 elif ( opt == '-server_mode' ): #Add for server mode usage
301     pass
302     elif ( opt == '-server_name' ):
303     pass
304 nsmirnov 1.1
305     elif ( opt == '-cfg' ):
306     pass
307    
308     elif ( opt in ('-continue', '-c') ):
309 nsmirnov 1.4 # Already processed in processContinueOption_()
310 nsmirnov 1.1 pass
311    
312     elif ( opt == '-jobtype' ):
313     if val : self.job_type_name = string.upper(val)
314     else : usage()
315     pass
316    
317     elif ( opt == '-Q' ):
318     self.flag_quiet = 1
319     pass
320    
321     elif ( opt == '-debug' ):
322 slacapra 1.6 if val: self.debug_level = int(val)
323     else: self.debug_level = 1
324 nsmirnov 1.1 pass
325    
326     elif ( opt == '-scheduler' ):
327     pass
328 slacapra 1.22
329 nsmirnov 1.3 elif string.find(opt,'.') == -1:
330     print common.prog_name+'. Unrecognized option '+opt
331     usage()
332     pass
333 nsmirnov 1.1
334 nsmirnov 1.3 # Override config parameters from INI-file with cmd-line params
335     if string.find(opt,'.') == -1 :
336     self.cfg_params['CRAB.'+opt[1:]] = val
337 nsmirnov 1.1 pass
338 nsmirnov 1.3 else:
339 nsmirnov 1.1 # Command line parameters in the form -SECTION.ENTRY=VALUE
340     self.cfg_params[opt[1:]] = val
341     pass
342     pass
343     return
344    
345 slacapra 1.8 def parseRange_(self, aRange):
346 nsmirnov 1.4 """
347 slacapra 1.8 Takes as the input a string with a range defined in any of the following
348     way, including combination, and return a tuple with the ints defined
349     according to following table. A consistency check is done.
350     NB: the first job is "1", not "0".
351     'all' -> [1,2,..., NJobs]
352     '' -> [1,2,..., NJobs]
353     'n1' -> [n1]
354     'n1-n2' -> [n1, n1+1, n1+2, ..., n2-1, n2]
355     'n1,n2' -> [n1, n2]
356     'n1,n2-n3' -> [n1, n2, n2+1, n2+2, ..., n3-1, n3]
357     """
358     result = []
359 farinafa 1.128
360 slacapra 1.9 common.logger.debug(5,"parseRange_ "+str(aRange))
361     if aRange=='all' or aRange==None or aRange=='':
362 slacapra 1.73 result=range(1,common.jobDB.nJobs()+1)
363 slacapra 1.8 return result
364 slacapra 1.9 elif aRange=='0':
365     return result
366 slacapra 1.8
367 farinafa 1.128 subRanges = str(aRange).split(',') # DEPRECATED # Fabio #string.split(aRange, ',')
368 slacapra 1.8 for subRange in subRanges:
369     result = result+self.parseSimpleRange_(subRange)
370    
371     if self.checkUniqueness_(result):
372     return result
373     else:
374 slacapra 1.33 common.logger.message("Error "+result)
375 slacapra 1.8 return []
376    
377     def checkUniqueness_(self, list):
378     """
379 slacapra 1.9 check if a list contains only unique elements
380 slacapra 1.8 """
381    
382     uniqueList = []
383     # use a list comprehension statement (takes a while to understand)
384    
385     [uniqueList.append(it) for it in list if not uniqueList.count(it)]
386    
387     return (len(list)==len(uniqueList))
388    
389 spiga 1.107 def uuidgen(self):
390     """Generate a UUID"""
391     return commands.getoutput('uuidgen')
392    
393    
394 slacapra 1.8 def parseSimpleRange_(self, aRange):
395     """
396     Takes as the input a string with two integers separated by
397     the minus sign and returns the tuple with these numbers:
398     'n1-n2' -> [n1, n1+1, n1+2, ..., n2-1, n2]
399     'n1' -> [n1]
400     """
401     (start, end) = (None, None)
402    
403     result = []
404 farinafa 1.128 minus = str(aRange).find('-') #DEPRECATED #Fabio #string.find(aRange, '-')
405 slacapra 1.8 if ( minus < 0 ):
406 farinafa 1.128 if int(aRange)>0:
407 corvo 1.97 # FEDE
408     #result.append(int(aRange)-1)
409     ###
410 slacapra 1.62 result.append(int(aRange))
411 slacapra 1.8 else:
412 spiga 1.47 common.logger.message("parseSimpleRange_ ERROR "+aRange)
413     usage()
414     pass
415    
416 nsmirnov 1.4 pass
417     else:
418 farinafa 1.128 (start, end) = str(aRange).split('-')
419 slacapra 1.8 if isInt(start) and isInt(end) and int(start)>0 and int(start)<int(end):
420 corvo 1.97 #result=range(int(start)-1, int(end))
421     result=range(int(start), int(end)+1) #Daniele
422 slacapra 1.8 else:
423 slacapra 1.33 common.logger.message("parseSimpleRange_ ERROR "+start+end)
424 slacapra 1.8
425     return result
426 nsmirnov 1.4
427 nsmirnov 1.3 def initializeActions_(self, opts):
428 nsmirnov 1.1 """
429     For each user action instantiate a corresponding
430     object and put it in the action dictionary.
431     """
432 spiga 1.15
433     for opt in opts.keys():
434    
435 nsmirnov 1.1 val = opts[opt]
436 spiga 1.15
437    
438     if ( opt == '-create' ):
439 gutsche 1.83 if val and val != 'all':
440     msg = 'Per default, CRAB will create all jobs as specified in the crab.cfg file, not the command line!'
441     common.logger.message(msg)
442     msg = 'Submission will still take into account the number of jobs specified on the command line!\n'
443     common.logger.message(msg)
444 slacapra 1.82 ncjobs = 'all'
445    
446     # Instantiate Creator object
447     self.creator = Creator(self.job_type_name,
448     self.cfg_params,
449     ncjobs)
450     self.actions[opt] = self.creator
451    
452     # Initialize the JobDB object if needed
453     if not self.flag_continue:
454     common.jobDB.create(self.creator.nJobs())
455 nsmirnov 1.1 pass
456 nsmirnov 1.3
457 slacapra 1.82 # Create and initialize JobList
458 nsmirnov 1.3
459 slacapra 1.82 common.job_list = JobList(common.jobDB.nJobs(),
460     self.creator.jobType())
461 nsmirnov 1.3
462 slacapra 1.82 common.taskDB.setDict('ScriptName',common.work_space.jobDir()+"/"+self.job_type_name+'.sh')
463     common.taskDB.setDict('JdlName',common.work_space.jobDir()+"/"+self.job_type_name+'.jdl')
464     common.taskDB.setDict('CfgName',common.work_space.jobDir()+"/"+self.creator.jobType().configFilename())
465     common.job_list.setScriptNames(self.job_type_name+'.sh')
466     common.job_list.setJDLNames(self.job_type_name+'.jdl')
467     common.job_list.setCfgNames(self.creator.jobType().configFilename())
468 slacapra 1.9
469 slacapra 1.82 self.creator.writeJobsSpecsToDB()
470 spiga 1.107 taskUnicId= self.uuidgen()
471     common.taskDB.setDict('TasKUUID',taskUnicId)
472 slacapra 1.77
473 slacapra 1.82 common.taskDB.save()
474 nsmirnov 1.3 pass
475 nsmirnov 1.1
476     elif ( opt == '-submit' ):
477 spiga 1.107 # modified to support server mode
478     if (self.UseServer== 1):
479 mcinquil 1.119 from SubmitterServer import SubmitterServer
480 farinafa 1.125 self.actions[opt] = SubmitterServer(self.cfg_params, self.parseRange_(val), val)
481 spiga 1.107 else:
482     # modified to support server mode
483     # get user request
484     nsjobs = -1
485 mcinquil 1.126 chosenJobsList = None
486 spiga 1.107 if val:
487 farinafa 1.125 if val=='all':
488 spiga 1.107 pass
489 farinafa 1.125 elif (type(eval(val)) is int) and eval(val) > 0:
490     # positive number
491     nsjobs = eval(val)
492     # NEW PART # Fabio
493     # put here code for LIST MANAGEMEN
494     elif (type(eval(val)) is tuple)or( type(eval(val)) is int and eval(val)<0 ) :
495     chosenJobsList = self.parseRange_(val)
496     chosenJobsList = [i-1 for i in chosenJobsList ]
497     nsjobs = len(chosenJobsList)
498     #
499 spiga 1.107 else:
500     msg = 'Bad submission option <'+str(val)+'>\n'
501     msg += ' Must be an integer or "all"'
502     msg += ' Generic range is not allowed"'
503     raise CrabException(msg)
504     pass
505    
506     common.logger.debug(5,'nsjobs '+str(nsjobs))
507     # total jobs
508     nj_list = []
509     # get the first not already submitted
510     common.logger.debug(5,'Total jobs '+str(common.jobDB.nJobs()))
511     jobSetForSubmission = 0
512 gutsche 1.110 jobSkippedInSubmission = []
513 slacapra 1.114 datasetpath=self.cfg_params['CMSSW.datasetpath']
514 farinafa 1.125
515     # NEW PART # Fabio
516     # modified to handle list of jobs by the users # Fabio
517     tmp_jList = range(common.jobDB.nJobs())
518     if chosenJobsList != None:
519     tmp_jList = chosenJobsList
520     # build job list
521     for nj in tmp_jList:
522     cleanedBlackWhiteList = self.blackWhiteListParser.cleanForBlackWhiteList(common.jobDB.destination(nj)) # More readable # Fabio
523 mcinquil 1.127 if (cleanedBlackWhiteList != '') or (datasetpath == "None" ) or (datasetpath == None): ## Matty's fix
524 gutsche 1.110 if (common.jobDB.status(nj) not in ['R','S','K','Y','A','D','Z']):
525     jobSetForSubmission +=1
526     nj_list.append(nj)
527 farinafa 1.125 else:
528     continue
529 gutsche 1.110 else :
530     jobSkippedInSubmission.append(nj+1)
531 farinafa 1.125 #
532 spiga 1.107 if nsjobs >0 and nsjobs == jobSetForSubmission:
533     break
534     pass
535 farinafa 1.125 del tmp_jList
536     #
537    
538 spiga 1.107 if nsjobs>jobSetForSubmission:
539     common.logger.message('asking to submit '+str(nsjobs)+' jobs, but only '+str(jobSetForSubmission)+' left: submitting those')
540 gutsche 1.110 if len(jobSkippedInSubmission) > 0 :
541     common.logger.message("Jobs: " + spanRanges(jobSkippedInSubmission) + " skipped because no sites are hosting this data")
542 spiga 1.107 # submit N from last submitted job
543     common.logger.debug(5,'nj_list '+str(nj_list))
544    
545     if len(nj_list) != 0:
546     # Instantiate Submitter object
547     self.actions[opt] = Submitter(self.cfg_params, nj_list)
548     # Create and initialize JobList
549     if len(common.job_list) == 0 :
550     common.job_list = JobList(common.jobDB.nJobs(),
551     None)
552     common.job_list.setJDLNames(self.job_type_name+'.jdl')
553     pass
554 slacapra 1.23 pass
555 slacapra 1.22 else:
556 spiga 1.107 common.logger.message('No jobs left to submit: exiting...')
557 nsmirnov 1.1 pass
558    
559 nsmirnov 1.4 elif ( opt == '-list' ):
560 slacapra 1.8 jobs = self.parseRange_(val)
561    
562     common.jobDB.dump(jobs)
563 nsmirnov 1.4 pass
564    
565 slacapra 1.67 elif ( opt == '-printId' ):
566 spiga 1.115 # modified to support server mode
567     if (self.UseServer== 1):
568     try:
569     common.taskDB.load()
570     WorkDirName =os.path.basename(os.path.split(common.work_space.topDir())[0])
571     projectUniqName = 'crab_'+str(WorkDirName)+'_'+common.taskDB.dict('TasKUUID')
572     print "Task Id = %-40s " %(projectUniqName)
573     except:
574     common.logger.message("Warning :Interaction in query task unique ID failed")
575     pass
576     else:
577     try:
578 slacapra 1.117 common.scheduler.bossTask.load(ALL)
579 spiga 1.115 except RuntimeError,e:
580     common.logger.message( e.__str__() )
581     except ValueError,e:
582     common.logger.message("Warning : Scheduler interaction in query operation failed for jobs:")
583     common.logger.message(e.what())
584     pass
585     task = common.scheduler.bossTask.jobsDict()
586    
587     for c, v in task.iteritems():
588     k = int(c)
589     nj=k
590     id = v['CHAIN_ID']
591     jid = v['SCHED_ID']
592     if jid:
593     print "Job: %-5s Id = %-40s " %(id,jid)
594     #else:
595     # print "Job: ",id," No ID yet"
596 corvo 1.97 pass
597 slacapra 1.67
598 nsmirnov 1.4 elif ( opt == '-status' ):
599 spiga 1.107 # modified to support server mode
600     if (self.UseServer== 1):
601 mcinquil 1.119 from StatusServer import StatusServer
602 spiga 1.107 self.actions[opt] = StatusServer(self.cfg_params)
603     else:
604     jobs = self.parseRange_(val)
605    
606     if len(jobs) != 0:
607     self.actions[opt] = StatusBoss(self.cfg_params)
608     pass
609 slacapra 1.22
610 nsmirnov 1.4 elif ( opt == '-kill' ):
611 slacapra 1.8
612 corvo 1.109 if (self.UseServer== 1):
613 mcinquil 1.119 from KillerServer import KillerServer
614 farinafa 1.128 self.actions[opt] = KillerServer(self.cfg_params,val, self.parseRange_(val)) #Fabio
615 corvo 1.109 else:
616 farinafa 1.120 if val:
617 corvo 1.109 if val =='all':
618     jobs = common.scheduler.listBoss()
619     else:
620     jobs = self.parseRange_(val)
621     common.scheduler.cancel(jobs)
622 spiga 1.31 else:
623 corvo 1.109 common.logger.message("Warning: with '-kill' you _MUST_ specify a job range or 'all'")
624 nsmirnov 1.1
625 farinafa 1.120
626    
627 slacapra 1.70 elif ( opt == '-getoutput' or opt == '-get'):
628 spiga 1.107 # modified to support server mode
629     if (self.UseServer== 1):
630 mcinquil 1.119 from GetOutputServer import GetOutputServer
631 spiga 1.107 self.actions[opt] = GetOutputServer(self.cfg_params)
632 spiga 1.20 else:
633 spiga 1.107 if val=='all' or val==None or val=='':
634     jobs = common.scheduler.listBoss()
635     else:
636     jobs = self.parseRange_(val)
637    
638     jobs_done = []
639     for nj in jobs:
640     jobs_done.append(nj)
641     common.scheduler.getOutput(jobs_done)
642     pass
643 nsmirnov 1.4
644     elif ( opt == '-resubmit' ):
645 slacapra 1.78 if val=='all' or val==None or val=='':
646     jobs = common.scheduler.listBoss()
647 fanzago 1.37 else:
648 slacapra 1.78 jobs = self.parseRange_(val)
649 fanzago 1.37
650 slacapra 1.11 if val:
651     # create a list of jobs to be resubmitted.
652 corvo 1.93 val = string.replace(val,'-',':')
653 slacapra 1.8
654 slacapra 1.22 ### as before, create a Resubmittter Class
655 slacapra 1.78 maxIndex = common.scheduler.listBoss()
656 corvo 1.93 ##
657     # Marco. Vediamo se va meglio cosi'...
658     ##
659 corvo 1.97 try:
660     common.scheduler.bossTask.query(ALL, val)
661     except RuntimeError,e:
662     common.logger.message( e.__str__() )
663     except ValueError,e:
664 slacapra 1.103 common.logger.message( "Warning : Scheduler interaction in query operation failed for jobs:")
665     common.logger.message(e.what())
666 corvo 1.97 pass
667 corvo 1.93 task = common.scheduler.bossTask.jobsDict()
668    
669 slacapra 1.11 nj_list = []
670 corvo 1.93 for c, v in task.iteritems():
671 corvo 1.97 k = int(c)
672     nj=k
673 corvo 1.93 st = v['STATUS']
674    
675 corvo 1.97 if int(nj) <= int(len(maxIndex)) :
676 spiga 1.104 if st in ['K','SA','Z','DA']:
677 corvo 1.97 nj_list.append(int(nj)-1)
678     common.jobDB.setStatus(int(nj)-1,'C')
679 spiga 1.99 elif st in ['E','SE']:
680 spiga 1.60 common.scheduler.moveOutput(nj)
681 corvo 1.97 nj_list.append(int(nj)-1)
682     st = common.jobDB.setStatus(int(nj)-1,'RC')
683 corvo 1.93 elif st in ['W']:
684 corvo 1.97 common.logger.message('Job #'+`int(nj)`+' has status '+crabJobStatusToString(st)+' not yet submitted!!!')
685 spiga 1.60 pass
686 corvo 1.93 elif st in ['SD', 'OR']:
687 corvo 1.97 common.logger.message('Job #'+`int(nj)`+' has status '+crabJobStatusToString(st)+' must be retrieved before resubmission')
688 spiga 1.60 else:
689     common.logger.message('Job #'+`nj`+' has status '+crabJobStatusToString(st)+' must be "killed" before resubmission')
690 slacapra 1.11 else:
691 corvo 1.97 common.logger.message('Job #'+`int(nj)`+' no possible to resubmit!! out of range')
692 fanzago 1.37 if len(common.job_list) == 0 :
693     common.job_list = JobList(common.jobDB.nJobs(),None)
694     common.job_list.setJDLNames(self.job_type_name+'.jdl')
695     pass
696    
697 slacapra 1.11 if len(nj_list) != 0:
698 corvo 1.93 nj_list.sort()
699 slacapra 1.11 # Instantiate Submitter object
700 fanzago 1.58 self.actions[opt] = Submitter(self.cfg_params, nj_list)
701 slacapra 1.11
702 slacapra 1.8 pass
703     pass
704 slacapra 1.11 else:
705     common.logger.message("Warning: with '-resubmit' you _MUST_ specify a job range or 'all'")
706 spiga 1.60 common.logger.message("WARNING: _all_ job specified in the range will be resubmitted!!!")
707 slacapra 1.11 pass
708 fanzago 1.37 common.jobDB.save()
709 slacapra 1.8 pass
710 gutsche 1.61
711 slacapra 1.8 elif ( opt == '-cancelAndResubmit' ):
712 nsmirnov 1.5
713 slacapra 1.78 if val:
714     if val =='all':
715     jobs = common.scheduler.listBoss()
716 spiga 1.47 else:
717 slacapra 1.78 jobs = self.parseRange_(val)
718     # kill submitted jobs
719     common.scheduler.cancel(jobs)
720 spiga 1.47 else:
721 slacapra 1.78 common.logger.message("Warning: with '-cancelAndResubmit' you _MUST_ specify a job range or 'all'")
722 nsmirnov 1.5
723 spiga 1.47 # resubmit cancelled jobs.
724     if val:
725     nj_list = []
726     for nj in jobs:
727     st = common.jobDB.status(int(nj)-1)
728     if st in ['K','A']:
729 corvo 1.97 nj_list.append(int(nj)-1)
730     common.jobDB.setStatus(int(nj)-1,'C')
731 spiga 1.47 elif st == 'Y':
732     common.scheduler.moveOutput(nj)
733 corvo 1.97 nj_list.append(int(nj)-1)
734     st = common.jobDB.setStatus(int(nj)-1,'RC')
735 spiga 1.47 elif st in ['C','X']:
736 corvo 1.97 common.logger.message('Job #'+`int(nj)`+' has status '+crabJobStatusToString(st)+' not yet submitted!!!')
737 spiga 1.47 pass
738     elif st == 'D':
739 corvo 1.97 common.logger.message('Job #'+`int(nj)`+' has status '+crabJobStatusToString(st)+' must be retrieved before resubmission')
740 spiga 1.47 else:
741     common.logger.message('Job #'+`nj`+' has status '+crabJobStatusToString(st)+' must be "killed" before resubmission')
742     pass
743    
744 nsmirnov 1.5 if len(common.job_list) == 0 :
745 spiga 1.47 common.job_list = JobList(common.jobDB.nJobs(),None)
746 nsmirnov 1.5 common.job_list.setJDLNames(self.job_type_name+'.jdl')
747     pass
748 spiga 1.47
749     if len(nj_list) != 0:
750 spiga 1.86 # common.scheduler.resubmit(nj_list)
751 fanzago 1.58 self.actions[opt] = Submitter(self.cfg_params, nj_list)
752 spiga 1.47 pass
753     pass
754     else:
755     common.logger.message("WARNING: _all_ job specified in the rage will be cancelled and resubmitted!!!")
756 nsmirnov 1.5 pass
757 spiga 1.47 common.jobDB.save()
758 nsmirnov 1.4 pass
759 spiga 1.47
760 slacapra 1.28 elif ( opt == '-testJdl' ):
761 slacapra 1.8 jobs = self.parseRange_(val)
762     nj_list = []
763     for nj in jobs:
764 slacapra 1.62 st = common.jobDB.status(nj-1)
765     if st == 'C': nj_list.append(nj-1)
766 slacapra 1.8 pass
767    
768     if len(nj_list) != 0:
769 slacapra 1.77 # Instantiate Checker object
770 slacapra 1.8 self.actions[opt] = Checker(self.cfg_params, nj_list)
771    
772     # Create and initialize JobList
773    
774     if len(common.job_list) == 0 :
775     common.job_list = JobList(common.jobDB.nJobs(), None)
776     common.job_list.setJDLNames(self.job_type_name+'.jdl')
777     pass
778     pass
779    
780 slacapra 1.9 elif ( opt == '-postMortem' ):
781 corvo 1.95
782 spiga 1.108 # modified to support server mode
783     if (self.UseServer== 1):
784 mcinquil 1.119 from PostMortemServer import PostMortemServer
785 spiga 1.108 self.actions[opt] = PostMortemServer(self.cfg_params)
786     else:
787     if val:
788     val = string.replace(val,'-',':')
789     else: val=''
790     nj_list = {}
791 corvo 1.97
792 spiga 1.108 try:
793     common.scheduler.bossTask.query(ALL, val)
794     except RuntimeError,e:
795     common.logger.message( e.__str__() )
796     except ValueError,e:
797     common.logger.message("Warning : Scheduler interaction in query operation failed for jobs:")
798     common.logger.message( e.what())
799     pass
800 corvo 1.93
801 spiga 1.108 task = common.scheduler.bossTask.jobsDict()
802    
803     for c, v in task.iteritems():
804     k = int(c)
805     nj=k
806     if v['SCHED_ID']: nj_list[v['CHAIN_ID']]=v['SCHED_ID']
807     pass
808 slacapra 1.9
809 spiga 1.108 if len(nj_list) != 0:
810 corvo 1.93 # Instantiate PostMortem object
811 spiga 1.108 self.actions[opt] = PostMortem(self.cfg_params, nj_list)
812 slacapra 1.9 # Create and initialize JobList
813 spiga 1.108 if len(common.job_list) == 0 :
814     common.job_list = JobList(common.jobDB.nJobs(), None)
815     common.job_list.setJDLNames(self.job_type_name+'.jdl')
816     pass
817 slacapra 1.9 pass
818 spiga 1.108 else:
819     common.logger.message("No jobs to analyze")
820 slacapra 1.9
821     elif ( opt == '-clean' ):
822     if val != None:
823     raise CrabException("No range allowed for '-clean'")
824 mcinquil 1.118 if (self.UseServer== 1):
825 mcinquil 1.119 from CleanerServer import CleanerServer
826 mcinquil 1.118 self.actions[opt] = CleanerServer(self.cfg_params)
827     else:
828     self.actions[opt] = Cleaner(self.cfg_params)
829    
830 fanzago 1.111 ### FEDE DBS/DLS OUTPUT PUBLICATION
831     elif ( opt == '-publish' ):
832 slacapra 1.113 from DBS2Publisher import Publisher
833 slacapra 1.116 self.actions[opt] = Publisher(self.cfg_params)
834    
835     #precessedData=self.cfg_params['USER.publish_data_name']
836     #self.cfg_params['USER.processed_datasetname']
837     #thePublisher = Publisher(self.cfg_params)
838     # publish_exit_status = thePublisher.publish()
839     # if (publish_exit_status == '1'):
840     # common.logger.message("user data publication --> problems")
841     # else:
842     # common.logger.message("user data publication --> ok ")
843     #########################################
844 nsmirnov 1.1 pass
845     return
846    
847 nsmirnov 1.3 def createWorkingSpace_(self):
848 slacapra 1.9 new_dir = ''
849    
850     try:
851     new_dir = self.cfg_params['USER.ui_working_dir']
852 corvo 1.50 self.cfg_params['taskId'] = self.cfg_params['user'] + '_' + string.split(new_dir, '/')[len(string.split(new_dir, '/')) - 1] + '_' + self.current_time
853 slacapra 1.122 if len(string.split(new_dir, '/')) == 1:
854     new_dir = self.cwd + new_dir
855     else:
856     new_dir = new_dir
857 fanzago 1.48 if os.path.exists(new_dir):
858     if os.listdir(new_dir):
859     msg = new_dir + ' already exists and is not empty. Please remove it before create new task'
860     raise CrabException(msg)
861 slacapra 1.9 except KeyError:
862     new_dir = common.prog_name + '_' + self.name + '_' + self.current_time
863 corvo 1.50 self.cfg_params['taskId'] = self.cfg_params['user'] + '_' + new_dir
864 slacapra 1.9 new_dir = self.cwd + new_dir
865     pass
866 fanzago 1.49 common.work_space = WorkSpace(new_dir, self.cfg_params)
867 nsmirnov 1.1 common.work_space.create()
868     return
869    
870 nsmirnov 1.3 def loadConfiguration_(self, opts):
871 nsmirnov 1.1
872     save_opts = common.work_space.loadSavedOptions()
873    
874     # Override saved options with new command-line options
875    
876     for k in opts.keys():
877     save_opts[k] = opts[k]
878     pass
879    
880     # Return updated options
881     return save_opts
882    
883 nsmirnov 1.3 def createLogger_(self, args):
884 nsmirnov 1.1
885     log = Logger()
886     log.quiet(self.flag_quiet)
887     log.setDebugLevel(self.debug_level)
888     log.write(args+'\n')
889 nsmirnov 1.3 log.message(self.headerString_())
890 nsmirnov 1.1 log.flush()
891     common.logger = log
892     return
893    
894 nsmirnov 1.3 def updateHistory_(self, args):
895 nsmirnov 1.1 history_fname = common.prog_name+'.history'
896     history_file = open(history_fname, 'a')
897     history_file.write(self.current_time+': '+args+'\n')
898     history_file.close()
899     return
900    
901 nsmirnov 1.3 def headerString_(self):
902 nsmirnov 1.1 """
903     Creates a string describing program options either given in
904     the command line or their default values.
905     """
906     header = common.prog_name + ' (version ' + common.prog_version_str + \
907     ') running on ' + \
908     time.ctime(time.time())+'\n\n' + \
909     common.prog_name+'. Working options:\n'
910 fanzago 1.59 #print self.job_type_name
911 nsmirnov 1.1 header = header +\
912 slacapra 1.85 ' scheduler ' + self.cfg_params['CRAB.scheduler'] + '\n'+\
913 nsmirnov 1.1 ' job type ' + self.job_type_name + '\n'+\
914     ' working directory ' + common.work_space.topDir()\
915     + '\n'
916     return header
917    
918 nsmirnov 1.3 def createScheduler_(self):
919 nsmirnov 1.1 """
920     Creates a scheduler object instantiated by its name.
921     """
922 slacapra 1.101 klass_name = 'SchedulerBoss'
923 nsmirnov 1.1 file_name = klass_name
924     try:
925     klass = importName(file_name, klass_name)
926     except KeyError:
927     msg = 'No `class '+klass_name+'` found in file `'+file_name+'.py`'
928     raise CrabException(msg)
929     except ImportError, e:
930 slacapra 1.101 msg = 'Cannot create scheduler Boss'
931 nsmirnov 1.1 msg += ' (file: '+file_name+', class '+klass_name+'):\n'
932     msg += str(e)
933     raise CrabException(msg)
934    
935     common.scheduler = klass()
936     common.scheduler.configure(self.cfg_params)
937     return
938    
939     def run(self):
940     """
941     For each
942     """
943    
944     for act in self.main_actions:
945     if act in self.actions.keys(): self.actions[act].run()
946     pass
947    
948     for act in self.aux_actions:
949     if act in self.actions.keys(): self.actions[act].run()
950     pass
951     return
952    
953     ###########################################################################
954     def processHelpOptions(opts):
955    
956 slacapra 1.11 if len(opts):
957     for opt in opts.keys():
958     if opt in ('-v', '-version', '--version') :
959     print Crab.version()
960     return 1
961     if opt in ('-h','-help','--help') :
962     if opts[opt] : help(opts[opt])
963     else: help()
964     return 1
965     else:
966     usage()
967 corvo 1.93
968 nsmirnov 1.1 return 0
969    
970 corvo 1.93 ###########################################################################
971 nsmirnov 1.1 if __name__ == '__main__':
972 slacapra 1.92 ## Get rid of some useless warning
973 slacapra 1.94 try:
974     import warnings
975     warnings.simplefilter("ignore", RuntimeWarning)
976     except:
977     pass # too bad, you'll get the warning
978 corvo 1.93
979 spiga 1.123 os.putenv("PATH", definePath("new") )
980    
981 nsmirnov 1.1 # Parse command-line options and create a dictionary with
982     # key-value pairs.
983    
984     options = parseOptions(sys.argv[1:])
985    
986     # Process "help" options, such as '-help', '-version'
987    
988 slacapra 1.11 if processHelpOptions(options) : sys.exit(0)
989 nsmirnov 1.1
990     # Create, initialize, and run a Crab object
991    
992     try:
993 nsmirnov 1.3 crab = Crab(options)
994 nsmirnov 1.1 crab.run()
995 corvo 1.54 crab.cfg_params['apmon'].free()
996 nsmirnov 1.1 except CrabException, e:
997     print '\n' + common.prog_name + ': ' + str(e) + '\n'
998     if common.logger:
999     common.logger.write('ERROR: '+str(e)+'\n')
1000     pass
1001     pass
1002    
1003     pass