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("--printsequence", action="store_true",
183  help="print the sequence")
184  if not sys.platform.startswith("win"):
185  # These options can be used only on unix platforms
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).")
193 
194  # Option to use a profiler
195  parser.add_option("--profilerName", type="string",
196  help="Select one profiler among: igprofPerf, igprofMem and valgrind<toolname>")
197 
198  # Option to specify the filename where to collect the profiler's output
199  parser.add_option("--profilerOutput", type="string",
200  help="Specify the name of the output file for the profiler output")
201 
202  # Option to specify the filename where to collect the profiler's 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)")
205 
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 '
210  'memory)')
211  parser.add_option("--run-info-file", type="string",
212  help="Save gaudi process information to the file specified (in JSON format)")
213 
214  parser.set_defaults(options = [],
215  tcmalloc = False,
216  profilerName = '',
217  profilerOutput = '',
218  profilerExtraOptions = '',
219  preload = [],
220  ncpus = None,
221  # the old logic can be turned off with an env variable
222  old_conf_user_apply='GAUDI_FIXED_APPLY_CONF' not in os.environ,
223  run_info_file = None)
224 
225  # replace .qmt files in the command line with their contained args
226  argv = []
227  for a in sys.argv[1:]:
228  if a.endswith('.qmt') and os.path.exists(a):
229  argv.extend(getArgsFromQmt(a))
230  else:
231  argv.append(a)
232  if argv != sys.argv[1:]:
233  print '# Running', sys.argv[0], 'with arguments', argv
234 
235  opts, args = parser.parse_args(args=argv)
236 
237  # Check consistency of options
238 
239  # Parallel Option ---------------------------------------------------------
240  if opts.ncpus:
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
245  parser.error(s)
246  elif opts.ncpus < -1 :
247  s = "Invalid value : --ncpus must be integer >= -1"
248  parser.error(s)
249  else:
250  # FIXME: is it really needed to set it to None if it is 0 or False?
251  opts.ncpus = None
252 
253  # configure the logging
254  import logging
255  from GaudiKernel.ProcessJobOptions import (InstallRootLoggingHandler,
256  PrintOff)
257 
258  if opts.old_opts: prefix = "// "
259  else: prefix = "# "
260  level = logging.INFO
261  if opts.debug:
262  level = logging.DEBUG
263  InstallRootLoggingHandler(prefix, level = level, with_time = opts.debug)
264  root_logger = logging.getLogger()
265 
266  # tcmalloc support
267  if opts.tcmalloc:
268  opts.preload.insert(0, os.environ.get("TCMALLOCLIB", "libtcmalloc.so"))
269  # allow preloading of libraries
270  if opts.preload:
271  preload = os.environ.get("LD_PRELOAD", "")
272  if preload:
273  preload = preload.replace(" ", ":").split(":")
274  else:
275  preload = []
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)
279  to_load = [libname
280  for libname in opts.preload
281  if libname not in set(preload)]
282  if to_load:
283  preload += to_load
284  preload = ":".join(preload)
285  os.environ["LD_PRELOAD"] = preload
286  logging.info("Restarting with LD_PRELOAD='%s'", preload)
287  # remove the --tcmalloc option from the arguments
288  # FIXME: the --preload arguments will issue a warning but it's tricky to remove them
289  args = [ a for a in sys.argv if a != '-T' and not '--tcmalloc'.startswith(a) ]
290  os.execv(sys.executable, [sys.executable] + args)
291 
292  # Profiler Support ------
293  if opts.profilerName:
294  profilerName = opts.profilerName
295  profilerExecName = ""
296  profilerOutput = opts.profilerOutput or (profilerName + ".output")
297 
298  # To restart the application removing the igprof option and prepending the string
299  args = getArgsWithoutoProfilerInfo(sys.argv)
300 
301  igprofPerfOptions = "-d -pp -z -o igprof.pp.gz".split()
302 
303  profilerOptions = ""
304  if profilerName == "igprof":
305  if not opts.profilerOutput:
306  profilerOutput += ".profile.gz"
307  profilerOptions = "-d -z -o %s" % profilerOutput
308  profilerExecName = "igprof"
309 
310  elif profilerName == "igprofPerf":
311  if not opts.profilerOutput:
312  profilerOutput += ".pp.gz"
313  profilerOptions = "-d -pp -z -o %s" % profilerOutput
314  profilerExecName = "igprof"
315 
316  elif profilerName == "igprofMem":
317  if not opts.profilerOutput:
318  profilerOutput += ".mp.gz"
319  profilerOptions = "-d -mp -z -o %s" % profilerOutput
320  profilerExecName = "igprof"
321 
322  elif "valgrind" in profilerName:
323  # extract the tool
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"
332 
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"
336  else:
337  root_logger.warning("Profiler %s not recognized!" % profilerName)
338 
339  # Add potential extra options
340  if opts.profilerExtraOptions!="":
341  profilerExtraOptions = opts.profilerExtraOptions
342  profilerExtraOptions = profilerExtraOptions.replace("__","--")
343  profilerOptions += " %s" % profilerExtraOptions
344 
345  # now we look for the full path of the profiler: is it really there?
346  if profilerExecName:
347  import distutils.spawn
348  profilerPath = distutils.spawn.find_executable(profilerExecName)
349  if not profilerPath:
350  root_logger.error("Cannot locate profiler %s" % profilerExecName)
351  sys.exit(1)
352 
353  root_logger.info("------ Profiling options are on ------ \n"\
354  " o Profiler: %s\n"\
355  " o Options: '%s'.\n"\
356  " o Output: %s" % (profilerExecName or profilerName, profilerOptions, profilerOutput))
357 
358  # allow preloading of libraries
359  # That code need to be acsracted from above
360  to_reload = []
361  if opts.preload:
362  to_reload = setLibraryPreload(opts.preload)
363 
364  if profilerExecName:
365  # We profile python
366  profilerOptions += " python"
367 
368  # now we have all the ingredients to prepare our command
369  arglist = [profilerPath] + profilerOptions.split() + args
370  arglist = [ a for a in arglist if a!='' ]
371  #print profilerPath
372  #for arg in arglist:
373  #print arg
374  os.execv(profilerPath, arglist)
375  else:
376  arglist = [a for a in sys.argv if not a.startswith("--profiler")]
377  os.execv(sys.executable, [sys.executable] + arglist)
378 
379  # End Profiler Support ------
380 
381  if opts.pickle_output:
382  if opts.output:
383  root_logger.error("Conflicting options: use only --pickle-output or --output")
384  sys.exit(1)
385  else:
386  root_logger.warning("--pickle-output is deprecated, use --output instead")
387  opts.output = opts.pickle_output
388 
389  from Gaudi.Main import gaudimain
390  c = gaudimain()
391 
392  # Prepare the "configuration script" to parse (like this it is easier than
393  # having a list with files and python commands, with an if statements that
394  # decides to do importOptions or exec)
395  options = [ "importOptions(%r)" % f for f in args ]
396  # The option lines are inserted into the list of commands using their
397  # position on the command line
398  optlines = list(opts.options)
399  optlines.reverse() # this allows to avoid to have to care about corrections of the positions
400  for pos, l in optlines:
401  options.insert(pos,l)
402 
403  # prevent the usage of GaudiPython
404  class FakeModule(object):
405  def __init__(self, exception):
406  self.exception = exception
407  def __getattr__(self, *args, **kwargs):
408  raise self.exception
409  sys.modules["GaudiPython"] = FakeModule(RuntimeError("GaudiPython cannot be used in option files"))
410 
411  # when the special env GAUDI_TEMP_OPTS_FILE is set, it overrides any
412  # option(file) on the command line
413  if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
414  options = ['importOptions(%r)' % os.environ['GAUDI_TEMP_OPTS_FILE']]
415  PrintOff(100)
416 
417  # "execute" the configuration script generated (if any)
418  if options:
419  g = {}
420  l = {}
421  exec "from Gaudi.Configuration import *" in g, l
422  for o in options:
423  logging.debug(o)
424  exec o in g, l
425 
427  if opts.no_conf_user_apply:
428  logging.info("Disabling automatic apply of ConfigurableUser")
429  # pretend that they have been already applied
430  GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ = True
431 
432  # This need to be done before dumping
433  if opts.old_conf_user_apply:
434  from GaudiKernel.Proxy.Configurable import applyConfigurableUsers_old as applyConfigurableUsers
435  else:
436  from GaudiKernel.Proxy.Configurable import applyConfigurableUsers
438 
439  # Options to be processed after applyConfigurableUsers
440  if opts.post_options:
441  g = {}
442  l = {}
443  exec "from Gaudi.Configuration import *" in g, l
444  for o in opts.post_options:
445  logging.debug(o)
446  exec o in g, l
447 
448  if 'GAUDI_TEMP_OPTS_FILE' in os.environ:
449  os.remove(os.environ['GAUDI_TEMP_OPTS_FILE'])
450  opts.use_temp_opts = False
451 
452  if opts.verbose and not opts.use_temp_opts:
453  c.printconfig(opts.old_opts, opts.all_opts)
454  if opts.output:
455  c.writeconfig(opts.output, opts.all_opts)
456 
457  if opts.use_temp_opts:
458  fd, tmpfile = mkstemp('.opts')
459  os.close(fd)
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)
464 
465  c.printsequence = opts.printsequence
466  if opts.printsequence:
467  if opts.ncpus:
468  logging.warning("--printsequence not supported with --ncpus: ignored")
469  elif opts.dry_run:
470  logging.warning("--printsequence not supported with --dry-run: ignored")
471 
472  # re-enable the GaudiPython module
473  del sys.modules["GaudiPython"]
474 
475  if not opts.dry_run:
476  # Do the real processing
477  retcode = c.run(opts.ncpus)
478 
479  # Now saving the run information pid, retcode and executable path to
480  # a file is requested
481  if opts.run_info_file:
482  import os, json
483  run_info = {}
484  run_info["pid"] = os.getpid()
485  run_info["retcode"] = retcode
486  if os.path.exists('/proc/self/exe'):
487  # These options can be used only on unix platforms
488  run_info["exe"] = os.readlink('/proc/self/exe')
489 
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)
493 
494  sys.exit(retcode)
def __init__(self, exception)
Definition: gaudirun.py:405
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:407
def setLibraryPreload(newpreload)
Definition: gaudirun.py:35