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
| import subprocess import time import logging from typing import Dict, List, Optional import requests
class FaultSelfHealingManager: def __init__(self): self.logger = logging.getLogger(__name__) self.healing_actions = {} self.healing_history = {} self.max_retry_count = 3 def register_healing_action(self, alert_name: str, action_func): """注册自愈动作""" self.healing_actions[alert_name] = action_func self.logger.info(f"注册自愈动作: {alert_name}") def execute_healing_action(self, alert: Dict) -> bool: """执行自愈动作""" try: labels = alert.get('labels', {}) alertname = labels.get('alertname', '') if alertname not in self.healing_actions: self.logger.info(f"没有找到自愈动作: {alertname}") return False instance = labels.get('instance', 'unknown') retry_key = f"{alertname}:{instance}" if retry_key not in self.healing_history: self.healing_history[retry_key] = 0 if self.healing_history[retry_key] >= self.max_retry_count: self.logger.warning(f"自愈动作重试次数超限: {retry_key}") return False action_func = self.healing_actions[alertname] success = action_func(alert) if success: self.logger.info(f"自愈动作执行成功: {alertname}") self.healing_history[retry_key] = 0 else: self.logger.warning(f"自愈动作执行失败: {alertname}") self.healing_history[retry_key] += 1 return success except Exception as e: self.logger.error(f"执行自愈动作异常: {str(e)}") return False def restart_service(self, service_name: str) -> bool: """重启服务""" try: result = subprocess.run( ['systemctl', 'restart', service_name], capture_output=True, text=True, timeout=30 ) if result.returncode == 0: self.logger.info(f"服务重启成功: {service_name}") return True else: self.logger.error(f"服务重启失败: {service_name}, {result.stderr}") return False except Exception as e: self.logger.error(f"重启服务异常: {str(e)}") return False def clear_cache(self, cache_type: str) -> bool: """清理缓存""" try: if cache_type == 'redis': result = subprocess.run( ['redis-cli', 'FLUSHALL'], capture_output=True, text=True, timeout=10 ) if result.returncode == 0: self.logger.info("Redis缓存清理成功") return True else: self.logger.error(f"Redis缓存清理失败: {result.stderr}") return False elif cache_type == 'memory': result = subprocess.run( ['sync', '&&', 'echo', '3', '>', '/proc/sys/vm/drop_caches'], shell=True, capture_output=True, text=True, timeout=10 ) if result.returncode == 0: self.logger.info("内存缓存清理成功") return True else: self.logger.error(f"内存缓存清理失败: {result.stderr}") return False return False except Exception as e: self.logger.error(f"清理缓存异常: {str(e)}") return False def scale_service(self, service_name: str, scale_count: int) -> bool: """扩缩容服务""" try: result = subprocess.run( ['docker-compose', 'up', '-d', '--scale', f'{service_name}={scale_count}'], capture_output=True, text=True, timeout=60 ) if result.returncode == 0: self.logger.info(f"服务扩缩容成功: {service_name} -> {scale_count}") return True else: self.logger.error(f"服务扩缩容失败: {service_name}, {result.stderr}") return False except Exception as e: self.logger.error(f"扩缩容服务异常: {str(e)}") return False def execute_custom_script(self, script_path: str, args: List[str] = None) -> bool: """执行自定义脚本""" try: cmd = [script_path] if args: cmd.extend(args) result = subprocess.run( cmd, capture_output=True, text=True, timeout=60 ) if result.returncode == 0: self.logger.info(f"自定义脚本执行成功: {script_path}") return True else: self.logger.error(f"自定义脚本执行失败: {script_path}, {result.stderr}") return False except Exception as e: self.logger.error(f"执行自定义脚本异常: {str(e)}") return False
def define_healing_actions(healing_manager: FaultSelfHealingManager): """定义自愈动作""" def mysql_high_connections_healing(alert: Dict) -> bool: labels = alert.get('labels', {}) instance = labels.get('instance', '') return healing_manager.restart_service('mysql') def redis_high_memory_healing(alert: Dict) -> bool: return healing_manager.clear_cache('redis') def service_down_healing(alert: Dict) -> bool: labels = alert.get('labels', {}) service = labels.get('service', '') if service: return healing_manager.restart_service(service) return False def high_cpu_usage_healing(alert: Dict) -> bool: return healing_manager.clear_cache('memory') healing_manager.register_healing_action('MySQLHighConnections', mysql_high_connections_healing) healing_manager.register_healing_action('RedisHighMemoryUsage', redis_high_memory_healing) healing_manager.register_healing_action('ServiceDown', service_down_healing) healing_manager.register_healing_action('HighCPUUsage', high_cpu_usage_healing)
if __name__ == "__main__": healing_manager = FaultSelfHealingManager() define_healing_actions(healing_manager) alert = { 'labels': { 'alertname': 'MySQLHighConnections', 'instance': 'mysql1', 'service': 'mysql' }, 'annotations': { 'summary': 'MySQL连接数过高', 'description': 'MySQL连接数超过阈值' } } success = healing_manager.execute_healing_action(alert) print(f"自愈动作执行结果: {success}")
|