예전에 아는 선배형이 만들어주셨던 코드입니다. 개인 서버를 구축하고 홈페이지를 굴리면 가끔 DB 서버가 죽는 경우가 생겨서 Uptime Robot도 쓰고 그랬었는데, 이걸 쓰니까 직접 다시 켜줄 필요가 없어져서 참 좋았습니다. Python으로 작성되었습니다.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
#USAGE :: nohup python revive.py 2>/dev/null & import os import logging import logging.handlers import subprocess import time import sys import inspect #####STATIC##### MYSQL_OFF = 0 MYSQL_ON = 1 INTERVAL = 1*1*15 ################ log = logging.getLogger("log") form = logging.Formatter('[%(levelname)s]%(asctime)s :: %(message)s') fh = logging.FileHandler("watcher_log") fh.setFormatter(form) log.addHandler(fh) log.setLevel(logging.DEBUG) def check_sql(): r = subprocess.Popen("ps -ef |grep mysql",shell=True,stdout=subprocess.PIPE).communicate()[0].split("\n") for result in r: if 'grep' not in result and result is not "": return MYSQL_ON return MYSQL_OFF if __name__ == "__main__": log.info("SCRIPT START") if os.getuid() is not 0: log.error("ROOT ONLY::"+os.getuid()) exit(-1) while (1): ret = subprocess.Popen("ps -ef |grep mysqld",shell=True,stdout=subprocess.PIPE).communicate()[0].split("\n") state = check_sql() if state is MYSQL_OFF: log.info("SERVICE DOWN") subprocess.Popen("service mysql stop",shell=True,stdout=subprocess.PIPE) subprocess.Popen("service mysql start",shell=True,stdout=subprocess.PIPE) if check_sql() is MYSQL_OFF: log.error("SERVICE START FAIL. RETRY") continue else: log.info("SERVICE START SUCCESS") time.sleep(INTERVAL) |