You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
85 lines
2.4 KiB
85 lines
2.4 KiB
6 months ago
|
import os
|
||
|
import sys
|
||
|
import time
|
||
|
|
||
|
import psutil
|
||
|
|
||
|
|
||
|
# 定义状态
|
||
|
NORMAL = 'NORMAL'
|
||
|
ABNORMAL = 'ABNORMAL'
|
||
|
|
||
|
# 定义状态持续时间阈值(秒)
|
||
|
NORMAL_THRESHOLD = 10 * 60
|
||
|
ABNORMAL_THRESHOLD = 30
|
||
|
|
||
|
|
||
|
def get_process(name="mysqld"):
|
||
|
|
||
|
for proc in psutil.process_iter():
|
||
|
if proc.name() == name:
|
||
|
return proc
|
||
|
return None
|
||
|
|
||
|
|
||
|
# 定义状态机类
|
||
|
class ProcessMonitorStateMachine:
|
||
|
def __init__(self, process_name):
|
||
|
self.process_name = process_name
|
||
|
self.state = NORMAL
|
||
|
self.last_state_change_time = time.time()
|
||
|
|
||
|
def check_process(self):
|
||
|
"""检查进程是否存在,并返回其状态"""
|
||
|
process = get_process(name=self.process_name)
|
||
|
if process:
|
||
|
return NORMAL
|
||
|
else:
|
||
|
return ABNORMAL
|
||
|
|
||
|
def process_event(self):
|
||
|
"""处理事件,根据事件类型切换状态"""
|
||
|
current_time = time.time()
|
||
|
|
||
|
process_state = self.check_process()
|
||
|
print(f"当前状态:{process_state} {current_time}")
|
||
|
if process_state != self.state:
|
||
|
self.state = process_state
|
||
|
self.last_state_change_time = current_time
|
||
|
print(f"状态变更为: {self.state}")
|
||
|
if self.state == ABNORMAL:
|
||
|
self.handle_abnormal_timeout()
|
||
|
|
||
|
else:
|
||
|
if self.state == NORMAL and (current_time - self.last_state_change_time) > NORMAL_THRESHOLD:
|
||
|
self.handle_normal_timeout()
|
||
|
self.last_state_change_time = current_time
|
||
|
|
||
|
elif self.state == ABNORMAL and (current_time - self.last_state_change_time) > ABNORMAL_THRESHOLD:
|
||
|
self.handle_abnormal_timeout()
|
||
|
self.last_state_change_time = current_time
|
||
|
|
||
|
def handle_normal_timeout(self):
|
||
|
"""处理正常状态超时的指令"""
|
||
|
print("程序已正常,退出监控")
|
||
|
sys.exit(0)
|
||
|
|
||
|
def handle_abnormal_timeout(self):
|
||
|
"""处理异常状态超时的指令"""
|
||
|
print("异常状态持续时间过长,执行特定指令。")
|
||
|
os.system("/usr/bin/mysqld_bootstrap")
|
||
|
|
||
|
|
||
|
# 使用状态机监控进程
|
||
|
def main():
|
||
|
process_name = "mysqld" # 指定要监控的进程名称
|
||
|
monitor = ProcessMonitorStateMachine(process_name)
|
||
|
print("start...")
|
||
|
# 模拟定时检查进程状态
|
||
|
while True:
|
||
|
monitor.process_event()
|
||
|
time.sleep(10) # 每10秒检查一次
|
||
|
|
||
|
|
||
|
if __name__ == '__main__':
|
||
|
main()
|