我正在进行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',))
我试图使用状态代码以及request.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()
对此可能的解决方案是什么?
答案 0 :(得分: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()