log
2026-07-09 bee20e574656edaaf98f30799faf8daabeba7fc6
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
#!/usr/bin/env python3
"""
系统管理器
功能:
1. 统一管理系统组件
2. 提供插件系统
3. 配置管理
4. 系统健康检查
5. 组件间通信
"""
 
import importlib
import os
import sys
import json
from datetime import datetime
from typing import Dict, List, Optional, Any
import logging
 
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
 
 
class Plugin:
    """插件基类"""
    
    def __init__(self, name: str, config: Dict = None):
        self.name = name
        self.config = config or {}
        self.enabled = True
    
    def initialize(self) -> bool:
        """初始化插件"""
        raise NotImplementedError
    
    def run(self, *args, **kwargs) -> Any:
        """运行插件"""
        raise NotImplementedError
    
    def shutdown(self) -> bool:
        """关闭插件"""
        raise NotImplementedError
 
 
class PluginManager:
    """插件管理器"""
    
    def __init__(self):
        self.plugins = {}
        self.plugin_paths = []
    
    def add_plugin_path(self, path: str):
        """添加插件路径"""
        if os.path.exists(path):
            self.plugin_paths.append(path)
            sys.path.insert(0, path)
            logger.info(f"添加插件路径: {path}")
    
    def load_plugin(self, name: str, module_path: str, config: Dict = None) -> bool:
        """加载插件"""
        try:
            # 动态导入模块
            module = importlib.import_module(module_path)
            # 假设插件类名为Plugin
            plugin_class = getattr(module, 'Plugin', None)
            if not plugin_class:
                logger.error(f"插件 {name} 中未找到Plugin类")
                return False
            
            # 创建插件实例
            plugin = plugin_class(name, config)
            if plugin.initialize():
                self.plugins[name] = plugin
                logger.info(f"插件 {name} 加载成功")
                return True
            else:
                logger.error(f"插件 {name} 初始化失败")
                return False
        except Exception as e:
            logger.error(f"加载插件 {name} 失败: {e}")
            return False
    
    def run_plugin(self, name: str, *args, **kwargs) -> Any:
        """运行插件"""
        if name in self.plugins and self.plugins[name].enabled:
            try:
                return self.plugins[name].run(*args, **kwargs)
            except Exception as e:
                logger.error(f"运行插件 {name} 失败: {e}")
                return None
        else:
            logger.warning(f"插件 {name} 未加载或未启用")
            return None
    
    def shutdown_plugin(self, name: str) -> bool:
        """关闭插件"""
        if name in self.plugins:
            try:
                result = self.plugins[name].shutdown()
                del self.plugins[name]
                logger.info(f"插件 {name} 关闭成功")
                return result
            except Exception as e:
                logger.error(f"关闭插件 {name} 失败: {e}")
                return False
        return False
    
    def shutdown_all(self):
        """关闭所有插件"""
        for name in list(self.plugins.keys()):
            self.shutdown_plugin(name)
 
 
class ConfigManager:
    """配置管理器"""
    
    def __init__(self, config_dir: str = 'config'):
        self.config_dir = config_dir
        self.configs = {}
        self._load_configs()
    
    def _load_configs(self):
        """加载配置文件"""
        if not os.path.exists(self.config_dir):
            os.makedirs(self.config_dir)
            logger.info(f"创建配置目录: {self.config_dir}")
        
        for filename in os.listdir(self.config_dir):
            if filename.endswith('.json'):
                filepath = os.path.join(self.config_dir, filename)
                try:
                    with open(filepath, 'r', encoding='utf-8') as f:
                        config = json.load(f)
                        config_name = filename.replace('.json', '')
                        self.configs[config_name] = config
                        logger.info(f"加载配置: {config_name}")
                except Exception as e:
                    logger.error(f"加载配置文件 {filename} 失败: {e}")
    
    def get(self, config_name: str, key: str = None, default: Any = None) -> Any:
        """获取配置"""
        if config_name not in self.configs:
            return default
        
        if key is None:
            return self.configs[config_name]
        
        return self.configs[config_name].get(key, default)
    
    def set(self, config_name: str, key: str, value: Any):
        """设置配置"""
        if config_name not in self.configs:
            self.configs[config_name] = {}
        
        self.configs[config_name][key] = value
        
        # 保存配置
        filepath = os.path.join(self.config_dir, f"{config_name}.json")
        try:
            with open(filepath, 'w', encoding='utf-8') as f:
                json.dump(self.configs[config_name], f, indent=2, ensure_ascii=False)
            logger.info(f"保存配置: {config_name}")
        except Exception as e:
            logger.error(f"保存配置文件 {config_name} 失败: {e}")
    
    def reload(self):
        """重新加载配置"""
        self._load_configs()
        logger.info("配置重新加载完成")
 
 
class SystemManager:
    """系统管理器"""
    
    def __init__(self, base_dir: str = None):
        self.base_dir = base_dir or os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
        self.config_manager = ConfigManager(os.path.join(self.base_dir, 'config'))
        self.plugin_manager = PluginManager()
        self.components = {}
        self.system_status = 'initialized'
        self.start_time = datetime.now()
        
        # 添加插件路径
        plugin_dir = os.path.join(self.base_dir, 'plugins')
        if os.path.exists(plugin_dir):
            self.plugin_manager.add_plugin_path(plugin_dir)
    
    def register_component(self, name: str, component: Any):
        """注册组件"""
        self.components[name] = component
        logger.info(f"组件 {name} 注册成功")
    
    def get_component(self, name: str) -> Optional[Any]:
        """获取组件"""
        return self.components.get(name)
    
    def load_plugin(self, name: str, module_path: str, config: Dict = None) -> bool:
        """加载插件"""
        return self.plugin_manager.load_plugin(name, module_path, config)
    
    def run_plugin(self, name: str, *args, **kwargs) -> Any:
        """运行插件"""
        return self.plugin_manager.run_plugin(name, *args, **kwargs)
    
    def get_config(self, config_name: str, key: str = None, default: Any = None) -> Any:
        """获取配置"""
        return self.config_manager.get(config_name, key, default)
    
    def set_config(self, config_name: str, key: str, value: Any):
        """设置配置"""
        self.config_manager.set(config_name, key, value)
    
    def health_check(self) -> Dict:
        """系统健康检查"""
        check_time = datetime.now()
        uptime = (check_time - self.start_time).total_seconds()
        
        # 检查组件状态
        component_status = {}
        for name, component in self.components.items():
            try:
                # 检查组件是否有health_check方法
                if hasattr(component, 'health_check'):
                    status = component.health_check()
                else:
                    status = {'status': 'ok'}
                component_status[name] = status
            except Exception as e:
                component_status[name] = {'status': 'error', 'message': str(e)}
        
        # 检查插件状态
        plugin_status = {}
        for name, plugin in self.plugin_manager.plugins.items():
            plugin_status[name] = {'enabled': plugin.enabled}
        
        health_report = {
            'timestamp': check_time.strftime('%Y-%m-%d %H:%M:%S'),
            'system_status': self.system_status,
            'uptime_seconds': uptime,
            'components': component_status,
            'plugins': plugin_status,
            'configs_loaded': list(self.config_manager.configs.keys())
        }
        
        return health_report
    
    def start(self):
        """启动系统"""
        logger.info("🚀 启动系统...")
        
        # 初始化组件
        for name, component in self.components.items():
            if hasattr(component, 'initialize'):
                try:
                    component.initialize()
                    logger.info(f"组件 {name} 初始化成功")
                except Exception as e:
                    logger.error(f"组件 {name} 初始化失败: {e}")
        
        self.system_status = 'running'
        logger.info("✅ 系统启动完成")
    
    def shutdown(self):
        """关闭系统"""
        logger.info("🛑 关闭系统...")
        
        # 关闭插件
        self.plugin_manager.shutdown_all()
        
        # 关闭组件
        for name, component in self.components.items():
            if hasattr(component, 'shutdown'):
                try:
                    component.shutdown()
                    logger.info(f"组件 {name} 关闭成功")
                except Exception as e:
                    logger.error(f"组件 {name} 关闭失败: {e}")
        
        self.system_status = 'shutdown'
        logger.info("✅ 系统关闭完成")
    
    def generate_system_report(self) -> Dict:
        """生成系统报告"""
        report = {
            'system': {
                'base_dir': self.base_dir,
                'status': self.system_status,
                'start_time': self.start_time.strftime('%Y-%m-%d %H:%M:%S'),
                'uptime': (datetime.now() - self.start_time).total_seconds()
            },
            'components': list(self.components.keys()),
            'plugins': list(self.plugin_manager.plugins.keys()),
            'configs': list(self.config_manager.configs.keys()),
            'health': self.health_check()
        }
        
        return report
    
    def save_system_report(self, output_dir: str = 'reports/system'):
        """保存系统报告"""
        os.makedirs(output_dir, exist_ok=True)
        
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        report = self.generate_system_report()
        
        # 保存JSON报告
        json_path = os.path.join(output_dir, f'system_report_{timestamp}.json')
        with open(json_path, 'w', encoding='utf-8') as f:
            json.dump(report, f, indent=2, ensure_ascii=False, default=str)
        
        # 生成Markdown报告
        md_report = self._generate_markdown_report(report)
        md_path = os.path.join(output_dir, f'system_report_{timestamp}.md')
        with open(md_path, 'w', encoding='utf-8') as f:
            f.write(md_report)
        
        logger.info(f"系统报告已保存: {json_path}")
        logger.info(f"Markdown报告已保存: {md_path}")
        
        return json_path
    
    def _generate_markdown_report(self, report: Dict) -> str:
        """生成Markdown报告"""
        lines = []
        
        lines.append("# 系统状态报告\n")
        lines.append(f"**生成时间:** {report['health']['timestamp']}\n")
        lines.append("---\n")
        
        # 系统信息
        lines.append("## 🖥️ 系统信息\n")
        lines.append(f"- **基础目录:** {report['system']['base_dir']}\n")
        lines.append(f"- **系统状态:** {report['system']['status']}\n")
        lines.append(f"- **启动时间:** {report['system']['start_time']}\n")
        lines.append(f"- **运行时间:** {report['system']['uptime']:.2f} 秒\n\n")
        
        # 组件状态
        lines.append("## 🧩 组件状态\n")
        if report['components']:
            for component in report['components']:
                status = report['health']['components'].get(component, {'status': 'unknown'})
                status_str = status.get('status', 'unknown')
                if status_str == 'ok':
                    status_str = '✅ 正常'
                elif status_str == 'error':
                    status_str = f"❌ 错误: {status.get('message', '未知错误')}"
                elif status_str == 'disabled':
                    status_str = '⏸️ 禁用'
                lines.append(f"- **{component}:** {status_str}\n")
        else:
            lines.append("无组件\n")
        lines.append("\n")
        
        # 插件状态
        lines.append("## 🔌 插件状态\n")
        if report['plugins']:
            for plugin in report['plugins']:
                enabled = report['health']['plugins'].get(plugin, {'enabled': False})['enabled']
                status_str = "✅ 启用" if enabled else "⏸️ 禁用"
                lines.append(f"- **{plugin}:** {status_str}\n")
        else:
            lines.append("无插件\n")
        lines.append("\n")
        
        # 配置信息
        lines.append("## ⚙️ 配置信息\n")
        if report['configs']:
            lines.append("已加载的配置文件:\n")
            for config in report['configs']:
                lines.append(f"- {config}.json\n")
        else:
            lines.append("无配置文件\n")
        lines.append("\n")
        
        lines.append("---\n")
        lines.append("\n## 📋 总结\n\n")
        lines.append("本报告提供了系统的详细状态信息,包括组件、插件和配置的运行情况。\n")
        
        return '\n'.join(lines)
 
 
class DataPipeline:
    """数据处理管道"""
    
    def __init__(self, system_manager: SystemManager):
        self.system_manager = system_manager
        self.steps = []
    
    def add_step(self, name: str, func: callable, **kwargs):
        """添加处理步骤"""
        self.steps.append({'name': name, 'func': func, 'kwargs': kwargs})
        logger.info(f"添加数据处理步骤: {name}")
    
    def run(self, data: Any) -> Any:
        """运行数据处理管道"""
        logger.info("运行数据处理管道...")
        
        current_data = data
        for step in self.steps:
            try:
                logger.info(f"执行步骤: {step['name']}")
                current_data = step['func'](current_data, **step['kwargs'])
            except Exception as e:
                logger.error(f"执行步骤 {step['name']} 失败: {e}")
                return None
        
        logger.info("数据处理管道执行完成")
        return current_data
    
    def clear(self):
        """清空处理步骤"""
        self.steps = []
        logger.info("数据处理管道已清空")
 
 
if __name__ == '__main__':
    # 测试系统管理器
    print("=== 系统管理器测试 ===")
    
    # 创建系统管理器
    system_manager = SystemManager()
    
    # 注册组件
    class TestComponent:
        def initialize(self):
            logger.info("测试组件初始化")
        
        def health_check(self):
            return {'status': 'ok'}
    
    system_manager.register_component('test_component', TestComponent())
    
    # 启动系统
    system_manager.start()
    
    # 运行健康检查
    health = system_manager.health_check()
    print(f"系统健康状态: {health['system_status']}")
    
    # 生成系统报告
    system_manager.save_system_report()
    
    # 关闭系统
    system_manager.shutdown()