Gaudi Framework, version v23r5

Home   Generated: Wed Nov 28 2012
 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 #---------------------------------------------------------------------
4 if __name__ == "__main__":
5  import os, sys
6  from optparse import OptionParser
7  parser = OptionParser(usage = "%prog [options] <opts_file> ...")
8  parser.add_option("-n","--dry-run", action="store_true",
9  help="do not run the application, just parse option files")
10  parser.add_option("-p","--pickle-output", action="store", type="string",
11  metavar = "FILE",
12  help="DEPRECATED: use '--output file.pkl' instead. Write "
13  "the parsed options as a pickle file (static option "
14  "file)")
15  parser.add_option("-v","--verbose", action="store_true",
16  help="print the parsed options")
17  parser.add_option("--old-opts", action="store_true",
18  help="format printed options in old option files style")
19  parser.add_option("--all-opts", action="store_true",
20  help="print all the option (even if equal to default)")
21  # GaudiPython Parallel Mode Option
22  # Argument must be an integer in range [ -1, sys_cpus ]
23  # -1 : All available cpus
24  # 0 : Serial Mode (traditional gaudirun)
25  # n>0 : parallel with n cpus (n <= sys_cpus)
26  parser.add_option("--ncpus", action="store", type="int", default=0,
27  help="start the application in parallel mode using NCPUS processes. "
28  "0 => serial mode (default), -1 => use all CPUs")
29 
30  def option_cb(option, opt, value, parser):
31  """Add the option line to a list together with its position in the
32  argument list.
33  """
34  parser.values.options.append((len(parser.largs), value))
35  parser.add_option("--option", action="callback", callback=option_cb,
36  type = "string", nargs = 1,
37  help="add a single line (Python) option to the configuration. "
38  "All options lines are executed, one after the other, in "
39  "the same context.")
40  parser.add_option("--no-conf-user-apply", action="store_true",
41  help="disable the automatic application of configurable "
42  "users (for backward compatibility)")
43  parser.add_option("-o", "--output", action = "store", type = "string",
44  help ="dump the configuration to a file. The format of "
45  "the options is determined by the extension of the "
46  "file name: .pkl = pickle, .py = python, .opts = "
47  "old style options. The python format cannot be "
48  "used to run the application and it contains the "
49  "same dictionary printed with -v")
50  parser.add_option("--post-option", action="append", type="string",
51  dest="post_options",
52  help="Python options to be executed after the ConfigurableUser "
53  "are applied. "
54  "All options lines are executed, one after the other, in "
55  "the same context.")
56  parser.add_option("--debug", action="store_true",
57  help="enable some debug print-out")
58  parser.add_option("--printsequence", action="store_true",
59  help="print the sequence")
60  if not sys.platform.startswith("win"):
61  # These options can be used only on unix platforms
62  parser.add_option("-T", "--tcmalloc", action="store_true",
63  help="Use the Google malloc replacement. The environment "
64  "variable TCMALLOCLIB can be used to specify a different "
65  "name for the library (the default is libtcmalloc.so)")
66  parser.add_option("--preload", action="append",
67  help="Allow pre-loading of special libraries (e.g. Google "
68  "profiling libraries).")
69  parser.set_defaults(options = [],
70  tcmalloc = False,
71  preload = [],
72  ncpus = None)
73 
74  opts, args = parser.parse_args()
75 
76  # Check consistency of options
77 
78  # Parallel Option ---------------------------------------------------------
79  if opts.ncpus:
80  from multiprocessing import cpu_count
81  sys_cpus = cpu_count()
82  if opts.ncpus > sys_cpus:
83  s = "Invalid value : --ncpus : only %i cpus available" % sys_cpus
84  parser.error(s)
85  elif opts.ncpus < -1 :
86  s = "Invalid value : --ncpus must be integer >= -1"
87  parser.error(s)
88  else:
89  # FIXME: is it really needed to set it to None if it is 0 or False?
90  opts.ncpus = None
91 
92  # configure the logging
93  import logging
94  from GaudiKernel.ProcessJobOptions import InstallRootLoggingHandler
95 
96  if opts.old_opts: prefix = "// "
97  else: prefix = "# "
98  level = logging.INFO
99  if opts.debug:
100  level = logging.DEBUG
101  InstallRootLoggingHandler(prefix, level = level)
102  root_logger = logging.getLogger()
103 
104  # tcmalloc support
105  if opts.tcmalloc:
106  opts.preload.insert(0, os.environ.get("TCMALLOCLIB", "libtcmalloc.so"))
107  # allow preloading of libraries
108  if opts.preload:
109  preload = os.environ.get("LD_PRELOAD", "")
110  if preload:
111  preload = preload.replace(" ", ":").split(":")
112  else:
113  preload = []
114  for libname in set(preload).intersection(opts.preload):
115  logging.warning("Ignoring preload of library %s because it is "
116  "already in LD_PRELOAD.", libname)
117  to_load = [libname
118  for libname in opts.preload
119  if libname not in set(preload)]
120  if to_load:
121  preload += to_load
122  preload = ":".join(preload)
123  os.environ["LD_PRELOAD"] = preload
124  logging.info("Restarting with LD_PRELOAD='%s'", preload)
125  # remove the --tcmalloc option from the arguments
126  # FIXME: the --preload arguments will issue a warning but it's tricky to remove them
127  args = [ a for a in sys.argv if a != '-T' and not '--tcmalloc'.startswith(a) ]
128  os.execv(sys.executable, [sys.executable] + args)
129 
130  if opts.pickle_output:
131  if opts.output:
132  root_logger.error("Conflicting options: use only --pickle-output or --output")
133  sys.exit(1)
134  else:
135  root_logger.warning("--pickle-output is deprecated, use --output instead")
136  opts.output = opts.pickle_output
137 
138  from Gaudi.Main import gaudimain
139  c = gaudimain()
140 
141  # Prepare the "configuration script" to parse (like this it is easier than
142  # having a list with files and python commands, with an if statements that
143  # decides to do importOptions or exec)
144  options = [ "importOptions(%r)" % f for f in args ]
145  # The option lines are inserted into the list of commands using their
146  # position on the command line
147  optlines = list(opts.options)
148  optlines.reverse() # this allows to avoid to have to care about corrections of the positions
149  for pos, l in optlines:
150  options.insert(pos,l)
151 
152  # prevent the usage of GaudiPython
153  class FakeModule(object):
154  def __init__(self, exception):
155  self.exception = exception
156  def __getattr__(self, *args, **kwargs):
157  raise self.exception
158  sys.modules["GaudiPython"] = FakeModule(RuntimeError("GaudiPython cannot be used in option files"))
159 
160  # "execute" the configuration script generated (if any)
161  if options:
162  g = {}
163  l = {}
164  exec "from Gaudi.Configuration import *" in g, l
165  for o in options:
166  logging.debug(o)
167  exec o in g, l
168 
169  import GaudiKernel.Proxy.Configurable
170  if opts.no_conf_user_apply:
171  logging.info("Disabling automatic apply of ConfigurableUser")
172  # pretend that they have been already applied
173  GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ = True
174 
175  # This need to be done before dumping
176  from GaudiKernel.Proxy.Configurable import applyConfigurableUsers
178 
179  # Options to be processed after applyConfigurableUsers
180  if opts.post_options:
181  g = {}
182  l = {}
183  exec "from Gaudi.Configuration import *" in g, l
184  for o in opts.post_options:
185  logging.debug(o)
186  exec o in g, l
187 
188  if opts.verbose:
189  c.printconfig(opts.old_opts, opts.all_opts)
190  if opts.output:
191  c.writeconfig(opts.output, opts.all_opts)
192 
193  c.printsequence = opts.printsequence
194  if opts.printsequence:
195  if opts.ncpus:
196  logging.warning("--printsequence not supported with --ncpus: ignored")
197  elif opts.dry_run:
198  logging.warning("--printsequence not supported with --dry-run: ignored")
199 
200  # re-enable the GaudiPython module
201  del sys.modules["GaudiPython"]
202 
203  if not opts.dry_run:
204  # Do the real processing
205  sys.exit(c.run(opts.ncpus))

Generated at Wed Nov 28 2012 12:17:09 for Gaudi Framework, version v23r5 by Doxygen version 1.8.2 written by Dimitri van Heesch, © 1997-2004