变更内容: - 重构指标系统实现,支持基于 Redis 的多实例指标管理。 - 替换原有的 Pushgateway 和 Redis Exporter 方案。 - 更新 Prometheus 配置,适配新的指标抓取方式。 - 添加 Redis 指标相关配置和告警规则文件。 - 更新 Dockerfile 和 docker-compose 文件,移除多余服务,精简配置。 - 编写 `metrics_unified.py` 模块及单元测试。 - 修复部分代码中的冗余和格式问题。
76 lines
2.2 KiB
Python
76 lines
2.2 KiB
Python
"""算法基类"""
|
|
|
|
from abc import ABC, abstractmethod
|
|
from typing import Any, Dict
|
|
import time
|
|
import logging
|
|
|
|
logger = logging.getLogger(__name__)
|
|
|
|
|
|
class BaseAlgorithm(ABC):
|
|
"""算法基类,所有算法必须继承此类"""
|
|
|
|
def __init__(self):
|
|
self.name = self.__class__.__name__
|
|
self.version = "1.0.0"
|
|
|
|
@abstractmethod
|
|
def process(self, *args, **kwargs) -> Dict[str, Any]:
|
|
"""
|
|
算法处理逻辑,子类必须实现此方法
|
|
|
|
Returns:
|
|
Dict[str, Any]: 算法处理结果
|
|
"""
|
|
pass
|
|
|
|
def execute(self, *args, **kwargs) -> Dict[str, Any]:
|
|
"""
|
|
执行算法,包含埋点和错误处理
|
|
|
|
Returns:
|
|
Dict[str, Any]: 包含结果和元数据的字典
|
|
"""
|
|
from ..core.metrics_unified import incr, observe
|
|
|
|
start_time = time.time()
|
|
status = "success"
|
|
|
|
try:
|
|
logger.info(f"Starting algorithm: {self.name}")
|
|
result = self.process(*args, **kwargs)
|
|
elapsed_time = time.time() - start_time
|
|
|
|
logger.info(f"Algorithm {self.name} completed successfully in {elapsed_time:.3f}s")
|
|
|
|
return {
|
|
"success": True,
|
|
"result": result,
|
|
"metadata": {
|
|
"algorithm": self.name,
|
|
"version": self.version,
|
|
"elapsed_time": elapsed_time,
|
|
},
|
|
}
|
|
|
|
except Exception as e:
|
|
status = "error"
|
|
elapsed_time = time.time() - start_time
|
|
logger.error(f"Algorithm {self.name} failed: {str(e)}", exc_info=True)
|
|
|
|
return {
|
|
"success": False,
|
|
"error": str(e),
|
|
"metadata": {
|
|
"algorithm": self.name,
|
|
"version": self.version,
|
|
"elapsed_time": elapsed_time,
|
|
},
|
|
}
|
|
finally:
|
|
# 记录算法执行指标
|
|
elapsed_time = time.time() - start_time
|
|
incr("algorithm_executions_total", {"algorithm": self.name, "status": status})
|
|
observe("algorithm_execution_duration_seconds", {"algorithm": self.name}, elapsed_time)
|