Ejemplo n.º 1
0
    def __init__(self):
        '''
      The client tries to connect to :class:ResourceStatusDB by default. If it
      fails, then tries to connect to the Service :class:ResourceStatusHandler.
    '''

        self.rssService = RPCClient("ResourceStatus/ResourceStatus")
        self.validElements = RssConfiguration.getValidElements()
Ejemplo n.º 2
0
  def execute( self ):
    
#    try:
       
    # Cleans history tables from entries older than 6 months.
    now          = datetime.utcnow().replace( microsecond = 0, second = 0 )
    sixMonthsAgo = now - timedelta( days = 180 )
      
    validElements = RssConfiguration.getValidElements()
      
    for granularity in validElements:
      #deleter = getattr( self.rsClient, 'delete%sHistory' % g )

      kwargs = { 'meta' : { 'minor' : { 'DateEnd' : sixMonthsAgo } } }
      self.log.info( 'Deleting %sHistory older than %s' % ( granularity, sixMonthsAgo ) )
      res = self.rsClient.deleteElementHistory( granularity, **kwargs )
      if not res[ 'OK' ]:
        self.log.error( res[ 'Message' ] )            

    # Cleans ClientsCache table from DownTimes older than a day.
    aDayAgo = now - timedelta( days = 1 )
      
    kwargs = { 'meta' : {
                 'value'  : 'EndDate',
                 'columns': 'Opt_ID',
                 'minor'  : { 'Result' : str( aDayAgo ) }
                } 
              }
    opt_IDs = self.rmClient.getClientCache( **kwargs )              
    opt_IDs = [ ID[ 0 ] for ID in opt_IDs[ 'Value' ] ]
      
    if opt_IDs:
      self.log.info( 'Found %s ClientCache items to be deleted' % len( opt_IDs) )
      self.log.debug( opt_IDs )
      
    res = self.rmClient.deleteClientCache( opt_ID = opt_IDs )
    if not res[ 'OK' ]:
      self.log.error( res[ 'Message' ] )
      
    # Cleans AccountingCache table from plots not updated nor checked in the last 30 mins      
    anHourAgo = now - timedelta( minutes = 30 )
    self.log.info( 'Deleting AccountingCache older than %s' % ( anHourAgo ) )
    res = self.rmClient.deleteAccountingCache( meta = {'minor': { 'LastCheckTime' : anHourAgo }} )
    if not res[ 'OK' ]:
      self.log.error( res[ 'Message' ] )

    # Cleans PolicyResultLog
    twoWeeksAgo = now - timedelta( days = 10 )
    self.log.info( 'Deleting PolicyResultLog older than %s' % ( twoWeeksAgo ) )
    res = self.rmClient.deletePolicyResultLog( meta = {'minor': { 'LastCheckTime' : twoWeeksAgo }} )
    if not res[ 'OK' ]:
      self.log.error( res[ 'Message' ] )

    return S_OK()
Ejemplo n.º 3
0
    def doCommand(self):
        """
    Uses :meth:`DIRAC.ResourceStatusSystem.Client.ResourceStatusClient.getMonitoredStatus`

    :params:
      :attr:`args`: a tuple
        - `args[0]`: string          - should be a ValidElement
        - `args[1]`: string          - should be the name of the ValidElement
        - `args[2]`: optional string - a ValidElement (get status of THIS ValidElement
          for name in args[1], will call getGeneralName)

    :returns:
      {'MonitoredStatus': 'Active'|'Probing'|'Banned'}
    """

        #    try:

        validElements = RssConfiguration.getValidElements()

        if len(self.args) == 3:
            if validElements.index(self.args[2]) >= validElements.index(
                    self.args[0]):
                return self.returnERROR(
                    S_ERROR('Error in MonitoredStatus_Command'))
            toBeFound = self.rsClient.getGeneralName(self.args[0],
                                                     self.args[1],
                                                     self.args[2])['Value']
        else:
            toBeFound = self.args[1]

        res = self.rsClient.getMonitoredStatus(self.args[2], toBeFound)
        if res['OK']:
            res = res['Value']
            if res:
                res = S_OK(res[0][0])
            else:
                res = S_OK(None)

        else:
            res = self.returnERROR(res)
#    except Exception, e:
#      _msg = '%s (%s): %s' % ( self.__class__.__name__, self.args, e )
#      gLogger.exception( _msg )
#      return S_ERROR( _msg )

        return res


#  doCommand.__doc__ = Command.doCommand.__doc__ + doCommand.__doc__

################################################################################
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
Ejemplo n.º 4
0
    def __init__(self, serviceIn=None):
        '''
      The client tries to connect to :class:ResourceStatusDB by default. If it
      fails, then tries to connect to the Service :class:ResourceStatusHandler.
    '''

        if not serviceIn:
            #self.gate = ResourceStatusDB()
            self.gate = RPCClient("ResourceStatus/ResourceStatus")
        else:
            self.gate = serviceIn

        self.validElements = RssConfiguration.getValidElements()
Ejemplo n.º 5
0
  def __init__( self , serviceIn = None ):
    '''
      The client tries to connect to :class:ResourceStatusDB by default. If it 
      fails, then tries to connect to the Service :class:ResourceStatusHandler.
    '''
    
    if not serviceIn:
      #self.gate = ResourceStatusDB()           
      self.gate = RPCClient( "ResourceStatus/ResourceStatus" )
    else:
      self.gate = serviceIn 

    self.validElements = RssConfiguration.getValidElements()
Ejemplo n.º 6
0
  def doCommand( self ):
    """
    Uses :meth:`DIRAC.ResourceStatusSystem.Client.ResourceStatusClient.getMonitoredStatus`

    :params:
      :attr:`args`: a tuple
        - `args[0]`: string          - should be a ValidElement
        - `args[1]`: string          - should be the name of the ValidElement
        - `args[2]`: optional string - a ValidElement (get status of THIS ValidElement
          for name in args[1], will call getGeneralName)

    :returns:
      {'MonitoredStatus': 'Active'|'Probing'|'Banned'}
    """

#    try:

    validElements = RssConfiguration.getValidElements()

    if len( self.args ) == 3:
      if validElements.index( self.args[2] ) >= validElements.index( self.args[0] ):
        return self.returnERROR( S_ERROR( 'Error in MonitoredStatus_Command' ) )
      toBeFound = self.rsClient.getGeneralName( self.args[0], self.args[1], self.args[2] )[ 'Value' ]
    else:
      toBeFound = self.args[1]

    res = self.rsClient.getMonitoredStatus( self.args[2], toBeFound )
    if res[ 'OK' ]:
      res = res[ 'Value' ]
      if res:
        res = S_OK( res[ 0 ][ 0 ] )
      else:
        res = S_OK( None )  

    else:
      res = self.returnERROR( res )
#    except Exception, e:
#      _msg = '%s (%s): %s' % ( self.__class__.__name__, self.args, e )
#      gLogger.exception( _msg )
#      return S_ERROR( _msg )

    return res 

#  doCommand.__doc__ = Command.doCommand.__doc__ + doCommand.__doc__

################################################################################
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
Ejemplo n.º 7
0
  def setArgs( self, argsIn ):
    '''
    Set `self.args`.

    :params:

      :attr:`argsIn`: a tuple: (Module Command doesn't handle lists for now.)
        - `args[0]` should be a ValidElement

        - `args[1]` should be the name of the ValidElement
    '''
    self.args = argsIn

    validElements = RssConfiguration.getValidElements()

    if self.args[0] not in validElements:
      gLogger.error( 'PolicyBase.setArgs got wrong ValidElement' )
Ejemplo n.º 8
0
    def setArgs(self, argsIn):
        '''
    Set `self.args`.

    :params:

      :attr:`argsIn`: a tuple: (Module Command doesn't handle lists for now.)
        - `args[0]` should be a ValidElement

        - `args[1]` should be the name of the ValidElement
    '''
        self.args = argsIn

        validElements = RssConfiguration.getValidElements()

        if self.args[0] not in validElements:
            gLogger.error('PolicyBase.setArgs got wrong ValidElement')
Ejemplo n.º 9
0
    def doCommand(self):
        """
    Uses :meth:`DIRAC.ResourceStatusSystem.Client.ResourceStatusClient.getMonitoredStatus`

    :params:
      :attr:`args`: a tuple
        - `args[0]`: string          - should be a ValidElement
        - `args[1]`: string          - should be the name of the ValidElement
        - `args[2]`: optional string - a ValidElement (get status of THIS ValidElement
          for name in args[1], will call getGeneralName)

    :returns:
      {'MonitoredStatus': 'Active'|'Probing'|'Banned'}
    """

        super(MonitoredStatus_Command, self).doCommand()
        self.APIs = initAPIs(self.__APIs__, self.APIs)

        try:

            validElements = RssConfiguration.getValidElements()

            if len(self.args) == 3:
                if validElements.index(self.args[2]) >= validElements.index(self.args[0]):
                    return {"Result": S_ERROR("Error in MonitoredStatus_Command")}
                toBeFound = self.APIs["ResourceStatusClient"].getGeneralName(self.args[0], self.args[1], self.args[2])[
                    "Value"
                ]
            else:
                toBeFound = self.args[1]

            res = self.APIs["ResourceStatusClient"].getMonitoredStatus(self.args[2], toBeFound)
            if res["OK"]:
                res = res["Value"]
                if res:
                    res = S_OK(res[0][0])
                else:
                    res = S_OK(None)

        except Exception, e:
            _msg = "%s (%s): %s" % (self.__class__.__name__, self.args, e)
            gLogger.exception(_msg)
            return {"Result": S_ERROR(_msg)}
Ejemplo n.º 10
0
  def initialize( self ):
    
    # Attribute defined outside __init__  
    # pylint: disable-msg=W0201
    
    try:
      
      self.rsClient      = ResourceStatusClient()
      self.rmClient      = ResourceManagementClient()  
      
      validElements      = RssConfiguration.getValidElements() 
      
      self.historyTables = [ '%sHistory' % x for x in validElements ]

      return S_OK()
      
    except Exception:
      errorStr = "CacheCleanerAgent initialization"
      self.log.exception( errorStr )
      return S_ERROR( errorStr )
Ejemplo n.º 11
0
    def initialize(self):

        # Attribute defined outside __init__
        # pylint: disable-msg=W0201

        try:

            self.rsClient = ResourceStatusClient()
            self.rmClient = ResourceManagementClient()

            validElements = RssConfiguration.getValidElements()

            self.historyTables = ['%sHistory' % x for x in validElements]

            return S_OK()

        except Exception:
            errorStr = "CacheCleanerAgent initialization"
            self.log.exception(errorStr)
            return S_ERROR(errorStr)
Ejemplo n.º 12
0
    def execute(self):
        '''
      The main TokenAgent execution method.
      Checks for tokens owned by users that are expiring, and notifies those users.
      Calls rsClient.setToken() to set 'RS_SVC' as owner for those tokens that expired.
    '''

        adminMail = ''

        try:

            reason = 'Out of date token'

            #reAssign the token to RS_SVC
            #for g in self.ELEMENTS:

            validElements = RssConfiguration.getValidElements()

            for granularity in validElements:
                tokensExpired = self.rsClient.getTokens(
                    granularity, tokenExpiration=datetime.datetime.utcnow())

                if tokensExpired['Value']:
                    adminMail += '\nLIST OF EXPIRED %s TOKENS\n' % granularity
                    adminMail += '%s|%s|%s\n' % (
                        'user'.ljust(20), 'name'.ljust(15), 'status type')

                for token in tokensExpired['Value']:

                    name = token[1]
                    stype = token[2]
                    user = token[9]

                    self.rsClient.setToken(
                        granularity, name, stype, reason, 'RS_SVC',
                        datetime.datetime(9999, 12, 31, 23, 59, 59))
                    adminMail += ' %s %s %s\n' % (user.ljust(20),
                                                  name.ljust(15), stype)

            #notify token owners
            inNHours = datetime.datetime.utcnow() + datetime.timedelta(
                hours=self.notifyHours)
            #for g in self.ELEMENTS:
            for granularity in validElements:

                tokensExpiring = self.rsClient.getTokens(
                    granularity, tokenExpiration=inNHours)

                if tokensExpiring['Value']:
                    adminMail += '\nLIST OF EXPIRING %s TOKENS\n' % granularity
                    adminMail += '%s|%s|%s\n' % (
                        'user'.ljust(20), 'name'.ljust(15), 'status type')

                for token in tokensExpiring['Value']:

                    name = token[1]
                    stype = token[2]
                    user = token[9]

                    adminMail += '\n %s %s %s\n' % (user.ljust(20),
                                                    name.ljust(15), stype)

                    #If user is RS_SVC, we ignore this, whenever the token is out, this
                    #agent will set again the token to RS_SVC
                    if user == 'RS_SVC':
                        continue

                    pdp = PDP(granularity=granularity,
                              name=name,
                              statusType=stype)

                    decision = pdp.takeDecision()
                    pcresult = decision['PolicyCombinedResult']
                    spresult = decision['SinglePolicyResults']

                    expiration = token[10]

                    mailMessage = "The token for %s %s ( %s )" % (granularity,
                                                                  name, stype)
                    mailMessage = mailMessage + " will expire on %s\n\n" % expiration
                    mailMessage = mailMessage + "You can renew it with command 'dirac-rss-renew-token'.\n"
                    mailMessage = mailMessage + "If you don't take any action, RSS will take control of the resource.\n\n"

                    policyMessage = ''

                    if pcresult['Action']:

                        policyMessage += "  Policies applied will set status to %s.\n" % pcresult[
                            'Status']

                        for spr in spresult:
                            policyMessage += "    %s Status->%s\n" % (
                                spr['PolicyName'].ljust(25), spr['Status'])

                    mailMessage += policyMessage
                    adminMail += policyMessage

                    self.noClient.sendMail(
                        self.rmClient.getUserRegistryCache(user)['Value'][0]
                        [2], 'Token for %s is expiring' % name, mailMessage)
            if adminMail != '':
                #FIXME: 'ubeda' is not generic ;p
                self.noClient.sendMail(
                    self.rmClient.getUserRegistryCache('ubeda')['Value'][0][2],
                    "Token's summary", adminMail)

            return S_OK()

        except Exception:
            errorStr = "TokenAgent execution"
            self.log.exception(errorStr)
            return S_ERROR(errorStr)


################################################################################
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
Ejemplo n.º 13
0
Archivo: PEP.py Proyecto: bmb/DIRAC
  def enforce( self, granularity = None, name = None, statusType = None,
               status = None, formerStatus = None, reason = None, 
               siteType = None, serviceType = None, resourceType = None, 
               tokenOwner = None, useNewRes = False, knownInfo = None  ):
    '''
      Enforce policies for given set of keyworkds. To be better explained.
    '''
  
    ##  real ban flag  #########################################################

    realBan = False
    if tokenOwner is not None:
      if tokenOwner == 'RS_SVC':
        realBan = True

    ## sanitize input ##########################################################
    ## IS IT REALLY NEEDED ??
    
    validElements = RssConfiguration.getValidElements()    
    if granularity is not None and granularity not in validElements:
      return S_ERROR( 'Granularity "%s" not valid' % granularity )

    validStatusTypes = RssConfiguration.getValidStatusTypes()
    if statusType is not None and statusType not in validStatusTypes[ granularity ]['StatusType']:
      return S_ERROR( 'StatusType "%s" not valid' % statusType )
    
    validStatus = RssConfiguration.getValidStatus()
    if status is not None and status not in validStatus:
      return S_ERROR( 'Status "%s" not valid' % status )

    validStatus = RssConfiguration.getValidStatus()
    if formerStatus is not None and formerStatus not in validStatus:
      return S_ERROR( 'FormerStatus "%s" not valid' % formerStatus )

    validSiteTypes = RssConfiguration.getValidSiteTypes()
    if siteType is not None and siteType not in validSiteTypes:
      return S_ERROR( 'SiteType "%s" not valid' % siteType )

    validServiceTypes = RssConfiguration.getValidServiceTypes()
    if serviceType is not None and serviceType not in validServiceTypes:
      return S_ERROR( 'ServiceType "%s" not valid' % serviceType )

    validResourceTypes = RssConfiguration.getValidResourceTypes() 
    if resourceType is not None and resourceType not in validResourceTypes:
      return S_ERROR( 'ResourceType "%s" not valid' % resourceType )
    
    ## policy setup ############################################################  

    self.pdp.setup( granularity = granularity, name = name, 
                    statusType = statusType, status = status,
                    formerStatus = formerStatus, reason = reason, 
                    siteType = siteType, serviceType = serviceType, 
                    resourceType = resourceType, useNewRes = useNewRes )

    ## policy decision #########################################################

    resDecisions = self.pdp.takeDecision( knownInfo = knownInfo )

    ## record all results before doing anything else    
    for resP in resDecisions[ 'SinglePolicyResults' ]:
      
      if not resP.has_key( 'OLD' ):       
        self.clients[ "rmClient" ].insertPolicyResultLog( granularity, name,
                                                          resP[ 'PolicyName' ], 
                                                          statusType,
                                                          resP[ 'Status' ], 
                                                          resP[ 'Reason' ], now )
        
      else:
        gLogger.warn( 'OLD: %s' % resP )
        
    res          = resDecisions[ 'PolicyCombinedResult' ] 
    actionBaseMod = "DIRAC.ResourceStatusSystem.PolicySystem.Actions"

    # Security mechanism in case there is no PolicyType returned
    if res == {}:
      EmptyAction(granularity, name, statusType, resDecisions).run()

    else:
      policyType   = res[ 'PolicyType' ]

      if 'Resource_PolType' in policyType:
        action = Utils.voimport( '%s.ResourceAction' % actionBaseMod )
        action.ResourceAction(granularity, name, statusType, resDecisions,
                         rsClient=self.rsClient,
                         rmClient=self.rmClient).run()

      if 'Alarm_PolType' in policyType:
        action = Utils.voimport( '%s.AlarmAction' % actionBaseMod )
        action.AlarmAction(granularity, name, statusType, resDecisions,
                       Clients=self.clients,
                       Params={"Granularity"  : granularity,
                               "SiteType"     : siteType,
                               "ServiceType"  : serviceType,
                               "ResourceType" : resourceType}).run()

      if 'RealBan_PolType' in policyType and realBan:
        action = Utils.voimport( '%s.RealBanAction' % actionBaseMod )
        action.RealBanAction(granularity, name, resDecisions).run()

    return resDecisions

################################################################################
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
Ejemplo n.º 14
0
from DIRAC.Core.Security.ProxyInfo                              import getProxyInfo
from DIRAC.ResourceStatusSystem.Client.ResourceStatusClient     import ResourceStatusClient
from DIRAC.ResourceStatusSystem.Client.ResourceManagementClient import ResourceManagementClient
from DIRAC.ResourceStatusSystem.Utilities                       import RssConfiguration 

res = getProxyInfo()
if not res['OK']:
  gLogger.error( "Failed to get proxy information", res['Message'] )
  DIRAC.exit( 2 )
userName = res['Value']['username']

if not params.has_key( 'k' ):
  params[ 'k' ] = userName

validElements = RssConfiguration.getValidElements()
if not params[ 'g' ] in validElements:
  gLogger.error( '"%s" is not a valid granularity' % params[ 'g' ] )
  DIRAC.exit( 2 )

if params[ 'k' ] != 'RS_SVC':
  
  rmc = ResourceManagementClient()
  u   = rmc.getUserRegistryCache( login = params[ 'k' ] )
  
  if not u[ 'OK' ] or not u[ 'Value' ]:
    gLogger.error( '"%s" is not a known user' % params[ 'k' ] )
    DIRAC.exit( 2 )

if not params.has_key( 't' ):
  params[ 't' ] = None
Ejemplo n.º 15
0
    def execute(self):

        #    try:

        # Cleans history tables from entries older than 6 months.
        now = datetime.utcnow().replace(microsecond=0, second=0)
        sixMonthsAgo = now - timedelta(days=180)

        validElements = RssConfiguration.getValidElements()

        for granularity in validElements:
            #deleter = getattr( self.rsClient, 'delete%sHistory' % g )

            kwargs = {'meta': {'minor': {'DateEnd': sixMonthsAgo}}}
            self.log.info('Deleting %sHistory older than %s' %
                          (granularity, sixMonthsAgo))
            res = self.rsClient.deleteElementHistory(granularity, **kwargs)
            if not res['OK']:
                self.log.error(res['Message'])

        # Cleans ClientsCache table from DownTimes older than a day.
        aDayAgo = now - timedelta(days=1)

        kwargs = {
            'meta': {
                'value': 'EndDate',
                'columns': 'Opt_ID',
                'minor': {
                    'Result': str(aDayAgo)
                }
            }
        }
        opt_IDs = self.rmClient.getClientCache(**kwargs)
        opt_IDs = [ID[0] for ID in opt_IDs['Value']]

        if opt_IDs:
            self.log.info('Found %s ClientCache items to be deleted' %
                          len(opt_IDs))
            self.log.debug(opt_IDs)

        res = self.rmClient.deleteClientCache(opt_ID=opt_IDs)
        if not res['OK']:
            self.log.error(res['Message'])

        # Cleans AccountingCache table from plots not updated nor checked in the last 30 mins
        anHourAgo = now - timedelta(minutes=30)
        self.log.info('Deleting AccountingCache older than %s' % (anHourAgo))
        res = self.rmClient.deleteAccountingCache(
            meta={'minor': {
                'LastCheckTime': anHourAgo
            }})
        if not res['OK']:
            self.log.error(res['Message'])

        # Cleans PolicyResultLog
        twoWeeksAgo = now - timedelta(days=10)
        self.log.info('Deleting PolicyResultLog older than %s' % (twoWeeksAgo))
        res = self.rmClient.deletePolicyResultLog(
            meta={'minor': {
                'LastCheckTime': twoWeeksAgo
            }})
        if not res['OK']:
            self.log.error(res['Message'])

        return S_OK()
Ejemplo n.º 16
0
  def execute( self ):
    '''
      The main TokenAgent execution method.
      Checks for tokens owned by users that are expiring, and notifies those users.
      Calls rsClient.setToken() to set 'RS_SVC' as owner for those tokens that expired.
    '''

    adminMail = ''

    try:

      reason = 'Out of date token'

      #reAssign the token to RS_SVC
      #for g in self.ELEMENTS:

      validElements = RssConfiguration.getValidElements()

      for granularity in validElements:
        tokensExpired = self.rsClient.getTokens( granularity, 
                                                 tokenExpiration = datetime.datetime.utcnow() )

        if tokensExpired[ 'Value' ]:
          adminMail += '\nLIST OF EXPIRED %s TOKENS\n' % granularity
          adminMail += '%s|%s|%s\n' % ( 'user'.ljust(20), 'name'.ljust(15), 'status type')

        for token in tokensExpired[ 'Value' ]:

          name  = token[ 1 ]
          stype = token[ 2 ]
          user  = token[ 9 ]

          self.rsClient.setToken( granularity, name, stype, reason, 'RS_SVC', 
                                  datetime.datetime( 9999, 12, 31, 23, 59, 59 ) )
          adminMail += ' %s %s %s\n' %( user.ljust(20), name.ljust(15), stype )

      #notify token owners
      inNHours = datetime.datetime.utcnow() + datetime.timedelta( hours = self.notifyHours )
      #for g in self.ELEMENTS:
      for granularity in validElements:

        tokensExpiring = self.rsClient.getTokens( granularity, tokenExpiration = inNHours )

        if tokensExpiring[ 'Value' ]:
          adminMail += '\nLIST OF EXPIRING %s TOKENS\n' % granularity
          adminMail += '%s|%s|%s\n' % ( 'user'.ljust(20),'name'.ljust(15),'status type')

        for token in tokensExpiring[ 'Value' ]:

          name  = token[ 1 ]
          stype = token[ 2 ]
          user  = token[ 9 ]

          adminMail += '\n %s %s %s\n' %( user.ljust(20), name.ljust(15), stype )

          #If user is RS_SVC, we ignore this, whenever the token is out, this
          #agent will set again the token to RS_SVC
          if user == 'RS_SVC':
            continue

          pdp = PDP( granularity = granularity, name = name, statusType = stype )

          decision = pdp.takeDecision()
          pcresult = decision[ 'PolicyCombinedResult' ]
          spresult = decision[ 'SinglePolicyResults' ]

          expiration = token[ 10 ]

          mailMessage = "The token for %s %s ( %s )" % ( granularity, name, stype )
          mailMessage = mailMessage + " will expire on %s\n\n" % expiration
          mailMessage = mailMessage + "You can renew it with command 'dirac-rss-renew-token'.\n"
          mailMessage = mailMessage + "If you don't take any action, RSS will take control of the resource.\n\n"

          policyMessage = ''

          if pcresult[ 'Action' ]:

            policyMessage += "  Policies applied will set status to %s.\n" % pcresult[ 'Status' ]

            for spr in spresult:
              policyMessage += "    %s Status->%s\n" % ( spr[ 'PolicyName' ].ljust(25), spr[ 'Status' ] )

          mailMessage += policyMessage
          adminMail   += policyMessage

          self.noClient.sendMail( self.rmClient.getUserRegistryCache( user )[ 'Value' ][ 0 ][ 2 ],
                            'Token for %s is expiring' % name, mailMessage )
      if adminMail != '':
        #FIXME: 'ubeda' is not generic ;p
        self.noClient.sendMail( self.rmClient.getUserRegistryCache( 'ubeda' )[ 'Value' ][ 0 ][ 2 ],
                            "Token's summary", adminMail )

      return S_OK()

    except Exception:
      errorStr = "TokenAgent execution"
      self.log.exception( errorStr )
      return S_ERROR( errorStr )

################################################################################
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
Ejemplo n.º 17
0
    gLogger.error('Status not found')
    Script.showHelp()
    DIRAC.exit(2)

from DIRAC.Core.Security.ProxyInfo import getProxyInfo
from DIRAC.ResourceStatusSystem import ValidStatus
from DIRAC.ResourceStatusSystem.Client.ResourceStatusClient import ResourceStatusClient
from DIRAC.ResourceStatusSystem.Utilities import RssConfiguration

res = getProxyInfo()
if not res['OK']:
    gLogger.error("Failed to get proxy information", res['Message'])
    DIRAC.exit(2)
userName = res['Value']['username']

validElements = RssConfiguration.getValidElements()
if not params['g'] in validElements:
    gLogger.error('"%s" is not a valid granularity' % params['g'])
    DIRAC.exit(2)

if not params['a'] in ValidStatus:
    gLogger.error('"%s" is not a valid status' % params['a'])
    DIRAC.exit(2)

if not params.has_key('t'):
    params['t'] = None

if not params.has_key('r'):
    params['r'] = 'Status forced by %s' % userName

rsCl = ResourceStatusClient()
Ejemplo n.º 18
0
Archivo: PEP.py Proyecto: zenglzh/DIRAC
    def enforce(self,
                granularity=None,
                name=None,
                statusType=None,
                status=None,
                formerStatus=None,
                reason=None,
                siteType=None,
                serviceType=None,
                resourceType=None,
                tokenOwner=None,
                useNewRes=False,
                knownInfo=None):
        '''
      Enforce policies for given set of keyworkds. To be better explained.
    '''

        ##  real ban flag  #########################################################

        realBan = False
        if tokenOwner is not None:
            if tokenOwner == 'RS_SVC':
                realBan = True

        ## sanitize input ##########################################################
        ## IS IT REALLY NEEDED ??

        validElements = RssConfiguration.getValidElements()
        if granularity is not None and granularity not in validElements:
            return S_ERROR('Granularity "%s" not valid' % granularity)

        validStatusTypes = RssConfiguration.getValidStatusTypes()
        if statusType is not None and statusType not in validStatusTypes[
                granularity]['StatusType']:
            return S_ERROR('StatusType "%s" not valid' % statusType)

        validStatus = RssConfiguration.getValidStatus()
        if status is not None and status not in validStatus:
            return S_ERROR('Status "%s" not valid' % status)

        validStatus = RssConfiguration.getValidStatus()
        if formerStatus is not None and formerStatus not in validStatus:
            return S_ERROR('FormerStatus "%s" not valid' % formerStatus)

        validSiteTypes = RssConfiguration.getValidSiteTypes()
        if siteType is not None and siteType not in validSiteTypes:
            return S_ERROR('SiteType "%s" not valid' % siteType)

        validServiceTypes = RssConfiguration.getValidServiceTypes()
        if serviceType is not None and serviceType not in validServiceTypes:
            return S_ERROR('ServiceType "%s" not valid' % serviceType)

        validResourceTypes = RssConfiguration.getValidResourceTypes()
        if resourceType is not None and resourceType not in validResourceTypes:
            return S_ERROR('ResourceType "%s" not valid' % resourceType)

        ## policy setup ############################################################

        self.pdp.setup(granularity=granularity,
                       name=name,
                       statusType=statusType,
                       status=status,
                       formerStatus=formerStatus,
                       reason=reason,
                       siteType=siteType,
                       serviceType=serviceType,
                       resourceType=resourceType,
                       useNewRes=useNewRes)

        ## policy decision #########################################################

        resDecisions = self.pdp.takeDecision(knownInfo=knownInfo)

        ## record all results before doing anything else
        for resP in resDecisions['SinglePolicyResults']:

            if not resP.has_key('OLD'):
                self.clients["rmClient"].insertPolicyResultLog(
                    granularity, name, resP['PolicyName'], statusType,
                    resP['Status'], resP['Reason'], now)

            else:
                gLogger.warn('OLD: %s' % resP)

        res = resDecisions['PolicyCombinedResult']
        actionBaseMod = "DIRAC.ResourceStatusSystem.PolicySystem.Actions"

        # Security mechanism in case there is no PolicyType returned
        if res == {}:
            EmptyAction(granularity, name, statusType, resDecisions).run()

        else:
            policyType = res['PolicyType']

            if 'Resource_PolType' in policyType:
                action = Utils.voimport('%s.ResourceAction' % actionBaseMod)
                action.ResourceAction(granularity,
                                      name,
                                      statusType,
                                      resDecisions,
                                      rsClient=self.rsClient,
                                      rmClient=self.rmClient).run()

            if 'Alarm_PolType' in policyType:
                action = Utils.voimport('%s.AlarmAction' % actionBaseMod)
                action.AlarmAction(granularity,
                                   name,
                                   statusType,
                                   resDecisions,
                                   Clients=self.clients,
                                   Params={
                                       "Granularity": granularity,
                                       "SiteType": siteType,
                                       "ServiceType": serviceType,
                                       "ResourceType": resourceType
                                   }).run()

            if 'RealBan_PolType' in policyType and realBan:
                action = Utils.voimport('%s.RealBanAction' % actionBaseMod)
                action.RealBanAction(granularity, name, resDecisions).run()

        return resDecisions


################################################################################
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF