feat: 综合平台services多服务支持+SW网络优先缓存修复+适配层/定时任务完善
This commit is contained in:
@@ -4,6 +4,7 @@
|
||||
评分按检查项加权:pass 满分、warn 半分、fail/unknown 零分。
|
||||
"""
|
||||
|
||||
from sqlalchemy import func
|
||||
from sqlmodel import Session, select
|
||||
|
||||
from app.models.monitor import SecurityCheck
|
||||
@@ -70,8 +71,42 @@ def get_asset_security(session: Session, asset_id: int) -> dict:
|
||||
|
||||
|
||||
def get_security_overview(session: Session) -> list:
|
||||
"""所有有安全检查数据的服务器评分总览(按评分升序,风险高的在前)"""
|
||||
asset_ids = session.exec(select(SecurityCheck.asset_id).distinct()).all()
|
||||
result = [get_asset_security(session, aid) for aid in asset_ids]
|
||||
"""所有有安全检查数据的服务器评分总览(按评分升序,风险高的在前)
|
||||
|
||||
性能优化:用子查询取每个 (asset_id, check_item) 的最新 ts,仅拉取最新记录,
|
||||
避免全表扫描(历史数据量大时内存可控)。
|
||||
"""
|
||||
latest_ts = (
|
||||
select(
|
||||
SecurityCheck.asset_id,
|
||||
SecurityCheck.check_item,
|
||||
func.max(SecurityCheck.ts).label("max_ts"),
|
||||
)
|
||||
.group_by(SecurityCheck.asset_id, SecurityCheck.check_item)
|
||||
.subquery()
|
||||
)
|
||||
stmt = select(SecurityCheck).join(
|
||||
latest_ts,
|
||||
(SecurityCheck.asset_id == latest_ts.c.asset_id)
|
||||
& (SecurityCheck.check_item == latest_ts.c.check_item)
|
||||
& (SecurityCheck.ts == latest_ts.c.max_ts),
|
||||
)
|
||||
all_checks = session.exec(stmt).all()
|
||||
|
||||
# 按 asset_id 分组
|
||||
latest_by_asset: dict = {}
|
||||
for check in all_checks:
|
||||
latest_by_asset.setdefault(check.asset_id, []).append(check)
|
||||
|
||||
result = []
|
||||
for asset_id, checks in latest_by_asset.items():
|
||||
score = compute_security_score(checks)
|
||||
result.append({
|
||||
"asset_id": asset_id,
|
||||
"score": score,
|
||||
"level": score_level(score),
|
||||
"checks_count": len(checks),
|
||||
"suggestions": [c.suggestion for c in checks if c.suggestion],
|
||||
})
|
||||
result.sort(key=lambda x: (x["score"] is None, x["score"] if x["score"] is not None else 0))
|
||||
return result
|
||||
|
||||
Reference in New Issue
Block a user