Отправка электронной почты с Python, когда кластер etcd не работает или не работает - PullRequest
0 голосов
/ 27 июня 2018

Я работаю над мониторингом кластера 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() 

Какое возможное решение для этого?

1 Ответ

0 голосов
/ 27 июня 2018

Вы можете перехватить исключение 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()
...