Gaudi Framework, version v24r2

Home   Generated: Wed Dec 4 2013
 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 optparse import OptionParser
97  parser = OptionParser(usage = "%prog [options] <opts_file> ...")
98  parser.add_option("-n","--dry-run", action="store_true",
99  help="do not run the application, just parse option files")
100  parser.add_option("-p","--pickle-output", action="store", type="string",
101  metavar = "FILE",
102  help="DEPRECATED: use '--output file.pkl' instead. Write "
103  "the parsed options as a pickle file (static option "
104  "file)")
105  parser.add_option("-v","--verbose", action="store_true",
106  help="print the parsed options")
107  parser.add_option("--old-opts", action="store_true",
108  help="format printed options in old option files style")
109  parser.add_option("--all-opts", action="store_true",
110  help="print all the option (even if equal to default)")
111  # GaudiPython Parallel Mode Option
112  # Argument must be an integer in range [ -1, sys_cpus ]
113  # -1 : All available cpus
114  # 0 : Serial Mode (traditional gaudirun)
115  # n>0 : parallel with n cpus (n <= sys_cpus)
116  parser.add_option("--ncpus", action="store", type="int", default=0,
117  help="start the application in parallel mode using NCPUS processes. "
118  "0 => serial mode (default), -1 => use all CPUs")
119 
120  def option_cb(option, opt, value, parser):
121  """Add the option line to a list together with its position in the
122  argument list.
123  """
124  parser.values.options.append((len(parser.largs), value))
125  parser.add_option("--option", action="callback", callback=option_cb,
126  type = "string", nargs = 1,
127  help="add a single line (Python) option to the configuration. "
128  "All options lines are executed, one after the other, in "
129  "the same context.")
130  parser.add_option("--no-conf-user-apply", action="store_true",
131  help="disable the automatic application of configurable "
132  "users (for backward compatibility)")
133  parser.add_option("-o", "--output", action = "store", type = "string",
134  help ="dump the configuration to a file. The format of "
135  "the options is determined by the extension of the "
136  "file name: .pkl = pickle, .py = python, .opts = "
137  "old style options. The python format cannot be "
138  "used to run the application and it contains the "
139  "same dictionary printed with -v")
140  parser.add_option("--post-option", action="append", type="string",
141  dest="post_options",
142  help="Python options to be executed after the ConfigurableUser "
143  "are applied. "
144  "All options lines are executed, one after the other, in "
145  "the same context.")
146  parser.add_option("--debug", action="store_true",
147  help="enable some debug print-out")
148  parser.add_option("--printsequence", action="store_true",
149  help="print the sequence")
150  if not sys.platform.startswith("win"):
151  # These options can be used only on unix platforms
152  parser.add_option("-T", "--tcmalloc", action="store_true",
153  help="Use the Google malloc replacement. The environment "
154  "variable TCMALLOCLIB can be used to specify a different "
155  "name for the library (the default is libtcmalloc.so)")
156  parser.add_option("--preload", action="append",
157  help="Allow pre-loading of special libraries (e.g. Google "
158  "profiling libraries).")
159 
160  # Option to use a profiler
161  parser.add_option("--profilerName", type="string",
162  help="Select one profiler among: igprofPerf, igprofMem and valgrind<toolname>")
163 
164  # Option to specify the filename where to collect the profiler's output
165  parser.add_option("--profilerOutput", type="string",
166  help="Specify the name of the output file for the profiler output")
167 
168  # Option to specify the filename where to collect the profiler's output
169  parser.add_option("--profilerExtraOptions", type="string",
170  help="Specify additional options for the profiler. The '--' string should be expressed as '__' (--my-opt becomes __my-opt)")
171 
172  parser.set_defaults(options = [],
173  tcmalloc = False,
174  profilerName = '',
175  profilerOutput = '',
176  profilerExtraOptions = '',
177  preload = [],
178  ncpus = None)
179 
180  # replace .qmt files in the command line with their contained args
181  argv = []
182  for a in sys.argv[1:]:
183  if a.endswith('.qmt') and os.path.exists(a):
184  argv.extend(getArgsFromQmt(a))
185  else:
186  argv.append(a)
187  if argv != sys.argv[1:]:
188  print '# Running', sys.argv[0], 'with arguments', argv
189 
190  opts, args = parser.parse_args(args=argv)
191 
192  # Check consistency of options
193 
194  # Parallel Option ---------------------------------------------------------
195  if opts.ncpus:
196  from multiprocessing import cpu_count
197  sys_cpus = cpu_count()
198  if opts.ncpus > sys_cpus:
199  s = "Invalid value : --ncpus : only %i cpus available" % sys_cpus
200  parser.error(s)
201  elif opts.ncpus < -1 :
202  s = "Invalid value : --ncpus must be integer >= -1"
203  parser.error(s)
204  else:
205  # FIXME: is it really needed to set it to None if it is 0 or False?
206  opts.ncpus = None
207 
208  # configure the logging
209  import logging
210  from GaudiKernel.ProcessJobOptions import InstallRootLoggingHandler
211 
212  if opts.old_opts: prefix = "// "
213  else: prefix = "# "
214  level = logging.INFO
215  if opts.debug:
216  level = logging.DEBUG
217  InstallRootLoggingHandler(prefix, level = level)
218  root_logger = logging.getLogger()
219 
220  # tcmalloc support
221  if opts.tcmalloc:
222  opts.preload.insert(0, os.environ.get("TCMALLOCLIB", "libtcmalloc.so"))
223  # allow preloading of libraries
224  if opts.preload:
225  preload = os.environ.get("LD_PRELOAD", "")
226  if preload:
227  preload = preload.replace(" ", ":").split(":")
228  else:
229  preload = []
230  for libname in set(preload).intersection(opts.preload):
231  logging.warning("Ignoring preload of library %s because it is "
232  "already in LD_PRELOAD.", libname)
233  to_load = [libname
234  for libname in opts.preload
235  if libname not in set(preload)]
236  if to_load:
237  preload += to_load
238  preload = ":".join(preload)
239  os.environ["LD_PRELOAD"] = preload
240  logging.info("Restarting with LD_PRELOAD='%s'", preload)
241  # remove the --tcmalloc option from the arguments
242  # FIXME: the --preload arguments will issue a warning but it's tricky to remove them
243  args = [ a for a in sys.argv if a != '-T' and not '--tcmalloc'.startswith(a) ]
244  os.execv(sys.executable, [sys.executable] + args)
245 
246  # Profiler Support ------
247  if opts.profilerName:
248  profilerName = opts.profilerName
249  profilerExecName = ""
250  profilerOutput = opts.profilerOutput or (profilerName + ".output")
251 
252  # To restart the application removing the igprof option and prepending the string
253  args = getArgsWithoutoProfilerInfo(sys.argv)
254 
255  igprofPerfOptions = "-d -pp -z -o igprof.pp.gz".split()
256 
257  profilerOptions = ""
258  if profilerName == "igprof":
259  if not opts.profilerOutput:
260  profilerOutput += ".profile.gz"
261  profilerOptions = "-d -z -o %s" % profilerOutput
262  profilerExecName = "igprof"
263 
264  elif profilerName == "igprofPerf":
265  if not opts.profilerOutput:
266  profilerOutput += ".pp.gz"
267  profilerOptions = "-d -pp -z -o %s" % profilerOutput
268  profilerExecName = "igprof"
269 
270  elif profilerName == "igprofMem":
271  if not opts.profilerOutput:
272  profilerOutput += ".mp.gz"
273  profilerOptions = "-d -mp -z -o %s" % profilerOutput
274  profilerExecName = "igprof"
275 
276  elif "valgrind" in profilerName:
277  # extract the tool
278  if not opts.profilerOutput:
279  profilerOutput += ".log"
280  toolname = profilerName.replace('valgrind','')
281  outoption = "--log-file"
282  if toolname in ("massif", "callgrind", "cachegrind"):
283  outoption = "--%s-out-file" % toolname
284  profilerOptions = "--tool=%s %s=%s" % (toolname, outoption, profilerOutput)
285  profilerExecName = "valgrind"
286 
287  else:
288  root_logger.warning("Profiler %s not recognized!" % profilerName)
289 
290  # Add potential extra options
291  if opts.profilerExtraOptions!="":
292  profilerExtraOptions = opts.profilerExtraOptions
293  profilerExtraOptions = profilerExtraOptions.replace("__","--")
294  profilerOptions += " %s" % profilerExtraOptions
295 
296  # now we look for the full path of the profiler: is it really there?
297  import distutils.spawn
298  profilerPath = distutils.spawn.find_executable(profilerExecName)
299  if not profilerPath:
300  root_logger.error("Cannot locate profiler %s" % profilerExecName)
301  sys.exit(1)
302 
303  root_logger.info("------ Profiling options are on ------ \n"\
304  " o Profiler: %s\n"\
305  " o Options: '%s'.\n"\
306  " o Output: %s" % (profilerExecName, profilerOptions, profilerOutput))
307 
308  # We profile python
309  profilerOptions += " python"
310 
311  # now we have all the ingredients to prepare our command
312  arglist = [profilerPath] + profilerOptions.split() + args
313  arglist = [ a for a in arglist if a!='' ]
314  #print profilerPath
315  #for arg in arglist:
316  #print arg
317  os.execv(profilerPath, arglist)
318 
319  # End Profiler Support ------
320 
321  if opts.pickle_output:
322  if opts.output:
323  root_logger.error("Conflicting options: use only --pickle-output or --output")
324  sys.exit(1)
325  else:
326  root_logger.warning("--pickle-output is deprecated, use --output instead")
327  opts.output = opts.pickle_output
328 
329  from Gaudi.Main import gaudimain
330  c = gaudimain()
331 
332  # Prepare the "configuration script" to parse (like this it is easier than
333  # having a list with files and python commands, with an if statements that
334  # decides to do importOptions or exec)
335  options = [ "importOptions(%r)" % f for f in args ]
336  # The option lines are inserted into the list of commands using their
337  # position on the command line
338  optlines = list(opts.options)
339  optlines.reverse() # this allows to avoid to have to care about corrections of the positions
340  for pos, l in optlines:
341  options.insert(pos,l)
342 
343  # prevent the usage of GaudiPython
344  class FakeModule(object):
345  def __init__(self, exception):
346  self.exception = exception
347  def __getattr__(self, *args, **kwargs):
348  raise self.exception
349  sys.modules["GaudiPython"] = FakeModule(RuntimeError("GaudiPython cannot be used in option files"))
350 
351  # "execute" the configuration script generated (if any)
352  if options:
353  g = {}
354  l = {}
355  exec "from Gaudi.Configuration import *" in g, l
356  for o in options:
357  logging.debug(o)
358  exec o in g, l
359 
360  import GaudiKernel.Proxy.Configurable
361  if opts.no_conf_user_apply:
362  logging.info("Disabling automatic apply of ConfigurableUser")
363  # pretend that they have been already applied
364  GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ = True
365 
366  # This need to be done before dumping
367  from GaudiKernel.Proxy.Configurable import applyConfigurableUsers
369 
370  # Options to be processed after applyConfigurableUsers
371  if opts.post_options:
372  g = {}
373  l = {}
374  exec "from Gaudi.Configuration import *" in g, l
375  for o in opts.post_options:
376  logging.debug(o)
377  exec o in g, l
378 
379  if opts.verbose:
380  c.printconfig(opts.old_opts, opts.all_opts)
381  if opts.output:
382  c.writeconfig(opts.output, opts.all_opts)
383 
384  c.printsequence = opts.printsequence
385  if opts.printsequence:
386  if opts.ncpus:
387  logging.warning("--printsequence not supported with --ncpus: ignored")
388  elif opts.dry_run:
389  logging.warning("--printsequence not supported with --dry-run: ignored")
390 
391  # re-enable the GaudiPython module
392  del sys.modules["GaudiPython"]
393 
394  if not opts.dry_run:
395  # Do the real processing
396  sys.exit(c.run(opts.ncpus))

Generated at Wed Dec 4 2013 14:33:06 for Gaudi Framework, version v24r2 by Doxygen version 1.8.2 written by Dimitri van Heesch, © 1997-2004