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
| import pymysql import subprocess import os import time import logging
class DataRecoveryManager: def __init__(self, db_config, backup_dir): self.db_config = db_config self.backup_dir = backup_dir self.logger = logging.getLogger(__name__) def full_recovery(self, backup_file): """全量恢复""" self.logger.info(f"开始全量恢复: {backup_file}") try: subprocess.run(['systemctl', 'stop', 'mysql'], check=True) backup_time = time.strftime('%Y%m%d_%H%M%S') subprocess.run(['mv', '/var/lib/mysql', f'/var/lib/mysql.backup.{backup_time}'], check=True) subprocess.run(['mysql_install_db', '--user=mysql', '--datadir=/var/lib/mysql'], check=True) subprocess.run(['systemctl', 'start', 'mysql'], check=True) time.sleep(10) with open(backup_file, 'r') as f: subprocess.run(['mysql', '-h', self.db_config['host'], '-u', self.db_config['user'], '-p' + self.db_config['password']], stdin=f, check=True) self.logger.info("全量恢复完成") return True except Exception as e: self.logger.error(f"全量恢复失败: {str(e)}") return False def incremental_recovery(self, backup_dir, target_time): """增量恢复""" self.logger.info(f"开始增量恢复到时间点: {target_time}") try: binlog_files = [f for f in os.listdir(backup_dir) if f.startswith('mysql-bin.')] binlog_files.sort() for binlog_file in binlog_files: binlog_path = os.path.join(backup_dir, binlog_file) cmd = ['mysqlbinlog', '--stop-datetime=' + target_time, binlog_path] result = subprocess.run(cmd, capture_output=True, text=True) if result.returncode == 0: subprocess.run(['mysql', '-h', self.db_config['host'], '-u', self.db_config['user'], '-p' + self.db_config['password']], input=result.stdout, text=True, check=True) self.logger.info("增量恢复完成") return True except Exception as e: self.logger.error(f"增量恢复失败: {str(e)}") return False def table_recovery(self, database, table, backup_file): """表级恢复""" self.logger.info(f"开始表级恢复: {database}.{table}") try: backup_time = time.strftime('%Y%m%d_%H%M%S') backup_cmd = [ 'mysqldump', '-h', self.db_config['host'], '-u', self.db_config['user'], '-p' + self.db_config['password'], database, table ] with open(f'/tmp/{database}_{table}_backup_{backup_time}.sql', 'w') as f: subprocess.run(backup_cmd, stdout=f, check=True) conn = pymysql.connect(**self.db_config) cursor = conn.cursor() cursor.execute(f"DROP TABLE IF EXISTS {database}.{table}") conn.close() with open(backup_file, 'r') as f: subprocess.run(['mysql', '-h', self.db_config['host'], '-u', self.db_config['user'], '-p' + self.db_config['password']], stdin=f, check=True) self.logger.info("表级恢复完成") return True except Exception as e: self.logger.error(f"表级恢复失败: {str(e)}") return False def point_in_time_recovery(self, target_time): """点对点恢复""" self.logger.info(f"开始点对点恢复到: {target_time}") try: latest_backup = self.find_latest_backup() if not latest_backup: self.logger.error("未找到备份文件") return False if not self.full_recovery(latest_backup): return False backup_dir = os.path.dirname(latest_backup) if not self.incremental_recovery(backup_dir, target_time): return False self.logger.info("点对点恢复完成") return True except Exception as e: self.logger.error(f"点对点恢复失败: {str(e)}") return False def find_latest_backup(self): """查找最新备份""" try: backup_files = [] for root, dirs, files in os.walk(self.backup_dir): for file in files: if file.endswith('.sql'): backup_files.append(os.path.join(root, file)) if backup_files: latest_backup = max(backup_files, key=os.path.getmtime) return latest_backup return None except Exception as e: self.logger.error(f"查找备份文件失败: {str(e)}") return None def verify_recovery(self): """验证恢复结果""" self.logger.info("验证恢复结果...") try: conn = pymysql.connect(**self.db_config) cursor = conn.cursor() cursor.execute("SELECT 1") result = cursor.fetchone() if result[0] != 1: self.logger.error("数据库连接验证失败") return False cursor.execute("SHOW DATABASES") databases = cursor.fetchall() for db in databases: db_name = db[0] if db_name not in ['information_schema', 'performance_schema', 'mysql', 'sys']: cursor.execute(f"USE {db_name}") cursor.execute("SHOW TABLES") tables = cursor.fetchall() for table in tables: table_name = table[0] cursor.execute(f"CHECK TABLE {db_name}.{table_name}") check_result = cursor.fetchone() if check_result[2] != 'OK': self.logger.error(f"表 {db_name}.{table_name} 检查失败") return False conn.close() self.logger.info("恢复结果验证通过") return True except Exception as e: self.logger.error(f"恢复结果验证失败: {str(e)}") return False
if __name__ == "__main__": db_config = { 'host': '192.168.1.10', 'user': 'root', 'password': 'password', 'database': 'mysql' } backup_dir = '/backup/mysql' recovery_manager = DataRecoveryManager(db_config, backup_dir) recovery_type = "point_in_time" if recovery_type == "full": success = recovery_manager.full_recovery('/backup/mysql/20231201_120000/full_backup.sql') elif recovery_type == "incremental": success = recovery_manager.incremental_recovery('/backup/mysql/20231201_120000', '2023-12-01 12:00:00') elif recovery_type == "point_in_time": success = recovery_manager.point_in_time_recovery('2023-12-01 12:00:00') else: success = False if success: if recovery_manager.verify_recovery(): print("数据恢复成功") else: print("数据恢复验证失败") else: print("数据恢复失败")
|