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'):
36 ''' Adds a list of libraries to LD_PRELOAD '''
37 preload = os.environ.get(
"LD_PRELOAD",
"")
39 preload = preload.replace(
" ",
":").split(
":")
43 for libname
in set(preload).intersection(newpreload):
44 logging.warning(
"Ignoring preload of library %s because it is "
45 "already in LD_PRELOAD.", libname)
48 for libname
in newpreload
49 if libname
not in set(preload)]
53 preload =
":".join(preload)
54 os.environ[
"LD_PRELOAD"] = preload
55 logging.info(
"Setting LD_PRELOAD='%s'", preload)
61 Convert the given path to a real path if the pointed file exists, otherwise
64 path = os.path.normpath(os.path.expandvars(path))
65 if os.path.exists(path):
66 path = os.path.realpath(path)
70 _qmt_tmp_opt_files = []
73 Given a .qmt file, return the command line arguments of the corresponding
76 from xml.etree
import ElementTree
as ET
77 global _qmt_tmp_opt_files
79 qmt = ET.parse(qmtfile)
80 args = [a.text
for a
in qmt.findall(
"argument[@name='args']//text")]
81 options = qmt.find(
"argument[@name='options']/text")
83 if options
is not None:
84 from tempfile
import NamedTemporaryFile
86 if re.search(
r"from\s+Gaudi.Configuration\s+import\s+\*"
87 r"|from\s+Configurables\s+import", options.text):
88 tmp_opts = NamedTemporaryFile(suffix=
'.py')
90 tmp_opts = NamedTemporaryFile(suffix=
'.opts')
91 tmp_opts.write(options.text)
93 args.append(tmp_opts.name)
94 _qmt_tmp_opt_files.append(tmp_opts)
98 qmtfile = os.path.abspath(qmtfile)
99 if 'qmtest' in qmtfile.split(os.path.sep):
102 while os.path.basename(testdir) !=
'qmtest':
103 testdir = os.path.dirname(testdir)
107 old_cwd = os.getcwd()
109 args =
map(rationalizepath, args)
115 if __name__ ==
"__main__":
117 if os.environ.get(
'LC_ALL') !=
'C':
118 print '# setting LC_ALL to "C"'
119 os.environ[
'LC_ALL'] =
'C'
121 from optparse
import OptionParser
122 parser = OptionParser(usage =
"%prog [options] <opts_file> ...")
123 parser.add_option(
"-n",
"--dry-run", action=
"store_true",
124 help=
"do not run the application, just parse option files")
125 parser.add_option(
"-p",
"--pickle-output", action=
"store", type=
"string",
127 help=
"DEPRECATED: use '--output file.pkl' instead. Write "
128 "the parsed options as a pickle file (static option "
130 parser.add_option(
"-v",
"--verbose", action=
"store_true",
131 help=
"print the parsed options")
132 parser.add_option(
"--old-opts", action=
"store_true",
133 help=
"format printed options in old option files style")
134 parser.add_option(
"--all-opts", action=
"store_true",
135 help=
"print all the option (even if equal to default)")
141 parser.add_option(
"--ncpus", action=
"store", type=
"int", default=0,
142 help=
"start the application in parallel mode using NCPUS processes. "
143 "0 => serial mode (default), -1 => use all CPUs")
146 """Add the option line to a list together with its position in the
149 parser.values.options.append((len(parser.largs), value))
150 parser.add_option(
"--option", action=
"callback", callback=option_cb,
151 type =
"string", nargs = 1,
152 help=
"add a single line (Python) option to the configuration. "
153 "All options lines are executed, one after the other, in "
155 parser.add_option(
"--no-conf-user-apply", action=
"store_true",
156 help=
"disable the automatic application of configurable "
157 "users (for backward compatibility)")
158 parser.add_option(
"--old-conf-user-apply", action=
"store_true",
159 help=
"use the old logic when applying ConfigurableUsers "
160 "(with bug #103803) [default]")
161 parser.add_option(
"--new-conf-user-apply", action=
"store_false",
162 dest=
"old_conf_user_apply",
163 help=
"use the new (correct) logic when applying "
164 "ConfigurableUsers (fixed bug #103803), can be "
165 "turned on also with the environment variable "
166 "GAUDI_FIXED_APPLY_CONF")
167 parser.add_option(
"-o",
"--output", action =
"store", type =
"string",
168 help =
"dump the configuration to a file. The format of "
169 "the options is determined by the extension of the "
170 "file name: .pkl = pickle, .py = python, .opts = "
171 "old style options. The python format cannot be "
172 "used to run the application and it contains the "
173 "same dictionary printed with -v")
174 parser.add_option(
"--post-option", action=
"append", type=
"string",
176 help=
"Python options to be executed after the ConfigurableUser "
178 "All options lines are executed, one after the other, in "
180 parser.add_option(
"--debug", action=
"store_true",
181 help=
"enable some debug print-out")
182 parser.add_option(
"--printsequence", action=
"store_true",
183 help=
"print the sequence")
184 if not sys.platform.startswith(
"win"):
186 parser.add_option(
"-T",
"--tcmalloc", action=
"store_true",
187 help=
"Use the Google malloc replacement. The environment "
188 "variable TCMALLOCLIB can be used to specify a different "
189 "name for the library (the default is libtcmalloc.so)")
190 parser.add_option(
"--preload", action=
"append",
191 help=
"Allow pre-loading of special libraries (e.g. Google "
192 "profiling libraries).")
195 parser.add_option(
"--profilerName", type=
"string",
196 help=
"Select one profiler among: igprofPerf, igprofMem and valgrind<toolname>")
199 parser.add_option(
"--profilerOutput", type=
"string",
200 help=
"Specify the name of the output file for the profiler output")
203 parser.add_option(
"--profilerExtraOptions", type=
"string",
204 help=
"Specify additional options for the profiler. The '--' string should be expressed as '__' (--my-opt becomes __my-opt)")
206 parser.add_option(
'--use-temp-opts', action=
'store_true',
207 help=
'when this option is enabled, the options are parsed'
208 ' and stored in a temporary file, then the job is '
209 'restarted using that file as input (to save '
211 parser.add_option(
"--run-info-file", type=
"string",
212 help=
"Save gaudi process information to the file specified (in JSON format)")
214 parser.set_defaults(options = [],
218 profilerExtraOptions =
'',
222 old_conf_user_apply=
'GAUDI_FIXED_APPLY_CONF' not in os.environ,
223 run_info_file =
None)
227 for a
in sys.argv[1:]:
228 if a.endswith(
'.qmt')
and os.path.exists(a):
232 if argv != sys.argv[1:]:
233 print '# Running', sys.argv[0],
'with arguments', argv
235 opts, args = parser.parse_args(args=argv)
241 from multiprocessing
import cpu_count
242 sys_cpus = cpu_count()
243 if opts.ncpus > sys_cpus:
244 s =
"Invalid value : --ncpus : only %i cpus available" % sys_cpus
246 elif opts.ncpus < -1 :
247 s =
"Invalid value : --ncpus must be integer >= -1"
258 if opts.old_opts: prefix =
"// "
262 level = logging.DEBUG
264 root_logger = logging.getLogger()
268 opts.preload.insert(0, os.environ.get(
"TCMALLOCLIB",
"libtcmalloc.so"))
271 preload = os.environ.get(
"LD_PRELOAD",
"")
273 preload = preload.replace(
" ",
":").split(
":")
276 for libname
in set(preload).intersection(opts.preload):
277 logging.warning(
"Ignoring preload of library %s because it is "
278 "already in LD_PRELOAD.", libname)
280 for libname
in opts.preload
281 if libname
not in set(preload)]
284 preload =
":".join(preload)
285 os.environ[
"LD_PRELOAD"] = preload
286 logging.info(
"Restarting with LD_PRELOAD='%s'", preload)
289 args = [ a
for a
in sys.argv
if a !=
'-T' and not '--tcmalloc'.startswith(a) ]
290 os.execv(sys.executable, [sys.executable] + args)
293 if opts.profilerName:
294 profilerName = opts.profilerName
295 profilerExecName =
""
296 profilerOutput = opts.profilerOutput
or (profilerName +
".output")
301 igprofPerfOptions =
"-d -pp -z -o igprof.pp.gz".split()
304 if profilerName ==
"igprof":
305 if not opts.profilerOutput:
306 profilerOutput +=
".profile.gz"
307 profilerOptions =
"-d -z -o %s" % profilerOutput
308 profilerExecName =
"igprof"
310 elif profilerName ==
"igprofPerf":
311 if not opts.profilerOutput:
312 profilerOutput +=
".pp.gz"
313 profilerOptions =
"-d -pp -z -o %s" % profilerOutput
314 profilerExecName =
"igprof"
316 elif profilerName ==
"igprofMem":
317 if not opts.profilerOutput:
318 profilerOutput +=
".mp.gz"
319 profilerOptions =
"-d -mp -z -o %s" % profilerOutput
320 profilerExecName =
"igprof"
322 elif "valgrind" in profilerName:
324 if not opts.profilerOutput:
325 profilerOutput +=
".log"
326 toolname = profilerName.replace(
'valgrind',
'')
327 outoption =
"--log-file"
328 if toolname
in (
"massif",
"callgrind",
"cachegrind"):
329 outoption =
"--%s-out-file" % toolname
330 profilerOptions =
"--tool=%s %s=%s" % (toolname, outoption, profilerOutput)
331 profilerExecName =
"valgrind"
333 elif profilerName ==
"jemalloc":
334 opts.preload.insert(0, os.environ.get(
"JEMALLOCLIB",
"libjemalloc.so"))
335 os.environ[
'MALLOC_CONF'] =
"prof:true,prof_leak:true"
337 root_logger.warning(
"Profiler %s not recognized!" % profilerName)
340 if opts.profilerExtraOptions!=
"":
341 profilerExtraOptions = opts.profilerExtraOptions
342 profilerExtraOptions = profilerExtraOptions.replace(
"__",
"--")
343 profilerOptions +=
" %s" % profilerExtraOptions
347 import distutils.spawn
348 profilerPath = distutils.spawn.find_executable(profilerExecName)
350 root_logger.error(
"Cannot locate profiler %s" % profilerExecName)
353 root_logger.info(
"------ Profiling options are on ------ \n"\
355 " o Options: '%s'.\n"\
356 " o Output: %s" % (profilerExecName
or profilerName, profilerOptions, profilerOutput))
366 profilerOptions +=
" python"
369 arglist = [profilerPath] + profilerOptions.split() + args
370 arglist = [ a
for a
in arglist
if a!=
'' ]
374 os.execv(profilerPath, arglist)
376 arglist = [a
for a
in sys.argv
if not a.startswith(
"--profiler")]
377 os.execv(sys.executable, [sys.executable] + arglist)
381 if opts.pickle_output:
383 root_logger.error(
"Conflicting options: use only --pickle-output or --output")
386 root_logger.warning(
"--pickle-output is deprecated, use --output instead")
387 opts.output = opts.pickle_output
395 options = [
"importOptions(%r)" % f
for f
in args ]
398 optlines = list(opts.options)
400 for pos, l
in optlines:
401 options.insert(pos,l)
409 sys.modules[
"GaudiPython"] =
FakeModule(RuntimeError(
"GaudiPython cannot be used in option files"))
413 if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
414 options = [
'importOptions(%r)' % os.environ[
'GAUDI_TEMP_OPTS_FILE']]
421 exec
"from Gaudi.Configuration import *" in g, l
427 if opts.no_conf_user_apply:
428 logging.info(
"Disabling automatic apply of ConfigurableUser")
430 GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ =
True
433 if opts.old_conf_user_apply:
440 if opts.post_options:
443 exec
"from Gaudi.Configuration import *" in g, l
444 for o
in opts.post_options:
448 if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
449 os.remove(os.environ[
'GAUDI_TEMP_OPTS_FILE'])
450 opts.use_temp_opts =
False
452 if opts.verbose
and not opts.use_temp_opts:
453 c.printconfig(opts.old_opts, opts.all_opts)
455 c.writeconfig(opts.output, opts.all_opts)
457 if opts.use_temp_opts:
458 fd, tmpfile = mkstemp(
'.opts')
460 c.writeconfig(tmpfile, opts.all_opts)
461 os.environ[
'GAUDI_TEMP_OPTS_FILE'] = tmpfile
462 logging.info(
'Restarting from pre-parsed options')
463 os.execv(sys.executable, [sys.executable] + sys.argv)
465 c.printsequence = opts.printsequence
466 if opts.printsequence:
468 logging.warning(
"--printsequence not supported with --ncpus: ignored")
470 logging.warning(
"--printsequence not supported with --dry-run: ignored")
473 del sys.modules[
"GaudiPython"]
477 retcode = c.run(opts.ncpus)
481 if opts.run_info_file:
484 run_info[
"pid"] = os.getpid()
485 run_info[
"retcode"] = retcode
486 if os.path.exists(
'/proc/self/exe'):
488 run_info[
"exe"] = os.readlink(
'/proc/self/exe')
490 logging.info(
"Saving run info to: %s" % opts.run_info_file)
491 with open(opts.run_info_file,
"w")
as f:
492 json.dump(run_info, f)
def InstallRootLoggingHandler
def applyConfigurableUsers()
def __init__(self, exception)
def option_cb(option, opt, value, parser)
def getArgsFromQmt(qmtfile)
struct GAUDI_API map
Parametrisation class for map-like implementation.
def rationalizepath(path)
def getArgsWithoutoProfilerInfo(args)
def __getattr__(self, args, kwargs)
def setLibraryPreload(newpreload)