Files
ctms/backend/app/services/permission_metric_aggregator.py
T
Cheng Zhou 6cefa620e4 权限监控与管理界面全面美化
重新设计权限系统所有 UI 组件的视觉风格,统一配色、圆角、阴影和交互动效:
- 实时概览:统计卡片加图标和渐变色条,健康评分改为环形进度,告警改为卡片式
- 趋势分析:图表卡片加彩色图标标识,ECharts 配色升级为渐变面积填充
- 访问日志:指标卡片带图标,日志审计改为卡片式入口,IP排行前三高亮
- IP属地:工具栏重设计,排行列表前三渐变高亮,指标卡片统一新风格
- 系统级权限:从 el-table 改为自定义卡片列表,模块块独立圆角卡片
- 项目权限配置:空状态引导优化,成员表格加头像,工具栏加背景容器
- 角色概览卡片:加进度条可视化,hover 微动效
- 接口权限矩阵:工具栏分离布局,表格圆角包裹
- 角色管理抽屉:侧边栏选中态渐变,操作行 hover 高亮

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-20 14:36:35 +08:00

83 lines
3.0 KiB
Python

"""权限指标小时聚合任务
每小时从 permission_access_logs 聚合数据写入 permission_metric_snapshots。
"""
from __future__ import annotations
import asyncio
import logging
import uuid
from datetime import datetime, timedelta, timezone
from sqlalchemy import func, select
from app.db.session import SessionLocal
from app.models.permission_access_log import PermissionAccessLog
from app.models.permission_metric_snapshot import PermissionMetricSnapshot
logger = logging.getLogger("ctms.permission_metric_aggregator")
async def _aggregate_hour(bucket_start: datetime, bucket_end: datetime) -> None:
async with SessionLocal() as session:
result = await session.execute(
select(
func.count().label("total"),
func.count().filter(PermissionAccessLog.allowed.is_(True)).label("allowed"),
func.count().filter(PermissionAccessLog.allowed.is_(False)).label("denied"),
func.coalesce(func.avg(PermissionAccessLog.elapsed_ms), 0).label("avg_ms"),
func.coalesce(func.max(PermissionAccessLog.elapsed_ms), 0).label("max_ms"),
).where(
PermissionAccessLog.created_at >= bucket_start,
PermissionAccessLog.created_at < bucket_end,
)
)
row = result.one()
if row.total == 0:
return
from app.core.permission_monitor import get_permission_monitor
monitor = get_permission_monitor()
cache_metrics = monitor.metrics.cache_metrics
snapshot = PermissionMetricSnapshot(
id=uuid.uuid4(),
bucket_time=bucket_start,
total_checks=row.total,
allowed_checks=row.allowed,
denied_checks=row.denied,
avg_elapsed_ms=float(row.avg_ms),
max_elapsed_ms=float(row.max_ms),
cache_hits=cache_metrics.cache_hits,
cache_misses=cache_metrics.cache_misses,
error_count=monitor.metrics.check_metrics.errors,
)
session.add(snapshot)
await session.commit()
logger.info("Aggregated permission metrics for bucket %s: %d checks", bucket_start, row.total)
async def run_hourly_metric_aggregation(stop_event: asyncio.Event) -> None:
logger.info("Permission metric aggregator started")
while not stop_event.is_set():
now = datetime.now(timezone.utc)
next_hour = now.replace(minute=0, second=0, microsecond=0) + timedelta(hours=1)
wait_seconds = (next_hour - now).total_seconds()
try:
await asyncio.wait_for(stop_event.wait(), timeout=wait_seconds)
break
except asyncio.TimeoutError:
pass
bucket_end = next_hour
bucket_start = bucket_end - timedelta(hours=1)
try:
await _aggregate_hour(bucket_start, bucket_end)
except Exception:
logger.exception("Failed to aggregate permission metrics for %s", bucket_start)
logger.info("Permission metric aggregator stopped")