2

I have the following python code:

#!/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

#Function to get the health of the cluster
def getClusterHealth():
    try:
        response = requests.get('http://127.0.0.1:2379/health')
        data = response.json()
        if data['health']=="true":
            print("Cluster is healthy")
            getClusterMetrics()
        elif data['health']!="true":
            print ("Cluster is not healthy")
            sendEmail()
    except requests.exceptions.ConnectionError as e:
        print e
        print("Cluster is down")
        sendEmail()

#Function to get the netrics of the cluster
def getClusterMetrics():
    try:
        response = requests.get('http://127.0.0.1:2379/metrics')
        with open('clusterMetrics.txt','w') as f:
            f.write(response.text)
            f.close()
            print("Cluster Metrics saved in file: clusterMetrics.txt")
    except requests.exceptions.ConnectionError as e:
        print e
        sendEmail()

#Function to send emails in case of failures
def sendEmail():
    msg = MIMEText("etcd Cluster Down Sample Mail")
    sender = "etcd Cluster - 10.35.14.141"
    recipients = ["sample@email.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()

if __name__ == "__main__":

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

I want to run the whole script X seconds as taken as input from user. However, using this input, I want to do some timer based functions in my functions. It should show the output/do certain things as I wish (cannot show the code here), but the inside functions will run for a multiple of input given by user. For example, if the input is 30, script should run every 30 seconds, but I should be able to check if the cluster is healthy every two minutes.

1 Answers1

1

I encountered a problem like this a while ago, just put the code that you want to execute every X seconds in a function then use threading python module to run it as a thread,, but don't forget to close the thread using thread.cancel() or thread.exit() before closing your program(using atexit or your own implementation) as the function will continue to execute if you don't.

import atexit
import threading
X = input("Repeat code every ? sec")
def code(X):
  thread = threading.Timer(float(X), code)
  thread.start()
  '''
  your
  code
  '''
def exit():
  thread.cancel() #or thread.exit()
atexit.register(exit)

More Info:
Run certain code every n seconds
How to close a thread from within?

Iyad Ahmed
  • 80
  • 2
  • 12