Gaudi Framework, version v25r1

Home   Generated: Mon Mar 24 2014
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Macros Groups Pages
gaudirun.py
Go to the documentation of this file.
1 #!/usr/bin/env python
2 
3 import os
4 import sys
5 
7  """
8  Remove from the arguments the presence of the profiler and its output in
9  order to relaunch the script w/o infinite loops.
10 
11  >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', 'myopts.py'])
12  ['myopts.py']
13 
14  >>> getArgsWithoutoProfilerInfo(['--profilerName=igprof', 'myopts.py'])
15  ['myopts.py']
16 
17  >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', '--profilerExtraOptions', 'a b c', 'myopts.py'])
18  ['myopts.py']
19 
20  >>> getArgsWithoutoProfilerInfo(['--profilerName', 'igprof', '--options', 'a b c', 'myopts.py'])
21  ['--options', 'a b c', 'myopts.py']
22  """
23  newargs = []
24  args = list(args) # make a temp copy
25  while args:
26  o = args.pop(0)
27  if o.startswith('--profile'):
28  if '=' not in o:
29  args.pop(0)
30  else:
31  newargs.append(o)
32  return newargs
33 
34 def rationalizepath(path):
35  '''
36  Convert the given path to a real path if the pointed file exists, otherwise
37  just normalize it.
38  '''
39  path = os.path.normpath(os.path.expandvars(path))
40  if os.path.exists(path):
41  path = os.path.realpath(path)
42  return path
43 
44 # variable used to keep alive the temporary option files extracted from the .qmt
45 _qmt_tmp_opt_files = []
46 def getArgsFromQmt(qmtfile):
47  '''
48  Given a .qmt file, return the command line arguments of the corresponding
49  test.
50  '''
51  from xml.etree import ElementTree as ET
52  global _qmt_tmp_opt_files
53  # parse the .qmt file and extract args and options
54  qmt = ET.parse(qmtfile)
55  args = [a.text for a in qmt.findall("argument[@name='args']//text")]
56  options = qmt.find("argument[@name='options']/text")
57 
58  if options is not None: # options need to be dumped in a temporary file
59  from tempfile import NamedTemporaryFile
60  import re
61  if re.search(r"from\s+Gaudi.Configuration\s+import\s+\*"
62  r"|from\s+Configurables\s+import", options.text):
63  tmp_opts = NamedTemporaryFile(suffix='.py')
64  else:
65  tmp_opts = NamedTemporaryFile(suffix='.opts')
66  tmp_opts.write(options.text)
67  tmp_opts.flush()
68  args.append(tmp_opts.name)
69  _qmt_tmp_opt_files.append(tmp_opts)
70 
71  # relative paths in a .qmt are rooted in the qmtest directory, so
72  # - find where the .qmt lives
73  qmtfile = os.path.abspath(qmtfile)
74  if 'qmtest' in qmtfile.split(os.path.sep):
75  # this return the path up to the 'qmtest' entry in qmtfile
76  testdir = qmtfile
77  while os.path.basename(testdir) != 'qmtest':
78  testdir = os.path.dirname(testdir)
79  else:
80  testdir = '.'
81  # - temporarily switch to that directory and rationalize the paths
82  old_cwd = os.getcwd()
83  os.chdir(testdir)
84  args = map(rationalizepath, args)
85  os.chdir(old_cwd)
86 
87  return args
88 
89 #---------------------------------------------------------------------
90 if __name__ == "__main__":
91  # ensure that we (and the subprocesses) use the C standard localization
92  if os.environ.get('LC_ALL') != 'C':
93  print '# setting LC_ALL to "C"'
94  os.environ['LC_ALL'] = 'C'
95 
96  from GaudiKernel import ROOT6WorkAroundEnabled
97  if ROOT6WorkAroundEnabled('ROOT-6125'):
98  try:
99  from ctypes import cdll
100  cdll.LoadLibrary('libCling.so')
101  except (ImportError, OSError):
102  pass
103 
104  from optparse import OptionParser
105  parser = OptionParser(usage = "%prog [options] <opts_file> ...")
106  parser.add_option("-n","--dry-run", action="store_true",
107  help="do not run the application, just parse option files")
108  parser.add_option("-p","--pickle-output", action="store", type="string",
109  metavar = "FILE",
110  help="DEPRECATED: use '--output file.pkl' instead. Write "
111  "the parsed options as a pickle file (static option "
112  "file)")
113  parser.add_option("-v","--verbose", action="store_true",
114  help="print the parsed options")
115  parser.add_option("--old-opts", action="store_true",
116  help="format printed options in old option files style")
117  parser.add_option("--all-opts", action="store_true",
118  help="print all the option (even if equal to default)")
119  # GaudiPython Parallel Mode Option
120  # Argument must be an integer in range [ -1, sys_cpus ]
121  # -1 : All available cpus
122  # 0 : Serial Mode (traditional gaudirun)
123  # n>0 : parallel with n cpus (n <= sys_cpus)
124  parser.add_option("--ncpus", action="store", type="int", default=0,
125  help="start the application in parallel mode using NCPUS processes. "
126  "0 => serial mode (default), -1 => use all CPUs")
127 
128  def option_cb(option, opt, value, parser):
129  """Add the option line to a list together with its position in the
130  argument list.
131  """
132  parser.values.options.append((len(parser.largs), value))
133  parser.add_option("--option", action="callback", callback=option_cb,
134  type = "string", nargs = 1,
135  help="add a single line (Python) option to the configuration. "
136  "All options lines are executed, one after the other, in "
137  "the same context.")
138  parser.add_option("--no-conf-user-apply", action="store_true",
139  help="disable the automatic application of configurable "
140  "users (for backward compatibility)")
141  parser.add_option("--old-conf-user-apply", action="store_true",
142  help="use the old logic when applying ConfigurableUsers "
143  "(with bug #103803) [default]")
144  parser.add_option("--new-conf-user-apply", action="store_false",
145  dest="old_conf_user_apply",
146  help="use the new (correct) logic when applying "
147  "ConfigurableUsers (fixed bug #103803), can be "
148  "turned on also with the environment variable "
149  "GAUDI_FIXED_APPLY_CONF")
150  parser.add_option("-o", "--output", action = "store", type = "string",
151  help ="dump the configuration to a file. The format of "
152  "the options is determined by the extension of the "
153  "file name: .pkl = pickle, .py = python, .opts = "
154  "old style options. The python format cannot be "
155  "used to run the application and it contains the "
156  "same dictionary printed with -v")
157  parser.add_option("--post-option", action="append", type="string",
158  dest="post_options",
159  help="Python options to be executed after the ConfigurableUser "
160  "are applied. "
161  "All options lines are executed, one after the other, in "
162  "the same context.")
163  parser.add_option("--debug", action="store_true",
164  help="enable some debug print-out")
165  parser.add_option("--printsequence", action="store_true",
166  help="print the sequence")
167  if not sys.platform.startswith("win"):
168  # These options can be used only on unix platforms
169  parser.add_option("-T", "--tcmalloc", action="store_true",
170  help="Use the Google malloc replacement. The environment "
171  "variable TCMALLOCLIB can be used to specify a different "
172  "name for the library (the default is libtcmalloc.so)")
173  parser.add_option("--preload", action="append",
174  help="Allow pre-loading of special libraries (e.g. Google "
175  "profiling libraries).")
176 
177  # Option to use a profiler
178  parser.add_option("--profilerName", type="string",
179  help="Select one profiler among: igprofPerf, igprofMem and valgrind<toolname>")
180 
181  # Option to specify the filename where to collect the profiler's output
182  parser.add_option("--profilerOutput", type="string",
183  help="Specify the name of the output file for the profiler output")
184 
185  # Option to specify the filename where to collect the profiler's output
186  parser.add_option("--profilerExtraOptions", type="string",
187  help="Specify additional options for the profiler. The '--' string should be expressed as '__' (--my-opt becomes __my-opt)")
188 
189  parser.set_defaults(options = [],
190  tcmalloc = False,
191  profilerName = '',
192  profilerOutput = '',
193  profilerExtraOptions = '',
194  preload = [],
195  ncpus = None,
196  # the old logic can be turned off with an env variable
197  old_conf_user_apply='GAUDI_FIXED_APPLY_CONF' not in os.environ)
198 
199  # replace .qmt files in the command line with their contained args
200  argv = []
201  for a in sys.argv[1:]:
202  if a.endswith('.qmt') and os.path.exists(a):
203  argv.extend(getArgsFromQmt(a))
204  else:
205  argv.append(a)
206  if argv != sys.argv[1:]:
207  print '# Running', sys.argv[0], 'with arguments', argv
208 
209  opts, args = parser.parse_args(args=argv)
210 
211  # Check consistency of options
212 
213  # Parallel Option ---------------------------------------------------------
214  if opts.ncpus:
215  from multiprocessing import cpu_count
216  sys_cpus = cpu_count()
217  if opts.ncpus > sys_cpus:
218  s = "Invalid value : --ncpus : only %i cpus available" % sys_cpus
219  parser.error(s)
220  elif opts.ncpus < -1 :
221  s = "Invalid value : --ncpus must be integer >= -1"
222  parser.error(s)
223  else:
224  # FIXME: is it really needed to set it to None if it is 0 or False?
225  opts.ncpus = None
226 
227  # configure the logging
228  import logging
229  from GaudiKernel.ProcessJobOptions import InstallRootLoggingHandler
230 
231  if opts.old_opts: prefix = "// "
232  else: prefix = "# "
233  level = logging.INFO
234  if opts.debug:
235  level = logging.DEBUG
236  InstallRootLoggingHandler(prefix, level = level)
237  root_logger = logging.getLogger()
238 
239  # tcmalloc support
240  if opts.tcmalloc:
241  opts.preload.insert(0, os.environ.get("TCMALLOCLIB", "libtcmalloc.so"))
242  # allow preloading of libraries
243  if opts.preload:
244  preload = os.environ.get("LD_PRELOAD", "")
245  if preload:
246  preload = preload.replace(" ", ":").split(":")
247  else:
248  preload = []
249  for libname in set(preload).intersection(opts.preload):
250  logging.warning("Ignoring preload of library %s because it is "
251  "already in LD_PRELOAD.", libname)
252  to_load = [libname
253  for libname in opts.preload
254  if libname not in set(preload)]
255  if to_load:
256  preload += to_load
257  preload = ":".join(preload)
258  os.environ["LD_PRELOAD"] = preload
259  logging.info("Restarting with LD_PRELOAD='%s'", preload)
260  # remove the --tcmalloc option from the arguments
261  # FIXME: the --preload arguments will issue a warning but it's tricky to remove them
262  args = [ a for a in sys.argv if a != '-T' and not '--tcmalloc'.startswith(a) ]
263  os.execv(sys.executable, [sys.executable] + args)
264 
265  # Profiler Support ------
266  if opts.profilerName:
267  profilerName = opts.profilerName
268  profilerExecName = ""
269  profilerOutput = opts.profilerOutput or (profilerName + ".output")
270 
271  # To restart the application removing the igprof option and prepending the string
272  args = getArgsWithoutoProfilerInfo(sys.argv)
273 
274  igprofPerfOptions = "-d -pp -z -o igprof.pp.gz".split()
275 
276  profilerOptions = ""
277  if profilerName == "igprof":
278  if not opts.profilerOutput:
279  profilerOutput += ".profile.gz"
280  profilerOptions = "-d -z -o %s" % profilerOutput
281  profilerExecName = "igprof"
282 
283  elif profilerName == "igprofPerf":
284  if not opts.profilerOutput:
285  profilerOutput += ".pp.gz"
286  profilerOptions = "-d -pp -z -o %s" % profilerOutput
287  profilerExecName = "igprof"
288 
289  elif profilerName == "igprofMem":
290  if not opts.profilerOutput:
291  profilerOutput += ".mp.gz"
292  profilerOptions = "-d -mp -z -o %s" % profilerOutput
293  profilerExecName = "igprof"
294 
295  elif "valgrind" in profilerName:
296  # extract the tool
297  if not opts.profilerOutput:
298  profilerOutput += ".log"
299  toolname = profilerName.replace('valgrind','')
300  outoption = "--log-file"
301  if toolname in ("massif", "callgrind", "cachegrind"):
302  outoption = "--%s-out-file" % toolname
303  profilerOptions = "--tool=%s %s=%s" % (toolname, outoption, profilerOutput)
304  profilerExecName = "valgrind"
305 
306  else:
307  root_logger.warning("Profiler %s not recognized!" % profilerName)
308 
309  # Add potential extra options
310  if opts.profilerExtraOptions!="":
311  profilerExtraOptions = opts.profilerExtraOptions
312  profilerExtraOptions = profilerExtraOptions.replace("__","--")
313  profilerOptions += " %s" % profilerExtraOptions
314 
315  # now we look for the full path of the profiler: is it really there?
316  import distutils.spawn
317  profilerPath = distutils.spawn.find_executable(profilerExecName)
318  if not profilerPath:
319  root_logger.error("Cannot locate profiler %s" % profilerExecName)
320  sys.exit(1)
321 
322  root_logger.info("------ Profiling options are on ------ \n"\
323  " o Profiler: %s\n"\
324  " o Options: '%s'.\n"\
325  " o Output: %s" % (profilerExecName, profilerOptions, profilerOutput))
326 
327  # We profile python
328  profilerOptions += " python"
329 
330  # now we have all the ingredients to prepare our command
331  arglist = [profilerPath] + profilerOptions.split() + args
332  arglist = [ a for a in arglist if a!='' ]
333  #print profilerPath
334  #for arg in arglist:
335  #print arg
336  os.execv(profilerPath, arglist)
337 
338  # End Profiler Support ------
339 
340  if opts.pickle_output:
341  if opts.output:
342  root_logger.error("Conflicting options: use only --pickle-output or --output")
343  sys.exit(1)
344  else:
345  root_logger.warning("--pickle-output is deprecated, use --output instead")
346  opts.output = opts.pickle_output
347 
348  from Gaudi.Main import gaudimain
349  c = gaudimain()
350 
351  # Prepare the "configuration script" to parse (like this it is easier than
352  # having a list with files and python commands, with an if statements that
353  # decides to do importOptions or exec)
354  options = [ "importOptions(%r)" % f for f in args ]
355  # The option lines are inserted into the list of commands using their
356  # position on the command line
357  optlines = list(opts.options)
358  optlines.reverse() # this allows to avoid to have to care about corrections of the positions
359  for pos, l in optlines:
360  options.insert(pos,l)
361 
362  # prevent the usage of GaudiPython
363  class FakeModule(object):
364  def __init__(self, exception):
365  self.exception = exception
366  def __getattr__(self, *args, **kwargs):
367  raise self.exception
368  sys.modules["GaudiPython"] = FakeModule(RuntimeError("GaudiPython cannot be used in option files"))
369 
370  # "execute" the configuration script generated (if any)
371  if options:
372  g = {}
373  l = {}
374  exec "from Gaudi.Configuration import *" in g, l
375  for o in options:
376  logging.debug(o)
377  exec o in g, l
378 
379  import GaudiKernel.Proxy.Configurable
380  if opts.no_conf_user_apply:
381  logging.info("Disabling automatic apply of ConfigurableUser")
382  # pretend that they have been already applied
383  GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ = True
384 
385  # This need to be done before dumping
386  if opts.old_conf_user_apply:
387  from GaudiKernel.Proxy.Configurable import applyConfigurableUsers_old as applyConfigurableUsers
388  else:
389  from GaudiKernel.Proxy.Configurable import applyConfigurableUsers
391 
392  # Options to be processed after applyConfigurableUsers
393  if opts.post_options:
394  g = {}
395  l = {}
396  exec "from Gaudi.Configuration import *" in g, l
397  for o in opts.post_options:
398  logging.debug(o)
399  exec o in g, l
400 
401  if opts.verbose:
402  c.printconfig(opts.old_opts, opts.all_opts)
403  if opts.output:
404  c.writeconfig(opts.output, opts.all_opts)
405 
406  c.printsequence = opts.printsequence
407  if opts.printsequence:
408  if opts.ncpus:
409  logging.warning("--printsequence not supported with --ncpus: ignored")
410  elif opts.dry_run:
411  logging.warning("--printsequence not supported with --dry-run: ignored")
412 
413  # re-enable the GaudiPython module
414  del sys.modules["GaudiPython"]
415 
416  if not opts.dry_run:
417  # Do the real processing
418  sys.exit(c.run(opts.ncpus))

Generated at Mon Mar 24 2014 18:27:42 for Gaudi Framework, version v25r1 by Doxygen version 1.8.2 written by Dimitri van Heesch, © 1997-2004