matlabMonitor/monitorV4.py
2025-03-06 17:56:56 +08:00

123 lines
4.5 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# -*- coding: utf-8 -*-
"""
Created on Mon Feb 24 22:55:11 2025
@author: fyx90
"""
import psutil
import time
import pandas as pd
import requests
from sqlalchemy import create_engine, text
from flask import Flask, Response
from prometheus_client import Gauge, generate_latest
# 创建 Flask 应用
app = Flask(__name__)
# 获取服务器的 IP 地址
update_servers = requests.get('http://ifconfig.me/ip', timeout=10).text.strip()
# 连接到数据库
engine_tencent = create_engine(
'mysql+pymysql://ainvest_luming:lm18242094506@bj-cdb-3gfxha84.sql.tencentcdb.com:59970/monitor_fund'
)
# 查询数据库中需要监控的 MATLAB 脚本
sql_query1 = text(fr'SELECT * FROM `server_scripts` WHERE ip="{update_servers }"')
with engine_tencent.connect() as connection:
df1 = pd.read_sql_query(sql_query1, connection)['scripts_name']
SCRIPTS_TO_MONITOR = df1.tolist()
# 定义 Prometheus 指标
MATLAB_PROCESS_RUNNING = Gauge('matlab_process_running', 'MATLAB process running status')
MATLAB_SCRIPT_RUNNING = Gauge('matlab_script_running', 'MATLAB script running status', ['script_name'])
MATLAB_SCRIPT_COUNT = Gauge('matlab_script_count', 'Number of MATLAB scripts running')
def get_matlab_script_count():
"""获取当前正在运行的 MATLAB 脚本数量"""
count = 0
for proc in psutil.process_iter(['name', 'cmdline']):
try:
if 'matlab' in proc.info['name'].lower() and any('.m' in part for part in proc.info['cmdline']):
count += 1
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
pass
return count
def check_matlab_process_status():
"""检查是否有 MATLAB 进程在运行"""
matlab_processes = [
proc for proc in psutil.process_iter(['name'])
if proc.info['name'] and 'matlab' in proc.info['name'].lower()
]
process_running = 1 if matlab_processes else 0
MATLAB_PROCESS_RUNNING.set(process_running)
print(f"🔍 MATLAB 进程状态: {'运行中' if process_running else '未运行'} (共 {len(matlab_processes)} 个进程)")
def check_matlab_script_status():
"""检查特定 MATLAB 脚本是否在运行"""
running_processes = []
for proc in psutil.process_iter(['pid', 'name', 'cmdline']):
try:
process_name = proc.info['name']
cmdline = " ".join(proc.info['cmdline']) if proc.info['cmdline'] else ""
running_processes.append((proc.info['pid'], process_name, cmdline))
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
# 更新 MATLAB 脚本运行状态
#for script in SCRIPTS_TO_MONITOR :
# is_running = any(script in cmdline for _, _, cmdline in running_processes)
# MATLAB_SCRIPT_RUNNING.labels(script_name=script).set(1 if is_running else 0)
# print(f"🔍 监控 {script}: {'✅ 运行中' if is_running else '❌ 未运行'}")
cpu_usage = get_matlab_cpu_usage()
if cpu_usage< 1.0:
for script in SCRIPTS_TO_MONITOR :
# is_running = False
MATLAB_SCRIPT_RUNNING.labels(script_name=script).set( 0)
is_running = False
print(f"🔍 监控 {script}: {'✅ 运行中' if is_running else '❌ 未运行'}")
else:
for script in SCRIPTS_TO_MONITOR :
MATLAB_SCRIPT_RUNNING.labels(script_name=script).set(1)
is_running = True
print(f"🔍 监控 {script}: {'✅ 运行中' if is_running else '❌ 未运行'}")
def get_matlab_cpu_usage():
"""获取 MATLAB 进程的 CPU 使用率"""
total_cpu_usage = 0.0
for proc in psutil.process_iter(['pid', 'name', 'cpu_percent']):
try:
if proc.info['name'] and 'matlab' in proc.info['name'].lower():
total_cpu_usage += proc.cpu_percent(interval=1) # 获取 CPU 使用率
except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
continue
return total_cpu_usage
# 定义 Prometheus 监控路由
@app.route('/metrics')
def metrics():
# 更新所有 Prometheus 指标
script_count = get_matlab_script_count()
MATLAB_SCRIPT_COUNT.set(script_count)
check_matlab_process_status()
check_matlab_script_status()
# 打印日志
print(f"当前 MATLAB 运行的脚本数量: {script_count}")
# 返回 Prometheus 指标
return Response(generate_latest(), mimetype='text/plain')
# 启动 Flask 服务器
if __name__ == '__main__':
print("🚀 启动 MATLAB 监控 Exporter监听端口 8001...")
app.run(host='0.0.0.0', port=8001)