ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/COMP/CRAB/python/multicrab.py
Revision: 1.7
Committed: Wed Jan 7 15:23:33 2009 UTC (16 years, 3 months ago) by slacapra
Content type: text/x-python
Branch: MAIN
Changes since 1.6: +16 -13 lines
Log Message:
fix problem with -cfg for multicrab plus cleanup

File Contents

# User Rev Content
1 slacapra 1.1 #!/usr/bin/env python
2     import sys, os, time, string, shutil
3     from crab_util import *
4     from crab import *
5     import common
6    
7     ###########################################################################
8     class MultiCrab:
9     def __init__(self, opts):
10     self.prog_name='multicrab'
11     # Configuration file
12     self.cfg_fname = None
13     # Continuation flag
14     self.flag_continue = 0
15     self.continue_dir = None
16     self.processContinueOption_(opts)
17    
18     self.processIniFile_(opts)
19     # configuration
20     self.opts=opts
21    
22     if not self.flag_continue:
23     self.createWorkSpace()
24    
25     print self.prog_name + ' running on ' + time.ctime(time.time())
26     print ' working directory ' + self.continue_dir
27    
28     crabs=[]
29    
30     def processContinueOption_(self,opts):
31    
32     # Look for the '-continue' option.
33    
34     for opt in opts.keys():
35     if ( opt in ('-continue','-c') ):
36     self.flag_continue = 1
37     val = opts[opt]
38     if val:
39     if val[0] == '/': self.continue_dir = val # abs path
40     else: self.continue_dir = os.getcwd() + '/' + val # rel path
41     pass
42     break
43     pass
44    
45     # Look for actions which has sense only with '-continue'
46    
47     if "-create" not in opts.keys() :
48     self.flag_continue = 1
49    
50     if not self.flag_continue: return
51    
52     if not self.continue_dir:
53     prefix = self.prog_name + '_'
54     self.continue_dir = findLastWorkDir(prefix)
55     pass
56    
57     if not self.continue_dir:
58     raise CrabException('Cannot find last working directory.')
59    
60     if not os.path.exists(self.continue_dir):
61     msg = 'Cannot continue because the working directory <'
62     msg += self.continue_dir
63     msg += '> does not exist.'
64     raise CrabException(msg)
65    
66     return
67    
68     def createWorkSpace(self):
69     # create WorkingDir for Multicrab
70     if 'MULTICRAB.working_dir' in self.opts.keys():
71     self.continue_dir = os.path.abspath(self.opts['MULTICRAB.working_dir'])
72     else:
73     current_time = time.strftime('%y%m%d_%H%M%S', time.localtime(time.time()))
74     self.continue_dir = os.getcwd() + '/' + self.prog_name + '_' + current_time
75    
76     if self.continue_dir and not os.path.exists(self.continue_dir):
77     try:
78     os.mkdir(self.continue_dir)
79     except OSError:
80     msg = 'Cannot create '+str(self.continue_dir) +' directory.\n'
81     raise CrabException(msg)
82     pass
83     else:
84     msg = 'Directory '+str(self.continue_dir) +' already exist.\n'
85     raise CrabException(msg)
86    
87     shutil.copyfile('multicrab.cfg',self.continue_dir+'/multicrab.cfg')
88    
89     return
90    
91     def processIniFile_(self, opts):
92     """
93     Processes a configuration INI-file.
94     """
95    
96     # Extract cfg-file name from the cmd-line options.
97    
98     for opt in opts.keys():
99     if ( opt == '-cfg' ):
100     if self.flag_continue:
101     raise CrabException('-continue and -cfg cannot coexist.')
102     if opts[opt] : self.cfg_fname = opts[opt]
103     else : processHelpOptions()
104     pass
105     pass
106    
107     # Set default cfg-fname
108    
109     if self.cfg_fname == None:
110     if self.flag_continue:
111     self.cfg_fname = self.continue_dir + '/multicrab.cfg'
112     else:
113     self.cfg_fname = 'multicrab.cfg'
114     pass
115     pass
116    
117     # Load cfg-file
118    
119 slacapra 1.7 cfg_params = {}
120 slacapra 1.1 if self.cfg_fname != None:
121     if os.path.exists(self.cfg_fname):
122 slacapra 1.7 cfg_params = self.loadMultiConfig(self.cfg_fname)
123 slacapra 1.1 pass
124     else:
125     msg = 'cfg-file '+self.cfg_fname+' not found.'
126     raise CrabException(msg)
127     pass
128     pass
129    
130     # process the [CRAB] section
131    
132     lhp = len('MULTICRAB.')
133 slacapra 1.7 for k in cfg_params.keys():
134 slacapra 1.1 if len(k) >= lhp and k[:lhp] == 'MULTICRAB.':
135     opt = '-'+k[lhp:]
136     if len(opt) >= 3 and opt[:3] == '-__': continue
137     if opt not in opts.keys():
138 slacapra 1.7 opts[opt] = cfg_params[k]
139 slacapra 1.1 pass
140     pass
141     pass
142    
143     self.cfg_params_dataset = {}
144 slacapra 1.3 common_opts = {}
145 slacapra 1.1 # first get common sections
146 slacapra 1.7 for sec in cfg_params:
147 slacapra 1.1 if sec in ['MULTICRAB']:
148 slacapra 1.7 cfg_common=cfg_params[sec]
149 slacapra 1.1 continue
150     if sec in ['COMMON']:
151 slacapra 1.7 common_opts=cfg_params[sec]
152 slacapra 1.1 continue
153     pass
154    
155     # then Dataset's specific
156 slacapra 1.7 for sec in cfg_params:
157 slacapra 1.1 if sec in ['MULTICRAB', 'COMMON']: continue
158 slacapra 1.7 self.cfg_params_dataset[sec]=cfg_params[sec]
159 slacapra 1.1 # add common to all dataset
160 slacapra 1.3 for key in common_opts:
161     self.cfg_params_dataset[sec][key]=common_opts[key]
162 slacapra 1.1 pass
163    
164     self.cfg=cfg_common['cfg']
165    
166 slacapra 1.2 # read crab.cfg file and search for storage_path
167 slacapra 1.7 crab_cfg_params = loadConfig(self.cfg,{})
168     if cfg_params.has_key("COMMON"):
169     self.user_remote_dir = cfg_params["COMMON"].get("user.user_remote_dir", crab_cfg_params.get("USER.user_remote_dir",None))
170 slacapra 1.6 else:
171 slacapra 1.7 self.user_remote_dir = crab_cfg_params.get("USER.user_remote_dir",None)
172 slacapra 1.1 return
173    
174     def loadMultiConfig(self, file):
175     """
176     returns a dictionary with keys of the form
177     <section>.<option> and the corresponding values
178     """
179     config={}
180     cp = ConfigParser.ConfigParser()
181     cp.read(file)
182     for sec in cp.sections():
183     # print 'Section',sec
184     config[sec]={}
185     for opt in cp.options(sec):
186     #print 'config['+sec+'.'+opt+'] = '+string.strip(cp.get(sec,opt))
187     config[sec][opt] = string.strip(cp.get(sec,opt))
188     return config
189    
190     def run(self):
191     #run crabs
192     for sec in self.cfg_params_dataset:
193     options={}
194     if self.flag_continue:
195     options['-c']=sec
196     # DatasetName to be used
197     options['-USER.ui_working_dir']=sec
198     # options from multicrab.cfg
199     for opt in self.cfg_params_dataset[sec]:
200     tmp="-"+string.upper(opt.split(".")[0])+"."+opt.split(".")[1]
201     options[tmp]=self.cfg_params_dataset[sec][opt]
202 slacapra 1.2 # add section to storage_path if exist in crab.cfg
203 slacapra 1.6 if not self.cfg_params_dataset.has_key("USER.user_remote_dir") and self.user_remote_dir:
204 slacapra 1.5 options["-USER.user_remote_dir"]=self.user_remote_dir+"/"+sec
205 slacapra 1.1 # Input options (command)
206     for opt in self.opts:
207 slacapra 1.7 # remove -cfg
208     if opt=='-cfg': continue
209 slacapra 1.1 options[opt]=self.opts[opt]
210     try:
211 slacapra 1.7 # print options
212 slacapra 1.1 crab = Crab(options)
213     crab.run()
214     common.apmon.free()
215 slacapra 1.5 del crab
216 slacapra 1.1 except CrabException, e:
217     print '\n' + common.prog_name + ': ' + str(e) + '\n'
218     if common.logger:
219     common.logger.write('ERROR: '+str(e)+'\n')
220     pass
221     pass
222     pass
223     pass
224    
225     #common.apmon.free()
226    
227     ###########################################################################
228     if __name__ == '__main__':
229     ## Get rid of some useless warning
230     try:
231     import warnings
232     warnings.simplefilter("ignore", RuntimeWarning)
233     except ImportError:
234     pass # too bad, you'll get the warning
235    
236     # Parse command-line options and create a dictionary with
237     # key-value pairs.
238     options = parseOptions(sys.argv[1:])
239    
240     # Process "help" options, such as '-help', '-version'
241     if processHelpOptions(options) : sys.exit(0)
242    
243     # Create, initialize, and run a Crab object
244     try:
245     multicrab = MultiCrab(options)
246     multicrab.run()
247     except CrabException, e:
248     print '\n' + common.prog_name + ': ' + str(e) + '\n'
249    
250     pass