Gaudi Framework, version v23r4

Home   Generated: Mon Sep 17 2012
Functions | Variables

genconfuser Namespace Reference

Functions

def _inheritsfrom
def loadConfigurableDb
def getConfigurableUsers
def main

Variables

tuple retcode = main()

Function Documentation

def genconfuser::_inheritsfrom (   derived,
  basename 
) [private]
Check if the class name 'basename' is anywhere in the base classes of the
class 'derived'.
If 'derived' _is_ 'basename', returns False.

Definition at line 21 of file genconfuser.py.

00022                                     :
00023     """
00024     Check if the class name 'basename' is anywhere in the base classes of the
00025     class 'derived'.
00026     If 'derived' _is_ 'basename', returns False.
00027     """
00028     for b in derived.__bases__:
00029         if b.__name__ == basename:
00030             return True
00031         else:
00032             if _inheritsfrom(b, basename):
00033                 return True
00034     return False

def genconfuser::getConfigurableUsers (   modulename,
  root,
  mayNotExist = False 
)
Find in the module 'modulename' all the classes that derive from ConfigurableUser.
Return the list of the names.
The flag mayNotExist is used to choose the level of the logging message in case
the requested module does not exist.

Definition at line 54 of file genconfuser.py.

00055                                                                :
00056     """
00057     Find in the module 'modulename' all the classes that derive from ConfigurableUser.
00058     Return the list of the names.
00059     The flag mayNotExist is used to choose the level of the logging message in case
00060     the requested module does not exist.
00061     """
00062     # remember the old system path
00063     oldpath = list(sys.path)
00064     # we need to hack the sys.path to add the first part of the module name after root
00065     moduleelements = modulename.split('.')
00066     if len(moduleelements) > 1:
00067         moddir = os.sep.join([root] + moduleelements[:-1])
00068     else:
00069         moddir = root
00070     # this is the name of the submodule to import
00071     shortmodname = moduleelements[-1]
00072     # check if the module file actually exists
00073     if not os.path.exists(os.path.join(moddir, shortmodname) + ".py"):
00074         msg = "Module %s does not exist" % modulename
00075         if mayNotExist:
00076             logging.verbose(msg)
00077         else:
00078             logging.error(msg)
00079         # no file -> do not try to import
00080         return []
00081     # prepend moddir to the path
00082     sys.path.insert(0, moddir)
00083     logging.verbose("sys.path prepended with %r", sys.path[0])
00084 
00085     logging.info("Looking for ConfigurableUser in %r", modulename)
00086     g, l = {}, {}
00087     try:
00088         logging.verbose("importing %s", shortmodname)
00089         exec "import %s as mod" % shortmodname in g, l
00090     finally:
00091         # restore old sys.path
00092         logging.verbose("restoring old sys.path")
00093         sys.path = oldpath
00094     mod = l["mod"]
00095     if "__all__" in dir(mod) and mod.__all__:
00096         all = mod.__all__
00097     else:
00098         all = [ n for n in dir(mod) if not n.startswith("_")]
00099     result = []
00100     for name in all:
00101         cfg = cfgDb.get(name)
00102         if cfg and cfg["module"] != modulename:
00103             # This name comes from another module
00104             logging.verbose("Object %r already found in module %r", name, cfg["module"])
00105             continue
00106         t = getattr(mod, name)
00107         if isinstance(t, type) and  _inheritsfrom(t, "ConfigurableUser"):
00108             result.append(name)
00109     logging.verbose("Found %r", result)
00110     return result

def genconfuser::loadConfigurableDb (  )
Equivalent to GaudiKernel.ConfigurableDb.loadConfigurableDb(), but does a
deep search and executes the '*_confDb.py' files instead of importing them.

Definition at line 35 of file genconfuser.py.

00036                         :
00037     '''
00038     Equivalent to GaudiKernel.ConfigurableDb.loadConfigurableDb(), but does a
00039     deep search and executes the '*_confDb.py' files instead of importing them.
00040     '''
00041     # find the '*_confDb.py' files that are not merged ones
00042     for p in sys.path:
00043         for f in [f for f in glob(os.path.join(p, '*', '*_confDb.py'))
00044                   if 'merged' not in f and os.path.isfile(f)]:
00045             logging.verbose('Loading %s', f)
00046             try:
00047                 execfile(f, {}, {})
00048             except:
00049                 # It may happen that the file is found but not completely
00050                 # written, usually during parallel builds, but we do not care.
00051                 pass
00052     # top up with the regular merged confDb (for the used projects)
00053     GaudiKernel.ConfigurableDb.loadConfigurableDb()

def genconfuser::main (  )

Definition at line 111 of file genconfuser.py.

00112           :
00113     from optparse import OptionParser
00114     parser = OptionParser(prog = os.path.basename(sys.argv[0]),
00115                           usage = "%prog [options] <PackageName> [<Module1> ...]")
00116     parser.add_option("-o", "--output", action="store", type="string",
00117                       help="output file for confDb data [default = '../genConf/<PackageName>_user_confDb.py'].")
00118     parser.add_option("-r", "--root", action="store", type="string",
00119                       help="root directory of the python modules [default = '../python'].")
00120     parser.add_option("-v", "--verbose", action="store_true",
00121                       help="print some debugging information")
00122     parser.add_option("--debug", action="store_true",
00123                       help="print more debugging information")
00124     parser.add_option("--lockerpath", action="store",
00125                       metavar = "DIRNAME",
00126                       help="directory where to find the module 'locker'")
00127     parser.set_defaults(root = os.path.join("..","python"))
00128 
00129     opts, args = parser.parse_args()
00130 
00131     if opts.debug:
00132         log_level = logging.DEBUG
00133     elif opts.verbose:
00134         log_level = logging.VERBOSE
00135     else:
00136         log_level = logging.INFO
00137     logging.basicConfig(format = "%(levelname)s: %(message)s",
00138                         stream = sys.stdout,
00139                         level = log_level)
00140 
00141     if len(args) < 1:
00142         parser.error("PackageName is required")
00143 
00144     package_name = args.pop(0)
00145 
00146     usingConvention = False
00147     if not args:
00148         # use the conventional module name <package>.Configuration
00149         args = [package_name + ".Configuration"]
00150         usingConvention = True
00151 
00152     genConfDir = os.path.join("..", os.environ.get("CMTCONFIG", ""), "genConf")
00153     if not os.path.exists(genConfDir):
00154         genConfDir = os.path.join("..", "genConf")
00155 
00156     if not opts.output:
00157         outputfile = os.path.join(genConfDir, package_name + '_user_confDb.py')
00158     else:
00159         outputfile = opts.output
00160 
00161 
00162     # The locking ensures that nobody tries to modify the python.zip file while
00163     # we read it.
00164     dbLock = None
00165     if "GAUDI_BUILD_LOCK" in os.environ:
00166         if opts.lockerpath:
00167             sys.path.append(opts.lockerpath)
00168         # Get the LockFile class from the locker module in GaudiPolicy or use a fake
00169         # factory.
00170         try:
00171             from locker import LockFile
00172         except ImportError:
00173             def LockFile(*args, **kwargs):
00174                 return None
00175         # obtain the lock
00176         dbLock = LockFile(os.environ["GAUDI_BUILD_LOCK"], temporary =  True)
00177 
00178     # We can disable the error on missing configurables only if we can import Gaudi.Configurables
00179     # It must be done at this point because it may conflict with logging.basicConfig
00180     try:
00181         import Gaudi.Configurables
00182         Gaudi.Configurables.ignoreMissingConfigurables = True
00183     except:
00184         pass
00185     # load configurables database to avoid fake duplicates
00186     loadConfigurableDb()
00187     # ensure that local configurables are in the database
00188     try:
00189         # Add the local python directories to the python path to be able to import the local
00190         # configurables
00191         sys.path.insert(0, genConfDir)
00192         sys.path.insert(0, os.path.join("..", "python"))
00193         localConfDb = os.path.join(genConfDir, package_name, package_name + '_confDb.py')
00194         if os.path.exists(localConfDb):
00195             execfile(localConfDb, {}, {})
00196             # Extend the search path of the package module to find the configurables
00197             package_module = __import__(package_name)
00198             package_module.__path__.insert(0, os.path.join(genConfDir, package_name))
00199     except:
00200         pass # ignore failures (not important)
00201     del dbLock # Now we can let the others operate on the install area python directory
00202 
00203     # Collecting ConfigurableUser specializations
00204     cus = {}
00205     for mod in args:
00206         lst = None
00207         try:
00208             lst = getConfigurableUsers(mod, root = opts.root, mayNotExist = usingConvention)
00209         except ImportError:
00210             import traceback
00211             logging.error("Cannot import module %r:\n%s", mod,
00212                           traceback.format_exc().rstrip()) # I remove the trailing '\n'
00213             return 2
00214         if lst:
00215             cus[mod] = lst
00216             # Add the configurables to the database as fake entries to avoid duplicates
00217             for m in lst:
00218                 cfgDb.add(configurable = m,
00219                           package = 'None',
00220                           module  = 'None',
00221                           lib     = 'None')
00222         elif not usingConvention:
00223             logging.warning("Specified module %r does not contain ConfigurableUser specializations", mod)
00224 
00225     if cus:
00226         logging.info("ConfigurableUser found:\n%s", pformat(cus))
00227         # header
00228         output = """##  -*- python -*-
00229 # db file automatically generated by %s on: %s
00230 ## insulates outside world against anything bad that could happen
00231 ## also prevents global scope pollution
00232 def _fillCfgDb():
00233     from GaudiKernel.Proxy.ConfigurableDb import CfgDb
00234 
00235     # get a handle on the repository of Configurables
00236     cfgDb = CfgDb()
00237 
00238     # populate the repository with informations on Configurables
00239 """ % (parser.prog, time.asctime())
00240 
00241         for mod in cus:
00242             for cu in cus[mod]:
00243                 output += """
00244     cfgDb.add( configurable = '%s',
00245                package = '%s',
00246                module  = '%s',
00247                lib     = 'None' )""" % (cu, package_name, mod)
00248 
00249         # trailer
00250         output += """
00251 
00252     return #_fillCfgDb
00253 
00254 # fill cfgDb at module import...
00255 try:
00256     _fillCfgDb()
00257     #house cleaning...
00258     del _fillCfgDb
00259 except Exception,err:
00260     print "Py:ConfigurableDb   ERROR Problem with [%%s] content!" %% __name__
00261     print "Py:ConfigurableDb   ERROR",err
00262     print "Py:ConfigurableDb   ERROR   ==> culprit is package [%s] !"
00263 """ % package_name
00264     elif usingConvention:
00265         logging.info("No ConfigurableUser found")
00266         output = ("# db file automatically generated by %s on: %s\n"
00267                   "# No ConfigurableUser specialization in %s\n") % (parser.prog, time.asctime(), package_name)
00268     else:
00269         logging.error("No ConfigurableUser specialization found")
00270         return 1
00271 
00272     # create the destination directory if not there
00273     output_dir = os.path.dirname(outputfile)
00274     if not os.path.exists(output_dir):
00275         logging.info("Creating directory %r", output_dir)
00276         os.makedirs(output_dir, 0755)
00277 
00278     # write output to file
00279     logging.verbose("Writing confDb data to %r", outputfile)
00280     open(outputfile, "w").write(output)
00281     return 0


Variable Documentation

tuple genconfuser::retcode = main()

Definition at line 283 of file genconfuser.py.

 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Properties Friends Defines

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