-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaimon_core_monitor.py
More file actions
600 lines (482 loc) · 23 KB
/
paimon_core_monitor.py
File metadata and controls
600 lines (482 loc) · 23 KB
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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PaimonCore Monitor - GUI监控工具
图形化监测P/E核占用率和性能状态,集成后台守护进程控制
作者: Geoffrey Wang
项目: PaimonCore Boost - Adaptive Hybrid Core Scheduler
许可证: Apache License 2.0
版本: v0.1.0
"""
import tkinter as tk
from tkinter import ttk, messagebox
import threading
import time
import queue
from datetime import datetime
import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from matplotlib.figure import Figure
import matplotlib.animation as animation
from collections import deque
import json
from pathlib import Path
import logging
try:
import psutil
import numpy as np
except ImportError as e:
print(f"❌ 缺少必要依赖: {e}")
print("请运行: pip install psutil numpy matplotlib")
exit(1)
# 导入守护进程核心类
from paimon_core_daemon import PaimonCoreDaemon
class PaimonCoreMonitor:
"""PaimonCore 图形化监控工具"""
def __init__(self):
# 创建主窗口
self.root = tk.Tk()
self.root.title("PaimonCore Monitor v0.1.0 - P/E核性能监控")
self.root.geometry("1000x700")
self.root.configure(bg='#f0f0f0')
# 数据存储
self.data_queue = queue.Queue()
self.cpu_history = deque(maxlen=60) # 保存60秒数据
self.time_history = deque(maxlen=60)
self.p_core_history = deque(maxlen=60)
self.e_core_history = deque(maxlen=60)
# 守护进程控制
self.daemon = None
self.daemon_running = False
self.daemon_thread = None
# 监控控制
self.monitoring = False
self.monitor_thread = None
# 设置日志
self.setup_logging()
# 创建GUI
self.create_widgets()
# 启动数据更新
self.start_monitoring()
# 绑定关闭事件
self.root.protocol("WM_DELETE_WINDOW", self.on_closing)
def setup_logging(self):
"""设置日志"""
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s - PaimonMonitor - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_dir / "paimon_monitor.log", encoding='utf-8'),
]
)
self.logger = logging.getLogger("PaimonMonitor")
def create_widgets(self):
"""创建GUI组件"""
# 创建主框架
main_frame = ttk.Frame(self.root)
main_frame.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
# 创建顶部控制面板
self.create_control_panel(main_frame)
# 创建状态显示面板
self.create_status_panel(main_frame)
# 创建图表面板
self.create_chart_panel(main_frame)
# 创建底部信息面板
self.create_info_panel(main_frame)
def create_control_panel(self, parent):
"""创建控制面板"""
control_frame = ttk.LabelFrame(parent, text="🎛️ 控制面板", padding=10)
control_frame.pack(fill=tk.X, pady=(0, 10))
# 守护进程控制
daemon_frame = ttk.Frame(control_frame)
daemon_frame.pack(fill=tk.X, pady=(0, 5))
ttk.Label(daemon_frame, text="后台守护进程:", font=("Arial", 10, "bold")).pack(side=tk.LEFT)
self.daemon_status_label = ttk.Label(daemon_frame, text="●", foreground="red", font=("Arial", 12))
self.daemon_status_label.pack(side=tk.LEFT, padx=(5, 0))
self.start_daemon_btn = ttk.Button(daemon_frame, text="启动守护进程", command=self.start_daemon)
self.start_daemon_btn.pack(side=tk.LEFT, padx=(10, 5))
self.stop_daemon_btn = ttk.Button(daemon_frame, text="停止守护进程", command=self.stop_daemon)
self.stop_daemon_btn.pack(side=tk.LEFT, padx=5)
self.stop_daemon_btn.configure(state=tk.DISABLED)
# 参数配置
params_frame = ttk.Frame(control_frame)
params_frame.pack(fill=tk.X, pady=(5, 0))
ttk.Label(params_frame, text="监控间隔:").pack(side=tk.LEFT)
self.interval_var = tk.StringVar(value="5")
interval_entry = ttk.Entry(params_frame, textvariable=self.interval_var, width=5)
interval_entry.pack(side=tk.LEFT, padx=(5, 10))
ttk.Label(params_frame, text="秒").pack(side=tk.LEFT)
ttk.Label(params_frame, text="CPU阈值:").pack(side=tk.LEFT, padx=(20, 5))
self.threshold_var = tk.StringVar(value="20.0")
threshold_entry = ttk.Entry(params_frame, textvariable=self.threshold_var, width=5)
threshold_entry.pack(side=tk.LEFT, padx=5)
ttk.Label(params_frame, text="%").pack(side=tk.LEFT)
# 手动P核激活按钮
manual_frame = ttk.Frame(control_frame)
manual_frame.pack(fill=tk.X, pady=(10, 0))
self.manual_activate_btn = ttk.Button(manual_frame, text="🚀 手动激活P核", command=self.manual_activate_p_cores)
self.manual_activate_btn.pack(side=tk.LEFT)
ttk.Label(manual_frame, text="(用于测试P核激活效果)", foreground="gray").pack(side=tk.LEFT, padx=(10, 0))
def create_status_panel(self, parent):
"""创建状态显示面板"""
status_frame = ttk.LabelFrame(parent, text="📊 系统状态", padding=10)
status_frame.pack(fill=tk.X, pady=(0, 10))
# 创建状态显示网格
stats_frame = ttk.Frame(status_frame)
stats_frame.pack(fill=tk.X)
# CPU总使用率
cpu_frame = ttk.Frame(stats_frame)
cpu_frame.grid(row=0, column=0, sticky="ew", padx=(0, 20))
ttk.Label(cpu_frame, text="CPU总使用率:", font=("Arial", 9, "bold")).pack(side=tk.LEFT)
self.cpu_label = ttk.Label(cpu_frame, text="0.0%", foreground="blue", font=("Arial", 12, "bold"))
self.cpu_label.pack(side=tk.LEFT, padx=(10, 0))
# 内存使用率
mem_frame = ttk.Frame(stats_frame)
mem_frame.grid(row=0, column=1, sticky="ew", padx=(0, 20))
ttk.Label(mem_frame, text="内存使用率:", font=("Arial", 9, "bold")).pack(side=tk.LEFT)
self.memory_label = ttk.Label(mem_frame, text="0.0%", foreground="green", font=("Arial", 12, "bold"))
self.memory_label.pack(side=tk.LEFT, padx=(10, 0))
# P核状态指示
p_core_frame = ttk.Frame(stats_frame)
p_core_frame.grid(row=1, column=0, sticky="ew", padx=(0, 20), pady=(10, 0))
ttk.Label(p_core_frame, text="P核状态:", font=("Arial", 9, "bold")).pack(side=tk.LEFT)
self.p_core_indicator = ttk.Label(p_core_frame, text="●", foreground="gray", font=("Arial", 14))
self.p_core_indicator.pack(side=tk.LEFT, padx=(10, 0))
self.p_core_status = ttk.Label(p_core_frame, text="待机", foreground="gray", font=("Arial", 10))
self.p_core_status.pack(side=tk.LEFT, padx=(5, 0))
# E核状态指示
e_core_frame = ttk.Frame(stats_frame)
e_core_frame.grid(row=1, column=1, sticky="ew", padx=(0, 20), pady=(10, 0))
ttk.Label(e_core_frame, text="E核状态:", font=("Arial", 9, "bold")).pack(side=tk.LEFT)
self.e_core_indicator = ttk.Label(e_core_frame, text="●", foreground="gray", font=("Arial", 14))
self.e_core_indicator.pack(side=tk.LEFT, padx=(10, 0))
self.e_core_status = ttk.Label(e_core_frame, text="待机", foreground="gray", font=("Arial", 10))
self.e_core_status.pack(side=tk.LEFT, padx=(5, 0))
# 配置网格权重
stats_frame.columnconfigure(0, weight=1)
stats_frame.columnconfigure(1, weight=1)
def create_chart_panel(self, parent):
"""创建图表面板"""
chart_frame = ttk.LabelFrame(parent, text="📈 实时性能监控", padding=5)
chart_frame.pack(fill=tk.BOTH, expand=True, pady=(0, 10))
# 创建matplotlib图表
self.fig = Figure(figsize=(12, 4), dpi=100)
# CPU使用率子图
self.ax1 = self.fig.add_subplot(131)
self.ax1.set_title("CPU使用率")
self.ax1.set_ylabel("使用率 (%)")
self.ax1.set_ylim(0, 100)
self.ax1.grid(True, alpha=0.3)
# P核活跃度子图
self.ax2 = self.fig.add_subplot(132)
self.ax2.set_title("P核活跃度")
self.ax2.set_ylabel("活跃度")
self.ax2.set_ylim(0, 1.2)
self.ax2.grid(True, alpha=0.3)
# E核活跃度子图
self.ax3 = self.fig.add_subplot(133)
self.ax3.set_title("E核活跃度")
self.ax3.set_ylabel("活跃度")
self.ax3.set_ylim(0, 1.2)
self.ax3.grid(True, alpha=0.3)
self.fig.tight_layout()
# 创建画布
self.canvas = FigureCanvasTkAgg(self.fig, chart_frame)
self.canvas.draw()
self.canvas.get_tk_widget().pack(fill=tk.BOTH, expand=True)
def create_info_panel(self, parent):
"""创建信息面板"""
info_frame = ttk.LabelFrame(parent, text="📋 日志信息", padding=5)
info_frame.pack(fill=tk.X)
# 创建文本框和滚动条
text_frame = ttk.Frame(info_frame)
text_frame.pack(fill=tk.X)
self.log_text = tk.Text(text_frame, height=6, wrap=tk.WORD, font=("Consolas", 9))
scrollbar = ttk.Scrollbar(text_frame, orient=tk.VERTICAL, command=self.log_text.yview)
self.log_text.configure(yscrollcommand=scrollbar.set)
self.log_text.pack(side=tk.LEFT, fill=tk.BOTH, expand=True)
scrollbar.pack(side=tk.RIGHT, fill=tk.Y)
# 添加初始信息
self.add_log_message("🎮 PaimonCore Monitor 启动完成!")
self.add_log_message("💡 提示:启动守护进程开始P核监控")
def add_log_message(self, message):
"""添加日志消息"""
timestamp = datetime.now().strftime("%H:%M:%S")
full_message = f"[{timestamp}] {message}\n"
self.log_text.insert(tk.END, full_message)
self.log_text.see(tk.END) # 自动滚动到底部
# 限制日志长度
lines = int(self.log_text.index('end-1c').split('.')[0])
if lines > 100:
self.log_text.delete('1.0', '20.0')
def start_daemon(self):
"""启动守护进程"""
if self.daemon_running:
return
try:
# 获取配置参数
interval = int(self.interval_var.get())
threshold = float(self.threshold_var.get())
# 创建守护进程
self.daemon = PaimonCoreDaemon(log_level="INFO")
self.daemon.monitor_interval = interval
self.daemon.cpu_threshold = threshold
# 在单独线程中启动守护进程
self.daemon_thread = threading.Thread(target=self._run_daemon, daemon=True)
self.daemon_thread.start()
# 更新UI状态
self.daemon_running = True
self.daemon_status_label.configure(text="●", foreground="green")
self.start_daemon_btn.configure(state=tk.DISABLED)
self.stop_daemon_btn.configure(state=tk.NORMAL)
self.add_log_message(f"✅ 守护进程已启动 (间隔:{interval}s, 阈值:{threshold}%)")
except ValueError:
messagebox.showerror("参数错误", "请检查监控间隔和CPU阈值的输入格式")
except Exception as e:
messagebox.showerror("启动失败", f"守护进程启动失败: {e}")
def _run_daemon(self):
"""在后台线程中运行守护进程"""
try:
if self.daemon:
self.daemon.start_daemon(background=False)
except Exception as e:
self.logger.error(f"守护进程运行异常: {e}")
# 更新UI状态为停止
self.root.after(100, lambda: self.stop_daemon())
def _daemon_error_handler(self):
"""守护进程错误处理"""
self.stop_daemon()
self.add_log_message("❌ 守护进程运行异常,已自动停止")
def stop_daemon(self):
"""停止守护进程"""
if not self.daemon_running:
return
try:
if self.daemon:
self.daemon.stop_daemon()
# 更新UI状态
self.daemon_running = False
self.daemon_status_label.configure(text="●", foreground="red")
self.start_daemon_btn.configure(state=tk.NORMAL)
self.stop_daemon_btn.configure(state=tk.DISABLED)
self.add_log_message("⏹️ 守护进程已停止")
except Exception as e:
messagebox.showerror("停止失败", f"守护进程停止失败: {e}")
def manual_activate_p_cores(self):
"""手动激活P核"""
def activate():
try:
self.add_log_message("🚀 手动激活P核中...")
# 使用守护进程的P核激活方法
if not self.daemon:
temp_daemon = PaimonCoreDaemon()
success = temp_daemon.activate_p_cores()
else:
success = self.daemon.activate_p_cores()
if success:
self.add_log_message("✅ P核激活完成")
else:
self.add_log_message("❌ P核激活失败")
except Exception as e:
self.add_log_message(f"❌ P核激活异常: {e}")
# 在后台线程中执行
threading.Thread(target=activate, daemon=True).start()
def get_system_metrics(self):
"""获取系统指标"""
try:
# 获取基本系统信息
cpu_percent = psutil.cpu_percent(interval=0.1)
memory = psutil.virtual_memory()
cpu_freq = psutil.cpu_freq()
# 获取每个核心的使用率
cpu_percents = psutil.cpu_percent(interval=0.1, percpu=True)
# 模拟P/E核心检测(简化版本)
# Intel 12代处理器通常前16个是P核,后8个是E核
total_cores = len(cpu_percents)
physical_cores = psutil.cpu_count(logical=False)
# 确保physical_cores不为None
if physical_cores is None:
physical_cores = total_cores // 2
# 假设前面的核心是P核,后面的是E核
p_core_count = physical_cores // 2 if physical_cores >= 8 else physical_cores
e_core_count = max(0, total_cores - p_core_count)
if total_cores >= p_core_count and p_core_count > 0:
p_core_usage = np.mean(cpu_percents[:p_core_count])
e_core_usage = np.mean(cpu_percents[p_core_count:]) if e_core_count > 0 else 0
else:
p_core_usage = cpu_percent
e_core_usage = 0
# 判断P/E核状态
p_core_active = p_core_usage > float(self.threshold_var.get())
e_core_active = e_core_usage > 20 # E核激活阈值
return {
'timestamp': datetime.now(),
'cpu_percent': cpu_percent,
'memory_percent': memory.percent,
'cpu_freq': cpu_freq.current if cpu_freq else 0,
'p_core_usage': p_core_usage,
'e_core_usage': e_core_usage,
'p_core_active': p_core_active,
'e_core_active': e_core_active,
'total_cores': total_cores,
'p_core_count': p_core_count,
'e_core_count': e_core_count
}
except Exception as e:
self.logger.error(f"获取系统指标失败: {e}")
return None
def update_status_display(self, metrics):
"""更新状态显示"""
# 更新数字显示
self.cpu_label.configure(text=f"{metrics['cpu_percent']:.1f}%")
self.memory_label.configure(text=f"{metrics['memory_percent']:.1f}%")
# 更新P核状态
if metrics['p_core_active']:
self.p_core_indicator.configure(foreground="orange")
self.p_core_status.configure(text="激活中", foreground="orange")
else:
self.p_core_indicator.configure(foreground="blue")
self.p_core_status.configure(text="空闲", foreground="gray")
# 更新E核状态
if metrics['e_core_active']:
self.e_core_indicator.configure(foreground="green")
self.e_core_status.configure(text="工作中", foreground="green")
else:
self.e_core_indicator.configure(foreground="gray")
self.e_core_status.configure(text="空闲", foreground="gray")
def update_charts(self):
"""更新图表"""
if len(self.time_history) < 2:
return
# 转换时间为相对秒数
times = [(t - self.time_history[0]).total_seconds() for t in self.time_history]
# 清除旧图表
self.ax1.clear()
self.ax2.clear()
self.ax3.clear()
# CPU使用率图表
self.ax1.plot(times, list(self.cpu_history), 'b-', linewidth=2, label='总CPU')
self.ax1.set_title("CPU使用率")
self.ax1.set_ylabel("使用率 (%)")
self.ax1.set_ylim(0, 100)
self.ax1.grid(True, alpha=0.3)
self.ax1.legend()
# P核活跃度图表
p_core_activity = [1.0 if usage > float(self.threshold_var.get()) else 0.2 for usage in self.p_core_history]
self.ax2.fill_between(times, p_core_activity, alpha=0.6, color='orange', label='P核激活')
self.ax2.plot(times, [usage/100 for usage in self.p_core_history], 'r-', linewidth=1, label='P核使用率')
self.ax2.set_title("P核活跃度")
self.ax2.set_ylabel("活跃度/使用率")
self.ax2.set_ylim(0, 1.2)
self.ax2.grid(True, alpha=0.3)
self.ax2.legend()
# E核活跃度图表
e_core_activity = [1.0 if usage > 20 else 0.2 for usage in self.e_core_history]
self.ax3.fill_between(times, e_core_activity, alpha=0.6, color='green', label='E核激活')
self.ax3.plot(times, [usage/100 for usage in self.e_core_history], 'g-', linewidth=1, label='E核使用率')
self.ax3.set_title("E核活跃度")
self.ax3.set_ylabel("活跃度/使用率")
self.ax3.set_ylim(0, 1.2)
self.ax3.grid(True, alpha=0.3)
self.ax3.legend()
# 设置x轴标签
for ax in [self.ax1, self.ax2, self.ax3]:
ax.set_xlabel("时间 (秒)")
self.fig.tight_layout()
self.canvas.draw()
def monitor_system(self):
"""系统监控主循环"""
while self.monitoring:
try:
metrics = self.get_system_metrics()
if metrics:
# 更新历史数据
self.time_history.append(metrics['timestamp'])
self.cpu_history.append(metrics['cpu_percent'])
self.p_core_history.append(metrics['p_core_usage'])
self.e_core_history.append(metrics['e_core_usage'])
# 将数据放入队列供UI线程处理
self.data_queue.put(metrics)
time.sleep(1) # 每秒更新一次
except Exception as e:
self.logger.error(f"监控循环异常: {e}")
time.sleep(1)
def process_data_queue(self):
"""处理数据队列并更新UI"""
try:
while not self.data_queue.empty():
metrics = self.data_queue.get_nowait()
self.update_status_display(metrics)
# 检测P核激活事件
if metrics['p_core_active'] and len(self.p_core_history) >= 2:
prev_active = self.p_core_history[-2] > float(self.threshold_var.get())
if not prev_active: # 刚刚激活
self.add_log_message(f"🔥 P核激活! CPU: {metrics['cpu_percent']:.1f}%")
# 更新图表
if len(self.time_history) > 1:
self.update_charts()
except queue.Empty:
pass
except Exception as e:
self.logger.error(f"数据处理异常: {e}")
# 继续调度
self.root.after(500, self.process_data_queue) # 每0.5秒更新UI
def start_monitoring(self):
"""启动监控"""
if not self.monitoring:
self.monitoring = True
self.monitor_thread = threading.Thread(target=self.monitor_system, daemon=True)
self.monitor_thread.start()
# 启动UI数据处理
self.process_data_queue()
def stop_monitoring(self):
"""停止监控"""
self.monitoring = False
def on_closing(self):
"""关闭窗口时的清理工作"""
self.stop_monitoring()
self.stop_daemon()
# 保存配置
self.save_config()
self.root.quit()
self.root.destroy()
def save_config(self):
"""保存配置"""
try:
config = {
'interval': self.interval_var.get(),
'threshold': self.threshold_var.get(),
}
with open('paimon_monitor_config.json', 'w', encoding='utf-8') as f:
json.dump(config, f, indent=2, ensure_ascii=False)
except Exception as e:
self.logger.error(f"保存配置失败: {e}")
def load_config(self):
"""加载配置"""
try:
if Path('paimon_monitor_config.json').exists():
with open('paimon_monitor_config.json', 'r', encoding='utf-8') as f:
config = json.load(f)
self.interval_var.set(config.get('interval', '5'))
self.threshold_var.set(config.get('threshold', '20.0'))
except Exception as e:
self.logger.error(f"加载配置失败: {e}")
def run(self):
"""运行GUI应用"""
self.load_config()
self.root.mainloop()
def main():
"""主程序入口"""
try:
app = PaimonCoreMonitor()
app.run()
except KeyboardInterrupt:
print("\n👋 用户中断")
except Exception as e:
print(f"❌ 应用程序错误: {e}")
return 1
return 0
if __name__ == "__main__":
exit(main())