Ejemplo n.º 1
0
    def export_getUsersTokensInfo(self, users: list):
        """Get the info about the user tokens in the database

        :param users: user names

        :return: S_OK(list) -- return list of tokens dictionaries
        """
        tokensInfo = []
        for user in users:
            # Find the user ID among his DNs
            result = Registry.getDNForUsername(user)
            if not result["OK"]:
                return result
            for dn in result["Value"]:
                uid = Registry.getIDFromDN(dn).get("Value")
                if uid:
                    result = self.__tokenDB.getTokensByUserID(uid)
                    if not result["OK"]:
                        self.log.error(result["Message"])
                    else:
                        for tokenDict in result["Value"]:
                            if tokenDict not in tokensInfo:
                                # The database does not contain a username,
                                # as it is a unique user ID exclusively for DIRAC
                                # and is not associated with a token.
                                tokenDict["username"] = user
                                tokensInfo.append(tokenDict)
        return S_OK(tokensInfo)
Ejemplo n.º 2
0
def findGenericCloudCredentials(vo=False, group=False):
    """Get the cloud credentials to use for a specific VO and/or group."""
    if not group and not vo:
        return S_ERROR(
            "Need a group or a VO to determine the Generic cloud credentials")
    if not vo:
        vo = Registry.getVOForGroup(group)
        if not vo:
            return S_ERROR("Group %s does not have a VO associated" % group)
    opsHelper = Operations.Operations(vo=vo)
    cloudGroup = opsHelper.getValue("Cloud/GenericCloudGroup", "")
    cloudDN = opsHelper.getValue("Cloud/GenericCloudDN", "")
    if not cloudDN:
        cloudUser = opsHelper.getValue("Cloud/GenericCloudUser", "")
        if cloudUser:
            result = Registry.getDNForUsername(cloudUser)
            if result["OK"]:
                cloudDN = result["Value"][0]
            else:
                return S_ERROR("Failed to find suitable CloudDN")
    if cloudDN and cloudGroup:
        gLogger.verbose("Cloud credentials from CS: %s@%s" %
                        (cloudDN, cloudGroup))
        result = gProxyManager.userHasProxy(cloudDN, cloudGroup, 86400)
        if not result["OK"]:
            return result
        return S_OK((cloudDN, cloudGroup))
    return S_ERROR("Cloud credentials not found")
Ejemplo n.º 3
0
def getProxyFileForCloud(ce):
    """Get a file with the proxy to be used to connect to the
        given cloud endpoint

    :param ce: cloud endpoint object
    :return: S_OK/S_ERROR, value is the path to the proxy file
    """

    vo = ce.parameters.get("VO")
    cloudDN = None
    cloudGroup = None
    if vo:
        result = findGenericCloudCredentials(vo=vo)
        if not result["OK"]:
            return result
        cloudDN, cloudGroup = result["Value"]

    cloudUser = ce.parameters.get("GenericCloudUser")
    if cloudUser:
        result = Registry.getDNForUsername(cloudUser)
        if not result["OK"]:
            return result
        cloudDN = result["Value"][0]
    cloudGroup = ce.parameters.get("GenericCloudGroup", cloudGroup)

    if cloudDN and cloudGroup:
        result = gProxyManager.getPilotProxyFromDIRACGroup(
            cloudDN, cloudGroup, 3600)
        if not result["OK"]:
            return result
        proxy = result["Value"]
        result = gProxyManager.dumpProxyToFile(proxy)
        return result
    else:
        return S_ERROR("Could not find generic cloud credentials")
Ejemplo n.º 4
0
def findGenericPilotCredentials(vo=False, group=False, pilotDN='', pilotGroup=''):
  """ Looks into the Operations/<>/Pilot section of CS to find the pilot credentials.
      Then check if the user has a registered proxy in ProxyManager.

      if pilotDN or pilotGroup are specified, use them
  """
  if not group and not vo:
    return S_ERROR("Need a group or a VO to determine the Generic pilot credentials")
  if not vo:
    vo = Registry.getVOForGroup(group)
    if not vo:
      return S_ERROR("Group %s does not have a VO associated" % group)
  opsHelper = Operations.Operations(vo=vo)
  if not pilotGroup:
    pilotGroup = opsHelper.getValue("Pilot/GenericPilotGroup", "")
  if not pilotDN:
    pilotDN = opsHelper.getValue("Pilot/GenericPilotDN", "")
  if not pilotDN:
    pilotUser = opsHelper.getValue("Pilot/GenericPilotUser", "")
    if pilotUser:
      result = Registry.getDNForUsername(pilotUser)
      if result['OK']:
        pilotDN = result['Value'][0]
  if pilotDN and pilotGroup:
    gLogger.verbose("Pilot credentials: %s@%s" % (pilotDN, pilotGroup))
    result = gProxyManager.userHasProxy(pilotDN, pilotGroup, 86400)
    if not result['OK']:
      return S_ERROR("%s@%s has no proxy in ProxyManager")
    return S_OK((pilotDN, pilotGroup))

  if pilotDN:
    return S_ERROR("DN %s does not have group %s" % (pilotDN, pilotGroup))
  return S_ERROR("No generic proxy in the Proxy Manager with groups %s" % pilotGroup)
Ejemplo n.º 5
0
def findGenericCloudCredentials(vo=False, group=False):
    if not group and not vo:
        return S_ERROR(
            "Need a group or a VO to determine the Generic cloud credentials")
    if not vo:
        vo = Registry.getVOForGroup(group)
        if not vo:
            return S_ERROR("Group %s does not have a VO associated" % group)
    opsHelper = Operations.Operations(vo=vo)
    cloudGroup = opsHelper.getValue("Cloud/GenericCloudGroup", "")
    cloudDN = opsHelper.getValue("Cloud/GenericCloudDN", "")
    if not cloudDN:
        cloudUser = opsHelper.getValue("Cloud/GenericCloudUser", "")
        if cloudUser:
            result = Registry.getDNForUsername(cloudUser)
            if result['OK']:
                cloudDN = result['Value'][0]
    if cloudDN and cloudGroup:
        gLogger.verbose("Cloud credentials from CS: %s@%s" %
                        (cloudDN, cloudGroup))
        result = gProxyManager.userHasProxy(cloudDN, cloudGroup, 86400)
        if not result['OK']:
            return S_ERROR("%s@%s has no proxy in ProxyManager")
        return S_OK((cloudDN, cloudGroup))
    return S_ERROR("Cloud credentials not found")
Ejemplo n.º 6
0
    def __generateUserProxiesInfo(self):
        """ Generate information dict about user proxies

        :return: dict
    """
        proxiesInfo = {}
        credDict = self.getRemoteCredentials()
        result = Registry.getDNForUsername(credDict['username'])
        if not result['OK']:
            return result
        selDict = {'UserDN': result['Value']}
        result = self.__proxyDB.getProxiesContent(selDict, {})
        if not result['OK']:
            return result
        contents = result['Value']
        userDNIndex = contents['ParameterNames'].index("UserDN")
        userGroupIndex = contents['ParameterNames'].index("UserGroup")
        expirationIndex = contents['ParameterNames'].index("ExpirationTime")
        for record in contents['Records']:
            userDN = record[userDNIndex]
            if userDN not in proxiesInfo:
                proxiesInfo[userDN] = {}
            userGroup = record[userGroupIndex]
            proxiesInfo[userDN][userGroup] = record[expirationIndex]
        return proxiesInfo
Ejemplo n.º 7
0
    def __setupManagerProxies(self):
        """setup grid proxy for all defined managers"""
        oHelper = Operations()
        shifters = oHelper.getSections("Shifter")
        if not shifters["OK"]:
            return shifters
        shifters = shifters["Value"]
        for shifter in shifters:
            shifterDict = oHelper.getOptionsDict("Shifter/%s" % shifter)
            if not shifterDict["OK"]:
                self.log.error("Cannot get options dict for shifter",
                               "%s: %s" % (shifter, shifterDict["Message"]))
                continue
            userName = shifterDict["Value"].get("User", "")
            userGroup = shifterDict["Value"].get("Group", "")

            userDN = Registry.getDNForUsername(userName)
            if not userDN["OK"]:
                self.log.error("Cannot get DN For Username",
                               "%s: %s" % (userName, userDN["Message"]))
                continue
            userDN = userDN["Value"][0]
            vomsAttr = Registry.getVOMSAttributeForGroup(userGroup)
            if vomsAttr:
                self.log.debug(
                    "getting VOMS [%s] proxy for shifter %s@%s (%s)" %
                    (vomsAttr, userName, userGroup, userDN))
                getProxy = gProxyManager.downloadVOMSProxyToFile(
                    userDN,
                    userGroup,
                    requiredTimeLeft=1200,
                    cacheTime=4 * 43200)
            else:
                self.log.debug("getting proxy for shifter %s@%s (%s)" %
                               (userName, userGroup, userDN))
                getProxy = gProxyManager.downloadProxyToFile(
                    userDN,
                    userGroup,
                    requiredTimeLeft=1200,
                    cacheTime=4 * 43200)
            if not getProxy["OK"]:
                return S_ERROR("unable to setup shifter proxy for %s: %s" %
                               (shifter, getProxy["Message"]))
            chain = getProxy["chain"]
            fileName = getProxy["Value"]
            self.log.debug("got %s: %s %s" % (shifter, userName, userGroup))
            self.__managersDict[shifter] = {
                "ShifterDN": userDN,
                "ShifterName": userName,
                "ShifterGroup": userGroup,
                "Chain": chain,
                "ProxyFile": fileName,
            }
        return S_OK()
Ejemplo n.º 8
0
def getShifterProxy(shifterType, fileName=False):
    """ This method returns a shifter's proxy

      :param str shifterType: ProductionManager / DataManager...
      :param str fileName: file name

      :return: S_OK(dict)/S_ERROR()
  """
    if fileName:
        mkDir(os.path.dirname(fileName))
    opsHelper = Operations()
    userName = opsHelper.getValue(cfgPath('Shifter', shifterType, 'User'), '')
    if not userName:
        return S_ERROR("No shifter User defined for %s" % shifterType)
    result = Registry.getDNForUsername(userName)
    if not result['OK']:
        return result
    userDN = result['Value'][0]
    result = Registry.findDefaultGroupForDN(userDN)
    if not result['OK']:
        return result
    defaultGroup = result['Value']
    userGroup = opsHelper.getValue(cfgPath('Shifter', shifterType, 'Group'),
                                   defaultGroup)
    vomsAttr = Registry.getVOMSAttributeForGroup(userGroup)
    if vomsAttr:
        gLogger.info("Getting VOMS [%s] proxy for shifter %s@%s (%s)" %
                     (vomsAttr, userName, userGroup, userDN))
        result = gProxyManager.downloadVOMSProxyToFile(userDN,
                                                       userGroup,
                                                       filePath=fileName,
                                                       requiredTimeLeft=86400,
                                                       cacheTime=86400)
    else:
        gLogger.info("Getting proxy for shifter %s@%s (%s)" %
                     (userName, userGroup, userDN))
        result = gProxyManager.downloadProxyToFile(userDN,
                                                   userGroup,
                                                   filePath=fileName,
                                                   requiredTimeLeft=86400,
                                                   cacheTime=86400)
    if not result['OK']:
        return result
    chain = result['chain']
    fileName = result['Value']
    return S_OK({
        'DN': userDN,
        'username': userName,
        'group': userGroup,
        'chain': chain,
        'proxyFile': fileName
    })
Ejemplo n.º 9
0
def findGenericPilotCredentials(vo=False,
                                group=False,
                                pilotDN="",
                                pilotGroup=""):
    """Looks into the Operations/<>/Pilot section of CS to find the pilot credentials.
    Then check if the user has a registered proxy in ProxyManager.

    if pilotDN or pilotGroup are specified, use them

    :param str vo: VO name
    :param str group: group name
    :param str pilotDN: pilot DN
    :param str pilotGroup: pilot group

    :return: S_OK(tuple)/S_ERROR()
    """
    if not group and not vo:
        return S_ERROR(
            "Need a group or a VO to determine the Generic pilot credentials")
    if not vo:
        vo = Registry.getVOForGroup(group)
        if not vo:
            return S_ERROR("Group %s does not have a VO associated" % group)
    opsHelper = Operations.Operations(vo=vo)
    if not pilotGroup:
        pilotGroup = opsHelper.getValue("Pilot/GenericPilotGroup", "")
    if not pilotDN:
        pilotDN = opsHelper.getValue("Pilot/GenericPilotDN", "")
    if not pilotDN:
        pilotUser = opsHelper.getValue("Pilot/GenericPilotUser", "")
        if pilotUser:
            result = Registry.getDNForUsername(pilotUser)
            if result["OK"]:
                pilotDN = result["Value"][0]
    if pilotDN and pilotGroup:
        gLogger.verbose("Pilot credentials: %s@%s" % (pilotDN, pilotGroup))
        result = gProxyManager.userHasProxy(pilotDN, pilotGroup, 86400)
        if not result["OK"]:
            return S_ERROR("%s@%s has no proxy in ProxyManager")
        return S_OK((pilotDN, pilotGroup))

    if pilotDN:
        return S_ERROR("DN %s does not have group %s" % (pilotDN, pilotGroup))
    return S_ERROR("No generic proxy in the Proxy Manager with groups %s" %
                   pilotGroup)
Ejemplo n.º 10
0
    def export_getUserTokensInfo(self):
        """Generate information dict about user tokens

        :return: dict
        """
        tokensInfo = []
        credDict = self.getRemoteCredentials()
        result = Registry.getDNForUsername(credDict["username"])
        if not result["OK"]:
            return result
        for dn in result["Value"]:
            result = Registry.getIDFromDN(dn)
            if result["OK"]:
                result = self.__tokenDB.getTokensByUserID(result["Value"])
                if not result["OK"]:
                    return result
                tokensInfo += result["Value"]
        return S_OK(tokensInfo)
Ejemplo n.º 11
0
def getProxyByVO( user, vo ):
  group = vo.lower() + '_user'
  
  userDN = Registry.getDNForUsername( user )
  if not userDN[ 'OK' ]:
    return S_ERROR( 'Cannot discover DN for user %s: %s' % ( user, userDN[ 'Message' ] ) )
  userDN = userDN[ 'Value' ][ 0 ]
  
  chain = gProxyManager.downloadVOMSProxy( userDN, group )
  if not chain[ 'OK' ]:
    return S_ERROR( 'Proxy file cannot be retrieved: %s' % chain[ 'Message' ] )
  chain = chain[ 'Value' ]
  
  proxyPath = "%s/proxy.%s.%s" % ( os.getcwd(), user, group )
  result = chain.dumpAllToFile( proxyPath )
  if not result[ 'OK' ]:
    return S_ERROR( 'Proxy file cannot be written to %s: %s' % ( proxyPath, result[ 'Message' ] ) )

  return S_OK( proxyPath )
Ejemplo n.º 12
0
def getProxyByVO( user, vo ):
  group = vo.lower() + '_user'

  userDN = Registry.getDNForUsername( user )
  if not userDN[ 'OK' ]:
    return S_ERROR( 'Cannot discover DN for user %s: %s' % ( user, userDN[ 'Message' ] ) )
  userDN = userDN[ 'Value' ][ 0 ]

  chain = gProxyManager.downloadVOMSProxy( userDN, group )
  if not chain[ 'OK' ]:
    return S_ERROR( 'Proxy file cannot be retrieved: %s' % chain[ 'Message' ] )
  chain = chain[ 'Value' ]

  proxyPath = "%s/proxy.%s.%s" % ( os.getcwd(), user, group )
  result = chain.dumpAllToFile( proxyPath )
  if not result[ 'OK' ]:
    return S_ERROR( 'Proxy file cannot be written to %s: %s' % ( proxyPath, result[ 'Message' ] ) )

  return S_OK( proxyPath )
Ejemplo n.º 13
0
 def __generateUserProxiesInfo( self ):
   proxiesInfo = {}
   credDict = self.getRemoteCredentials()
   result = Registry.getDNForUsername( credDict[ 'username' ] )
   if not result[ 'OK' ]:
     return result
   selDict = { 'UserDN' : result[ 'Value' ] }
   result = self.__proxyDB.getProxiesContent( selDict, {}, 0, 0 )
   if not result[ 'OK']:
     return result
   contents = result[ 'Value' ]
   userDNIndex = contents[ 'ParameterNames' ].index( "UserDN" )
   userGroupIndex = contents[ 'ParameterNames' ].index( "UserGroup" )
   expirationIndex = contents[ 'ParameterNames' ].index( "ExpirationTime" )
   for record in contents[ 'Records' ]:
     userDN = record[ userDNIndex ]
     if userDN not in proxiesInfo:
       proxiesInfo[ userDN ] = {}
     userGroup = record[ userGroupIndex ]
     proxiesInfo[ userDN ][ userGroup ] = record[ expirationIndex  ]
   return proxiesInfo
Ejemplo n.º 14
0
    def __getOwnerProxy(self, dirPath):
        ''' get owner creds for :dirPath: '''
        self.log.verbose("Retrieving dir metadata...")
        # get owner form the cached information, if not, try getDirectoryMetadata
        ownerName, ownerGroup = self.__directoryOwners.pop(
            dirPath, (None, None))
        if not ownerName or not ownerGroup:
            result = returnSingleResult(
                self.catalog.getDirectoryMetadata(dirPath))
            if not result['OK'] or 'OwnerRole' not in result['Value']:
                self.log.error("Could not get metadata info",
                               result['Message'])
                return result
            ownerRole = result['Value']['OwnerRole']
            ownerDN = result['Value']['OwnerDN']
            if ownerRole[0] != "/":
                ownerRole = "/%s" % ownerRole
            cacheKey = (ownerDN, ownerRole)
            ownerName = 'unknown'
            byGroup = False
        else:
            ownerDN = Registry.getDNForUsername(ownerName)
            if not ownerDN['OK']:
                self.log.error("Could not get DN from user name",
                               ownerDN['Message'])
                return ownerDN
            ownerDN = ownerDN['Value'][0]
            # This bloody method returns directly a string!!!!
            ownerRole = Registry.getVOMSAttributeForGroup(ownerGroup)
            byGroup = True
            # Get all groups for that VOMS Role, and add lhcb_user as in DFC this is a safe value
        ownerGroups = Registry.getGroupsWithVOMSAttribute(ownerRole) + [
            'lhcb_user'
        ]

        downErrors = []
        for ownerGroup in ownerGroups:
            if byGroup:
                ownerRole = None
                cacheKey = (ownerDN, ownerGroup)
            if cacheKey in self.__noProxy:
                return S_ERROR("Proxy not available")
                # Getting the proxy...
            upFile = self.proxyCache.get(cacheKey, 3600)
            if upFile and os.path.exists(upFile):
                self.log.verbose(
                    'Returning cached proxy for %s %s@%s [%s] in %s' %
                    (ownerName, ownerDN, ownerGroup, ownerRole, upFile))
                return S_OK(upFile)
            if ownerRole:
                result = gProxyManager.downloadVOMSProxy(
                    ownerDN,
                    ownerGroup,
                    limited=False,
                    requiredVOMSAttribute=ownerRole)
            else:
                result = gProxyManager.downloadProxy(ownerDN,
                                                     ownerGroup,
                                                     limited=False)
            if not result['OK']:
                downErrors.append("%s : %s" % (cacheKey, result['Message']))
                continue
            userProxy = result['Value']
            secsLeft = max(0, userProxy.getRemainingSecs()['Value'])
            upFile = userProxy.dumpAllToFile()
            if upFile['OK']:
                upFile = upFile['Value']
            else:
                return upFile
            self.proxyCache.add(cacheKey, secsLeft, upFile)
            self.log.info("Got proxy for %s %s@%s [%s]" %
                          (ownerName, ownerDN, ownerGroup, ownerRole))
            return S_OK(upFile)
        self.__noProxy.add(cacheKey)
        return S_ERROR("Could not download proxy for user (%s, %s):\n%s " %
                       (ownerDN, ownerRole, "\n ".join(downErrors)))
Ejemplo n.º 15
0
def main():
    params = Params()
    params.registerCLISwitches()
    # Registering arguments will automatically add their description to the help menu
    Script.registerArgument((
        "DN:       DN of the user",
        "user:     DIRAC user name (will fail if there is more than 1 DN registered)"
    ))
    Script.registerArgument(" group:    DIRAC group name")

    Script.parseCommandLine(ignoreErrors=True)
    # parseCommandLine show help when mandatory arguments are not specified or incorrect argument
    userDN, userGroup = Script.getPositionalArgs(group=True)

    userName = False
    if userDN.find("/") != 0:
        userName = userDN
        retVal = Registry.getDNForUsername(userName)
        if not retVal["OK"]:
            gLogger.notice("Cannot discover DN for username %s\n\t%s" %
                           (userName, retVal["Message"]))
            DIRAC.exit(2)
        DNList = retVal["Value"]
        if len(DNList) > 1:
            gLogger.notice("Username %s has more than one DN registered" %
                           userName)
            ind = 0
            for dn in DNList:
                gLogger.notice("%d %s" % (ind, dn))
                ind += 1
            inp = input("Which DN do you want to download? [default 0] ")
            if not inp:
                inp = 0
            else:
                inp = int(inp)
            userDN = DNList[inp]
        else:
            userDN = DNList[0]

    if not params.proxyPath:
        if not userName:
            result = Registry.getUsernameForDN(userDN)
            if not result["OK"]:
                gLogger.notice("DN '%s' is not registered in DIRAC" % userDN)
                DIRAC.exit(2)
            userName = result["Value"]
        params.proxyPath = "%s/proxy.%s.%s" % (os.getcwd(), userName,
                                               userGroup)

    if params.enableVOMS:
        result = gProxyManager.downloadVOMSProxy(
            userDN,
            userGroup,
            limited=params.limited,
            requiredTimeLeft=params.proxyLifeTime,
            requiredVOMSAttribute=params.vomsAttr,
        )
    else:
        result = gProxyManager.downloadProxy(
            userDN,
            userGroup,
            limited=params.limited,
            requiredTimeLeft=params.proxyLifeTime)
    if not result["OK"]:
        gLogger.notice("Proxy file cannot be retrieved: %s" %
                       result["Message"])
        DIRAC.exit(2)
    chain = result["Value"]
    result = chain.dumpAllToFile(params.proxyPath)
    if not result["OK"]:
        gLogger.notice("Proxy file cannot be written to %s: %s" %
                       (params.proxyPath, result["Message"]))
        DIRAC.exit(2)
    gLogger.notice("Proxy downloaded to %s" % params.proxyPath)
    DIRAC.exit(0)
Ejemplo n.º 16
0
def main():
    params = Params()
    params.registerCLISwitches()

    Script.parseCommandLine(ignoreErrors=True)
    args = Script.getPositionalArgs()

    if len(args) != 2:
        Script.showHelp()

    userGroup = str(args[1])
    userDN = str(args[0])
    userName = False
    if userDN.find("/") != 0:
        userName = userDN
        retVal = Registry.getDNForUsername(userName)
        if not retVal['OK']:
            gLogger.notice("Cannot discover DN for username %s\n\t%s" %
                           (userName, retVal['Message']))
            DIRAC.exit(2)
        DNList = retVal['Value']
        if len(DNList) > 1:
            gLogger.notice("Username %s has more than one DN registered" %
                           userName)
            ind = 0
            for dn in DNList:
                gLogger.notice("%d %s" % (ind, dn))
                ind += 1
            inp = six.moves.input(
                "Which DN do you want to download? [default 0] ")
            if not inp:
                inp = 0
            else:
                inp = int(inp)
            userDN = DNList[inp]
        else:
            userDN = DNList[0]

    if not params.proxyPath:
        if not userName:
            result = Registry.getUsernameForDN(userDN)
            if not result['OK']:
                gLogger.notice("DN '%s' is not registered in DIRAC" % userDN)
                DIRAC.exit(2)
            userName = result['Value']
        params.proxyPath = "%s/proxy.%s.%s" % (os.getcwd(), userName,
                                               userGroup)

    if params.enableVOMS:
        result = gProxyManager.downloadVOMSProxy(
            userDN,
            userGroup,
            limited=params.limited,
            requiredTimeLeft=params.proxyLifeTime,
            requiredVOMSAttribute=params.vomsAttr)
    else:
        result = gProxyManager.downloadProxy(
            userDN,
            userGroup,
            limited=params.limited,
            requiredTimeLeft=params.proxyLifeTime)
    if not result['OK']:
        gLogger.notice('Proxy file cannot be retrieved: %s' %
                       result['Message'])
        DIRAC.exit(2)
    chain = result['Value']
    result = chain.dumpAllToFile(params.proxyPath)
    if not result['OK']:
        gLogger.notice('Proxy file cannot be written to %s: %s' %
                       (params.proxyPath, result['Message']))
        DIRAC.exit(2)
    gLogger.notice("Proxy downloaded to %s" % params.proxyPath)
    DIRAC.exit(0)
Ejemplo n.º 17
0
def main():
    global userName
    Script.registerSwitch("u:", "user="******"User to query (by default oneself)", setUser)
    Script.parseCommandLine()

    result = getProxyInfo()
    if not result["OK"]:
        gLogger.notice("Do you have a valid proxy?")
        gLogger.notice(result["Message"])
        sys.exit(1)
    proxyProps = result["Value"]

    userName = userName or proxyProps.get("username")
    if not userName:
        gLogger.notice("Your proxy don`t have username extension")
        sys.exit(1)

    if userName in Registry.getAllUsers():
        if Properties.PROXY_MANAGEMENT not in proxyProps["groupProperties"]:
            if userName != proxyProps["username"] and userName != proxyProps["issuer"]:
                gLogger.notice("You can only query info about yourself!")
                sys.exit(1)
        result = Registry.getDNForUsername(userName)
        if not result["OK"]:
            gLogger.notice("Oops %s" % result["Message"])
        dnList = result["Value"]
        if not dnList:
            gLogger.notice("User %s has no DN defined!" % userName)
            sys.exit(1)
        userDNs = dnList
    else:
        userDNs = [userName]

    gLogger.notice("Checking for DNs %s" % " | ".join(userDNs))
    pmc = ProxyManagerClient()
    result = pmc.getDBContents({"UserDN": userDNs})
    if not result["OK"]:
        gLogger.notice("Could not retrieve the proxy list: %s" % result["Value"])
        sys.exit(1)

    data = result["Value"]
    colLengths = []
    for pN in data["ParameterNames"]:
        colLengths.append(len(pN))
    for row in data["Records"]:
        for i in range(len(row)):
            colLengths[i] = max(colLengths[i], len(str(row[i])))

    lines = [""]
    for i in range(len(data["ParameterNames"])):
        pN = data["ParameterNames"][i]
        lines[0] += "| %s " % pN.ljust(colLengths[i])
    lines[0] += "|"
    tL = len(lines[0])
    lines.insert(0, "-" * tL)
    lines.append("-" * tL)
    for row in data["Records"]:
        nL = ""
        for i in range(len(row)):
            nL += "| %s " % str(row[i]).ljust(colLengths[i])
        nL += "|"
        lines.append(nL)
        lines.append("-" * tL)

    gLogger.notice("\n".join(lines))
Ejemplo n.º 18
0
def findGenericPilotCredentials( vo = False, group = False ):
  if not group and not vo:
    return S_ERROR( "Need a group or a VO to determine the Generic pilot credentials" )
  if not vo:
    vo = Registry.getVOForGroup( group )
    if not vo:
      return S_ERROR( "Group %s does not have a VO associated" % group )
  opsHelper = Operations.Operations( vo = vo )
  pilotGroup = opsHelper.getValue( "Pilot/GenericPilotGroup", "" )
  pilotDN = opsHelper.getValue( "Pilot/GenericPilotDN", "" )
  if not pilotDN:
    pilotUser = opsHelper.getValue( "Pilot/GenericPilotUser", "" )
    if pilotUser:
      result = Registry.getDNForUsername( pilotUser )
      if result['OK']:
        pilotDN = result['Value']
  if pilotDN and pilotGroup:
    gLogger.verbose( "Pilot credentials from CS: %s@%s" % ( pilotDN, pilotGroup ) )
    result = gProxyManager.userHasProxy( pilotDN, pilotGroup, 86400 )
    if not result[ 'OK' ]:
      return S_ERROR( "%s@%s has no proxy in ProxyManager" )
    return S_OK( ( pilotDN, pilotGroup ) )

  #Auto discover
  gLogger.verbose( "Pilot credentials are not defined. Autodiscovering..." )
  if pilotGroup:
    pilotGroups = [ pilotGroup ]
  else:
    result = Registry.getGroupsWithProperty( Properties.GENERIC_PILOT )
    if not result[ 'OK' ]:
      return result
    pilotGroups = []
    groups = result[ 'Value' ]
    if not groups:
      return S_ERROR( "No group with %s property defined" % Properties.GENERIC_PILOT )
    result = Registry.getGroupsForVO( vo )
    if not result[ 'OK' ]:
      return result
    for voGroup in result[ 'Value' ]:
      if voGroup in groups:
        pilotGroups.append( voGroup )
  if not pilotGroups:
    return S_ERROR( "No generic pilot group for VO %s" % vo )
  for pilotGroup in pilotGroups:
    DNs = Registry.getDNsInGroup( pilotGroup )
    if not DNs:
      continue
    if pilotDN:
      if pilotDN not in DNs:
        continue
      result = gProxyManager.userHasProxy( pilotDN, pilotGroup, 86400 )
      if result[ 'OK' ] and result[ 'Value' ]:
        gLogger.verbose( "Discovered pilot credentials: %s@%s" % ( pilotDN, pilotGroup ) )
        return S_OK( ( pilotDN, pilotGroup ) )
    else:
      for DN in DNs:
        result = gProxyManager.userHasProxy( DN, pilotGroup, 86400 )
        if result[ 'OK' ] and result[ 'Value' ]:
          gLogger.verbose( "Discovered pilot credentials: %s@%s" % ( DN, pilotGroup ) )
          return S_OK( ( DN, pilotGroup ) )

  if pilotDN:
    return S_ERROR( "DN %s does not have group %s" % ( pilotDN, pilotGroups ) )
  return S_ERROR( "No generic proxy in the Proxy Manager with groups %s" % pilotGroups )
Ejemplo n.º 19
0
    '  user:     DIRAC user name (will fail if there is more than 1 DN registered)',
    '  group:    DIRAC group name'
]))

Script.parseCommandLine(ignoreErrors=True)
args = Script.getPositionalArgs()

if len(args) != 2:
    Script.showHelp()

userGroup = str(args[1])
userDN = str(args[0])
userName = False
if userDN.find("/") != 0:
    userName = userDN
    retVal = Registry.getDNForUsername(userName)
    if not retVal['OK']:
        gLogger.notice("Cannot discover DN for username %s\n\t%s" %
                       (userName, retVal['Message']))
        DIRAC.exit(2)
    DNList = retVal['Value']
    if len(DNList) > 1:
        gLogger.notice("Username %s has more than one DN registered" %
                       userName)
        ind = 0
        for dn in DNList:
            gLogger.notice("%d %s" % (ind, dn))
            ind += 1
        inp = raw_input("Which DN do you want to download? [default 0] ")
        if not inp:
            inp = 0
Ejemplo n.º 20
0
def findGenericPilotCredentials(vo=False, group=False):
    if not group and not vo:
        return S_ERROR(
            "Need a group or a VO to determine the Generic pilot credentials")
    if not vo:
        vo = Registry.getVOForGroup(group)
        if not vo:
            return S_ERROR("Group %s does not have a VO associated" % group)
    opsHelper = Operations.Operations(vo=vo)
    pilotGroup = opsHelper.getValue("Pilot/GenericPilotGroup", "")
    pilotDN = opsHelper.getValue("Pilot/GenericPilotDN", "")
    if not pilotDN:
        pilotUser = opsHelper.getValue("Pilot/GenericPilotUser", "")
        if pilotUser:
            result = Registry.getDNForUsername(pilotUser)
            if result['OK']:
                pilotDN = result['Value']
    if pilotDN and pilotGroup:
        gLogger.verbose("Pilot credentials from CS: %s@%s" %
                        (pilotDN, pilotGroup))
        result = gProxyManager.userHasProxy(pilotDN, pilotGroup, 86400)
        if not result['OK']:
            return S_ERROR("%s@%s has no proxy in ProxyManager")
        return S_OK((pilotDN, pilotGroup))

    #Auto discover
    gLogger.verbose("Pilot credentials are not defined. Autodiscovering...")
    if pilotGroup:
        pilotGroups = [pilotGroup]
    else:
        result = Registry.getGroupsWithProperty(Properties.GENERIC_PILOT)
        if not result['OK']:
            return result
        pilotGroups = []
        groups = result['Value']
        if not groups:
            return S_ERROR("No group with %s property defined" %
                           Properties.GENERIC_PILOT)
        result = Registry.getGroupsForVO(vo)
        if not result['OK']:
            return result
        for voGroup in result['Value']:
            if voGroup in groups:
                pilotGroups.append(voGroup)
    if not pilotGroups:
        return S_ERROR("No generic pilot group for VO %s" % vo)
    for pilotGroup in pilotGroups:
        DNs = Registry.getDNsInGroup(pilotGroup)
        if not DNs:
            continue
        if pilotDN:
            if pilotDN not in DNs:
                continue
            result = gProxyManager.userHasProxy(pilotDN, pilotGroup, 86400)
            if result['OK'] and result['Value']:
                gLogger.verbose("Discovered pilot credentials: %s@%s" %
                                (pilotDN, pilotGroup))
                return S_OK((pilotDN, pilotGroup))
        else:
            for DN in DNs:
                result = gProxyManager.userHasProxy(DN, pilotGroup, 86400)
                if result['OK'] and result['Value']:
                    gLogger.verbose("Discovered pilot credentials: %s@%s" %
                                    (DN, pilotGroup))
                    return S_OK((DN, pilotGroup))

    if pilotDN:
        return S_ERROR("DN %s does not have group %s" % (pilotDN, pilotGroups))
    return S_ERROR("No generic proxy in the Proxy Manager with groups %s" %
                   pilotGroups)
Ejemplo n.º 21
0
  gLogger.notice("Do you have a valid proxy?")
  gLogger.notice(result['Message'])
  sys.exit(1)
proxyProps = result['Value']

userName = userName or proxyProps.get('username')
if not userName:
  gLogger.notice("Your proxy don`t have username extension")
  sys.exit(1)

if userName in Registry.getAllUsers():
  if Properties.PROXY_MANAGEMENT not in proxyProps['groupProperties']:
    if userName != proxyProps['username'] and userName != proxyProps['issuer']:
      gLogger.notice("You can only query info about yourself!")
      sys.exit(1)
  result = Registry.getDNForUsername(userName)
  if not result['OK']:
    gLogger.notice("Oops %s" % result['Message'])
  dnList = result['Value']
  if not dnList:
    gLogger.notice("User %s has no DN defined!" % userName)
    sys.exit(1)
  userDNs = dnList
else:
  userDNs = [userName]


gLogger.notice("Checking for DNs %s" % " | ".join(userDNs))
pmc = ProxyManagerClient()
result = pmc.getDBContents({'UserDN': userDNs})
if not result['OK']:
Ejemplo n.º 22
0
                                     '  DN:       DN of the user',
                                     '  user:     DIRAC user name (will fail if there is more than 1 DN registered)',
                                     '  group:    DIRAC group name' ] ) )

Script.parseCommandLine( ignoreErrors = True )
args = Script.getPositionalArgs()

if len( args ) != 2:
  Script.showHelp()

userGroup = str( args[1] )
userDN = str( args[0] )
userName = False
if userDN.find( "/" ) != 0:
  userName = userDN
  retVal = Registry.getDNForUsername( userName )
  if not retVal[ 'OK' ]:
    print "Cannot discover DN for username %s\n\t%s" % ( userName, retVal[ 'Message' ] )
    DIRAC.exit( 2 )
  DNList = retVal[ 'Value' ]
  if len( DNList ) > 1:
    print "Username %s has more than one DN registered" % userName
    for dn in DNList:
      print " %s" % dn
    print "Which dn do you want to download?"
    DIRAC.exit( 2 )
  userDN = DNList[0]

if not params.proxyPath:
  if not userName:
    result = Registry.getUsernameForDN( userDN )