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
|
#!/usr/bin/env python3
# 智能告警系统
import asyncio
import aioredis
import logging
from datetime import datetime, timedelta
from typing import Dict, List, Optional
from dataclasses import dataclass
import smtplib
from email.mime.text import MimeText
from email.mime.multipart import MimeMultipart
@dataclass
class AlertRule:
name: str
metric: str
condition: str
threshold: float
duration: int # seconds
severity: str # critical, warning, info
description: str
class IntelligentAlerting:
def __init__(self, redis_url: str):
self.redis = aioredis.from_url(redis_url)
self.alert_rules = self._load_alert_rules()
self.notification_channels = self._setup_notification_channels()
def _load_alert_rules(self) -> List[AlertRule]:
"""加载告警规则"""
return [
AlertRule(
name="high_cpu_usage",
metric="cpu_usage_percent",
condition=">",
threshold=80.0,
duration=300, # 5分钟
severity="warning",
description="CPU使用率持续超过80%"
),
AlertRule(
name="critical_cpu_usage",
metric="cpu_usage_percent",
condition=">",
threshold=95.0,
duration=120, # 2分钟
severity="critical",
description="CPU使用率持续超过95%"
),
AlertRule(
name="high_memory_usage",
metric="memory_usage_percent",
condition=">",
threshold=85.0,
duration=300,
severity="warning",
description="内存使用率持续超过85%"
),
AlertRule(
name="service_down",
metric="service_health",
condition="==",
threshold=0.0,
duration=60,
severity="critical",
description="服务不可用"
)
]
async def evaluate_alerts(self):
"""评估告警规则"""
for rule in self.alert_rules:
try:
# 获取指标数据
metric_value = await self._get_metric_value(rule.metric)
# 检查是否触发告警
if self._evaluate_condition(metric_value, rule.condition, rule.threshold):
await self._check_alert_duration(rule, metric_value)
else:
# 清除告警状态
await self._clear_alert(rule)
except Exception as e:
logging.error(f"评估告警规则失败 {rule.name}: {e}")
async def _get_metric_value(self, metric: str) -> float:
"""获取指标值"""
# 这里应该连接Prometheus或其他监控系统
# 简化示例,直接从Redis获取
value = await self.redis.get(f"metric:{metric}")
return float(value) if value else 0.0
def _evaluate_condition(self, value: float, condition: str, threshold: float) -> bool:
"""评估条件"""
if condition == ">":
return value > threshold
elif condition == ">=":
return value >= threshold
elif condition == "<":
return value < threshold
elif condition == "<=":
return value <= threshold
elif condition == "==":
return value == threshold
elif condition == "!=":
return value != threshold
return False
async def _check_alert_duration(self, rule: AlertRule, metric_value: float):
"""检查告警持续时间"""
alert_key = f"alert:{rule.name}"
# 检查是否已经有告警
existing_alert = await self.redis.get(alert_key)
if existing_alert:
# 告警已存在,检查是否需要升级
alert_data = eval(existing_alert.decode())
if alert_data['severity'] != rule.severity:
await self._update_alert_severity(rule, alert_data)
else:
# 新告警,记录开始时间
alert_data = {
'start_time': datetime.now().isoformat(),
'metric_value': metric_value,
'severity': rule.severity,
'triggered_at': datetime.now().isoformat()
}
await self.redis.setex(
alert_key,
rule.duration + 300, # 额外5分钟缓冲
str(alert_data)
)
# 检查是否达到持续时间阈值
if rule.duration == 0: # 立即告警
await self._trigger_alert(rule, metric_value)
else:
# 启动定时检查
asyncio.create_task(self._check_alert_duration_async(rule, metric_value, rule.duration))
async def _check_alert_duration_async(self, rule: AlertRule, metric_value: float, duration: int):
"""异步检查告警持续时间"""
await asyncio.sleep(duration)
# 再次检查指标值
current_value = await self._get_metric_value(rule.metric)
if self._evaluate_condition(current_value, rule.condition, rule.threshold):
await self._trigger_alert(rule, current_value)
async def _trigger_alert(self, rule: AlertRule, metric_value: float):
"""触发告警"""
alert_data = {
'name': rule.name,
'metric': rule.metric,
'value': metric_value,
'threshold': rule.threshold,
'condition': rule.condition,
'severity': rule.severity,
'description': rule.description,
'triggered_at': datetime.now().isoformat()
}
# 记录告警
await self.redis.lpush("active_alerts", str(alert_data))
# 发送通知
await self._send_notifications(rule, alert_data)
logging.warning(f"告警触发: {rule.name} - {rule.description}")
async def _send_notifications(self, rule: AlertRule, alert_data: Dict):
"""发送告警通知"""
for channel in self.notification_channels:
try:
if channel['type'] == 'email':
await self._send_email_alert(rule, alert_data, channel)
elif channel['type'] == 'slack':
await self._send_slack_alert(rule, alert_data, channel)
elif channel['type'] == 'webhook':
await self._send_webhook_alert(rule, alert_data, channel)
except Exception as e:
logging.error(f"发送告警通知失败: {e}")
async def _send_email_alert(self, rule: AlertRule, alert_data: Dict, channel: Dict):
"""发送邮件告警"""
msg = MimeMultipart()
msg['From'] = channel['from']
msg['To'] = ', '.join(channel['to'])
msg['Subject'] = f"[{rule.severity.upper()}] {rule.name}"
body = f"""
告警详情:
告警名称:{rule.name}
告警级别:{rule.severity}
告警描述:{rule.description}
指标名称:{rule.metric}
当前值:{alert_data['value']}
阈值:{rule.threshold} {rule.condition}
触发时间:{alert_data['triggered_at']}
请及时处理!
"""
msg.attach(MimeText(body, 'plain', 'utf-8'))
server = smtplib.SMTP(channel['smtp_server'], channel['smtp_port'])
server.starttls()
server.login(channel['username'], channel['password'])
server.send_message(msg)
server.quit()
# 主程序
async def main():
alerting = IntelligentAlerting("redis://localhost:6379")
# 启动告警评估循环
while True:
await alerting.evaluate_alerts()
await asyncio.sleep(30) # 每30秒评估一次
if __name__ == "__main__":
asyncio.run(main())
|