Gaudi Framework, version v23r4

Home   Generated: Mon Sep 17 2012

gaudirun.py

Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 
00003 #---------------------------------------------------------------------
00004 if __name__ == "__main__":
00005     import os, sys
00006     from optparse import OptionParser
00007     parser = OptionParser(usage = "%prog [options] <opts_file> ...")
00008     parser.add_option("-n","--dry-run", action="store_true",
00009                       help="do not run the application, just parse option files")
00010     parser.add_option("-p","--pickle-output", action="store", type="string",
00011                       metavar = "FILE",
00012                       help="DEPRECATED: use '--output file.pkl' instead. Write "
00013                            "the parsed options as a pickle file (static option "
00014                            "file)")
00015     parser.add_option("-v","--verbose", action="store_true",
00016                       help="print the parsed options")
00017     parser.add_option("--old-opts", action="store_true",
00018                       help="format printed options in old option files style")
00019     parser.add_option("--all-opts", action="store_true",
00020                       help="print all the option (even if equal to default)")
00021     # GaudiPython Parallel Mode Option
00022     #   Argument must be an integer in range [ -1, sys_cpus ]
00023     #   -1   : All available cpus
00024     #    0   : Serial Mode (traditional gaudirun)
00025     #    n>0 : parallel with n cpus (n <= sys_cpus)
00026     parser.add_option("--ncpus", action="store", type="int", default=0,
00027                       help="start the application in parallel mode using NCPUS processes. "
00028                            "0 => serial mode (default), -1 => use all CPUs")
00029 
00030     def option_cb(option, opt, value, parser):
00031         """Add the option line to a list together with its position in the
00032         argument list.
00033         """
00034         parser.values.options.append((len(parser.largs), value))
00035     parser.add_option("--option", action="callback", callback=option_cb,
00036                       type = "string", nargs = 1,
00037                       help="add a single line (Python) option to the configuration. "
00038                            "All options lines are executed, one after the other, in "
00039                            "the same context.")
00040     parser.add_option("--no-conf-user-apply", action="store_true",
00041                       help="disable the automatic application of configurable "
00042                            "users (for backward compatibility)")
00043     parser.add_option("-o", "--output", action = "store", type = "string",
00044                       help ="dump the configuration to a file. The format of "
00045                             "the options is determined by the extension of the "
00046                             "file name: .pkl = pickle, .py = python, .opts = "
00047                             "old style options. The python format cannot be "
00048                             "used to run the application and it contains the "
00049                             "same dictionary printed with -v")
00050     parser.add_option("--post-option", action="append", type="string",
00051                       dest="post_options",
00052                       help="Python options to be executed after the ConfigurableUser "
00053                            "are applied. "
00054                            "All options lines are executed, one after the other, in "
00055                            "the same context.")
00056     parser.add_option("--debug", action="store_true",
00057                       help="enable some debug print-out")
00058     parser.add_option("--printsequence", action="store_true",
00059                       help="print the sequence")
00060     if not sys.platform.startswith("win"):
00061         # These options can be used only on unix platforms
00062         parser.add_option("-T", "--tcmalloc", action="store_true",
00063                           help="Use the Google malloc replacement. The environment "
00064                                "variable TCMALLOCLIB can be used to specify a different "
00065                                "name for the library (the default is libtcmalloc.so)")
00066         parser.add_option("--preload", action="append",
00067                           help="Allow pre-loading of special libraries (e.g. Google "
00068                                "profiling libraries).")
00069     parser.set_defaults(options = [],
00070                         tcmalloc = False,
00071                         preload = [],
00072                         ncpus = None)
00073 
00074     opts, args = parser.parse_args()
00075 
00076     # Check consistency of options
00077 
00078     # Parallel Option ---------------------------------------------------------
00079     if opts.ncpus:
00080         from multiprocessing import cpu_count
00081         sys_cpus = cpu_count()
00082         if opts.ncpus > sys_cpus:
00083             s = "Invalid value : --ncpus : only %i cpus available" % sys_cpus
00084             parser.error(s)
00085         elif opts.ncpus < -1 :
00086             s = "Invalid value : --ncpus must be integer >= -1"
00087             parser.error(s)
00088     else:
00089         # FIXME: is it really needed to set it to None if it is 0 or False?
00090         opts.ncpus = None
00091 
00092     # configure the logging
00093     import logging
00094     from GaudiKernel.ProcessJobOptions import InstallRootLoggingHandler
00095 
00096     if opts.old_opts: prefix = "// "
00097     else: prefix = "# "
00098     level = logging.INFO
00099     if opts.debug:
00100         level = logging.DEBUG
00101     InstallRootLoggingHandler(prefix, level = level)
00102     root_logger = logging.getLogger()
00103 
00104     # tcmalloc support
00105     if opts.tcmalloc:
00106         opts.preload.insert(0, os.environ.get("TCMALLOCLIB", "libtcmalloc.so"))
00107     # allow preloading of libraries
00108     if opts.preload:
00109         preload = os.environ.get("LD_PRELOAD", "")
00110         if preload:
00111             preload = preload.replace(" ", ":").split(":")
00112         else:
00113             preload = []
00114         for libname in set(preload).intersection(opts.preload):
00115             logging.warning("Ignoring preload of library %s because it is "
00116                             "already in LD_PRELOAD.", libname)
00117         to_load = [libname
00118                    for libname in opts.preload
00119                    if libname not in set(preload)]
00120         if to_load:
00121             preload += to_load
00122             preload = ":".join(preload)
00123             os.environ["LD_PRELOAD"] = preload
00124             logging.info("Restarting with LD_PRELOAD='%s'", preload)
00125             # remove the --tcmalloc option from the arguments
00126             # FIXME: the --preload arguments will issue a warning but it's tricky to remove them
00127             args = [ a for a in sys.argv if a != '-T' and not '--tcmalloc'.startswith(a) ]
00128             os.execv(sys.executable, [sys.executable] + args)
00129 
00130     if opts.pickle_output:
00131         if opts.output:
00132             root_logger.error("Conflicting options: use only --pickle-output or --output")
00133             sys.exit(1)
00134         else:
00135             root_logger.warning("--pickle-output is deprecated, use --output instead")
00136             opts.output = opts.pickle_output
00137 
00138     from Gaudi.Main import gaudimain
00139     c = gaudimain()
00140 
00141     # Prepare the "configuration script" to parse (like this it is easier than
00142     # having a list with files and python commands, with an if statements that
00143     # decides to do importOptions or exec)
00144     options = [ "importOptions(%r)" % f for f in args ]
00145     # The option lines are inserted into the list of commands using their
00146     # position on the command line
00147     optlines = list(opts.options)
00148     optlines.reverse() # this allows to avoid to have to care about corrections of the positions
00149     for pos, l in optlines:
00150         options.insert(pos,l)
00151 
00152     # prevent the usage of GaudiPython
00153     class FakeModule(object):
00154         def __init__(self, exception):
00155             self.exception = exception
00156         def __getattr__(self, *args, **kwargs):
00157             raise self.exception
00158     sys.modules["GaudiPython"] = FakeModule(RuntimeError("GaudiPython cannot be used in option files"))
00159 
00160     # "execute" the configuration script generated (if any)
00161     if options:
00162         g = {}
00163         l = {}
00164         exec "from Gaudi.Configuration import *" in g, l
00165         for o in options:
00166             logging.debug(o)
00167             exec o in g, l
00168 
00169     import GaudiKernel.Proxy.Configurable
00170     if opts.no_conf_user_apply:
00171         logging.info("Disabling automatic apply of ConfigurableUser")
00172         # pretend that they have been already applied
00173         GaudiKernel.Proxy.Configurable._appliedConfigurableUsers_ = True
00174 
00175     # This need to be done before dumping
00176     from GaudiKernel.Proxy.Configurable import applyConfigurableUsers
00177     applyConfigurableUsers()
00178 
00179     # Options to be processed after applyConfigurableUsers
00180     if opts.post_options:
00181         g = {}
00182         l = {}
00183         exec "from Gaudi.Configuration import *" in g, l
00184         for o in opts.post_options:
00185             logging.debug(o)
00186             exec o in g, l
00187 
00188     if opts.verbose:
00189         c.printconfig(opts.old_opts, opts.all_opts)
00190     if opts.output:
00191         c.writeconfig(opts.output, opts.all_opts)
00192 
00193     c.printsequence = opts.printsequence
00194     if opts.printsequence:
00195         if opts.ncpus:
00196             logging.warning("--printsequence not supported with --ncpus: ignored")
00197         elif opts.dry_run:
00198             logging.warning("--printsequence not supported with --dry-run: ignored")
00199 
00200     # re-enable the GaudiPython module
00201     del sys.modules["GaudiPython"]
00202 
00203     if not opts.dry_run:
00204         # Do the real processing
00205         sys.exit(c.run(opts.ncpus))
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Defines

Generated at Mon Sep 17 2012 13:49:25 for Gaudi Framework, version v23r4 by Doxygen version 1.7.2 written by Dimitri van Heesch, © 1997-2004