【问题标题】:Send email from Python when etcd cluster is down or unhealthy当 etcd 集群关闭或不健康时从 Python 发送电子邮件
【发布时间】:2018-12-06 05:15:00
【问题描述】:

我正在进行 etcd 集群监控,如果集群关闭,我必须发送电子邮件。当集群健康并且我在代码中使用 sendEmail() 函数时,它可以正常工作,但是当集群关闭/不健康或者我已经终止了进程时,它会说:

requests.exceptions.ConnectionError: HTTPConnectionPool(host='localhost', port=2379): Max retries exceeded with url: /health (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x1f6de50>: Failed to establish a new connection: [Errno 111] Connection refused',))

我尝试使用状态代码和 requests.exception 以便它访问我的代码,但无法这样做。以下是我的代码:

#!/usr/bin/python
# -*- coding: utf-8 -*-
import json
import requests
import sys
import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText
from subprocess import Popen, PIPE

def getClusterHealth():
    response = requests.get('http://localhost:2379/health')
    data = response.json()

    if response.status_code == 111:
        sendEmail() 

    elif data['health']=="true":
        print("Cluster is healthy")

    else:
        print ("Cluster is not healthy")
        sendEmail()

def sendEmail():
    msg = MIMEText("etcd Cluster Down Sample Mail")
    sender = "example@server.com"
    recipients = ["example1@server.com,example2@servr.com"]
    msg["Subject"] = "etcd Cluster Monitoring Test Multiple ID"  
    msg['From'] = sender
    msg['To'] = ", ".join(recipients)
    s = smtplib.SMTP('localhost')
    s.sendmail(sender,recipients,msg.as_string())
    s.quit()
    #p = Popen(["/usr/sbin/sendmail", "-t", "-oi"], stdin=PIPE, universal_newlines=True)
    #p.communicate(msg.as_string())  


if __name__ == "__main__":

    if(len(sys.argv) < 2):
        print("Usage : python etcdMonitoring.py [health|metrics|all]")
    elif(sys.argv[1] == "health"):
        getClusterHealth() 

对此有什么可能的解决方案?

【问题讨论】:

  • 看起来最大重试次数超出了 url,这就是您收到此错误的原因。
  • 是否有可能在最大重试次数后发送邮件?
  • 捕获 ConnectionError 并在其上触发邮件。
  • @min2bro 你能举个例子吗?

标签: python mime smtplib etcd


【解决方案1】:

您可以捕获 ConnectionError 异常并评估错误消息并根据需要发送电子邮件:

def getClusterHealth():
     try:
        response = requests.get('http://localhost:2379/health')
     except ConnectionError as e:
     // You can use the value of e to check for specific error message and trigger the email
       if str(e) == 'Max retries exceeded with url':
         sendEmail() 

        data = response.json()

        if response.status_code == 111:
            sendEmail() 

        elif data['health']=="true":
            print("Cluster is healthy")

        else:
            print ("Cluster is not healthy")
            sendEmail()

【讨论】:

  • 我使用 except requests.exceptions.ConnectionError as e 而不是 except ConnectionError as e。然后效果很好。
  • 不能。它说已记录但未公开显示
  • 说需要 15 声望。还是 13 点。
猜你喜欢
  • 2019-10-25
  • 1970-01-01
  • 2013-07-11
  • 2021-05-28
  • 1970-01-01
  • 1970-01-01
  • 2017-01-07
  • 2014-07-18
  • 2012-05-23
相关资源
最近更新 更多