コード例 #1
0
ファイル: JobMonitor.py プロジェクト: nikolalazovski/DIRACWeb
 def __getProxyStatus(self,secondsOverride = None):
     
   from DIRAC.FrameworkSystem.Client.ProxyManagerClient import ProxyManagerClient
   
   proxyManager = ProxyManagerClient()
   group = str(credentials.getSelectedGroup())
   if group == "visitor":
     return {"success":"false","error":"User is anonymous or is not registered in the system"}
   userDN = str(credentials.getUserDN())
   if secondsOverride and str(secondsOverride).isdigit():
     validSeconds = int(secondsOverride)
   else:
     defaultSeconds = 24 * 3600 + 60 # 24H + 1min
     validSeconds = gConfig.getValue("/Registry/DefaultProxyLifeTime",defaultSeconds)
   gLogger.info("\033[0;31m userHasProxy(%s, %s, %s) \033[0m" % (userDN,group,validSeconds))
   result = proxyManager.userHasProxy(userDN,group,validSeconds)
   if result["OK"]:
     if result["Value"]:
       c.result = {"success":"true","result":"true"}
     else:
       c.result = {"success":"true","result":"false"}
   else:
     c.result = {"success":"false","error":"false"}
   gLogger.info("\033[0;31m PROXY: \033[0m",result)
   return c.result
コード例 #2
0
  def __getProxyStatus(self, secondsOverride=None):
    from DIRAC.FrameworkSystem.Client.ProxyManagerClient import ProxyManagerClient

    proxyManager = ProxyManagerClient()

    userData = self.getSessionData()

    group = str(userData["user"]["group"])

    if group == "visitor":
      return {"success":"false", "error":"User is anonymous or is not registered in the system"}

    userDN = str(userData["user"]["DN"])

    defaultSeconds = 24 * 3600 + 60  # 24H + 1min
    validSeconds = gConfig.getValue("/Registry/DefaultProxyLifeTime", defaultSeconds)

    gLogger.info("\033[0;31m userHasProxy(%s, %s, %s) \033[0m" % (userDN, group, validSeconds))

    result = proxyManager.userHasProxy(userDN, group, validSeconds)

    if result["OK"]:
      if result["Value"]:
        return {"success":"true", "result":"true"}
      else:
        return {"success":"true", "result":"false"}
    else:
      return {"success":"false", "error":"false"}

    gLogger.info("\033[0;31m PROXY: \033[0m", result)
コード例 #3
0
ファイル: AuthServer.py プロジェクト: TaykYoku/DIRAC
 def __init__(self):
     self.db = AuthDB()  # place to store session information
     self.log = sLog
     self.idps = IdProviderFactory()
     self.proxyCli = ProxyManagerClient()  # take care about proxies
     self.tokenCli = TokenManagerClient()  # take care about tokens
     # The authorization server has its own settings, but they are standardized
     self.metadata = collectMetadata()
     self.metadata.validate()
     # Initialize AuthorizationServer
     _AuthorizationServer.__init__(self, scopes_supported=self.metadata["scopes_supported"])
     # authlib requires the following methods:
     # The following `save_token` method is called when requesting a new access token to save it after it is generated.
     # Let's skip this step, because getting tokens and saving them if necessary has already taken place in `generate_token` method.
     self.save_token = lambda x, y: None
     # Framework integration can re-implement this method to support signal system.
     # But in this implementation, this system is not used.
     self.send_signal = lambda *x, **y: None
     # The main method that will return an access token to the user (this can be a proxy)
     self.generate_token = self.generateProxyOrToken
     # Register configured grants
     self.register_grant(RefreshTokenGrant)  # Enable refreshing tokens
     # Enable device code flow
     self.register_grant(DeviceCodeGrant)
     self.register_endpoint(DeviceAuthorizationEndpoint)
     self.register_endpoint(RevocationEndpoint)  # Enable revokation tokens
     self.register_grant(AuthorizationCodeGrant, [CodeChallenge(required=True)])  # Enable authorization code flow
コード例 #4
0
ファイル: backends.py プロジェクト: t2k-software/t2kdm
    def __init__(self, **kwargs):
        GridBackend.__init__(self, catalogue_prefix='', **kwargs)

        from DIRAC.Core.Base import Script
        Script.initialize()
        from DIRAC.FrameworkSystem.Client.ProxyManagerClient import ProxyManagerClient
        self.pm = ProxyManagerClient()

        proxy = self.pm.getUserProxiesInfo()
        if not proxy['OK']:
            raise BackendException("Proxy error.")

        from DIRAC.Interfaces.API.Dirac import Dirac
        self.dirac = Dirac()

        from DIRAC.Resources.Catalog.FileCatalog import FileCatalog
        self.fc = FileCatalog()
        from DIRAC.DataManagementSystem.Client.DataManager import DataManager
        self.dm = DataManager()

        self._xattr_cmd = sh.Command('gfal-xattr').bake(_tty_out=False)
        self._replica_checksum_cmd = sh.Command('gfal-sum').bake(_tty_out=False)
        self._bringonline_cmd = sh.Command('gfal-legacy-bringonline').bake(_tty_out=False)
        self._cp_cmd = sh.Command('gfal-copy').bake(_tty_out=False)
        self._ls_se_cmd = sh.Command('gfal-ls').bake(color='never', _tty_out=False)
        self._move_cmd = sh.Command('gfal-rename').bake(_tty_out=False)
        self._mkdir_cmd = sh.Command('gfal-mkdir').bake(_tty_out=False)

        self._replicate_cmd = sh.Command('dirac-dms-replicate-lfn').bake(_tty_out=False)
        self._add_cmd = sh.Command('dirac-dms-add-file').bake(_tty_out=False)
コード例 #5
0
 def __getProxyStatus(self, validSeconds=0):
     from DIRAC.FrameworkSystem.Client.ProxyManagerClient import ProxyManagerClient
     proxyManager = ProxyManagerClient()
     group = str(credentials.getSelectedGroup())
     if group == "visitor":
         return {"success": "false", "error": "User not registered"}
     userDN = str(credentials.getUserDN())
     gLogger.info("\033[0;31m userHasProxy(%s, %s, %s) \033[0m" %
                  (userDN, group, validSeconds))
     result = proxyManager.userHasProxy(userDN, group, validSeconds)
     if result["OK"]:
         if result["Value"]:
             c.result = {"success": "true", "result": "true"}
         else:
             c.result = {"success": "true", "result": "false"}
     else:
         c.result = {"success": "false", "error": "false"}
     gLogger.info("\033[0;31m PROXY: \033[0m", result)
     return c.result
コード例 #6
0
    def _renewCloudProxy(self):
        """Takes short lived proxy from the site director and
        promotes it to a long lived proxy keeping the DIRAC group.

        :returns: True on success, false otherwise.
        :rtype: bool
        """
        if not self._cloudDN or not self._cloudGroup:
            self.log.error(
                "Could not renew cloud proxy, DN and/or Group not set.")
            return False

        proxyLifetime = int(
            self.ceParameters.get("Context_ProxyLifetime", DEF_PROXYLIFETIME))
        # only renew proxy if lifetime is less than configured lifetime
        # self.valid is a datetime
        if self.valid - datetime.datetime.utcnow(
        ) > proxyLifetime * datetime.timedelta(seconds=1):
            return True
        proxyLifetime += DEF_PROXYGRACE
        proxyManager = ProxyManagerClient()
        self.log.info("Downloading proxy with cloudDN and cloudGroup: %s, %s" %
                      (self._cloudDN, self._cloudGroup))
        res = proxyManager.downloadProxy(self._cloudDN,
                                         self._cloudGroup,
                                         limited=True,
                                         requiredTimeLeft=proxyLifetime)
        if not res["OK"]:
            self.log.error("Could not download proxy", res["Message"])
            return False
        resdump = res["Value"].dumpAllToString()
        if not resdump["OK"]:
            self.log.error("Failed to dump proxy to string",
                           resdump["Message"])
            return False
        self.proxy = resdump["Value"]
        self.valid = datetime.datetime.utcnow(
        ) + proxyLifetime * datetime.timedelta(seconds=1)
        return True
コード例 #7
0
                'issuer']:
            print "You can only query info about yourself!"
            sys.exit(1)
    result = CS.getDNForUsername(userName)
    if not result['OK']:
        print "Oops %s" % result['Message']
    dnList = result['Value']
    if not dnList:
        print "User %s has no DN defined!" % userName
        sys.exit(1)
    userDNs = dnList
else:
    userDNs = [userName]

print "Checking for DNs %s" % " | ".join(userDNs)
pmc = ProxyManagerClient()
result = pmc.getDBContents({'UserDN': userDNs})
if not result['OK']:
    print "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'])):
コード例 #8
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))
コード例 #9
0
  def web_proxy(self):
    """ Proxy management endpoint, use:
          GET /proxy?<options> -- retrieve personal proxy
            * options:
              * voms - to get VOMSproxy(optional)
              * lifetime - requested proxy live time(optional)

          GET /proxy/<user>/<group>?<options> -- retrieve proxy
            * user - user name
            * group - group name
            * options:
              * voms - to get VOMSproxy(optional)
              * lifetime - requested proxy live time(optional)

          GET /proxy/metadata?<options> -- retrieve proxy metadata..
            * options:

        :return: json
    """
    voms = self.args.get('voms')
    proxyLifeTime = 3600 * 12
    if re.match('[0-9]+', self.args.get('lifetime') or ''):
      proxyLifeTime = int(self.args.get('lifetime'))
    optns = self.overpath.strip('/').split('/')
    
    # GET
    if self.request.method == 'GET':
      # Return content of Proxy DB
      if 'metadata' in optns:
        pass

      # Return personal proxy
      elif not self.overpath:
        result = yield self.threadTask(ProxyManagerClient().downloadPersonalProxy, self.getUserName(),
                                       self.getUserGroup(), requiredTimeLeft=proxyLifeTime, voms=voms)
        if not result['OK']:
          raise WErr(500, result['Message'])
        self.log.notice('Proxy was created.')
        result = result['Value'].dumpAllToString()
        if not result['OK']:
          raise WErr(500, result['Message'])
        self.finishJEncode(result['Value'])

      # Return proxy
      elif len(optns) == 2:
        user = optns[0]
        group = optns[1]
        
        # Get proxy to string
        result = getDNForUsernameInGroup(user, group)
        if not result['OK'] or not result.get('Value'):
          raise WErr(500, '%s@%s has no registred DN: %s' % (user, group, result.get('Message') or ""))
        
        if voms:
          result = yield self.threadTask(ProxyManagerClient().downloadVOMSProxy, user, group, requiredTimeLeft=proxyLifeTime)
        else:
          result = yield self.threadTask(ProxyManagerClient().downloadProxy, user, group, requiredTimeLeft=proxyLifeTime)
        if not result['OK']:
          raise WErr(500, result['Message'])
        self.log.notice('Proxy was created.')
        result = result['Value'].dumpAllToString()
        if not result['OK']:
          raise WErr(500, result['Message'])
        self.finishJEncode(result['Value'])

      else:
        raise WErr(404, "Wrone way")