Created
September 24, 2014 12:00
-
-
Save vicendominguez/b2421fd06ad7e466584c to your computer and use it in GitHub Desktop.
Fast process monitor daemon in python with logger and email notifier
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
import os, smtplib | |
from sys import exit | |
from time import sleep, gmtime, strftime | |
########## Configuration here ############## | |
processname = 'init' | |
checkseconds = 5 | |
maxalerts = 2 | |
sender = '[email protected]' | |
receivers = ['[email protected]'] | |
emailpassword = 'myemailpass' | |
smtpserver = 'smtp.server.net' | |
logfilename = 'monitor.log' | |
########## End configuration ########### | |
message = ("From: Monitor <%s>\r\nTo: Warning <%s>\r\nSubject: e-mail Alert Monitor\r\nProcess is down!" % (sender, ", ".join(receivers))) | |
fail = 0 | |
#Crazy logger | |
def writelog (message): | |
global logfile | |
try: | |
# This tries to open an existing file but creates a new file if necessary. | |
logfile = open(logfilename, "a") | |
try: | |
logfile.write(message) | |
finally: | |
logfile.close() | |
except IOError: | |
pass | |
# Notifying via Email | |
def advice(): | |
try: | |
smtpObj = smtplib.SMTP(smtpserver, 25) | |
smtpObj.login (sender,emailpassword) | |
smtpObj.sendmail(sender, receivers, message) | |
writelog ("%s Successfully sent email\n" % (strftime("%d %b %Y %H:%M:%S", gmtime()))) | |
smtpObj.quit() | |
except SMTPException: | |
writelog ("%s Error: unable to send email\n" % (strftime("%d %b %Y %H:%M:%S", gmtime()))) | |
# print ("exiting...") | |
# exit (1) | |
# Vicente trick of the hell | |
def monitor(): | |
global fail | |
tmp = os.popen("ps -Af").read() | |
proccount = tmp.count(processname) | |
if proccount < 1: | |
fail = fail + 1 | |
writelog ('%s %s **STOPPED** (alert %d)\n' % (strftime("%d %b %Y %H:%M:%S", gmtime()), processname, fail)) | |
if fail == maxalerts: | |
advice() | |
else: | |
fail = 0 | |
sleep(checkseconds) | |
def main(): | |
while 1: | |
monitor() | |
# Dual fork hack to make process run as a daemon thanks to Active Programmer Network | |
if __name__ == "__main__": | |
try: | |
pid = os.fork() | |
if pid > 0: | |
exit(0) | |
except OSError, e: | |
exit(1) | |
os.chdir("/tmp") | |
os.setsid() | |
os.umask(0) | |
try: | |
pid = os.fork() | |
if pid > 0: | |
exit(0) | |
except OSError, e: | |
exit(1) | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment