Gaudi Framework, version v23r2

Home   Generated: Thu Jun 28 2012
Functions | Variables

genconfuser Namespace Reference

Functions

def _inheritsfrom
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 15 of file genconfuser.py.

00016                                     :
00017     """
00018     Check if the class name 'basename' is anywhere in the base classes of the
00019     class 'derived'.
00020     If 'derived' _is_ 'basename', returns False.
00021     """
00022     for b in derived.__bases__:
00023         if b.__name__ == basename:
00024             return True
00025         else:
00026             if _inheritsfrom(b, basename):
00027                 return True
00028     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 29 of file genconfuser.py.

00030                                                                :
00031     """
00032     Find in the module 'modulename' all the classes that derive from ConfigurableUser.
00033     Return the list of the names.
00034     The flag mayNotExist is used to choose the level of the logging message in case
00035     the requested module does not exist.
00036     """
00037     # remember the old system path
00038     oldpath = list(sys.path)
00039     # we need to hack the sys.path to add the first part of the module name after root
00040     moduleelements = modulename.split('.')
00041     if len(moduleelements) > 1:
00042         moddir = os.sep.join([root] + moduleelements[:-1])
00043     else:
00044         moddir = root
00045     # this is the name of the submodule to import
00046     shortmodname = moduleelements[-1]
00047     # check if the module file actually exists
00048     if not os.path.exists(os.path.join(moddir, shortmodname) + ".py"):
00049         msg = "Module %s does not exist" % modulename
00050         if mayNotExist:
00051             logging.verbose(msg)
00052         else:
00053             logging.error(msg)
00054         # no file -> do not try to import
00055         return []
00056     # prepend moddir to the path
00057     sys.path.insert(0, moddir)
00058     logging.verbose("sys.path prepended with %r", sys.path[0])
00059 
00060     logging.info("Looking for ConfigurableUser in %r", modulename)
00061     g, l = {}, {}
00062     try:
00063         logging.verbose("importing %s", shortmodname)
00064         exec "import %s as mod" % shortmodname in g, l
00065     finally:
00066         # restore old sys.path
00067         logging.verbose("restoring old sys.path")
00068         sys.path = oldpath
00069     mod = l["mod"]
00070     if "__all__" in dir(mod) and mod.__all__:
00071         all = mod.__all__
00072     else:
00073         all = [ n for n in dir(mod) if not n.startswith("_")]
00074     result = []
00075     for name in all:
00076         cfg = cfgDb.get(name)
00077         if cfg and cfg["module"] != modulename:
00078             # This name comes from another module
00079             logging.verbose("Object %r already found in module %r", name, cfg["module"])
00080             continue
00081         t = getattr(mod, name)
00082         if isinstance(t, type) and  _inheritsfrom(t, "ConfigurableUser"):
00083             result.append(name)
00084     logging.verbose("Found %r", result)
00085     return result

def genconfuser::main (  )

Definition at line 86 of file genconfuser.py.

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


Variable Documentation

tuple genconfuser::retcode = main()

Definition at line 250 of file genconfuser.py.

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

Generated at Thu Jun 28 2012 23:27:53 for Gaudi Framework, version v23r2 by Doxygen version 1.7.2 written by Dimitri van Heesch, © 1997-2004