-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpaimon_core_daemon.py
More file actions
264 lines (213 loc) · 9.27 KB
/
paimon_core_daemon.py
File metadata and controls
264 lines (213 loc) · 9.27 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
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PaimonCore Daemon - 轻量级后台驻留P核激活工具
提取核心P核激活功能,作为系统后台服务运行
作者: Geoffrey Wang
项目: PaimonCore Boost - Adaptive Hybrid Core Scheduler
许可证: Apache License 2.0
版本: v0.1.0
"""
import time
import sys
import threading
import signal
from typing import Optional
import logging
from pathlib import Path
try:
import numpy as np
import psutil
except ImportError as e:
print(f"❌ 缺少必要依赖: {e}")
print("请运行: pip install numpy psutil")
sys.exit(1)
class PaimonCoreDaemon:
"""PaimonCore 后台驻留服务 - 专注于P核激活"""
def __init__(self, log_level: str = "INFO"):
self.running = False
self.activation_thread: Optional[threading.Thread] = None
self.monitor_interval = 30 # 30秒检查一次
self.setup_logging(log_level)
# 核心参数
self.cpu_threshold = 20.0 # CPU使用率超过20%时激活P核
self.activation_duration = 10 # 激活持续10秒
# 注册信号处理
signal.signal(signal.SIGINT, self._signal_handler)
signal.signal(signal.SIGTERM, self._signal_handler)
self.logger.info("PaimonCore Daemon initialized successfully")
def setup_logging(self, level: str):
"""设置日志记录"""
log_dir = Path("logs")
log_dir.mkdir(exist_ok=True)
logging.basicConfig(
level=getattr(logging, level.upper()),
format='%(asctime)s - PaimonCore - %(levelname)s - %(message)s',
handlers=[
logging.FileHandler(log_dir / "paimon_daemon.log", encoding='utf-8'),
logging.StreamHandler(sys.stdout)
]
)
self.logger = logging.getLogger("PaimonCoreDaemon")
def _signal_handler(self, signum, frame):
"""优雅退出信号处理"""
self.logger.info(f"收到退出信号 {signum},正在停止服务...")
self.stop_daemon()
def activate_p_cores(self) -> bool:
"""核心P核激活算法"""
try:
# 生成高强度计算任务来激活P核
self.logger.debug("开始P核激活...")
# 使用矩阵运算激活P核
for _ in range(3):
# 创建计算密集型任务
matrix_size = 800
a = np.random.rand(matrix_size, matrix_size)
b = np.random.rand(matrix_size, matrix_size)
# 执行矩阵乘法,触发P核调度
result = np.dot(a, b)
# 短暂休眠,让系统响应
time.sleep(0.1)
self.logger.debug("P核激活完成")
return True
except Exception as e:
self.logger.error(f"P核激活失败: {e}")
return False
def get_system_load(self) -> dict:
"""获取系统负载信息"""
try:
cpu_percent = psutil.cpu_percent(interval=1)
memory = psutil.virtual_memory()
return {
'cpu_percent': cpu_percent,
'memory_percent': memory.percent,
'available_memory': memory.available,
'cpu_count': psutil.cpu_count(),
'physical_cores': psutil.cpu_count(logical=False)
}
except Exception as e:
self.logger.error(f"获取系统负载失败: {e}")
return {}
def should_activate_p_cores(self, system_load: dict) -> bool:
"""判断是否需要激活P核"""
if not system_load:
return False
cpu_percent = system_load.get('cpu_percent', 0)
memory_percent = system_load.get('memory_percent', 0)
# 激活条件:CPU使用率超过阈值且内存使用率不过高
if cpu_percent > self.cpu_threshold and memory_percent < 90:
self.logger.info(f"P-core activation triggered: CPU {cpu_percent:.1f}%, Memory {memory_percent:.1f}%")
return True
return False
def daemon_loop(self):
"""守护进程主循环"""
self.logger.info("PaimonCore Daemon starting...")
while self.running:
try:
# 获取系统负载
system_load = self.get_system_load()
if system_load:
# 记录系统状态
cpu_percent = system_load.get('cpu_percent', 0)
memory_percent = system_load.get('memory_percent', 0)
self.logger.debug(f"系统状态: CPU {cpu_percent:.1f}%, 内存 {memory_percent:.1f}%")
# 判断是否需要激活P核
if self.should_activate_p_cores(system_load):
self.activate_p_cores()
# 等待下一次检查
time.sleep(self.monitor_interval)
except Exception as e:
self.logger.error(f"守护进程循环异常: {e}")
time.sleep(5) # 异常时短暂休眠
def start_daemon(self, background: bool = False):
"""启动守护进程"""
if self.running:
self.logger.warning("守护进程已在运行")
return
self.running = True
if background:
# 后台线程模式
self.activation_thread = threading.Thread(target=self.daemon_loop, daemon=True)
self.activation_thread.start()
self.logger.info("PaimonCore Daemon 以后台模式启动")
else:
# 前台模式
self.logger.info("PaimonCore Daemon 以前台模式启动")
self.daemon_loop()
def stop_daemon(self):
"""停止守护进程"""
if not self.running:
return
self.running = False
if self.activation_thread and self.activation_thread.is_alive():
self.activation_thread.join(timeout=2)
self.logger.info("PaimonCore Daemon 已停止")
def get_status(self) -> dict:
"""获取守护进程状态"""
system_load = self.get_system_load()
return {
'daemon_running': self.running,
'monitor_interval': self.monitor_interval,
'cpu_threshold': self.cpu_threshold,
'system_load': system_load,
'thread_alive': self.activation_thread.is_alive() if self.activation_thread else False
}
def main():
"""主程序入口"""
import argparse
parser = argparse.ArgumentParser(description='PaimonCore Daemon - 轻量级P核激活守护进程')
parser.add_argument('--background', '-b', action='store_true',
help='以后台模式运行')
parser.add_argument('--interval', '-i', type=int, default=30,
help='监控间隔(秒,默认30)')
parser.add_argument('--threshold', '-t', type=float, default=20.0,
help='CPU激活阈值(百分比,默认20.0)')
parser.add_argument('--log-level', '-l', default='INFO',
choices=['DEBUG', 'INFO', 'WARNING', 'ERROR'],
help='日志级别')
parser.add_argument('--status', '-s', action='store_true',
help='显示状态信息并退出')
args = parser.parse_args()
# 创建守护进程实例
daemon = PaimonCoreDaemon(log_level=args.log_level)
daemon.monitor_interval = args.interval
daemon.cpu_threshold = args.threshold
if args.status:
# 显示状态
status = daemon.get_status()
print("🔍 PaimonCore Daemon 状态:")
print(f" 运行状态: {'运行中' if status['daemon_running'] else '已停止'}")
print(f" 监控间隔: {status['monitor_interval']}秒")
print(f" CPU阈值: {status['cpu_threshold']:.1f}%")
if status['system_load']:
load = status['system_load']
print(f" 当前CPU: {load.get('cpu_percent', 0):.1f}%")
print(f" 当前内存: {load.get('memory_percent', 0):.1f}%")
print(f" CPU核心: {load.get('physical_cores', 0)}物理/{load.get('cpu_count', 0)}逻辑")
return
try:
# 启动守护进程
print("🚀 启动 PaimonCore Daemon...")
print(f"⚙️ 监控间隔: {args.interval}秒")
print(f"📊 CPU阈值: {args.threshold:.1f}%")
print("💡 提示: 按 Ctrl+C 停止服务\n")
daemon.start_daemon(background=args.background)
if args.background:
# 后台模式,保持主线程运行
try:
while daemon.running:
time.sleep(1)
except KeyboardInterrupt:
pass
finally:
daemon.stop_daemon()
except KeyboardInterrupt:
print("\n👋 用户中断,正在停止...")
daemon.stop_daemon()
except Exception as e:
print(f"❌ 守护进程异常: {e}")
daemon.stop_daemon()
return 1
return 0
if __name__ == "__main__":
sys.exit(main())