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


Python DiracAdmin.sendMail方法代码示例

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


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

示例1: _sendMail

# 需要导入模块: from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin [as 别名]
# 或者: from DIRAC.Interfaces.API.DiracAdmin.DiracAdmin import sendMail [as 别名]
  def _sendMail( self, subject, body ):
    
    from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin
    diracAdmin = DiracAdmin()
    
    address = InfoGetter().getNotificationsThatApply( self.decissionParams, self.actionName )
    if not address[ 'OK' ]:
      return address 
    address = address[ 'Value' ]
    
    for addressDict in address:
      if not 'name' in addressDict:
        return S_ERROR( 'Malformed address dict %s' % addressDict ) 
      if not 'users' in addressDict:
        return S_ERROR( 'Malformed address dict %s' % addressDict )     
      
      for user in addressDict[ 'users' ]:
      
      #FIXME: should not I get the info from the RSS User cache ?
      
        resEmail = diracAdmin.sendMail( user, subject, body )
        if not resEmail[ 'OK' ]:
          return S_ERROR( 'Cannot send email to user "%s"' % user )    
      
    return resEmail 
    
################################################################################
#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
开发者ID:cgrefe,项目名称:DIRAC,代码行数:30,代码来源:EmailAction.py

示例2: TokenAgent

# 需要导入模块: from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin [as 别名]
# 或者: from DIRAC.Interfaces.API.DiracAdmin.DiracAdmin import sendMail [as 别名]

#.........这里部分代码省略.........

    for tokenElement in tokenElements:

      try:
        name = tokenElement[ 'Name' ]
        statusType = tokenElement[ 'StatusType' ]
        status = tokenElement[ 'Status' ]
        tokenOwner = tokenElement[ 'TokenOwner' ]
        tokenExpiration = tokenElement[ 'TokenExpiration' ]
      except KeyError as e:
        return S_ERROR( e )

      # If token has already expired
      if tokenExpiration < datetime.utcnow():
        _msg = '%s with statusType "%s" and owner %s EXPIRED'
        self.log.info( _msg % ( name, statusType, tokenOwner ) )

        result = self.rsClient.addOrModifyStatusElement( element, 'Status', name = name,
                                                         statusType = statusType,
                                                         tokenOwner = self.__rssToken,
                                                         tokenExpiration = never )
        if not result[ 'OK' ]:
          return result

      else:
        _msg = '%s with statusType "%s" and owner %s -> %s'
        self.log.info( _msg % ( name, statusType, tokenOwner, tokenExpiration ) )

      if tokenOwner not in self.tokenDict:
        self.tokenDict[ tokenOwner ] = []

      self.tokenDict[ tokenOwner ].append( [ tokenOwner, element, name, statusType, status, tokenExpiration ] )

    return S_OK()

  def _notifyOfTokens( self ):
    '''
      Splits interesing tokens between expired and expiring. Also splits them
      among users. It ends sending notifications to the users.
    '''

    now = datetime.utcnow()

    adminExpired = []
    adminExpiring = []

    for tokenOwner, tokenLists in self.tokenDict.items():

      expired = []
      expiring = []

      for tokenList in tokenLists:

        if tokenList[ 5 ] < now:
          expired.append( tokenList )
          adminExpired.append( tokenList )
        else:
          expiring.append( tokenList )
          adminExpiring.append( tokenList )

      resNotify = self._notify( tokenOwner, expired, expiring )
      if not resNotify[ 'OK' ]:
        self.log.error( 'Failed to notify token owner', resNotify[ 'Message' ] )

    if (adminExpired or adminExpiring) and self.adminMail:
      return self._notify(self.adminMail, adminExpired, adminExpiring)

    return S_OK()

  def _notify( self, tokenOwner, expired, expiring ):
    '''
      Given a token owner and a list of expired and expiring tokens, sends an
      email to the user.
    '''

    subject = 'RSS token summary for tokenOwner %s' % tokenOwner

    mail = '\nEXPIRED tokens ( RSS has taken control of them )\n'
    for tokenList in expired:

      mail += ' '.join( [ str(x) for x in tokenList ] )
      mail += '\n'

    mail = '\nEXPIRING tokens ( RSS will take control of them )\n'
    for tokenList in expiring:

      mail += ' '.join( [ str(x) for x in tokenList ] )
      mail += '\n'

    mail += "\n\n You can extend for another 24 hours using the web interface (Set token -> Acquire)\n"
    mail += " Or you can use the dirac-rss-set-token script\n\n"
    mail += "Through the same interfaces you can release the token any time\n"

    # FIXME: you can re-take control of them using this or that...

    resEmail = self.diracAdmin.sendMail( tokenOwner, subject, mail )
    if not resEmail[ 'OK' ]:
      return S_ERROR( 'Cannot send email to user "%s"' % tokenOwner )

    return resEmail
开发者ID:DIRACGrid,项目名称:DIRAC,代码行数:104,代码来源:TokenAgent.py

示例3:

# 需要导入模块: from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin [as 别名]
# 或者: from DIRAC.Interfaces.API.DiracAdmin.DiracAdmin import sendMail [as 别名]
  for se in readAllowed:
    body = "%s\n%s" % ( body, se )
if write:
  body = "%s\n\nThe following storage elements were allowed for writing:" % body
  for se in writeAllowed:
    body = "%s\n%s" % ( body, se )
if check:
  body = "%s\n\nThe following storage elements were allowed for checking:" % body
  for se in checkAllowed:
    body = "%s\n%s" % ( body, se )
if remove:
  body = "%s\n\nThe following storage elements were allowed for removing:" % body
  for se in removeAllowed:
    body = "%s\n%s" % ( body, se )

if not address:
  gLogger.notice( "'%s' not defined in Operations, can not send Mail\n" % addressPath, body )
  DIRAC.exit( 0 )

res = diracAdmin.sendMail( address, subject, body )
gLogger.notice( 'Notifying %s' % address )
if res[ 'OK' ]:
  gLogger.notice( res[ 'Value' ] )
else:
  gLogger.notice( res[ 'Message' ] )

DIRAC.exit( 0 )

################################################################################
# EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF#EOF
开发者ID:Kiyoshi-Hayasaka,项目名称:DIRAC,代码行数:32,代码来源:dirac-admin-allow-se.py

示例4: EmailAgent

# 需要导入模块: from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin [as 别名]
# 或者: from DIRAC.Interfaces.API.DiracAdmin.DiracAdmin import sendMail [as 别名]
class EmailAgent( AgentModule ):

  def __init__( self, *args, **kwargs ):

    AgentModule.__init__( self, *args, **kwargs )
    self.diracAdmin = None
    self.default_value = None

    if 'DIRAC' in os.environ:
      self.cacheFile = os.path.join( os.getenv('DIRAC'), 'work/ResourceStatus/cache.db' )
    else:
      self.cacheFile = os.path.realpath('cache.db')

  def initialize( self ):
    ''' EmailAgent initialization
    '''

    self.diracAdmin = DiracAdmin()

    return S_OK()

  def execute( self ):

    if os.path.isfile(self.cacheFile):
      with sqlite3.connect(self.cacheFile) as conn:

        result = conn.execute("SELECT DISTINCT SiteName from ResourceStatusCache;")
        for site in result:
          cursor = conn.execute("SELECT StatusType, ResourceName, Status, Time, PreviousStatus from ResourceStatusCache WHERE SiteName='"+ site[0] +"';")

          if gConfig.getValue('/DIRAC/Setup'):
            email_body = "(" + gConfig.getValue('/DIRAC/Setup') + ")\n\n"
          else:
            email_body = ""
            
          for StatusType, ResourceName, Status, Time, PreviousStatus in cursor:
            email_body += StatusType + " of " + ResourceName + " has been " + Status + " since " + Time + " (Previous status: " + PreviousStatus + ")\n"

          subject = "RSS actions taken for " + site[0] + "\n"
          self._sendMail(subject, email_body)

        conn.execute("DELETE FROM ResourceStatusCache;")
        conn.execute("VACUUM;")

    return S_OK()

  def _sendMail( self, subject, body ):

    userEmails = self._getUserEmails()
    if not userEmails[ 'OK' ]:
      return userEmails

    # User email address used to send the emails from.
    fromAddress = RssConfiguration.RssConfiguration().getConfigFromAddress()

    for user in userEmails[ 'Value' ]:

      #FIXME: should not I get the info from the RSS User cache ?

      resEmail = self.diracAdmin.sendMail( user, subject, body, fromAddress = fromAddress )
      if not resEmail[ 'OK' ]:
        return S_ERROR( 'Cannot send email to user "%s"' % user )

    return S_OK()

  def _getUserEmails( self ):

    configResult = RssConfiguration.getnotificationGroups()
    if not configResult[ 'OK' ]:
      return configResult
    try:
      notificationGroups = configResult[ 'Value' ][ 'notificationGroups' ]
    except KeyError:
      return S_ERROR( '%s/notificationGroups not found' )

    notifications = RssConfiguration.getNotifications()
    if not notifications[ 'OK' ]:
      return notifications
    notifications = notifications[ 'Value' ]

    userEmails = []

    for notificationGroupName in notificationGroups:
      try:
        userEmails.extend( notifications[ notificationGroupName ][ 'users' ] )
      except KeyError:
        self.log.error( '%s not present' % notificationGroupName )

    return S_OK( userEmails )
开发者ID:ahaupt,项目名称:DIRAC,代码行数:91,代码来源:EmailAgent.py

示例5: EmailAction

# 需要导入模块: from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin [as 别名]
# 或者: from DIRAC.Interfaces.API.DiracAdmin.DiracAdmin import sendMail [as 别名]
class EmailAction( BaseAction ):
  '''
    Action that sends an email with the information concerning the status and 
    the policies run.
  '''
  
  def __init__( self, name, decissionParams, enforcementResult, singlePolicyResults, 
                clients = None ):
    
    super( EmailAction, self ).__init__( name, decissionParams, enforcementResult, 
                                         singlePolicyResults, clients )
    self.diracAdmin = DiracAdmin()

  def run( self ):
    '''
      Checks it has the parameters it needs and tries to send an email to the users
      that apply.
    '''    
    
    # Minor security checks
    
    element = self.decissionParams[ 'element' ]
    if element is None:
      return S_ERROR( 'element should not be None' )
   
    name = self.decissionParams[ 'name' ] 
    if name is None:
      return S_ERROR( 'name should not be None' )
    
    statusType = self.decissionParams[ 'statusType' ]
    if statusType is None:
      return S_ERROR( 'statusType should not be None' )
    
    status = self.enforcementResult[ 'Status' ]    
    if status is None:
      return S_ERROR( 'status should not be None' )

    reason = self.enforcementResult[ 'Reason' ]
    if reason is None:
      return S_ERROR( 'reason should not be None' )
    
#    if self.decissionParams[ 'status' ] == status:
#      # If status has not changed, we skip
#      return S_OK()

#    if self.decissionParams[ 'reason' ] == reason:
#      # If reason has not changed, we skip
#      return S_OK()

#    if not set( ( 'Banned', 'Error', 'Unknown' ) ) & set( ( status, self.decissionParams[ 'status' ] ) ):
#      # if not 'Banned', 'Error', 'Unknown' in ( status, self.decissionParams[ 'status' ] ):
#      # not really interesting to send an email
#      return S_OK()
      
    setup = gConfig.getValue( 'DIRAC/Setup' )  
      
    #subject2 = '[%s]%s %s %s is on status %s' % ( setup, element, name, statusType, status )
    subject = '[RSS](%s) %s (%s) %s' % ( setup, name, statusType, self.actionName )
    
    body = 'ENFORCEMENT RESULT\n\n'
    body += '\n'.join( [ '%s : "%s"' % ( key, value ) for key, value in self.enforcementResult.items() ] )
    body += '\n\n'
    body += '*' * 80
    body += '\nORGINAL PARAMETERS\n\n'
    body += '\n'.join( [ '%s : "%s"' % ( key, value ) for key, value in self.decissionParams.items() ] )
    body += '\n\n'
    body += '*' * 80
    body += '\nPOLICIES RUN\n\n'
    
    for policy in self.singlePolicyResults:
      
      body += '\n'.join( [ '%s : "%s"' % ( key, value ) for key, value in policy.items() if not key == 'Policy' ] )
      body += '\n'
      body += '\n'.join( [ '%s : "%s"' % ( key, value ) for key, value in policy[ 'Policy' ].items() ] )
      body += '\n\n'
        
    return self._sendMail( subject, body )

  def _getUserEmails( self ):

    policyActions = RssConfiguration.getPolicyActions()
    if not policyActions[ 'OK' ]:
      return policyActions
    try:
      notificationGroups = policyActions[ 'Value' ][ self.actionName ][ 'notificationGroups' ]
    except KeyError:
      return S_ERROR( '%s/notificationGroups not found' % self.actionName )  
    
    notifications = RssConfiguration.getNotifications()
    if not notifications[ 'OK' ]:
      return notifications
    notifications = notifications[ 'Value' ]  

    userEmails = []
    
    for notificationGroupName in notificationGroups:
      try:
        userEmails.extend( notifications[ notificationGroupName ][ 'users' ] ) 
      except KeyError:
        gLogger.error( '%s not present' % notificationGroupName )
#.........这里部分代码省略.........
开发者ID:IgorPelevanyuk,项目名称:DIRAC,代码行数:103,代码来源:EmailAction.py

示例6: Synchronizer

# 需要导入模块: from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin [as 别名]
# 或者: from DIRAC.Interfaces.API.DiracAdmin.DiracAdmin import sendMail [as 别名]

#.........这里部分代码省略.........
    is sent to Operations( EMail/Production ) email address.
    
    examples:
      >>> s.notify( {}, {}, {} )
      >>> s.notify( { 'Site' : { 'added' : [], 'deleted' : [ 'RubbishSite' ] }, {}, {} )
      >>> s.notify( { 'Site' : { 'added' : [], 'deleted' : [ 'RubbishSite' ] }, 
                    { 'Computing : { 'added' : [ 'newCE01', 'newCE02' ], 'deleted' : [] }}, {} )
    
    :Parameters:
      **syncSites** - dict() ( keys: added, deleted )
        dictionary with the sites added and deleted from the DB
      **syncResources** - dict() ( keys: added, deleted )
        dictionary with the resources added and deleted from the DB
      **syncNodes** - dict() ( keys: added, deleted )
        dictionary with the nodes added and deleted from the DB
      
    :return: S_OK
    """
    
    # Human readable summary
    msgBody = self.getBody( syncSites, syncResources, syncNodes ) 
    self.log.info( msgBody )
    
    # Email addresses
    toAddress   = self.operations.getValue( 'EMail/Production', '' )
    fromAddress = self.rssConfig.getConfigFromAddress( '' )
    
    if toAddress and fromAddress and msgBody:
      
      # Subject of the email
      setup   = gConfig.getValue( 'DIRAC/Setup' )
      subject = '[RSS](%s) CS Synchronization' % setup
      
      self.diracAdmin.sendMail( toAddress, subject, msgBody, fromAddress = fromAddress )
     
  def getBody( self, syncSites, syncResources, syncNodes ):
    """
    Method that given the outputs of the three synchronization methods builds a
    human readable string.
    
    examples:
      >>> s.getBody( {}, {}, {} )
          ''
      >>> s.getBody( { 'Site' : { 'added' : [], 'deleted' : [ 'RubbishSite' ] }, {}, {} )
          '''
          SITES:
          Site:
            deleted:1
              RubbishSite
          '''
      >>> s.getBody( { 'Site' : { 'added' : [], 'deleted' : [ 'RubbishSite' ] }, 
                     { 'Computing : { 'added' : [ 'newCE01', 'newCE02' ], 'deleted' : [] }}, {} )    
          '''
          SITES:
          Site:
            deleted:1
              RubbishSite
          RESOURCES:
          Computing:
            added:2
              newCE01
              newCE02    
          '''
          
    :Parameters:
      **syncSites** - dict() ( keys: added, deleted )
开发者ID:graciani,项目名称:DIRAC,代码行数:70,代码来源:Synchronizer.py

示例7: EmailAgent

# 需要导入模块: from DIRAC.Interfaces.API.DiracAdmin import DiracAdmin [as 别名]
# 或者: from DIRAC.Interfaces.API.DiracAdmin.DiracAdmin import sendMail [as 别名]
class EmailAgent( AgentModule ):

  def __init__( self, *args, **kwargs ):

    AgentModule.__init__( self, *args, **kwargs )
    self.diracAdmin = None
    self.default_value = None

    if 'DIRAC' in os.environ:
      self.cacheFile = os.path.join( os.getenv('DIRAC'), 'work/ResourceStatus/cache.db' )
    else:
      self.cacheFile = os.path.realpath('cache.db')

  def initialize( self ):
    ''' EmailAgent initialization
    '''

    self.diracAdmin = DiracAdmin()

    return S_OK()

  def execute( self ):

    if os.path.isfile(self.cacheFile):
      with sqlite3.connect(self.cacheFile) as conn:

        result = conn.execute("SELECT DISTINCT SiteName from ResourceStatusCache;")
        for site in result:
          cursor = conn.execute("SELECT StatusType, ResourceName, Status, Time, PreviousStatus from ResourceStatusCache WHERE SiteName='"+ site[0] +"';")

          email = ""
          html_body = ""
          html_elements = ""

          if gConfig.getValue('/DIRAC/Setup'):
            setup = "(" + gConfig.getValue('/DIRAC/Setup') + ")\n\n"
          else:
            setup = ""

          html_header = """\
          <!DOCTYPE html>
          <html>
          <head>
          <meta charset='UTF-8'>
            <style>
              table{{color:#333;font-family:Helvetica,Arial,sans-serif;min-width:700px;border-collapse:collapse;border-spacing:0}}
              td,th{{border:1px solid transparent;height:30px;transition:all .3s}}th{{background:#DFDFDF;font-weight:700}}
              td{{background:#FAFAFA;text-align:center}}.setup{{font-size:150%;color:grey}}.Banned{{color:red}}.Error{{color:#8b0000}}
              .Degraded{{color:gray}}.Probing{{color:#00f}}.Active{{color:green}}tr:nth-child(even) td{{background:#F1F1F1}}tr:nth-child(odd)
              td{{background:#FEFEFE}}tr td:hover{{background:#666;color:#FFF}}
            </style>
          </head>
          <body>
            <p class="setup">{setup}</p>
          """.format(setup=setup)

          for StatusType, ResourceName, Status, Time, PreviousStatus in cursor:
            html_elements += "<tr>" + \
                             "<td>" + StatusType + "</td>" + \
                             "<td>" + ResourceName + "</td>" + \
                             "<td class='" + Status + "'>" + Status + "</td>" + \
                             "<td>" + Time + "</td>" + \
                             "<td class='" + PreviousStatus + "'>" + PreviousStatus + "</td>" + \
                             "</tr>"

          html_body = """\
            <table>
              <tr>
                  <th>Status Type</th>
                  <th>Resource Name</th>
                  <th>Status</th>
                  <th>Time</th>
                  <th>Previous Status</th>
              </tr>
              {html_elements}
            </table>
          </body>
          </html>
          """.format(html_elements=html_elements)

          email = html_header + html_body

          subject = "RSS actions taken for " + site[0] + "\n"
          self._sendMail(subject, email, html = True)

        conn.execute("DELETE FROM ResourceStatusCache;")
        conn.execute("VACUUM;")

    return S_OK()

  def _sendMail( self, subject, body, html = False ):

    userEmails = self._getUserEmails()
    if not userEmails[ 'OK' ]:
      return userEmails

    # User email address used to send the emails from.
    fromAddress = RssConfiguration.RssConfiguration().getConfigFromAddress()

    for user in userEmails[ 'Value' ]:
#.........这里部分代码省略.........
开发者ID:DIRACGrid-test,项目名称:DIRAC,代码行数:103,代码来源:EmailAgent.py


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