当前位置: 首页>>代码示例>>Python>>正文


Python CFG.loadFromBuffer方法代码示例

本文整理汇总了Python中DIRAC.Core.Utilities.CFG.CFG.loadFromBuffer方法的典型用法代码示例。如果您正苦于以下问题:Python CFG.loadFromBuffer方法的具体用法?Python CFG.loadFromBuffer怎么用?Python CFG.loadFromBuffer使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在DIRAC.Core.Utilities.CFG.CFG的用法示例。


在下文中一共展示了CFG.loadFromBuffer方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: mergeWithServer

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
 def mergeWithServer( self ):
   retVal = self.rpcClient.getCompressedData()
   if retVal[ 'OK' ]:
     remoteCFG = CFG()
     remoteCFG.loadFromBuffer( zlib.decompress( retVal[ 'Value' ] ) )
     serverVersion = gConfigurationData.getVersion( remoteCFG )
     self.cfgData = remoteCFG.mergeWith( self.cfgData )
     gConfigurationData.setVersion( serverVersion, self.cfgData )
   return retVal
开发者ID:ahaupt,项目名称:DIRAC,代码行数:11,代码来源:Modificator.py

示例2: JobManifest

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
class JobManifest( object ):

  def __init__( self, manifest = "" ):
    self.__manifest = CFG()
    self.__dirty = False
    if manifest:
      result = self.loadManifest( manifest )
      if not result[ 'OK' ]:
        raise Exception( result[ 'Message' ] )

  def isDirty( self ):
    return self.__dirty

  def setDirty( self ):
    self.__dirty = True

  def clearDirty( self ):
    self.__dirty = False

  def load( self, dataString ):
    """
    Auto discover format type based on [ .. ] of JDL
    """
    dataString = dataString.strip()
    if dataString[0] == "[" and dataString[-1] == "]":
      return self.loadJDL( dataString )
    else:
      return self.loadCFG( dataString )

  def loadJDL( self, jdlString ):
    """
    Load job manifest from JDL format
    """
    result = loadJDLAsCFG( jdlString.strip() )
    if not result[ 'OK' ]:
      self.__manifest = CFG()
      return result
    self.__manifest = result[ 'Value' ][0]
    return S_OK()

  def loadCFG( self, cfgString ):
    """
    Load job manifest from CFG format
    """
    try:
      self.__manifest.loadFromBuffer( cfgString )
    except Exception, e:
      return S_ERROR( "Can't load manifest from cfg: %s" % str( e ) )
    return S_OK()
开发者ID:cgrefe,项目名称:DIRAC,代码行数:51,代码来源:JobManifest.py

示例3: showTextConfiguration

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
 def showTextConfiguration(self):
     response.headers["Content-type"] = "text/plain"
     if "download" in request.params and request.params["download"] in ("yes", "true", "1"):
         version = ""
         try:
             cfg = CFG()
             cfg.loadFromBuffer(session["cfgData"])
             cfg = cfg["DIRAC"]["Configuration"]
             version = ".%s.%s" % (cfg["Name"], cfg["Version"].replace(":", "").replace("-", ""))
         except Exception, e:
             print e
         print 'attachment; filename="cs%s.cfg"' % version.replace(" ", "_")
         response.headers["Content-Disposition"] = 'attachment; filename="cs%s.cfg"' % version.replace(" ", "")
         response.headers["Content-Length"] = len(session["cfgData"])
         response.headers["Content-Transfer-Encoding"] = "Binary"
开发者ID:sfayer,项目名称:DIRACWeb,代码行数:17,代码来源:configuration.py

示例4: setUp

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
  def setUp( self ):
    self.authMgr = AuthManager( '/Systems/Service/Authorization' )
    cfg = CFG()
    cfg.loadFromBuffer( testSystemsCFG )
    gConfig.loadCFG( cfg )
    cfg.loadFromBuffer( testRegistryCFG )
    gConfig.loadCFG( cfg )

    self.noAuthCredDict = { 'group': 'group_test' }

    self.userCredDict = { 'DN': '/User/test/DN/CN=userA',
                          'group': 'group_test' }

    self.badUserCredDict = { 'DN': '/User/test/DN/CN=userB',
                             'group': 'group_bad' }
    self.hostCredDict = { 'DN': '/User/test/DN/CN=test.hostA.ch',
                          'group': 'hosts' }
    self.badHostCredDict = { 'DN': '/User/test/DN/CN=test.hostB.ch',
                             'group': 'hosts' }
开发者ID:DIRACGrid,项目名称:DIRAC,代码行数:21,代码来源:Test_AuthManager.py

示例5: __saveVomsMapping

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
  def __saveVomsMapping(self, params):
    sectionPath = "/Registry/VOMS/Mapping"
    sectionCfg = self.getSectionCfg(sectionPath)

    for opt in sectionCfg.listAll():
      if not sectionCfg.isSection(opt):
        self.__configData[ 'cfgData' ].removeOption(sectionPath + "/" + opt)

    configText = ""

    for newOpt in params:
      if newOpt != "op":
        if configText == "":
          configText = newOpt + "=" + params[newOpt] + "\n"
        else:
          configText = configText + newOpt + "=" + params[newOpt] + "\n"

    newCFG = CFG()
    newCFG.loadFromBuffer(configText)
    self.__configData[ 'cfgData' ].mergeSectionFromCFG(sectionPath, newCFG)

    return {"op":"saveVomsMapping", "success": 1}
开发者ID:DIRACGrid,项目名称:WebAppDIRAC,代码行数:24,代码来源:RegistryManagerHandler.py

示例6: __init__

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
class JobDescription:

  def __init__( self ):
    self.__description = CFG()
    self.__dirty = False

  def isDirty( self ):
    return self.__dirty

  def loadDescription( self, dataString ):
    """
    Auto discover format type based on [ .. ] of JDL
    """
    dataString = dataString.strip()
    if dataString[0] == "[" and dataString[-1] == "]":
      return self.loadDescriptionFromJDL( dataString )
    else:
      return self.loadDescriptionFromCFG( dataString )

  def loadDescriptionFromJDL( self, jdlString ):
    """
    Load job description from JDL format
    """
    result = loadJDLAsCFG( jdlString.strip() )
    if not result[ 'OK' ]:
      self.__description = CFG()
      return result
    self.__description = result[ 'Value' ][0]
    return S_OK()

  def loadDescriptionFromCFG( self, cfgString ):
    """
    Load job description from CFG format
    """
    try:
      self.__description.loadFromBuffer( cfgString )
    except Exception, e:
      return S_ERROR( "Can't load description from cfg: %s" % str( e ) )
    return S_OK()
开发者ID:sbel,项目名称:bes3-jinr,代码行数:41,代码来源:JobDescription.py

示例7: JobManifest

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
class JobManifest(object):
    def __init__(self, manifest=""):
        self.__manifest = CFG()
        self.__dirty = False
        self.__ops = False
        if manifest:
            result = self.load(manifest)
            if not result["OK"]:
                raise Exception(result["Message"])

    def isDirty(self):
        return self.__dirty

    def setDirty(self):
        self.__dirty = True

    def clearDirty(self):
        self.__dirty = False

    def load(self, dataString):
        """
    Auto discover format type based on [ .. ] of JDL
    """
        dataString = dataString.strip()
        if dataString[0] == "[" and dataString[-1] == "]":
            return self.loadJDL(dataString)
        else:
            return self.loadCFG(dataString)

    def loadJDL(self, jdlString):
        """
    Load job manifest from JDL format
    """
        result = loadJDLAsCFG(jdlString.strip())
        if not result["OK"]:
            self.__manifest = CFG()
            return result
        self.__manifest = result["Value"][0]
        return S_OK()

    def loadCFG(self, cfgString):
        """
    Load job manifest from CFG format
    """
        try:
            self.__manifest.loadFromBuffer(cfgString)
        except Exception as e:
            return S_ERROR("Can't load manifest from cfg: %s" % str(e))
        return S_OK()

    def dumpAsCFG(self):
        return str(self.__manifest)

    def getAsCFG(self):
        return self.__manifest.clone()

    def dumpAsJDL(self):
        return dumpCFGAsJDL(self.__manifest)

    def __getCSValue(self, varName, defaultVal=None):
        if not self.__ops:
            self.__ops = Operations(group=self.__manifest["OwnerGroup"], setup=self.__manifest["DIRACSetup"])
        if varName[0] != "/":
            varName = "JobDescription/%s" % varName
        return self.__ops.getValue(varName, defaultVal)

    def __checkNumericalVar(self, varName, defaultVal, minVal, maxVal):
        """
    Check a numerical var
    """
        initialVal = False
        if varName not in self.__manifest:
            varValue = self.__getCSValue("Default%s" % varName, defaultVal)
        else:
            varValue = self.__manifest[varName]
            initialVal = varValue
        try:
            varValue = long(varValue)
        except:
            return S_ERROR("%s must be a number" % varName)
        minVal = self.__getCSValue("Min%s" % varName, minVal)
        maxVal = self.__getCSValue("Max%s" % varName, maxVal)
        varValue = max(minVal, min(varValue, maxVal))
        if initialVal != varValue:
            self.__manifest.setOption(varName, varValue)
        return S_OK(varValue)

    def __checkChoiceVar(self, varName, defaultVal, choices):
        """
    Check a choice var
    """
        initialVal = False
        if varName not in self.__manifest:
            varValue = self.__getCSValue("Default%s" % varName, defaultVal)
        else:
            varValue = self.__manifest[varName]
            initialVal = varValue
        if varValue not in self.__getCSValue("Choices%s" % varName, choices):
            return S_ERROR("%s is not a valid value for %s" % (varValue, varName))
        if initialVal != varValue:
#.........这里部分代码省略.........
开发者ID:DIRACGrid,项目名称:DIRAC,代码行数:103,代码来源:JobManifest.py

示例8: __editItem

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
  def __editItem(self, params):

    ret = self.__deleteItem(params)
    if ret["success"] == 1:
      ret = self.__addItem(params)
      ret["op"] = "editItem"
      return ret
    ret["op"] = "editItem"
    return ret

    sectionPath = "/Registry/"
    configText = ""
    if params["type"] == "users":

      sectionPath = sectionPath + "Users"
      if params["dn"].strip() != "":
        configText = "DN = " + params["dn"].strip() + "\n"

      if params["ca"].strip() != "":
        configText = configText + "CA = " + params["ca"].strip() + "\n"

      if params["email"].strip() != "":
        configText = configText + "Email = " + params["email"].strip()

    elif params["type"] == "groups":

      sectionPath = sectionPath + "Groups"
      if params["users"].strip() != "":
        configText = "Users = " + params["users"].strip() + "\n"

      if params["properties"].strip() != "":
        configText = configText + "Properties = " + params["properties"].strip() + "\n"

      if str(params["jobshare"]).strip() != "":
        configText = configText + "JobShare = " + str(params["jobshare"]) + "\n"

      if params["autouploadproxy"].strip() != "":
        configText = configText + "AutoUploadProxy = " + params["autouploadproxy"].strip() + "\n"

      if params["autouploadpilotproxy"].strip() != "":
        configText = configText + "AutoUploadPilotProxy = " + params["autouploadpilotproxy"].strip() + "\n"

      if params["autoaddvoms"].strip() != "":
        configText = configText + "AutoAddVOMS = " + params["autoaddvoms"].strip()

    elif params["type"] == "hosts":

      sectionPath = sectionPath + "Hosts"
      if params["dn"].strip() != "":
        configText = "DN = " + params["dn"].strip() + "\n"

      if params["properties"].strip() != "":
        configText = configText + "Properties = " + params["properties"].strip()

    sectionPath = sectionPath + "/" + params["name"]

#   deleting the options underneath
    sectionCfg = self.getSectionCfg(sectionPath)

    for opt in sectionCfg.listAll():
      print "deleting " + opt + "\n"
      self.__configData[ 'cfgData' ].removeOption(sectionPath + "/" + opt)

    newCFG = CFG()
    newCFG.loadFromBuffer(configText)
    self.__configData[ 'cfgData' ].mergeSectionFromCFG(sectionPath, newCFG)
    return {"success":1, "op": "editItem"}
开发者ID:DIRACGrid,项目名称:WebAppDIRAC,代码行数:69,代码来源:RegistryManagerHandler.py

示例9: __addItem

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
  def __addItem(self, params):

    sectionPath = "/Registry/"
    configText = ""
    if params["type"] == "users":

      sectionPath = sectionPath + "Users"
      if params["dn"].strip() != "":
        configText = "DN = " + params["dn"].strip() + "\n"

      if params["ca"].strip() != "":
        configText = configText + "CA = " + params["ca"].strip() + "\n"

      if params["email"].strip() != "":
        configText = configText + "Email = " + params["email"].strip()

    elif params["type"] == "groups":

      sectionPath = sectionPath + "Groups"
      if params["users"].strip() != "":
        configText = "Users = " + params["users"].strip() + "\n"

      if params["properties"].strip() != "":
        configText = configText + "Properties = " + params["properties"].strip() + "\n"

      if str(params["jobshare"]).strip() != "":
        configText = configText + "JobShare = " + str(params["jobshare"]) + "\n"

      if params["autouploadproxy"].strip() != "":
        configText = configText + "AutoUploadProxy = " + params["autouploadproxy"].strip() + "\n"

      if params["autouploadpilotproxy"].strip() != "":
        configText = configText + "AutoUploadPilotProxy = " + params["autouploadpilotproxy"].strip() + "\n"

      if params["autoaddvoms"].strip() != "":
        configText = configText + "AutoAddVOMS = " + params["autoaddvoms"].strip()

    elif params["type"] == "hosts":

      sectionPath = sectionPath + "Hosts"
      if params["dn"].strip() != "":
        configText = "DN = " + params["dn"].strip() + "\n"

      if params["properties"].strip() != "":
        configText = configText + "Properties = " + params["properties"].strip()

    elif params["type"] == "voms":

      sectionPath = sectionPath + "VOMS/Servers"

    elif params["type"] == "servers":

      sectionPath = sectionPath + "VOMS/Servers/" + params["vom"]
      if params["dn"].strip() != "":
        configText = "DN = " + params["dn"].strip() + "\n"

      if params["port"].strip() != "":
        configText = configText + "Port = " + params["port"].strip() + "\n"

      if params["ca"].strip() != "":
        configText = configText + "CA = " + params["ca"].strip()

    sectionPath = sectionPath + "/" + params["name"]

    if self.__configData[ 'cfgData' ].createSection(sectionPath):
      cfgData = self.__configData[ 'cfgData' ].getCFG()
      newCFG = CFG()
      newCFG.loadFromBuffer(configText)
      self.__configData[ 'cfgData' ].mergeSectionFromCFG(sectionPath, newCFG)
      return {"success":1, "op": "addItem"}
    else:
      return {"success":0, "op":"addItem", "message":"Section can't be created. It already exists?"}
开发者ID:DIRACGrid,项目名称:WebAppDIRAC,代码行数:74,代码来源:RegistryManagerHandler.py

示例10: CFG

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
from DIRAC.Core.Utilities.CFG import CFG

DIRAC.gLogger.initialize('test_gConfig','/testSectionDebug')

testconfig = '%s/DIRAC/ConfigurationSystem/test/test.cfg' % DIRAC.rootPath
dumpconfig = '%s/DIRAC/ConfigurationSystem/test/dump.cfg' % DIRAC.rootPath

cfg1 = CFG()
cfg1.loadFromFile( testconfig )

fd = file( testconfig )
cfg1String = fd.read()
fd.close()

cfg2 = CFG()
cfg2.loadFromBuffer( cfg1.serialize() )

cfg3 = cfg1.mergeWith( cfg2 )

testList = [{ 'method'    : DIRAC.gConfig.loadFile,
              'arguments' : ( testconfig, ),
              'output'    : {'OK': True, 'Value': ''}
            },
            { 'method'    : DIRAC.gConfig.dumpLocalCFGToFile,
              'arguments' : ( dumpconfig, ),
              'output'    : {'OK': True, 'Value': ''}
            },
            { 'method'    : cfg1.serialize,
              'arguments' : ( ),
              'output'    : cfg1String
            },
开发者ID:sbel,项目名称:bes3-jinr,代码行数:33,代码来源:test_gCFG.py

示例11: __init__

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
class Modificator:

  def __init__( self, rpcClient = False, commiterId = "unknown" ):
    self.commiterTag = "@@-"
    self.commiterId = commiterId
    self.cfgData = CFG()
    self.rpcClient = None
    if rpcClient:
      self.setRPCClient( rpcClient )

  def loadCredentials( self ):
    retVal = getProxyInfo()
    if retVal[ 'OK' ]:
      credDict = retVal[ 'Value' ]
      self.commiterId = "%[email protected]%s - %s" % ( credDict[ 'username' ],
                                         credDict[ 'group' ],
                                         Time.dateTime().strftime( "%Y-%m-%d %H:%M:%S" ) )
      return retVal
    return retVal

  def setRPCClient( self, rpcClient ):
    self.rpcClient = rpcClient

  def loadFromRemote( self ):
    retVal = self.rpcClient.getCompressedData()
    if retVal[ 'OK' ]:
      self.cfgData = CFG()
      self.cfgData.loadFromBuffer( zlib.decompress( retVal[ 'Value' ] ) )
    return retVal

  def getCFG( self ):
    return self.cfgData

  def getSections( self, sectionPath ):
    return gConfigurationData.getSectionsFromCFG( sectionPath, self.cfgData )

  def getComment( self, sectionPath ):
    return gConfigurationData.getCommentFromCFG( sectionPath, self.cfgData )

  def getOptions( self, sectionPath ):
    return gConfigurationData.getOptionsFromCFG( sectionPath, self.cfgData )

  def getOptionsDict(self, sectionPath):
    """Gives the options of a CS section in a Python dict with values as
    lists"""

    opts = self.getOptions(sectionPath)
    pathDict = dict( ( o, self.getValue( "%s/%s" % ( sectionPath, o ) ) ) for o in opts )
    return pathDict

  def getDictRootedAt(self, relpath = "", root = ""):
    """Gives the configuration rooted at path in a Python dict. The
    result is a Python dictionary that reflects the structure of the
    config file."""
    def getDictRootedAt(path):
      retval = {}
      opts = self.getOptionsDict(path)
      secs = self.getSections(path)
      for k in opts:
        retval[k] = opts[k]
      for i in secs:
        retval[i] = getDictRootedAt(path + "/" + i)
      return retval

    return getDictRootedAt(root + "/" + relpath)

  def getValue( self, optionPath ):
    return gConfigurationData.extractOptionFromCFG( optionPath, self.cfgData )

  def sortAlphabetically( self, path, ascending = True ):
    cfg = self.__getParentCFG( path, parentLevel = 0 )
    if cfg:
      if cfg.sortAlphabetically( ascending ):
        self.__setCommiter( path )

  def __getParentCFG( self, path, parentLevel = 1 ):
    sectionList = List.fromChar( path, "/" )
    cfg = self.cfgData
    try:
      if parentLevel > 0:
        sectionList = sectionList[:-parentLevel]
      for section in sectionList:
        cfg = cfg[ section ]
      return cfg
    except:
      return False

  def __setCommiter( self, entryPath, cfg = False ):
    if not cfg:
      cfg = self.__getParentCFG( entryPath )
    entry = List.fromChar( entryPath, "/" )[-1]
    comment = cfg.getComment( entry )
    filteredComment = [ line.strip() for line in comment.split( "\n" ) if line.find( self.commiterTag ) != 0 ]
    filteredComment.append( "%s%s" % ( self.commiterTag, self.commiterId ) )
    cfg.setComment( entry, "\n".join( filteredComment ) )

  def setOptionValue( self, optionPath, value ):
    levelList = [ level.strip() for level in optionPath.split( "/" ) if level.strip() != "" ]
    parentPath = "/%s" % "/".join( levelList[:-1] )
    optionName = List.fromChar( optionPath, "/" )[-1]
#.........这里部分代码省略.........
开发者ID:ahaupt,项目名称:DIRAC,代码行数:103,代码来源:Modificator.py

示例12: len

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
      if len(sectionName) == 0:
        return {"success":0, "op":"createSection", "message":"Put any name for the section!"}
      sectionPath = "%s/%s" % (parentPath, sectionName)
      gLogger.info("Creating section", "%s" % sectionPath)
      
      if self.__configData[ 'cfgData' ].createSection(sectionPath):
        nD = { 'text' : sectionName, 'csName' : sectionName, 'csComment' : self.__configData[ 'cfgData' ].getComment(sectionPath) }
        htmlC = self.__htmlComment(nD[ 'csComment' ])
        if htmlC:
          qtipDict = { 'text' : htmlC }
          nD[ 'qtipCfg' ] = qtipDict
#       If config Text is provided then a section is created out of that text    
        if configText != "":
          cfgData = self.__configData[ 'cfgData' ].getCFG()
          newCFG = CFG()
          newCFG.loadFromBuffer(configText)
          self.__configData[ 'cfgData' ].mergeSectionFromCFG(sectionPath, newCFG)
#           newCreatedSection = cfgData.getRecursive(sectionPath)["value"]
#           newCreatedSection.loadFromBuffer(configText)
          return {"success":1, "op":"createSection", "parentNodeId":params["parentNodeId"], "node":nD, "sectionFromConfig": 1}
        else:
          return {"success":1, "op":"createSection", "parentNodeId":params["parentNodeId"], "node":nD, "sectionFromConfig": 0}
      else:
        return {"success":0, "op":"createSection", "message":"Section can't be created. It already exists?"}
    except Exception, e:
      return {"success":0, "op":"createSection", "message":"Can't create section: %s" % str(e)}

  def __createOption(self, params):
    try:
      parentPath = str(params[ 'path' ]).strip()
      optionName = str(params[ 'name' ]).strip()
开发者ID:sbel,项目名称:bes3-jinr,代码行数:33,代码来源:ConfigurationManagerHandler.py

示例13: ConfigurationData

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
class ConfigurationData( object ):

  def __init__( self, loadDefaultCFG = True ):
    lr = LockRing()
    self.threadingEvent = lr.getEvent()
    self.threadingEvent.set()
    self.threadingLock = lr.getLock()
    self.runningThreadsNumber = 0
    self.__compressedConfigurationData = None
    self.configurationPath = "/DIRAC/Configuration"
    self.backupsDir = os.path.join( DIRAC.rootPath, "etc", "csbackup" )
    self._isService = False
    self.localCFG = CFG()
    self.remoteCFG = CFG()
    self.mergedCFG = CFG()
    self.remoteServerList = []
    if loadDefaultCFG:
      defaultCFGFile = os.path.join( DIRAC.rootPath, "etc", "dirac.cfg" )
      gLogger.debug( "dirac.cfg should be at", "%s" % defaultCFGFile )
      retVal = self.loadFile( defaultCFGFile )
      if not retVal[ 'OK' ]:
        gLogger.warn( "Can't load %s file" % defaultCFGFile )
    self.sync()

  def getBackupDir( self ):
    return self.backupsDir

  def sync( self ):
    gLogger.debug( "Updating configuration internals" )
    self.mergedCFG = self.remoteCFG.mergeWith( self.localCFG )
    self.remoteServerList = []
    localServers = self.extractOptionFromCFG( "%s/Servers" % self.configurationPath,
                                              self.localCFG,
                                              disableDangerZones = True )
    if localServers:
      self.remoteServerList.extend( List.fromChar( localServers, "," ) )
    remoteServers = self.extractOptionFromCFG( "%s/Servers" % self.configurationPath,
                                               self.remoteCFG,
                                               disableDangerZones = True )
    if remoteServers:
      self.remoteServerList.extend( List.fromChar( remoteServers, "," ) )
    self.remoteServerList = List.uniqueElements( self.remoteServerList )
    self.__compressedConfigurationData = None

  def loadFile( self, fileName ):
    try:
      fileCFG = CFG()
      fileCFG.loadFromFile( fileName )
    except IOError:
      self.localCFG = self.localCFG.mergeWith( fileCFG )
      return S_ERROR( "Can't load a cfg file '%s'" % fileName )
    return self.mergeWithLocal( fileCFG )

  def mergeWithLocal( self, extraCFG ):
    self.lock()
    try:
      self.localCFG = self.localCFG.mergeWith( extraCFG )
      self.unlock()
      gLogger.debug( "CFG merged" )
    except Exception as e:
      self.unlock()
      return S_ERROR( "Cannot merge with new cfg: %s" % str( e ) )
    self.sync()
    return S_OK()

  def loadRemoteCFGFromCompressedMem( self, data ):
    sUncompressedData = zlib.decompress( data )
    self.loadRemoteCFGFromMem( sUncompressedData )

  def loadRemoteCFGFromMem( self, data ):
    self.lock()
    self.remoteCFG.loadFromBuffer( data )
    self.unlock()
    self.sync()

  def loadConfigurationData( self, fileName = False ):
    name = self.getName()
    self.lock()
    try:
      if not fileName:
        fileName = "%s.cfg" % name
      if fileName[0] != "/":
        fileName = os.path.join( DIRAC.rootPath, "etc", fileName )
      self.remoteCFG.loadFromFile( fileName )
    except Exception as e:
      print e
      pass
    self.unlock()
    self.sync()

  def getCommentFromCFG( self, path, cfg = False ):
    if not cfg:
      cfg = self.mergedCFG
    self.dangerZoneStart()
    try:
      levelList = [ level.strip() for level in path.split( "/" ) if level.strip() != "" ]
      for section in levelList[:-1]:
        cfg = cfg[ section ]
      return self.dangerZoneEnd( cfg.getComment( levelList[-1] ) )
    except Exception:
#.........这里部分代码省略.........
开发者ID:DIRACGrid-test,项目名称:DIRAC,代码行数:103,代码来源:ConfigurationData.py

示例14: S_ERROR

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
        modifier = self.__getModificator()
        modifier.loadFromBuffer(session["cfgData"])
        retDict = modifier.commit()
        if not retDict["OK"]:
            return S_ERROR(retDict["Message"])
        return S_OK()

    @jsonify
    def expandSection(self):
        try:
            parentNodeId = str(request.params["node"])
            sectionPath = str(request.params["nodePath"])
        except Exception, e:
            return S_ERROR("Cannot expand section %s" % str(e))
        cfgData = CFG()
        cfgData.loadFromBuffer(session["cfgData"])
        gLogger.info("Expanding section", "%s" % sectionPath)
        try:
            sectionCfg = cfgData
            for section in [section for section in sectionPath.split("/") if not section.strip() == ""]:
                sectionCfg = sectionCfg[section]
        except Exception, v:
            gLogger.error("Section does not exist", "%s -> %s" % (sectionPath, str(v)))
            return S_ERROR("Section %s does not exist: %s" % (sectionPath, str(v)))
        gLogger.verbose("Section to expand %s" % sectionPath)
        retData = []
        for entryName in sectionCfg.listAll():
            id = "%s/%s" % (parentNodeId, entryName)
            comment = sectionCfg.getComment(entryName)
            nodeDef = {"text": entryName, "csName": entryName, "csComment": comment}
            if not sectionCfg.isSection(entryName):
开发者ID:sfayer,项目名称:DIRACWeb,代码行数:33,代码来源:configuration.py

示例15: JobDescription

# 需要导入模块: from DIRAC.Core.Utilities.CFG import CFG [as 别名]
# 或者: from DIRAC.Core.Utilities.CFG.CFG import loadFromBuffer [as 别名]
class JobDescription( object ):

  def __init__( self ):
    self.__description = CFG()
    self.__dirty = False

  def isDirty( self ):
    return self.__dirty

  def loadDescription( self, dataString ):
    """
    Auto discover format type based on [ .. ] of JDL
    """
    dataString = dataString.strip()
    if dataString[0] == "[" and dataString[-1] == "]":
      return self.loadDescriptionFromJDL( dataString )
    else:
      return self.loadDescriptionFromCFG( dataString )

  def loadDescriptionFromJDL( self, jdlString ):
    """
    Load job description from JDL format
    """
    result = loadJDLAsCFG( jdlString.strip() )
    if not result[ 'OK' ]:
      self.__description = CFG()
      return result
    self.__description = result[ 'Value' ][0]
    return S_OK()

  def loadDescriptionFromCFG( self, cfgString ):
    """
    Load job description from CFG format
    """
    try:
      self.__description.loadFromBuffer( cfgString )
    except Exception as e:
      return S_ERROR( "Can't load description from cfg: %s" % str( e ) )
    return S_OK()

  def dumpDescriptionAsCFG( self ):
    return str( self.__description )

  def dumpDescriptionAsJDL( self ):
    return dumpCFGAsJDL( self.__description )

  def __checkNumericalVarInDescription( self, varName, defaultVal, minVal, maxVal ):
    """
    Check a numerical var
    """
    initialVal = 0
    if varName not in self.__description:
      varValue = Operations().getValue( "JobDescription/Default%s" % varName , defaultVal )
    else:
      varValue = self.__description[ varName ]
      initialVal = varValue
    try:
      varValue = long( varValue )
    except:
      return S_ERROR( "%s must be a number" % varName )
    minVal = Operations().getValue( "JobDescription/Min%s" % varName, minVal )
    maxVal = Operations().getValue( "JobDescription/Max%s" % varName, maxVal )
    varValue = max( minVal, min( varValue, maxVal ) )
    if initialVal != varValue:
      self.__description.setOption( varName, varValue )
    return S_OK( varValue )

  def __checkChoiceVarInDescription( self, varName, defaultVal, choices ):
    """
    Check a choice var
    """
    initialVal = False
    if varName not in self.__description:
      varValue = Operations().getValue( "JobDescription/Default%s" % varName , defaultVal )
    else:
      varValue = self.__description[ varName ]
      initialVal = varValue
    if varValue not in Operations().getValue( "JobDescription/Choices%s" % varName , choices ):
      return S_ERROR( "%s is not a valid value for %s" % ( varValue, varName ) )
    if initialVal != varValue:
      self.__description.setOption( varName, varValue )
    return S_OK( varValue )

  def __checkMultiChoiceInDescription( self, varName, choices ):
    """
    Check a multi choice var
    """
    initialVal = False
    if varName not in self.__description:
      return S_OK()
    else:
      varValue = self.__description[ varName ]
      initialVal = varValue
    choices = Operations().getValue( "JobDescription/Choices%s" % varName , choices )
    for v in List.fromChar( varValue ):
      if v not in choices:
        return S_ERROR( "%s is not a valid value for %s" % ( v, varName ) )
    if initialVal != varValue:
      self.__description.setOption( varName, varValue )
    return S_OK( varValue )
#.........这里部分代码省略.........
开发者ID:DIRACGrid-test,项目名称:DIRAC,代码行数:103,代码来源:JobDescription.py


注:本文中的DIRAC.Core.Utilities.CFG.CFG.loadFromBuffer方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。