| # Gaudi Framework, version v22r4 |

Home |  | Generated: Fri Sep 2 2011

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     if not opts.output:
    00124         outputfile = os.path.join("..", "genConf", package_name + '_user_confDb.py')
    00125     else:
    00126         outputfile = opts.output
    00127
    00128     # The locking ensures that nobody tries to modify the python.zip file while
    00129     # we read it.
    00130     dbLock = None
    00131     if "GAUDI_BUILD_LOCK" in os.environ:
    00132         if opts.lockerpath:
    00133             sys.path.append(opts.lockerpath)
    00134         # Get the LockFile class from the locker module in GaudiPolicy or use a fake
    00135         # factory.
    00136         try:
    00137             from locker import LockFile
    00138         except ImportError:
    00139             def LockFile(*args, **kwargs):
    00140                 return None
    00141         # obtain the lock
    00142         dbLock = LockFile(os.environ["GAUDI_BUILD_LOCK"], temporary =  True)
    00143
    00144     # We can disable the error on missing configurables only if we can import Gaudi.Configurables
    00145     # It must be done at this point because it may conflict with logging.basicConfig
    00146     try:
    00147         import Gaudi.Configurables
    00148         Gaudi.Configurables.ignoreMissingConfigurables = True
    00149     except:
    00150         pass
    00151     # load configurables database to avoid fake duplicates
    00152     loadConfigurableDb()
    00153     # ensure that local configurables are in the database
    00154     try:
    00155         # Add the local python directories to the python path to be able to import the local
    00156         # configurables
    00157         sys.path.insert(0, os.path.join("..", "genConf"))
    00158         sys.path.insert(0, os.path.join("..", "python"))
    00159         localConfDb = os.path.join("..", "genConf", package_name, package_name + '_confDb.py')
    00160         if os.path.exists(localConfDb):
    00161             execfile(localConfDb, {}, {})
    00162     except:
    00163         pass # ignore failures (not important)
    00164     del dbLock # Now we can let the others operate on the install area python directory
    00165
    00166     # Collecting ConfigurableUser specializations
    00167     cus = {}
    00168     for mod in args:
    00169         lst = None
    00170         try:
    00171             lst = getConfigurableUsers(mod, root = opts.root, mayNotExist = usingConvention)
    00172         except ImportError:
    00173             import traceback
    00174             logging.error("Cannot import module %r:\n%s", mod,
    00175                           traceback.format_exc().rstrip()) # I remove the trailing '\n'
    00176             return 2
    00177         if lst:
    00178             cus[mod] = lst
    00179             # Add the configurables to the database as fake entries to avoid duplicates
    00180             for m in lst:
    00181                 cfgDb.add(configurable = m,
    00182                           package = 'None',
    00183                           module  = 'None',
    00184                           lib     = 'None')
    00185         elif not usingConvention:
    00186             logging.warning("Specified module %r does not contain ConfigurableUser specializations", mod)
    00187
    00188     if cus:
    00189         logging.info("ConfigurableUser found:\n%s", pformat(cus))
    00190         # header
    00191         output = """##  -*- python -*-
    00192 # db file automatically generated by %s on: %s
    00193 ## insulates outside world against anything bad that could happen
    00194 ## also prevents global scope pollution
    00195 def _fillCfgDb():
    00196     from GaudiKernel.Proxy.ConfigurableDb import CfgDb
    00197
    00198     # get a handle on the repository of Configurables
    00199     cfgDb = CfgDb()
    00200
    00201     # populate the repository with informations on Configurables
    00202 """ % (parser.prog, time.asctime())
    00203
    00204         for mod in cus:
    00205             for cu in cus[mod]:
    00206                 output += """
    00207     cfgDb.add( configurable = '%s',
    00208                package = '%s',
    00209                module  = '%s',
    00210                lib     = 'None' )""" % (cu, package_name, mod)
    00211
    00212         # trailer
    00213         output += """
    00214
    00215     return #_fillCfgDb
    00216
    00217 # fill cfgDb at module import...
    00218 try:
    00219     _fillCfgDb()
    00220     #house cleaning...
    00221     del _fillCfgDb
    00222 except Exception,err:
    00223     print "Py:ConfigurableDb   ERROR Problem with [%%s] content!" %% __name__
    00224     print "Py:ConfigurableDb   ERROR",err
    00225     print "Py:ConfigurableDb   ERROR   ==> culprit is package [%s] !"
    00226 """ % package_name
    00227     elif usingConvention:
    00228         logging.info("No ConfigurableUser found")
    00229         output = "# No ConfigurableUser specialization\n"
    00230     else:
    00231         logging.error("No ConfigurableUser specialization found")
    00232         return 1
    00233
    00234     # create the destination directory if not there
    00235     output_dir = os.path.dirname(outputfile)
    00236     if not os.path.exists(output_dir):
    00237         logging.info("Creating directory %r", output_dir)
    00238         os.makedirs(output_dir, 0755)
    00239
    00240     # write output to file
    00241     logging.verbose("Writing confDb data to %r", outputfile)
    00242     open(outputfile, "w").write(output)
    00243     return 0

## Variable Documentation

tuple genconfuser::retcode = main()

Definition at line 245 of file genconfuser.py.

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