gaudirun.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import os
4 import sys
5 from tempfile import mkstemp
6 
8  """
9  Remove from the arguments the presence of the profiler and its output in
10  order to relaunch the script w/o infinite loops.
11 
12  >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', 'myopts.py'])
13  ['myopts.py']
14 
15  >>> getArgsWithoutoProfilerInfo(['--profilerName=igprof', 'myopts.py'])
16  ['myopts.py']
17 
18  >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', '--profilerExtraOptions', 'a b c', 'myopts.py'])
19  ['myopts.py']
20 
21  >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', '--options', 'a b c', 'myopts.py'])
22  ['--options', 'a b c', 'myopts.py']
23  """
24  newargs = []
25  args = list(args) # make a temp copy
26  while args:
27  o = args.pop(0)
28  if o.startswith('--profile'):
29  if '=' not in o:
30  args.pop(0)
31  else:
32  newargs.append(o)
33  return newargs
34 
35 def setLibraryPreload(newpreload):
36  ''' Adds a list of libraries to LD_PRELOAD '''
37  preload = os.environ.get("LD_PRELOAD", "")
38  if preload:
39  preload = preload.replace(" ", ":").split(":")
40  else:
41  preload = []
42 
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)
46 
47  to_load = [libname
48  for libname in newpreload
49  if libname not in set(preload)]
50 
51  if to_load:
52  preload += to_load
53  preload = ":".join(preload)
54  os.environ["LD_PRELOAD"] = preload
55  logging.info("Setting LD_PRELOAD='%s'", preload)
56 
57  return to_load
58 
59 def rationalizepath(path):
60  '''
61  Convert the given path to a real path if the pointed file exists, otherwise
62  just normalize it.
63  '''
64  path = os.path.normpath(os.path.expandvars(path))
65  if os.path.exists(path):
66  path = os.path.realpath(path)
67  return path
68 
69 # variable used to keep alive the temporary option files extracted from the .qmt
70 _qmt_tmp_opt_files = []
71 def getArgsFromQmt(qmtfile):
72  '''
73  Given a .qmt file, return the command line arguments of the corresponding
74  test.
75  '''
76  from xml.etree import ElementTree as ET
77  global _qmt_tmp_opt_files
78  # parse the .qmt file and extract args and options
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")
82 
83  if options is not None: # options need to be dumped in a temporary file
84  from tempfile import NamedTemporaryFile
85  import re
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')
89  else:
90  tmp_opts = NamedTemporaryFile(suffix='.opts')
91  tmp_opts.write(options.text)
92  tmp_opts.flush()
93  args.append(tmp_opts.name)
94  _qmt_tmp_opt_files.append(tmp_opts)
95 
96  # relative paths in a .qmt are rooted in the qmtest directory, so
97  # - find where the .qmt lives
98  qmtfile = os.path.abspath(qmtfile)
99  if 'qmtest' in qmtfile.split(os.path.sep):
100  # this return the path up to the 'qmtest' entry in qmtfile
101  testdir = qmtfile
102  while os.path.basename(testdir) != 'qmtest':
103  testdir = os.path.dirname(testdir)
104  else:
105  testdir = '.'
106  # - temporarily switch to that directory and rationalize the paths
107  old_cwd = os.getcwd()
108  os.chdir(testdir)
109  args = map(rationalizepath, args)
110  os.chdir(old_cwd)
111 
112  return args
113 
114 #---------------------------------------------------------------------
115 if __name__ == "__main__":
116  # ensure that we (and the subprocesses) use the C standard localization
117  if os.environ.get('LC_ALL') != 'C':
118  print '# setting LC_ALL to "C"'
119  os.environ['LC_ALL'] = 'C'
120 
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",
126  metavar = "FILE",
127  help="DEPRECATED: use '--output file.pkl' instead. Write "
128  "the parsed options as a pickle file (static option "
129  "file)")
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)")
136  # GaudiPython Parallel Mode Option
137  # Argument must be an integer in range [ -1, sys_cpus ]
138  # -1 : All available cpus
139  # 0 : Serial Mode (traditional gaudirun)
140  # n>0 : parallel with n cpus (n <= sys_cpus)
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")
144 
145  def option_cb(option, opt, value, parser):
146  """Add the option line to a list together with its position in the
147  argument list.
148  """
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 "
154  "the same context.")
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",
175  dest="post_options",
176  help="Python options to be executed after the ConfigurableUser "
177  "are applied. "
178  "All options lines are executed, one after the other, in "
179  "the same context.")
180  parser.add_option("--debug", action="store_true",
181  help="enable some debug print-out")
182  parser.add_option("--gdb", action="store_true",
183  help="attach gdb")
184  parser.add_option("--printsequence", action="store_true",
185  help="print the sequence")
186  if not sys.platform.startswith("win"):
187  # These options can be used only on unix platforms
188  parser.add_option("-T", "--tcmalloc", action="store_true",
189  help="Use the Google malloc replacement. The environment "
190  "variable TCMALLOCLIB can be used to specify a different "
191  "name for the library (the default is libtcmalloc.so)")
192  parser.add_option("--preload", action="append",
193  help="Allow pre-loading of special libraries (e.g. Google "
194  "profiling libraries).")
195 
196  # Option to use a profiler
197  parser.add_option("--profilerName", type="string",
198  help="Select one profiler among: igprofPerf, igprofMem and valgrind<toolname>")
199 
200  # Option to specify the filename where to collect the profiler's output
201  parser.add_option("--profilerOutput", type="string",
202  help="Specify the name of the output file for the profiler output")
203 
204  # Option to specify the filename where to collect the profiler's output
205  parser.add_option("--profilerExtraOptions", type="string",
206  help="Specify additional options for the profiler. The '--' string should be expressed as '__' (--my-opt becomes __my-opt)")
207 
208  parser.add_option('--use-temp-opts', action='store_true',
209  help='when this option is enabled, the options are parsed'
210  ' and stored in a temporary file, then the job is '
211  'restarted using that file as input (to save '
212  'memory)')
213  parser.add_option("--run-info-file", type="string",
214  help="Save gaudi process information to the file specified (in JSON format)")
215 
216  parser.set_defaults(options = [],
217  tcmalloc = False,
218  profilerName = '',
219  profilerOutput = '',
220  profilerExtraOptions = '',
221  preload = [],
222  ncpus = None,
223  # the old logic can be turned off with an env variable
224  old_conf_user_apply='GAUDI_FIXED_APPLY_CONF' not in os.environ,
225  run_info_file = None)
226 
227  # replace .qmt files in the command line with their contained args
228  argv = []
229  for a in sys.argv[1:]:
230  if a.endswith('.qmt') and os.path.exists(a):
231  argv.extend(getArgsFromQmt(a))
232  else:
233  argv.append(a)
234  if argv != sys.argv[1:]:
235  print '# Running', sys.argv[0], 'with arguments', argv
236 
237  opts, args = parser.parse_args(args=argv)
238 
239  # Check consistency of options
240 
241  # Parallel Option ---------------------------------------------------------
242  if opts.ncpus:
243  from multiprocessing import cpu_count
244  sys_cpus = cpu_count()
245  if opts.ncpus > sys_cpus:
246  s = "Invalid value : --ncpus : only %i cpus available" % sys_cpus
247  parser.error(s)
248  elif opts.ncpus < -1 :
249  s = "Invalid value : --ncpus must be integer >= -1"
250  parser.error(s)
251  else:
252  # FIXME: is it really needed to set it to None if it is 0 or False?
253  opts.ncpus = None
254 
255  # configure the logging
256  import logging
257  from GaudiKernel.ProcessJobOptions import (InstallRootLoggingHandler,
258  PrintOff)
259 
260  if opts.old_opts: prefix = "// "
261  else: prefix = "# "
262  level = logging.INFO
263  if opts.debug:
264  level = logging.DEBUG
265  InstallRootLoggingHandler(prefix, level = level, with_time = opts.debug)
266  root_logger = logging.getLogger()
267 
268  # tcmalloc support
269  if opts.tcmalloc:
270  opts.preload.insert(0, os.environ.get("TCMALLOCLIB", "libtcmalloc.so"))
271  # allow preloading of libraries
272  if opts.preload:
273  preload = os.environ.get("LD_PRELOAD", "")
274  if preload:
275  preload = preload.replace(" ", ":").split(":")
276  else:
277  preload = []
278  for libname in set(preload).intersection(opts.preload):
279  logging.warning("Ignoring preload of library %s because it is "
280  "already in LD_PRELOAD.", libname)
281  to_load = [libname
282  for libname in opts.preload
283  if libname not in set(preload)]
284  if to_load:
285  preload += to_load
286  preload = ":".join(preload)
287  os.environ["LD_PRELOAD"] = preload
288  logging.info("Restarting with LD_PRELOAD='%s'", preload)
289  # remove the --tcmalloc option from the arguments
290  # FIXME: the --preload arguments will issue a warning but it's tricky to remove them
291  args = [ a for a in sys.argv if a != '-T' and not '--tcmalloc'.startswith(a) ]
292  os.execv(sys.executable, [sys.executable] + args)
293 
294  # Profiler Support ------
295  if opts.profilerName:
296  profilerName = opts.profilerName
297  profilerExecName = ""
298  profilerOutput = opts.profilerOutput or (profilerName + ".output")
299 
300  # To restart the application removing the igprof option and prepending the string
301  args = getArgsWithoutoProfilerInfo(sys.argv)
302 
303  igprofPerfOptions = "-d -pp -z -o igprof.pp.gz".split()
304 
305  profilerOptions = ""
306  if profilerName == "igprof":
307  if not opts.profilerOutput:
308  profilerOutput += ".profile.gz"
309  profilerOptions = "-d -z -o %s" % profilerOutput
310  profilerExecName = "igprof"
311 
312  elif profilerName == "igprofPerf":
313  if not opts.profilerOutput:
314  profilerOutput += ".pp.gz"
315  profilerOptions = "-d -pp -z -o %s" % profilerOutput
316  profilerExecName = "igprof"
317 
318  elif profilerName == "igprofMem":
319  if not opts.profilerOutput:
320  profilerOutput += ".mp.gz"
321  profilerOptions = "-d -mp -z -o %s" % profilerOutput
322  profilerExecName = "igprof"
323 
324  elif "valgrind" in profilerName:
325  # extract the tool
326  if not opts.profilerOutput:
327  profilerOutput += ".log"
328  toolname = profilerName.replace('valgrind','')
329  outoption = "--log-file"
330  if toolname in ("massif", "callgrind", "cachegrind"):
331  outoption = "--%s-out-file" % toolname
332  profilerOptions = "--tool=%s %s=%s" % (toolname, outoption, profilerOutput)
333  profilerExecName = "valgrind"
334 
335  elif profilerName == "jemalloc":
336  opts.preload.insert(0, os.environ.get("JEMALLOCLIB", "libjemalloc.so"))
337  os.environ['MALLOC_CONF'] = "prof:true,prof_leak:true"
338  else:
339  root_logger.warning("Profiler %s not recognized!" % profilerName)
340 
341  # Add potential extra options
342  if opts.profilerExtraOptions!="":
343  profilerExtraOptions = opts.profilerExtraOptions
344  profilerExtraOptions = profilerExtraOptions.replace("__","--")
345  profilerOptions += " %s" % profilerExtraOptions
346 
347  # now we look for the full path of the profiler: is it really there?
348  if profilerExecName:
349  import distutils.spawn
350  profilerPath = distutils.spawn.find_executable(profilerExecName)
351  if not profilerPath:
352  root_logger.error("Cannot locate profiler %s" % profilerExecName)
353  sys.exit(1)
354 
355  root_logger.info("------ Profiling options are on ------ \n"\
356  " o Profiler: %s\n"\
357  " o Options: '%s'.\n"\
358  " o Output: %s" % (profilerExecName or profilerName, profilerOptions, profilerOutput))
359 
360  # allow preloading of libraries
361  # That code need to be acsracted from above
362  to_reload = []
363  if opts.preload:
364  to_reload = setLibraryPreload(opts.preload)
365 
366  if profilerExecName:
367  # We profile python
368  profilerOptions += " python"
369 
370  # now we have all the ingredients to prepare our command
371  arglist = [profilerPath] + profilerOptions.split() + args
372  arglist = [ a for a in arglist if a!='' ]
373  #print profilerPath
374  #for arg in arglist:
375  #print arg
376  os.execv(profilerPath, arglist)
377  else:
378  arglist = [a for a in sys.argv if not a.startswith("--profiler")]
379  os.execv(sys.executable, [sys.executable] + arglist)
380 
381  # End Profiler Support ------
382 
383  if opts.pickle_output:
384  if opts.output:
385  root_logger.error("Conflicting options: use only --pickle-output or --output")
386  sys.exit(1)
387  else:
388  root_logger.warning("--pickle-output is deprecated, use --output instead")
389  opts.output = opts.pickle_output
390 
391  from Gaudi.Main import gaudimain
392  c = gaudimain()
393 
394  # Prepare the "configuration script" to parse (like this it is easier than
395  # having a list with files and python commands, with an if statements that
396  # decides to do importOptions or exec)
397  options = [ "importOptions(%r)" % f for f in args ]
398  # The option lines are inserted into the list of commands using their
399  # position on the command line
400  optlines = list(opts.options)
401  optlines.reverse() # this allows to avoid to have to care about corrections of the positions
402  for pos, l in optlines:
403  options.insert(pos,l)
404 
405  # prevent the usage of GaudiPython
406  class FakeModule(object):
407  def __init__(self, exception):
408  self.exception = exception
409  def __getattr__(self, *args, **kwargs):
410  raise self.exception
411  sys.modules["GaudiPython"] = FakeModule(RuntimeError("GaudiPython cannot be used in option files"))
412 
413  # when the special env GAUDI_TEMP_OPTS_FILE is set, it overrides any
414  # option(file) on the command line
415  if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
416  options = ['importOptions(%r)' % os.environ['GAUDI_TEMP_OPTS_FILE']]
417  PrintOff(100)
418 
419  # "execute" the configuration script generated (if any)
420  if options:
421  g = {}
422  l = {}
423  exec "from Gaudi.Configuration import *" in g, l
424  for o in options:
425  logging.debug(o)
426  exec o in g, l
427 
429  if opts.no_conf_user_apply:
430  logging.info("Disabling automatic apply of ConfigurableUser")
431  # pretend that they have been already applied
432  GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ = True
433 
434  # This need to be done before dumping
435  if opts.old_conf_user_apply:
436  from GaudiKernel.Proxy.Configurable import applyConfigurableUsers_old as applyConfigurableUsers
437  else:
438  from GaudiKernel.Proxy.Configurable import applyConfigurableUsers
440 
441  # Options to be processed after applyConfigurableUsers
442  if opts.post_options:
443  g = {}
444  l = {}
445  exec "from Gaudi.Configuration import *" in g, l
446  for o in opts.post_options:
447  logging.debug(o)
448  exec o in g, l
449 
450  if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
451  os.remove(os.environ['GAUDI_TEMP_OPTS_FILE'])
452  opts.use_temp_opts = False
453 
454  if opts.verbose and not opts.use_temp_opts:
455  c.printconfig(opts.old_opts, opts.all_opts)
456  if opts.output:
457  c.writeconfig(opts.output, opts.all_opts)
458 
459  if opts.use_temp_opts:
460  fd, tmpfile = mkstemp('.opts')
461  os.close(fd)
462  c.writeconfig(tmpfile, opts.all_opts)
463  os.environ['GAUDI_TEMP_OPTS_FILE'] = tmpfile
464  logging.info('Restarting from pre-parsed options')
465  os.execv(sys.executable, [sys.executable] + sys.argv)
466 
467  c.printsequence = opts.printsequence
468  if opts.printsequence:
469  if opts.ncpus:
470  logging.warning("--printsequence not supported with --ncpus: ignored")
471  elif opts.dry_run:
472  logging.warning("--printsequence not supported with --dry-run: ignored")
473 
474  # re-enable the GaudiPython module
475  del sys.modules["GaudiPython"]
476 
477  if not opts.dry_run:
478  # Do the real processing
479  retcode = c.run(opts.gdb,opts.ncpus)
480 
481  # Now saving the run information pid, retcode and executable path to
482  # a file is requested
483  if opts.run_info_file:
484  import os, json
485  run_info = {}
486  run_info["pid"] = os.getpid()
487  run_info["retcode"] = retcode
488  if os.path.exists('/proc/self/exe'):
489  # These options can be used only on unix platforms
490  run_info["exe"] = os.readlink('/proc/self/exe')
491 
492  logging.info("Saving run info to: %s" % opts.run_info_file)
493  with open(opts.run_info_file, "w") as f:
494  json.dump(run_info, f)
495 
496  sys.exit(retcode)
def __init__(self, exception)
Definition: gaudirun.py:407
def option_cb(option, opt, value, parser)
Definition: gaudirun.py:145
def getArgsFromQmt(qmtfile)
Definition: gaudirun.py:71
struct GAUDI_API map
Parametrisation class for map-like implementation.
def rationalizepath(path)
Definition: gaudirun.py:59
def getArgsWithoutoProfilerInfo(args)
Definition: gaudirun.py:7
def __getattr__(self, args, kwargs)
Definition: gaudirun.py:409
def setLibraryPreload(newpreload)
Definition: gaudirun.py:35