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
| import asyncio import aiohttp import json from datetime import datetime, timedelta from dataclasses import dataclass from typing import List, Dict, Optional import smtplib from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart
@dataclass class AlertRule: """告警规则定义""" name: str metric: str threshold: float operator: str severity: str cooldown_minutes: int = 15
class RPAMonitoringSystem: """RPA智能监控系统""" def __init__(self, config: dict): self.config = config self.orchestrator_url = config['orchestrator_url'] self.api_key = config['api_key'] self.alert_rules = self._load_alert_rules() self.alert_history = {} def _load_alert_rules(self) -> List[AlertRule]: """加载告警规则""" return [ AlertRule("机器人故障率过高", "robot_fault_rate", 0.2, ">", "high"), AlertRule("作业失败率过高", "job_failure_rate", 0.15, ">", "medium"), AlertRule("API响应时间过长", "api_response_time", 5.0, ">", "medium"), AlertRule("系统CPU使用率过高", "cpu_usage", 80.0, ">", "high"), AlertRule("系统内存使用率过高", "memory_usage", 85.0, ">", "high"), AlertRule("数据库连接数过多", "db_connections", 150, ">", "critical"), AlertRule("队列积压过多", "queue_backlog", 100, ">", "medium") ] async def collect_metrics(self) -> Dict[str, float]: """收集系统指标""" metrics = {} async with aiohttp.ClientSession() as session: tasks = [ self._collect_robot_metrics(session), self._collect_job_metrics(session), self._collect_system_metrics(), self._collect_queue_metrics(session) ] results = await asyncio.gather(*tasks, return_exceptions=True) for result in results: if isinstance(result, dict): metrics.update(result) return metrics async def _collect_robot_metrics(self, session: aiohttp.ClientSession) -> Dict[str, float]: """收集机器人指标""" try: headers = {"Authorization": f"Bearer {self.api_key}"} async with session.get( f"{self.orchestrator_url}/odata/Robots", headers=headers ) as response: if response.status != 200: return {} data = await response.json() robots = data.get('value', []) total_robots = len(robots) faulted_robots = len([r for r in robots if r.get('State') == 'Faulted']) return { "total_robots": total_robots, "faulted_robots": faulted_robots, "robot_fault_rate": faulted_robots / total_robots if total_robots > 0 else 0 } except Exception: return {} async def _collect_job_metrics(self, session: aiohttp.ClientSession) -> Dict[str, float]: """收集作业指标""" try: headers = {"Authorization": f"Bearer {self.api_key}"} end_time = datetime.now() start_time = end_time - timedelta(hours=1) filter_query = f"CreationTime ge {start_time.isoformat()}Z" async with session.get( f"{self.orchestrator_url}/odata/Jobs", headers=headers, params={"$filter": filter_query} ) as response: if response.status != 200: return {} data = await response.json() jobs = data.get('value', []) total_jobs = len(jobs) failed_jobs = len([j for j in jobs if j.get('State') == 'Faulted']) running_jobs = len([j for j in jobs if j.get('State') == 'Running']) return { "total_jobs_1h": total_jobs, "failed_jobs_1h": failed_jobs, "running_jobs": running_jobs, "job_failure_rate": failed_jobs / total_jobs if total_jobs > 0 else 0 } except Exception: return {} async def _collect_system_metrics(self) -> Dict[str, float]: """收集系统指标""" try: import psutil return { "cpu_usage": psutil.cpu_percent(interval=1), "memory_usage": psutil.virtual_memory().percent, "disk_usage": psutil.disk_usage('/').percent } except Exception: return {} async def _collect_queue_metrics(self, session: aiohttp.ClientSession) -> Dict[str, float]: """收集队列指标""" try: headers = {"Authorization": f"Bearer {self.api_key}"} async with session.get( f"{self.orchestrator_url}/odata/QueueItems", headers=headers, params={"$filter": "Status eq 'New'"} ) as response: if response.status != 200: return {} data = await response.json() queue_items = data.get('value', []) return { "queue_backlog": len(queue_items) } except Exception: return {} def check_alerts(self, metrics: Dict[str, float]) -> List[Dict]: """检查告警条件""" alerts = [] current_time = datetime.now() for rule in self.alert_rules: if rule.metric not in metrics: continue metric_value = metrics[rule.metric] if self._evaluate_condition(metric_value, rule.threshold, rule.operator): last_alert_time = self.alert_history.get(rule.name) if last_alert_time: time_diff = (current_time - last_alert_time).total_seconds() / 60 if time_diff < rule.cooldown_minutes: continue alert = { "rule_name": rule.name, "metric": rule.metric, "current_value": metric_value, "threshold": rule.threshold, "severity": rule.severity, "timestamp": current_time.isoformat(), "message": f"{rule.name}: {rule.metric}当前值{metric_value}超过阈值{rule.threshold}" } alerts.append(alert) self.alert_history[rule.name] = current_time return alerts def _evaluate_condition(self, value: float, threshold: float, operator: str) -> bool: """评估告警条件""" if operator == ">": return value > threshold elif operator == "<": return value < threshold elif operator == ">=": return value >= threshold elif operator == "<=": return value <= threshold elif operator == "==": return value == threshold return False async def send_alert(self, alert: Dict) -> bool: """发送告警通知""" try: await self._send_email_alert(alert) return True except Exception as e: print(f"发送告警失败: {e}") return False async def _send_email_alert(self, alert: Dict): """发送邮件告警""" smtp_config = self.config.get('smtp', {}) msg = MIMEMultipart() msg['From'] = smtp_config.get('from_email') msg['To'] = ', '.join(smtp_config.get('to_emails', [])) msg['Subject'] = f"[RPA告警] {alert['severity'].upper()} - {alert['rule_name']}" body = f""" 告警详情:
规则名称: {alert['rule_name']} 指标名称: {alert['metric']} 当前值: {alert['current_value']} 阈值: {alert['threshold']} 严重程度: {alert['severity']} 触发时间: {alert['timestamp']}
详细信息: {alert['message']}
请及时处理! """ msg.attach(MIMEText(body, 'plain', 'utf-8')) async def run_monitoring_loop(self, interval_seconds: int = 60): """运行监控循环""" print(f"RPA监控系统启动,监控间隔: {interval_seconds}秒") while True: try: metrics = await self.collect_metrics() print(f"收集到指标: {metrics}") alerts = self.check_alerts(metrics) for alert in alerts: print(f"触发告警: {alert['message']}") await self.send_alert(alert) await asyncio.sleep(interval_seconds) except Exception as e: print(f"监控循环异常: {e}") await asyncio.sleep(interval_seconds)
if __name__ == "__main__": config = { "orchestrator_url": "https://your-orchestrator.com", "api_key": "your-api-key", "smtp": { "host": "smtp.company.com", "port": 587, "from_email": "rpa-monitor@company.com", "to_emails": ["admin@company.com", "ops@company.com"] } } monitor = RPAMonitoringSystem(config) asyncio.run(monitor.run_monitoring_loop(60))
|