5 from tempfile
import mkstemp
10 Remove from the arguments the presence of the profiler and its output in 11 order to relaunch the script w/o infinite loops. 13 >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', 'myopts.py']) 16 >>> getArgsWithoutoProfilerInfo(['--profilerName=igprof', 'myopts.py']) 19 >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', '--profilerExtraOptions', 'a b c', 'myopts.py']) 22 >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', '--options', 'a b c', 'myopts.py']) 23 ['--options', 'a b c', 'myopts.py'] 29 if o.startswith(
'--profile'):
38 ''' Adds a list of libraries to LD_PRELOAD ''' 39 preload = os.environ.get(
"LD_PRELOAD",
"")
41 preload = preload.replace(
" ",
":").split(
":")
45 for libname
in set(preload).intersection(newpreload):
46 logging.warning(
"Ignoring preload of library %s because it is " 47 "already in LD_PRELOAD.", libname)
50 for libname
in newpreload
51 if libname
not in set(preload)]
55 preload =
":".join(preload)
56 os.environ[
"LD_PRELOAD"] = preload
57 logging.info(
"Setting LD_PRELOAD='%s'", preload)
64 Convert the given path to a real path if the pointed file exists, otherwise 67 path = os.path.normpath(os.path.expandvars(path))
68 if os.path.exists(path):
69 path = os.path.realpath(path)
75 _qmt_tmp_opt_files = []
80 Given a .qmt file, return the command line arguments of the corresponding 83 from xml.etree
import ElementTree
as ET
84 global _qmt_tmp_opt_files
86 qmt = ET.parse(qmtfile)
87 args = [a.text
for a
in qmt.findall(
"argument[@name='args']//text")]
88 options = qmt.find(
"argument[@name='options']/text")
90 if options
is not None:
91 from tempfile
import NamedTemporaryFile
93 if re.search(
r"from\s+Gaudi.Configuration\s+import\s+\*" 94 r"|from\s+Configurables\s+import", options.text):
95 tmp_opts = NamedTemporaryFile(suffix=
'.py')
97 tmp_opts = NamedTemporaryFile(suffix=
'.opts')
98 tmp_opts.write(options.text)
100 args.append(tmp_opts.name)
101 _qmt_tmp_opt_files.append(tmp_opts)
105 qmtfile = os.path.abspath(qmtfile)
106 if 'qmtest' in qmtfile.split(os.path.sep):
109 while os.path.basename(testdir) !=
'qmtest':
110 testdir = os.path.dirname(testdir)
114 old_cwd = os.getcwd()
116 args =
map(rationalizepath, args)
123 if __name__ ==
"__main__":
125 if os.environ.get(
'LC_ALL') !=
'C':
126 print '# setting LC_ALL to "C"' 127 os.environ[
'LC_ALL'] =
'C' 129 from optparse
import OptionParser
130 parser = OptionParser(usage=
"%prog [options] <opts_file> ...")
131 parser.add_option(
"-n",
"--dry-run", action=
"store_true",
132 help=
"do not run the application, just parse option files")
133 parser.add_option(
"-p",
"--pickle-output", action=
"store", type=
"string",
135 help=
"DEPRECATED: use '--output file.pkl' instead. Write " 136 "the parsed options as a pickle file (static option " 138 parser.add_option(
"-v",
"--verbose", action=
"store_true",
139 help=
"print the parsed options")
140 parser.add_option(
"--old-opts", action=
"store_true",
141 help=
"format printed options in old option files style")
142 parser.add_option(
"--all-opts", action=
"store_true",
143 help=
"print all the option (even if equal to default)")
149 parser.add_option(
"--ncpus", action=
"store", type=
"int", default=0,
150 help=
"start the application in parallel mode using NCPUS processes. " 151 "0 => serial mode (default), -1 => use all CPUs")
154 """Add the option line to a list together with its position in the 157 parser.values.options.append((len(parser.largs), value))
158 parser.add_option(
"--option", action=
"callback", callback=option_cb,
159 type=
"string", nargs=1,
160 help=
"add a single line (Python) option to the configuration. " 161 "All options lines are executed, one after the other, in " 163 parser.add_option(
"--no-conf-user-apply", action=
"store_true",
164 help=
"disable the automatic application of configurable " 165 "users (for backward compatibility)")
166 parser.add_option(
"--old-conf-user-apply", action=
"store_true",
167 help=
"use the old logic when applying ConfigurableUsers " 168 "(with bug #103803) [default]")
169 parser.add_option(
"--new-conf-user-apply", action=
"store_false",
170 dest=
"old_conf_user_apply",
171 help=
"use the new (correct) logic when applying " 172 "ConfigurableUsers (fixed bug #103803), can be " 173 "turned on also with the environment variable " 174 "GAUDI_FIXED_APPLY_CONF")
175 parser.add_option(
"-o",
"--output", action=
"store", type=
"string",
176 help=
"dump the configuration to a file. The format of " 177 "the options is determined by the extension of the " 178 "file name: .pkl = pickle, .py = python, .opts = " 179 "old style options. The python format cannot be " 180 "used to run the application and it contains the " 181 "same dictionary printed with -v")
182 parser.add_option(
"--post-option", action=
"append", type=
"string",
184 help=
"Python options to be executed after the ConfigurableUser " 186 "All options lines are executed, one after the other, in " 188 parser.add_option(
"--debug", action=
"store_true",
189 help=
"enable some debug print-out")
190 parser.add_option(
"--gdb", action=
"store_true",
192 parser.add_option(
"--printsequence", action=
"store_true",
193 help=
"print the sequence")
194 if not sys.platform.startswith(
"win"):
196 parser.add_option(
"-T",
"--tcmalloc", action=
"store_true",
197 help=
"Use the Google malloc replacement. The environment " 198 "variable TCMALLOCLIB can be used to specify a different " 199 "name for the library (the default is libtcmalloc.so)")
200 parser.add_option(
"--preload", action=
"append",
201 help=
"Allow pre-loading of special libraries (e.g. Google " 202 "profiling libraries).")
204 parser.add_option(
"--profilerName", type=
"string",
205 help=
"Select one profiler among: igprofPerf, igprofMem and valgrind<toolname>")
208 parser.add_option(
"--profilerOutput", type=
"string",
209 help=
"Specify the name of the output file for the profiler output")
212 parser.add_option(
"--profilerExtraOptions", type=
"string",
213 help=
"Specify additional options for the profiler. The '--' string should be expressed as '__' (--my-opt becomes __my-opt)")
215 parser.add_option(
'--use-temp-opts', action=
'store_true',
216 help=
'when this option is enabled, the options are parsed' 217 ' and stored in a temporary file, then the job is ' 218 'restarted using that file as input (to save ' 220 parser.add_option(
"--run-info-file", type=
"string",
221 help=
"Save gaudi process information to the file specified (in JSON format)")
223 parser.set_defaults(options=[],
227 profilerExtraOptions=
'',
231 old_conf_user_apply=
'GAUDI_FIXED_APPLY_CONF' not in os.environ,
236 for a
in sys.argv[1:]:
237 if a.endswith(
'.qmt')
and os.path.exists(a):
241 if argv != sys.argv[1:]:
242 print '# Running', sys.argv[0],
'with arguments', argv
244 opts, args = parser.parse_args(args=argv)
250 from multiprocessing
import cpu_count
251 sys_cpus = cpu_count()
252 if opts.ncpus > sys_cpus:
253 s =
"Invalid value : --ncpus : only %i cpus available" % sys_cpus
255 elif opts.ncpus < -1:
256 s =
"Invalid value : --ncpus must be integer >= -1" 273 level = logging.DEBUG
275 root_logger = logging.getLogger()
279 opts.preload.insert(0, os.environ.get(
"TCMALLOCLIB",
"libtcmalloc.so"))
282 preload = os.environ.get(
"LD_PRELOAD",
"")
284 preload = preload.replace(
" ",
":").split(
":")
287 for libname
in set(preload).intersection(opts.preload):
288 logging.warning(
"Ignoring preload of library %s because it is " 289 "already in LD_PRELOAD.", libname)
291 for libname
in opts.preload
292 if libname
not in set(preload)]
295 preload =
":".join(preload)
296 os.environ[
"LD_PRELOAD"] = preload
297 logging.info(
"Restarting with LD_PRELOAD='%s'", preload)
300 args = [a
for a
in sys.argv
if a !=
301 '-T' and not '--tcmalloc'.startswith(a)]
302 os.execv(sys.executable, [sys.executable] + args)
305 if opts.profilerName:
306 profilerName = opts.profilerName
307 profilerExecName =
"" 308 profilerOutput = opts.profilerOutput
or (profilerName +
".output")
313 igprofPerfOptions =
"-d -pp -z -o igprof.pp.gz".split()
316 if profilerName ==
"igprof":
317 if not opts.profilerOutput:
318 profilerOutput +=
".profile.gz" 319 profilerOptions =
"-d -z -o %s" % profilerOutput
320 profilerExecName =
"igprof" 322 elif profilerName ==
"igprofPerf":
323 if not opts.profilerOutput:
324 profilerOutput +=
".pp.gz" 325 profilerOptions =
"-d -pp -z -o %s" % profilerOutput
326 profilerExecName =
"igprof" 328 elif profilerName ==
"igprofMem":
329 if not opts.profilerOutput:
330 profilerOutput +=
".mp.gz" 331 profilerOptions =
"-d -mp -z -o %s" % profilerOutput
332 profilerExecName =
"igprof" 334 elif "valgrind" in profilerName:
336 if not opts.profilerOutput:
337 profilerOutput +=
".log" 338 toolname = profilerName.replace(
'valgrind',
'')
339 outoption =
"--log-file" 340 if toolname
in (
"massif",
"callgrind",
"cachegrind"):
341 outoption =
"--%s-out-file" % toolname
342 profilerOptions =
"--tool=%s %s=%s" % (
343 toolname, outoption, profilerOutput)
344 profilerExecName =
"valgrind" 346 elif profilerName ==
"jemalloc":
347 opts.preload.insert(0, os.environ.get(
348 "JEMALLOCLIB",
"libjemalloc.so"))
349 os.environ[
'MALLOC_CONF'] =
"prof:true,prof_leak:true" 351 root_logger.warning(
"Profiler %s not recognized!" % profilerName)
354 if opts.profilerExtraOptions !=
"":
355 profilerExtraOptions = opts.profilerExtraOptions
356 profilerExtraOptions = profilerExtraOptions.replace(
"__",
"--")
357 profilerOptions +=
" %s" % profilerExtraOptions
361 import distutils.spawn
362 profilerPath = distutils.spawn.find_executable(profilerExecName)
364 root_logger.error(
"Cannot locate profiler %s" %
368 root_logger.info(
"------ Profiling options are on ------ \n" 370 " o Options: '%s'.\n" 371 " o Output: %s" % (profilerExecName
or profilerName, profilerOptions, profilerOutput))
381 profilerOptions +=
" python" 384 arglist = [profilerPath] + profilerOptions.split() + args
385 arglist = [a
for a
in arglist
if a !=
'']
389 os.execv(profilerPath, arglist)
391 arglist = [a
for a
in sys.argv
if not a.startswith(
"--profiler")]
392 os.execv(sys.executable, [sys.executable] + arglist)
396 if opts.pickle_output:
399 "Conflicting options: use only --pickle-output or --output")
403 "--pickle-output is deprecated, use --output instead")
404 opts.output = opts.pickle_output
412 options = [
"importOptions(%r)" % f
for f
in args]
415 optlines = list(opts.options)
418 for pos, l
in optlines:
419 options.insert(pos, l)
429 RuntimeError(
"GaudiPython cannot be used in option files"))
433 if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
434 options = [
'importOptions(%r)' % os.environ[
'GAUDI_TEMP_OPTS_FILE']]
441 exec
"from Gaudi.Configuration import *" in g, l
447 if opts.no_conf_user_apply:
448 logging.info(
"Disabling automatic apply of ConfigurableUser")
450 GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ =
True 453 if opts.old_conf_user_apply:
460 if opts.post_options:
463 exec
"from Gaudi.Configuration import *" in g, l
464 for o
in opts.post_options:
468 if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
469 os.remove(os.environ[
'GAUDI_TEMP_OPTS_FILE'])
470 opts.use_temp_opts =
False 472 if opts.verbose
and not opts.use_temp_opts:
473 c.printconfig(opts.old_opts, opts.all_opts)
475 c.writeconfig(opts.output, opts.all_opts)
477 if opts.use_temp_opts:
478 fd, tmpfile = mkstemp(
'.opts')
480 c.writeconfig(tmpfile, opts.all_opts)
481 os.environ[
'GAUDI_TEMP_OPTS_FILE'] = tmpfile
482 logging.info(
'Restarting from pre-parsed options')
483 os.execv(sys.executable, [sys.executable] + sys.argv)
485 c.printsequence = opts.printsequence
486 if opts.printsequence:
489 "--printsequence not supported with --ncpus: ignored")
492 "--printsequence not supported with --dry-run: ignored")
495 del sys.modules[
"GaudiPython"]
499 retcode = c.run(opts.gdb, opts.ncpus)
503 if opts.run_info_file:
507 run_info[
"pid"] = os.getpid()
508 run_info[
"retcode"] = retcode
509 if os.path.exists(
'/proc/self/exe'):
511 run_info[
"exe"] = os.readlink(
'/proc/self/exe')
513 logging.info(
"Saving run info to: %s" % opts.run_info_file)
514 with open(opts.run_info_file,
"w")
as f:
515 json.dump(run_info, f)
def __init__(self, exception)
def option_cb(option, opt, value, parser)
def rationalizepath(path)
def applyConfigurableUsers()
def getArgsFromQmt(qmtfile)
def InstallRootLoggingHandler(prefix=None, level=None, stream=None, with_time=False)
struct GAUDI_API map
Parametrisation class for map-like implementation.
def getArgsWithoutoProfilerInfo(args)
def __getattr__(self, args, kwargs)
def setLibraryPreload(newpreload)