13 from __future__
import print_function
17 from tempfile
import mkstemp
22 Remove from the arguments the presence of the profiler and its output in
23 order to relaunch the script w/o infinite loops.
25 >>> getArgsWithoutProfilerInfo(['--profilerName', 'igprof', 'myopts.py'])
28 >>> getArgsWithoutProfilerInfo(['--profilerName=igprof', 'myopts.py'])
31 >>> getArgsWithoutProfilerInfo(['--profilerName', 'igprof', '--profilerExtraOptions', 'a b c', 'myopts.py'])
34 >>> getArgsWithoutProfilerInfo(['--profilerName', 'igprof', '--options', 'a b c', 'myopts.py'])
35 ['--options', 'a b c', 'myopts.py']
41 if o.startswith(
"--profile"):
50 """Adds a list of libraries to LD_PRELOAD"""
51 preload = os.environ.get(
"LD_PRELOAD",
"")
53 preload = preload.replace(
" ",
":").split(
":")
57 for libname
in set(preload).intersection(newpreload):
59 "Ignoring preload of library %s because it is " "already in LD_PRELOAD.",
63 to_load = [libname
for libname
in newpreload
if libname
not in set(preload)]
67 preload =
":".join(preload)
68 os.environ[
"LD_PRELOAD"] = preload
69 logging.info(
"Setting LD_PRELOAD='%s'", preload)
76 Convert the given path to a real path if the pointed file exists, otherwise
79 path = os.path.normpath(os.path.expandvars(path))
80 if os.path.exists(path):
81 path = os.path.realpath(path)
87 _qmt_tmp_opt_files = []
92 Given a .qmt file, return the command line arguments of the corresponding
95 from xml.etree
import ElementTree
as ET
97 global _qmt_tmp_opt_files
99 qmt = ET.parse(qmtfile)
100 args = [a.text
for a
in qmt.findall(
"argument[@name='args']//text")]
101 options = qmt.find(
"argument[@name='options']/text")
104 options
is not None and options.text
is not None
107 from tempfile
import NamedTemporaryFile
110 r"from\s+Gaudi.Configuration\s+import\s+\*"
111 r"|from\s+Configurables\s+import",
114 tmp_opts = NamedTemporaryFile(suffix=
".py")
116 tmp_opts = NamedTemporaryFile(suffix=
".opts")
117 tmp_opts.write(options.text.encode(
"ascii"))
119 args.append(tmp_opts.name)
120 _qmt_tmp_opt_files.append(tmp_opts)
124 qmtfile = os.path.abspath(qmtfile)
125 if "qmtest" in qmtfile.split(os.path.sep):
128 while os.path.basename(testdir) !=
"qmtest":
129 testdir = os.path.dirname(testdir)
133 old_cwd = os.getcwd()
142 if __name__ ==
"__main__":
144 if os.environ.get(
"LC_ALL") !=
"C":
145 print(
'# setting LC_ALL to "C"')
147 os.environ[
"LC_ALL"] =
"C"
149 from optparse
import OptionParser
151 parser = OptionParser(usage=
"%prog [options] <opts_file|function_id> ...")
156 help=
"do not run the application, just parse option files",
164 help=
"DEPRECATED: use '--output file.pkl' instead. Write "
165 "the parsed options as a pickle file (static option "
169 "-v",
"--verbose", action=
"store_true", help=
"print the parsed options"
174 help=
"format printed options in old option files style",
179 help=
"print all the option (even if equal to default)",
191 help=
"start the application in parallel mode using NCPUS processes. "
192 "0 => serial mode (default), -1 => use all CPUs",
196 """Add the option line to a list together with its position in the
199 parser.values.options.append((len(parser.largs), value))
207 help=
"add a single line (Python) option to the configuration. "
208 "All options lines are executed, one after the other, in "
212 "--no-conf-user-apply",
214 help=
"disable the automatic application of configurable "
215 "users (for backward compatibility)",
218 "--old-conf-user-apply",
220 help=
"use the old logic when applying ConfigurableUsers "
221 "(with bug #103803) [default]",
224 "--new-conf-user-apply",
225 action=
"store_false",
226 dest=
"old_conf_user_apply",
227 help=
"use the new (correct) logic when applying "
228 "ConfigurableUsers (fixed bug #103803), can be "
229 "turned on also with the environment variable "
230 "GAUDI_FIXED_APPLY_CONF",
237 help=
"dump the configuration to a file. The format of "
238 "the options is determined by the extension of the "
239 "file name: .pkl = pickle, .py = python, .opts = "
240 "old style options. The python format cannot be "
241 "used to run the application and it contains the "
242 "same dictionary printed with -v",
249 help=
"Python options to be executed after the ConfigurableUser "
251 "All options lines are executed, one after the other, in "
255 "--debug", action=
"store_true", help=
"enable some debug print-out"
257 parser.add_option(
"--gdb", action=
"store_true", help=
"attach gdb")
258 parser.add_option(
"--printsequence", action=
"store_true", help=
"print the sequence")
259 if not sys.platform.startswith(
"win"):
265 help=
"Use the Google malloc replacement. The environment "
266 "variable TCMALLOCLIB can be used to specify a different "
267 "name for the library (the default is libtcmalloc.so)",
272 help=
"Allow pre-loading of special libraries (e.g. Google "
273 "profiling libraries).",
279 help=
"Select one profiler among: igprofPerf, igprofMem and valgrind<toolname>",
286 help=
"Specify the name of the output file for the profiler output",
291 "--profilerExtraOptions",
293 help=
"Specify additional options for the profiler. The '--' string should be expressed as '__' (--my-opt becomes __my-opt)",
299 help=
"when this option is enabled, the options are parsed"
300 " and stored in a temporary file, then the job is "
301 "restarted using that file as input (to save "
307 help=
"Save gaudi process information to the file specified (in JSON format)",
311 help=
"name of the Gaudi::Application to use [default: %default]",
319 profilerExtraOptions=
"",
323 old_conf_user_apply=
"GAUDI_FIXED_APPLY_CONF" not in os.environ,
325 application=
"Gaudi::Application",
330 for a
in sys.argv[1:]:
331 if a.endswith(
".qmt")
and os.path.exists(a):
335 if argv != sys.argv[1:]:
336 print(
"# Running", sys.argv[0],
"with arguments", argv)
338 opts, args = parser.parse_args(args=argv)
344 from multiprocessing
import cpu_count
346 sys_cpus = cpu_count()
347 if opts.ncpus > sys_cpus:
348 s =
"Invalid value : --ncpus : only %i cpus available" % sys_cpus
350 elif opts.ncpus < -1:
351 s =
"Invalid value : --ncpus must be integer >= -1"
368 level = logging.DEBUG
370 root_logger = logging.getLogger()
373 sanitizers = os.environ.get(
"PRELOAD_SANITIZER_LIB",
"")
374 preload = os.environ.get(
"LD_PRELOAD",
"")
376 os.environ[
"PRELOAD_SANITIZER_LIB"] =
""
377 if preload
and sanitizers != preload:
379 "Ignoring PRELOAD_SANITIZER_LIB (={}) as LD_PRELOAD (={}) is "
380 "different and takes precedence.".
format(sanitizers, preload)
383 for sanitizer
in reversed(sanitizers.split(
":")):
384 if sanitizer
not in preload:
385 opts.preload.insert(0, sanitizer)
386 if opts.profilerName ==
"jemalloc":
387 logging.warning(
"jemalloc disabled when using a sanitizer")
388 opts.profilerName =
None
394 logging.warning(
"tcmalloc preload disabled when using a sanitizer")
396 opts.preload.insert(0, os.environ.get(
"TCMALLOCLIB",
"libtcmalloc.so"))
400 preload = os.environ.get(
"LD_PRELOAD",
"")
402 preload = preload.replace(
" ",
":").split(
":")
405 for libname
in set(preload).intersection(opts.preload):
407 "Ignoring preload of library %s because it is "
408 "already in LD_PRELOAD.",
411 to_load = [libname
for libname
in opts.preload
if libname
not in set(preload)]
414 preload =
":".join(preload)
415 os.environ[
"LD_PRELOAD"] = preload
416 logging.info(
"Restarting with LD_PRELOAD='%s'", preload)
419 args = [a
for a
in sys.argv
if a !=
"-T" and not "--tcmalloc".startswith(a)]
420 os.execv(sys.executable, [sys.executable] + args)
423 if opts.profilerName:
424 profilerName = opts.profilerName
425 profilerExecName =
""
426 profilerOutput = opts.profilerOutput
or (profilerName +
".output")
431 igprofPerfOptions =
"-d -pp -z -o igprof.pp.gz".split()
434 if profilerName ==
"igprof":
435 if not opts.profilerOutput:
436 profilerOutput +=
".profile.gz"
437 profilerOptions =
"-d -z -o %s" % profilerOutput
438 profilerExecName =
"igprof"
440 elif profilerName ==
"igprofPerf":
441 if not opts.profilerOutput:
442 profilerOutput +=
".pp.gz"
443 profilerOptions =
"-d -pp -z -o %s" % profilerOutput
444 profilerExecName =
"igprof"
446 elif profilerName ==
"igprofMem":
447 if not opts.profilerOutput:
448 profilerOutput +=
".mp.gz"
449 profilerOptions =
"-d -mp -z -o %s" % profilerOutput
450 profilerExecName =
"igprof"
452 elif "valgrind" in profilerName:
454 if not opts.profilerOutput:
455 profilerOutput +=
".log"
456 toolname = profilerName.replace(
"valgrind",
"")
457 outoption =
"--log-file"
458 if toolname
in (
"massif",
"callgrind",
"cachegrind"):
459 outoption =
"--%s-out-file" % toolname
460 profilerOptions =
"--tool=%s %s=%s" % (toolname, outoption, profilerOutput)
461 profilerExecName =
"valgrind"
463 elif profilerName ==
"jemalloc":
464 opts.preload.insert(0, os.environ.get(
"JEMALLOCLIB",
"libjemalloc.so"))
465 os.environ[
"MALLOC_CONF"] =
"prof:true,prof_leak:true"
467 root_logger.warning(
"Profiler %s not recognized!" % profilerName)
470 if opts.profilerExtraOptions !=
"":
471 profilerExtraOptions = opts.profilerExtraOptions
472 profilerExtraOptions = profilerExtraOptions.replace(
"__",
"--")
473 profilerOptions +=
" %s" % profilerExtraOptions
477 import distutils.spawn
479 profilerPath = distutils.spawn.find_executable(profilerExecName)
481 root_logger.error(
"Cannot locate profiler %s" % profilerExecName)
485 "------ Profiling options are on ------ \n"
487 " o Options: '%s'.\n"
489 % (profilerExecName
or profilerName, profilerOptions, profilerOutput)
500 profilerOptions +=
" python"
503 arglist = [profilerPath] + profilerOptions.split() + args
504 arglist = [a
for a
in arglist
if a !=
""]
508 os.execv(profilerPath, arglist)
510 arglist = [a
for a
in sys.argv
if not a.startswith(
"--profiler")]
511 os.execv(sys.executable, [sys.executable] + arglist)
515 if opts.pickle_output:
518 "Conflicting options: use only --pickle-output or --output"
522 root_logger.warning(
"--pickle-output is deprecated, use --output instead")
523 opts.output = opts.pickle_output
531 Helper class to be able to process option files or options
532 callables as they come along in the arguments.
536 self.
config = {}
if initial_config
is None else initial_config
540 from GaudiConfig2
import CALLABLE_FORMAT, invokeConfig, mergeConfigs
542 if CALLABLE_FORMAT.match(arg):
552 options = [
"process({!r})".
format(arg)
for arg
in args]
555 optlines = list(opts.options)
558 for pos, l
in optlines:
559 options.insert(pos, l)
570 RuntimeError(
"GaudiPython cannot be used in option files")
575 if "GAUDI_TEMP_OPTS_FILE" in os.environ:
576 options = [
"process({!r})".
format(os.environ[
"GAUDI_TEMP_OPTS_FILE"])]
581 g = {
"process": process}
583 exec(
"from Gaudi.Configuration import *", g, l)
588 import GaudiKernel.Proxy.Configurable
590 if opts.no_conf_user_apply:
591 logging.info(
"Disabling automatic apply of ConfigurableUser")
593 GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ =
True
596 if opts.old_conf_user_apply:
597 from GaudiKernel.Proxy.Configurable
import (
598 applyConfigurableUsers_old
as applyConfigurableUsers,
601 from GaudiKernel.Proxy.Configurable
import applyConfigurableUsers
605 if opts.post_options:
606 g = {
"process": process}
608 exec(
"from Gaudi.Configuration import *", g, l)
609 for o
in opts.post_options:
613 if "GAUDI_TEMP_OPTS_FILE" in os.environ:
614 os.remove(os.environ[
"GAUDI_TEMP_OPTS_FILE"])
615 opts.use_temp_opts =
False
619 from GaudiConfig2
import Configurable, mergeConfigs
621 Configurable.instances =
mergeConfigs(Configurable.instances, process.config)
623 if opts.verbose
and not opts.use_temp_opts:
624 c.printconfig(opts.old_opts, opts.all_opts)
626 c.writeconfig(opts.output, opts.all_opts)
628 if opts.use_temp_opts:
629 fd, tmpfile = mkstemp(
".opts")
631 c.writeconfig(tmpfile, opts.all_opts)
632 os.environ[
"GAUDI_TEMP_OPTS_FILE"] = tmpfile
633 logging.info(
"Restarting from pre-parsed options")
634 os.execv(sys.executable, [sys.executable] + sys.argv)
636 c.printsequence = opts.printsequence
637 if opts.printsequence:
639 logging.warning(
"--printsequence not supported with --ncpus: ignored")
641 logging.warning(
"--printsequence not supported with --dry-run: ignored")
643 c.application = opts.application
646 del sys.modules[
"GaudiPython"]
650 retcode = c.run(opts.gdb, opts.ncpus)
654 if opts.run_info_file:
659 run_info[
"pid"] = os.getpid()
660 run_info[
"retcode"] = retcode
661 if os.path.exists(
"/proc/self/exe"):
663 run_info[
"exe"] = os.readlink(
"/proc/self/exe")
665 logging.info(
"Saving run info to: %s" % opts.run_info_file)
666 with open(opts.run_info_file,
"w")
as f:
667 json.dump(run_info, f)