5 from tempfile
import mkstemp
9 Remove from the arguments the presence of the profiler and its output in
10 order to relaunch the script w/o infinite loops.
12 >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', 'myopts.py'])
15 >>> getArgsWithoutoProfilerInfo(['--profilerName=igprof', 'myopts.py'])
18 >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', '--profilerExtraOptions', 'a b c', 'myopts.py'])
21 >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', '--options', 'a b c', 'myopts.py'])
22 ['--options', 'a b c', 'myopts.py']
28 if o.startswith(
'--profile'):
37 Convert the given path to a real path if the pointed file exists, otherwise
40 path = os.path.normpath(os.path.expandvars(path))
41 if os.path.exists(path):
42 path = os.path.realpath(path)
46 _qmt_tmp_opt_files = []
49 Given a .qmt file, return the command line arguments of the corresponding
52 from xml.etree
import ElementTree
as ET
53 global _qmt_tmp_opt_files
55 qmt = ET.parse(qmtfile)
56 args = [a.text
for a
in qmt.findall(
"argument[@name='args']//text")]
57 options = qmt.find(
"argument[@name='options']/text")
59 if options
is not None:
60 from tempfile
import NamedTemporaryFile
62 if re.search(
r"from\s+Gaudi.Configuration\s+import\s+\*"
63 r"|from\s+Configurables\s+import", options.text):
64 tmp_opts = NamedTemporaryFile(suffix=
'.py')
66 tmp_opts = NamedTemporaryFile(suffix=
'.opts')
67 tmp_opts.write(options.text)
69 args.append(tmp_opts.name)
70 _qmt_tmp_opt_files.append(tmp_opts)
74 qmtfile = os.path.abspath(qmtfile)
75 if 'qmtest' in qmtfile.split(os.path.sep):
78 while os.path.basename(testdir) !=
'qmtest':
79 testdir = os.path.dirname(testdir)
85 args =
map(rationalizepath, args)
91 if __name__ ==
"__main__":
93 if os.environ.get(
'LC_ALL') !=
'C':
94 print '# setting LC_ALL to "C"'
95 os.environ[
'LC_ALL'] =
'C'
97 from optparse
import OptionParser
98 parser = OptionParser(usage =
"%prog [options] <opts_file> ...")
99 parser.add_option(
"-n",
"--dry-run", action=
"store_true",
100 help=
"do not run the application, just parse option files")
101 parser.add_option(
"-p",
"--pickle-output", action=
"store", type=
"string",
103 help=
"DEPRECATED: use '--output file.pkl' instead. Write "
104 "the parsed options as a pickle file (static option "
106 parser.add_option(
"-v",
"--verbose", action=
"store_true",
107 help=
"print the parsed options")
108 parser.add_option(
"--old-opts", action=
"store_true",
109 help=
"format printed options in old option files style")
110 parser.add_option(
"--all-opts", action=
"store_true",
111 help=
"print all the option (even if equal to default)")
117 parser.add_option(
"--ncpus", action=
"store", type=
"int", default=0,
118 help=
"start the application in parallel mode using NCPUS processes. "
119 "0 => serial mode (default), -1 => use all CPUs")
122 """Add the option line to a list together with its position in the
125 parser.values.options.append((len(parser.largs), value))
126 parser.add_option(
"--option", action=
"callback", callback=option_cb,
127 type =
"string", nargs = 1,
128 help=
"add a single line (Python) option to the configuration. "
129 "All options lines are executed, one after the other, in "
131 parser.add_option(
"--no-conf-user-apply", action=
"store_true",
132 help=
"disable the automatic application of configurable "
133 "users (for backward compatibility)")
134 parser.add_option(
"--old-conf-user-apply", action=
"store_true",
135 help=
"use the old logic when applying ConfigurableUsers "
136 "(with bug #103803) [default]")
137 parser.add_option(
"--new-conf-user-apply", action=
"store_false",
138 dest=
"old_conf_user_apply",
139 help=
"use the new (correct) logic when applying "
140 "ConfigurableUsers (fixed bug #103803), can be "
141 "turned on also with the environment variable "
142 "GAUDI_FIXED_APPLY_CONF")
143 parser.add_option(
"-o",
"--output", action =
"store", type =
"string",
144 help =
"dump the configuration to a file. The format of "
145 "the options is determined by the extension of the "
146 "file name: .pkl = pickle, .py = python, .opts = "
147 "old style options. The python format cannot be "
148 "used to run the application and it contains the "
149 "same dictionary printed with -v")
150 parser.add_option(
"--post-option", action=
"append", type=
"string",
152 help=
"Python options to be executed after the ConfigurableUser "
154 "All options lines are executed, one after the other, in "
156 parser.add_option(
"--debug", action=
"store_true",
157 help=
"enable some debug print-out")
158 parser.add_option(
"--printsequence", action=
"store_true",
159 help=
"print the sequence")
160 if not sys.platform.startswith(
"win"):
162 parser.add_option(
"-T",
"--tcmalloc", action=
"store_true",
163 help=
"Use the Google malloc replacement. The environment "
164 "variable TCMALLOCLIB can be used to specify a different "
165 "name for the library (the default is libtcmalloc.so)")
166 parser.add_option(
"--preload", action=
"append",
167 help=
"Allow pre-loading of special libraries (e.g. Google "
168 "profiling libraries).")
171 parser.add_option(
"--profilerName", type=
"string",
172 help=
"Select one profiler among: igprofPerf, igprofMem and valgrind<toolname>")
175 parser.add_option(
"--profilerOutput", type=
"string",
176 help=
"Specify the name of the output file for the profiler output")
179 parser.add_option(
"--profilerExtraOptions", type=
"string",
180 help=
"Specify additional options for the profiler. The '--' string should be expressed as '__' (--my-opt becomes __my-opt)")
182 parser.add_option(
'--use-temp-opts', action=
'store_true',
183 help=
'when this option is enabled, the options are parsed'
184 ' and stored in a temporary file, then the job is '
185 'restarted using that file as input (to save '
188 parser.set_defaults(options = [],
192 profilerExtraOptions =
'',
196 old_conf_user_apply=
'GAUDI_FIXED_APPLY_CONF' not in os.environ)
200 for a
in sys.argv[1:]:
201 if a.endswith(
'.qmt')
and os.path.exists(a):
205 if argv != sys.argv[1:]:
206 print '# Running', sys.argv[0],
'with arguments', argv
208 opts, args = parser.parse_args(args=argv)
214 from multiprocessing
import cpu_count
215 sys_cpus = cpu_count()
216 if opts.ncpus > sys_cpus:
217 s =
"Invalid value : --ncpus : only %i cpus available" % sys_cpus
219 elif opts.ncpus < -1 :
220 s =
"Invalid value : --ncpus must be integer >= -1"
231 if opts.old_opts: prefix =
"// "
235 level = logging.DEBUG
237 root_logger = logging.getLogger()
241 opts.preload.insert(0, os.environ.get(
"TCMALLOCLIB",
"libtcmalloc.so"))
244 preload = os.environ.get(
"LD_PRELOAD",
"")
246 preload = preload.replace(
" ",
":").split(
":")
249 for libname
in set(preload).intersection(opts.preload):
250 logging.warning(
"Ignoring preload of library %s because it is "
251 "already in LD_PRELOAD.", libname)
253 for libname
in opts.preload
254 if libname
not in set(preload)]
257 preload =
":".join(preload)
258 os.environ[
"LD_PRELOAD"] = preload
259 logging.info(
"Restarting with LD_PRELOAD='%s'", preload)
262 args = [ a
for a
in sys.argv
if a !=
'-T' and not '--tcmalloc'.startswith(a) ]
263 os.execv(sys.executable, [sys.executable] + args)
266 if opts.profilerName:
267 profilerName = opts.profilerName
268 profilerExecName =
""
269 profilerOutput = opts.profilerOutput
or (profilerName +
".output")
274 igprofPerfOptions =
"-d -pp -z -o igprof.pp.gz".split()
277 if profilerName ==
"igprof":
278 if not opts.profilerOutput:
279 profilerOutput +=
".profile.gz"
280 profilerOptions =
"-d -z -o %s" % profilerOutput
281 profilerExecName =
"igprof"
283 elif profilerName ==
"igprofPerf":
284 if not opts.profilerOutput:
285 profilerOutput +=
".pp.gz"
286 profilerOptions =
"-d -pp -z -o %s" % profilerOutput
287 profilerExecName =
"igprof"
289 elif profilerName ==
"igprofMem":
290 if not opts.profilerOutput:
291 profilerOutput +=
".mp.gz"
292 profilerOptions =
"-d -mp -z -o %s" % profilerOutput
293 profilerExecName =
"igprof"
295 elif "valgrind" in profilerName:
297 if not opts.profilerOutput:
298 profilerOutput +=
".log"
299 toolname = profilerName.replace(
'valgrind',
'')
300 outoption =
"--log-file"
301 if toolname
in (
"massif",
"callgrind",
"cachegrind"):
302 outoption =
"--%s-out-file" % toolname
303 profilerOptions =
"--tool=%s %s=%s" % (toolname, outoption, profilerOutput)
304 profilerExecName =
"valgrind"
307 root_logger.warning(
"Profiler %s not recognized!" % profilerName)
310 if opts.profilerExtraOptions!=
"":
311 profilerExtraOptions = opts.profilerExtraOptions
312 profilerExtraOptions = profilerExtraOptions.replace(
"__",
"--")
313 profilerOptions +=
" %s" % profilerExtraOptions
316 import distutils.spawn
317 profilerPath = distutils.spawn.find_executable(profilerExecName)
319 root_logger.error(
"Cannot locate profiler %s" % profilerExecName)
322 root_logger.info(
"------ Profiling options are on ------ \n"\
324 " o Options: '%s'.\n"\
325 " o Output: %s" % (profilerExecName, profilerOptions, profilerOutput))
328 profilerOptions +=
" python"
331 arglist = [profilerPath] + profilerOptions.split() + args
332 arglist = [ a
for a
in arglist
if a!=
'' ]
336 os.execv(profilerPath, arglist)
340 if opts.pickle_output:
342 root_logger.error(
"Conflicting options: use only --pickle-output or --output")
345 root_logger.warning(
"--pickle-output is deprecated, use --output instead")
346 opts.output = opts.pickle_output
354 options = [
"importOptions(%r)" % f
for f
in args ]
357 optlines = list(opts.options)
359 for pos, l
in optlines:
360 options.insert(pos,l)
368 sys.modules[
"GaudiPython"] =
FakeModule(RuntimeError(
"GaudiPython cannot be used in option files"))
372 if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
373 options = [
'importOptions(%r)' % os.environ[
'GAUDI_TEMP_OPTS_FILE']]
380 exec
"from Gaudi.Configuration import *" in g, l
386 if opts.no_conf_user_apply:
387 logging.info(
"Disabling automatic apply of ConfigurableUser")
389 GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ =
True
392 if opts.old_conf_user_apply:
399 if opts.post_options:
402 exec
"from Gaudi.Configuration import *" in g, l
403 for o
in opts.post_options:
407 if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
408 os.remove(os.environ[
'GAUDI_TEMP_OPTS_FILE'])
409 opts.use_temp_opts =
False
411 if opts.verbose
and not opts.use_temp_opts:
412 c.printconfig(opts.old_opts, opts.all_opts)
414 c.writeconfig(opts.output, opts.all_opts)
416 if opts.use_temp_opts:
417 fd, tmpfile = mkstemp(
'.opts')
419 c.writeconfig(tmpfile, opts.all_opts)
420 os.environ[
'GAUDI_TEMP_OPTS_FILE'] = tmpfile
421 logging.info(
'Restarting from pre-parsed options')
422 os.execv(sys.executable, [sys.executable] + sys.argv)
424 c.printsequence = opts.printsequence
425 if opts.printsequence:
427 logging.warning(
"--printsequence not supported with --ncpus: ignored")
429 logging.warning(
"--printsequence not supported with --dry-run: ignored")
432 del sys.modules[
"GaudiPython"]
436 sys.exit(c.run(opts.ncpus))