BackupLogic.php 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822
  1. <?php
  2. namespace App\Module\Cleanup\Logics;
  3. use App\Module\Cleanup\Models\CleanupBackup;
  4. use App\Module\Cleanup\Models\CleanupBackupFile;
  5. use App\Module\Cleanup\Models\CleanupSqlBackup;
  6. use App\Module\Cleanup\Models\CleanupPlan;
  7. use App\Module\Cleanup\Models\CleanupTask;
  8. use App\Module\Cleanup\Enums\BACKUP_TYPE;
  9. use App\Module\Cleanup\Enums\BACKUP_STATUS;
  10. use App\Module\Cleanup\Enums\COMPRESSION_TYPE;
  11. use Illuminate\Support\Facades\DB;
  12. use Illuminate\Support\Facades\Log;
  13. use Illuminate\Support\Facades\Storage;
  14. use Illuminate\Support\Str;
  15. /**
  16. * 备份管理逻辑类
  17. *
  18. * 负责数据备份和恢复功能
  19. */
  20. class BackupLogic
  21. {
  22. /**
  23. * 为计划创建数据备份
  24. *
  25. * @param int $planId 计划ID
  26. * @param array $backupOptions 备份选项
  27. * @return array 备份结果
  28. */
  29. public static function createPlanBackup(int $planId, array $backupOptions = []): array
  30. {
  31. try {
  32. $plan = CleanupPlan::with('contents')->findOrFail($planId);
  33. // 验证备份选项
  34. $validatedOptions = static::validateBackupOptions($backupOptions);
  35. // 创建备份记录
  36. $backup = CleanupBackup::create([
  37. 'backup_name' => $validatedOptions['backup_name'] ?? "计划备份 - {$plan->plan_name}",
  38. 'plan_id' => $planId,
  39. 'backup_type' => $validatedOptions['backup_type'],
  40. 'compression_type' => $validatedOptions['compression_type'],
  41. 'status' => BACKUP_STATUS::PENDING->value,
  42. 'file_count' => 0,
  43. 'backup_size' => 0,
  44. 'created_by' => $validatedOptions['created_by'] ?? 0,
  45. ]);
  46. // 执行备份
  47. $result = static::performBackup($backup, $plan->contents->where('backup_enabled', true));
  48. return $result;
  49. } catch (\Exception $e) {
  50. Log::error('创建计划备份失败', [
  51. 'plan_id' => $planId,
  52. 'backup_options' => $backupOptions,
  53. 'error' => $e->getMessage(),
  54. 'trace' => $e->getTraceAsString()
  55. ]);
  56. return [
  57. 'success' => false,
  58. 'message' => '创建计划备份失败: ' . $e->getMessage(),
  59. 'data' => null
  60. ];
  61. }
  62. }
  63. /**
  64. * 为任务创建数据备份
  65. *
  66. * @param int $taskId 任务ID
  67. * @param array $backupOptions 备份选项
  68. * @return array 备份结果
  69. */
  70. public static function createTaskBackup(int $taskId, array $backupOptions = []): array
  71. {
  72. try {
  73. $task = CleanupTask::with('plan.contents')->findOrFail($taskId);
  74. if (!$task->plan) {
  75. throw new \Exception('任务关联的计划不存在');
  76. }
  77. // 验证备份选项
  78. $validatedOptions = static::validateBackupOptions($backupOptions);
  79. // 创建备份记录
  80. $backup = CleanupBackup::create([
  81. 'backup_name' => $validatedOptions['backup_name'] ?? "任务备份 - {$task->task_name}",
  82. 'task_id' => $taskId,
  83. 'plan_id' => $task->plan_id,
  84. 'backup_type' => $validatedOptions['backup_type'],
  85. 'compression_type' => $validatedOptions['compression_type'],
  86. 'status' => BACKUP_STATUS::PENDING->value,
  87. 'file_count' => 0,
  88. 'backup_size' => 0,
  89. 'created_by' => $validatedOptions['created_by'] ?? 0,
  90. ]);
  91. // 更新任务的备份ID
  92. $task->update(['backup_id' => $backup->id]);
  93. // 执行备份
  94. $result = static::performBackup($backup, $task->plan->contents->where('backup_enabled', true));
  95. return $result;
  96. } catch (\Exception $e) {
  97. Log::error('创建任务备份失败', [
  98. 'task_id' => $taskId,
  99. 'backup_options' => $backupOptions,
  100. 'error' => $e->getMessage(),
  101. 'trace' => $e->getTraceAsString()
  102. ]);
  103. return [
  104. 'success' => false,
  105. 'message' => '创建任务备份失败: ' . $e->getMessage(),
  106. 'data' => null
  107. ];
  108. }
  109. }
  110. /**
  111. * 执行备份操作
  112. *
  113. * @param CleanupBackup $backup 备份记录
  114. * @param \Illuminate\Support\Collection $contents 内容集合
  115. * @return array 备份结果
  116. */
  117. private static function performBackup(CleanupBackup $backup, $contents): array
  118. {
  119. $startTime = microtime(true);
  120. $totalSize = 0;
  121. $fileCount = 0;
  122. $errors = [];
  123. try {
  124. // 更新备份状态为进行中
  125. $backup->update([
  126. 'status' => BACKUP_STATUS::RUNNING->value,
  127. 'started_at' => now(),
  128. ]);
  129. $backupType = BACKUP_TYPE::from($backup->backup_type);
  130. $compressionType = COMPRESSION_TYPE::from($backup->compression_type);
  131. foreach ($contents as $content) {
  132. try {
  133. $result = static::backupTable($backup, $content->table_name, $backupType, $compressionType);
  134. if ($result['success']) {
  135. $totalSize += $result['file_size'];
  136. $fileCount++;
  137. } else {
  138. $errors[] = "表 {$content->table_name}: " . $result['message'];
  139. }
  140. } catch (\Exception $e) {
  141. $errors[] = "表 {$content->table_name}: " . $e->getMessage();
  142. Log::error("备份表失败", [
  143. 'backup_id' => $backup->id,
  144. 'table_name' => $content->table_name,
  145. 'error' => $e->getMessage()
  146. ]);
  147. }
  148. }
  149. $executionTime = round(microtime(true) - $startTime, 3);
  150. // 更新备份完成状态
  151. $finalStatus = empty($errors) ? BACKUP_STATUS::COMPLETED : BACKUP_STATUS::FAILED;
  152. $backup->update([
  153. 'status' => $finalStatus->value,
  154. 'file_count' => $fileCount,
  155. 'backup_size' => $totalSize,
  156. 'execution_time' => $executionTime,
  157. 'completed_at' => now(),
  158. 'error_message' => empty($errors) ? null : implode('; ', $errors),
  159. ]);
  160. return [
  161. 'success' => $finalStatus === BACKUP_STATUS::COMPLETED,
  162. 'message' => $finalStatus === BACKUP_STATUS::COMPLETED ? '备份创建成功' : '备份创建完成,但有错误',
  163. 'data' => [
  164. 'backup_id' => $backup->id,
  165. 'backup_name' => $backup->backup_name,
  166. 'file_count' => $fileCount,
  167. 'backup_size' => $totalSize,
  168. 'execution_time' => $executionTime,
  169. 'errors' => $errors,
  170. ]
  171. ];
  172. } catch (\Exception $e) {
  173. // 更新备份失败状态
  174. $backup->update([
  175. 'status' => BACKUP_STATUS::FAILED->value,
  176. 'execution_time' => round(microtime(true) - $startTime, 3),
  177. 'completed_at' => now(),
  178. 'error_message' => $e->getMessage(),
  179. ]);
  180. throw $e;
  181. }
  182. }
  183. /**
  184. * 备份单个表
  185. *
  186. * @param CleanupBackup $backup 备份记录
  187. * @param string $tableName 表名
  188. * @param BACKUP_TYPE $backupType 备份类型
  189. * @param COMPRESSION_TYPE $compressionType 压缩类型
  190. * @return array 备份结果
  191. */
  192. private static function backupTable(CleanupBackup $backup, string $tableName, BACKUP_TYPE $backupType, COMPRESSION_TYPE $compressionType): array
  193. {
  194. try {
  195. // 数据库备份类型直接存储到数据库
  196. if ($backupType === BACKUP_TYPE::DATABASE) {
  197. return static::backupTableToDatabase($backup, $tableName);
  198. }
  199. // 生成备份文件名
  200. $fileName = static::generateBackupFileName($backup, $tableName, $backupType);
  201. $filePath = "cleanup/backups/{$backup->id}/{$fileName}";
  202. // 根据备份类型执行备份
  203. $content = match ($backupType) {
  204. BACKUP_TYPE::SQL => static::exportTableToSQL($tableName),
  205. BACKUP_TYPE::JSON => static::exportTableToJSON($tableName),
  206. BACKUP_TYPE::CSV => static::exportTableToCSV($tableName),
  207. };
  208. // 压缩内容(如果需要)
  209. if ($compressionType !== COMPRESSION_TYPE::NONE) {
  210. $content = static::compressContent($content, $compressionType);
  211. $fileName .= static::getCompressionExtension($compressionType);
  212. $filePath .= static::getCompressionExtension($compressionType);
  213. }
  214. // 保存文件
  215. Storage::disk('local')->put($filePath, $content);
  216. $fileSize = Storage::disk('local')->size($filePath);
  217. // 计算文件哈希
  218. $fileHash = hash('sha256', $content);
  219. // 记录备份文件
  220. CleanupBackupFile::create([
  221. 'backup_id' => $backup->id,
  222. 'table_name' => $tableName,
  223. 'file_name' => $fileName,
  224. 'file_path' => $filePath,
  225. 'file_size' => $fileSize,
  226. 'file_hash' => $fileHash,
  227. 'backup_type' => $backupType->value,
  228. 'compression_type' => $compressionType->value,
  229. ]);
  230. return [
  231. 'success' => true,
  232. 'message' => "表 {$tableName} 备份成功",
  233. 'file_size' => $fileSize,
  234. 'file_path' => $filePath,
  235. ];
  236. } catch (\Exception $e) {
  237. return [
  238. 'success' => false,
  239. 'message' => $e->getMessage(),
  240. 'file_size' => 0,
  241. ];
  242. }
  243. }
  244. /**
  245. * 导出表为SQL格式
  246. *
  247. * @param string $tableName 表名
  248. * @return string SQL内容
  249. */
  250. private static function exportTableToSQL(string $tableName): string
  251. {
  252. $sql = "-- 表 {$tableName} 的数据备份\n";
  253. $sql .= "-- 备份时间: " . now()->toDateTimeString() . "\n\n";
  254. // 获取表结构
  255. $createTable = DB::select("SHOW CREATE TABLE `{$tableName}`")[0];
  256. $sql .= $createTable->{'Create Table'} . ";\n\n";
  257. // 获取表数据
  258. $records = DB::table($tableName)->get();
  259. if ($records->isNotEmpty()) {
  260. $sql .= "-- 数据插入\n";
  261. $sql .= "INSERT INTO `{$tableName}` VALUES\n";
  262. $values = [];
  263. foreach ($records as $record) {
  264. $recordArray = (array) $record;
  265. $escapedValues = array_map(function ($value) {
  266. return $value === null ? 'NULL' : "'" . addslashes($value) . "'";
  267. }, $recordArray);
  268. $values[] = '(' . implode(', ', $escapedValues) . ')';
  269. }
  270. $sql .= implode(",\n", $values) . ";\n";
  271. }
  272. return $sql;
  273. }
  274. /**
  275. * 导出表为JSON格式
  276. *
  277. * @param string $tableName 表名
  278. * @return string JSON内容
  279. */
  280. private static function exportTableToJSON(string $tableName): string
  281. {
  282. $data = [
  283. 'table_name' => $tableName,
  284. 'backup_time' => now()->toDateTimeString(),
  285. 'records' => DB::table($tableName)->get()->toArray(),
  286. ];
  287. return json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
  288. }
  289. /**
  290. * 导出表为CSV格式
  291. *
  292. * @param string $tableName 表名
  293. * @return string CSV内容
  294. */
  295. private static function exportTableToCSV(string $tableName): string
  296. {
  297. $records = DB::table($tableName)->get();
  298. if ($records->isEmpty()) {
  299. return '';
  300. }
  301. $csv = '';
  302. $headers = array_keys((array) $records->first());
  303. $csv .= implode(',', $headers) . "\n";
  304. foreach ($records as $record) {
  305. $recordArray = (array) $record;
  306. $escapedValues = array_map(function ($value) {
  307. return '"' . str_replace('"', '""', $value ?? '') . '"';
  308. }, $recordArray);
  309. $csv .= implode(',', $escapedValues) . "\n";
  310. }
  311. return $csv;
  312. }
  313. /**
  314. * 备份表到数据库
  315. *
  316. * @param CleanupBackup $backup 备份记录
  317. * @param string $tableName 表名
  318. * @return array 备份结果
  319. */
  320. private static function backupTableToDatabase(CleanupBackup $backup, string $tableName): array
  321. {
  322. try {
  323. // 获取表数据
  324. $records = DB::table($tableName)->get();
  325. if ($records->isEmpty()) {
  326. // 即使没有数据也创建记录,记录表结构
  327. $sqlContent = "-- 表 {$tableName} 的数据备份\n";
  328. $sqlContent .= "-- 备份时间: " . now()->toDateTimeString() . "\n";
  329. $sqlContent .= "-- 该表无数据记录\n\n";
  330. // 获取表结构
  331. $createTable = DB::select("SHOW CREATE TABLE `{$tableName}`")[0];
  332. $sqlContent .= $createTable->{'Create Table'} . ";\n";
  333. $recordsCount = 0;
  334. } else {
  335. // 生成INSERT语句
  336. $sqlContent = static::generateInsertStatements($tableName, $records);
  337. $recordsCount = $records->count();
  338. }
  339. $contentSize = strlen($sqlContent);
  340. $contentHash = hash('sha256', $sqlContent);
  341. // 保存到数据库
  342. CleanupSqlBackup::create([
  343. 'backup_id' => $backup->id,
  344. 'table_name' => $tableName,
  345. 'sql_content' => $sqlContent,
  346. 'records_count' => $recordsCount,
  347. 'content_size' => $contentSize,
  348. 'content_hash' => $contentHash,
  349. 'backup_conditions' => null, // 暂时不支持条件备份
  350. ]);
  351. return [
  352. 'success' => true,
  353. 'message' => "表 {$tableName} 数据库备份成功",
  354. 'file_size' => $contentSize, // 用内容大小代替文件大小
  355. 'records_count' => $recordsCount,
  356. ];
  357. } catch (\Exception $e) {
  358. return [
  359. 'success' => false,
  360. 'message' => $e->getMessage(),
  361. 'file_size' => 0,
  362. 'records_count' => 0,
  363. ];
  364. }
  365. }
  366. /**
  367. * 生成INSERT语句
  368. *
  369. * @param string $tableName 表名
  370. * @param \Illuminate\Support\Collection $records 记录集合
  371. * @return string SQL内容
  372. */
  373. private static function generateInsertStatements(string $tableName, $records): string
  374. {
  375. $sql = "-- 表 {$tableName} 的数据备份\n";
  376. $sql .= "-- 备份时间: " . now()->toDateTimeString() . "\n";
  377. $sql .= "-- 记录数量: " . $records->count() . "\n\n";
  378. // 获取表结构
  379. $createTable = DB::select("SHOW CREATE TABLE `{$tableName}`")[0];
  380. $sql .= $createTable->{'Create Table'} . ";\n\n";
  381. // 生成INSERT语句
  382. if ($records->isNotEmpty()) {
  383. $sql .= "-- 数据插入\n";
  384. // 获取字段名
  385. $firstRecord = (array) $records->first();
  386. $columns = array_keys($firstRecord);
  387. $columnList = '`' . implode('`, `', $columns) . '`';
  388. $sql .= "INSERT INTO `{$tableName}` ({$columnList}) VALUES\n";
  389. $values = [];
  390. foreach ($records as $record) {
  391. $recordArray = (array) $record;
  392. $escapedValues = array_map(function ($value) {
  393. if ($value === null) {
  394. return 'NULL';
  395. } elseif (is_numeric($value)) {
  396. return $value;
  397. } else {
  398. return "'" . addslashes($value) . "'";
  399. }
  400. }, $recordArray);
  401. $values[] = '(' . implode(', ', $escapedValues) . ')';
  402. }
  403. $sql .= implode(",\n", $values) . ";\n";
  404. }
  405. return $sql;
  406. }
  407. /**
  408. * 压缩内容
  409. *
  410. * @param string $content 原始内容
  411. * @param COMPRESSION_TYPE $compressionType 压缩类型
  412. * @return string 压缩后的内容
  413. */
  414. private static function compressContent(string $content, COMPRESSION_TYPE $compressionType): string
  415. {
  416. return match ($compressionType) {
  417. COMPRESSION_TYPE::GZIP => gzencode($content),
  418. COMPRESSION_TYPE::ZIP => static::createZipContent($content),
  419. default => $content,
  420. };
  421. }
  422. /**
  423. * 创建ZIP内容
  424. *
  425. * @param string $content 原始内容
  426. * @return string ZIP内容
  427. */
  428. private static function createZipContent(string $content): string
  429. {
  430. $zip = new \ZipArchive();
  431. $tempFile = tempnam(sys_get_temp_dir(), 'backup_');
  432. if ($zip->open($tempFile, \ZipArchive::CREATE) === TRUE) {
  433. $zip->addFromString('data.sql', $content);
  434. $zip->close();
  435. $zipContent = file_get_contents($tempFile);
  436. unlink($tempFile);
  437. return $zipContent;
  438. }
  439. throw new \Exception('创建ZIP文件失败');
  440. }
  441. /**
  442. * 获取压缩扩展名
  443. *
  444. * @param COMPRESSION_TYPE $compressionType 压缩类型
  445. * @return string 扩展名
  446. */
  447. private static function getCompressionExtension(COMPRESSION_TYPE $compressionType): string
  448. {
  449. return match ($compressionType) {
  450. COMPRESSION_TYPE::GZIP => '.gz',
  451. COMPRESSION_TYPE::ZIP => '.zip',
  452. default => '',
  453. };
  454. }
  455. /**
  456. * 生成备份文件名
  457. *
  458. * @param CleanupBackup $backup 备份记录
  459. * @param string $tableName 表名
  460. * @param BACKUP_TYPE $backupType 备份类型
  461. * @return string 文件名
  462. */
  463. private static function generateBackupFileName(CleanupBackup $backup, string $tableName, BACKUP_TYPE $backupType): string
  464. {
  465. $timestamp = now()->format('Y-m-d_H-i-s');
  466. $extension = match ($backupType) {
  467. BACKUP_TYPE::SQL => '.sql',
  468. BACKUP_TYPE::JSON => '.json',
  469. BACKUP_TYPE::CSV => '.csv',
  470. };
  471. return "{$tableName}_{$timestamp}{$extension}";
  472. }
  473. /**
  474. * 验证备份选项
  475. *
  476. * @param array $backupOptions 备份选项
  477. * @return array 验证后的选项
  478. */
  479. private static function validateBackupOptions(array $backupOptions): array
  480. {
  481. return [
  482. 'backup_name' => $backupOptions['backup_name'] ?? null,
  483. 'backup_type' => $backupOptions['backup_type'] ?? BACKUP_TYPE::SQL->value,
  484. 'compression_type' => $backupOptions['compression_type'] ?? COMPRESSION_TYPE::GZIP->value,
  485. 'created_by' => $backupOptions['created_by'] ?? 0,
  486. ];
  487. }
  488. /**
  489. * 清理过期备份
  490. *
  491. * @param int $retentionDays 保留天数
  492. * @return array 清理结果
  493. */
  494. public static function cleanExpiredBackups(int $retentionDays = 30): array
  495. {
  496. try {
  497. $expiredDate = now()->subDays($retentionDays);
  498. // 获取过期的备份
  499. $expiredBackups = CleanupBackup::where('created_at', '<', $expiredDate)
  500. ->where('status', BACKUP_STATUS::COMPLETED->value)
  501. ->get();
  502. $deletedCount = 0;
  503. $freedSpace = 0;
  504. $errors = [];
  505. foreach ($expiredBackups as $backup) {
  506. try {
  507. $result = static::deleteBackup($backup->id);
  508. if ($result['success']) {
  509. $deletedCount++;
  510. $freedSpace += $backup->backup_size;
  511. } else {
  512. $errors[] = "备份 {$backup->id}: " . $result['message'];
  513. }
  514. } catch (\Exception $e) {
  515. $errors[] = "备份 {$backup->id}: " . $e->getMessage();
  516. }
  517. }
  518. return [
  519. 'success' => true,
  520. 'message' => "清理完成,删除 {$deletedCount} 个过期备份",
  521. 'data' => [
  522. 'deleted_count' => $deletedCount,
  523. 'total_expired' => $expiredBackups->count(),
  524. 'freed_space' => $freedSpace,
  525. 'errors' => $errors,
  526. ]
  527. ];
  528. } catch (\Exception $e) {
  529. Log::error('清理过期备份失败', [
  530. 'retention_days' => $retentionDays,
  531. 'error' => $e->getMessage()
  532. ]);
  533. return [
  534. 'success' => false,
  535. 'message' => '清理过期备份失败: ' . $e->getMessage(),
  536. 'data' => null
  537. ];
  538. }
  539. }
  540. /**
  541. * 删除备份
  542. *
  543. * @param int $backupId 备份ID
  544. * @return array 删除结果
  545. */
  546. public static function deleteBackup(int $backupId): array
  547. {
  548. try {
  549. DB::beginTransaction();
  550. $backup = CleanupBackup::with(['files', 'sqlBackups'])->findOrFail($backupId);
  551. // 删除备份文件
  552. foreach ($backup->files as $file) {
  553. try {
  554. if (Storage::disk('local')->exists($file->file_path)) {
  555. Storage::disk('local')->delete($file->file_path);
  556. }
  557. } catch (\Exception $e) {
  558. Log::warning('删除备份文件失败', [
  559. 'file_path' => $file->file_path,
  560. 'error' => $e->getMessage()
  561. ]);
  562. }
  563. }
  564. // 删除备份文件记录
  565. $backup->files()->delete();
  566. // 删除SQL备份记录
  567. $backup->sqlBackups()->delete();
  568. // 删除备份记录
  569. $backup->delete();
  570. DB::commit();
  571. return [
  572. 'success' => true,
  573. 'message' => '备份删除成功',
  574. 'data' => [
  575. 'backup_id' => $backupId,
  576. 'deleted_files' => $backup->files->count(),
  577. ]
  578. ];
  579. } catch (\Exception $e) {
  580. DB::rollBack();
  581. Log::error('删除备份失败', [
  582. 'backup_id' => $backupId,
  583. 'error' => $e->getMessage()
  584. ]);
  585. return [
  586. 'success' => false,
  587. 'message' => '删除备份失败: ' . $e->getMessage(),
  588. 'data' => null
  589. ];
  590. }
  591. }
  592. /**
  593. * 获取备份详情
  594. *
  595. * @param int $backupId 备份ID
  596. * @return array 备份详情
  597. */
  598. public static function getBackupDetails(int $backupId): array
  599. {
  600. try {
  601. $backup = CleanupBackup::with(['files', 'plan', 'task'])->findOrFail($backupId);
  602. return [
  603. 'success' => true,
  604. 'data' => [
  605. 'backup' => [
  606. 'id' => $backup->id,
  607. 'backup_name' => $backup->backup_name,
  608. 'backup_type' => $backup->backup_type,
  609. 'backup_type_name' => BACKUP_TYPE::from($backup->backup_type)->getDescription(),
  610. 'compression_type' => $backup->compression_type,
  611. 'compression_type_name' => COMPRESSION_TYPE::from($backup->compression_type)->getDescription(),
  612. 'status' => $backup->status,
  613. 'status_name' => BACKUP_STATUS::from($backup->status)->getDescription(),
  614. 'file_count' => $backup->file_count,
  615. 'backup_size' => $backup->backup_size,
  616. 'execution_time' => $backup->execution_time,
  617. 'started_at' => $backup->started_at,
  618. 'completed_at' => $backup->completed_at,
  619. 'error_message' => $backup->error_message,
  620. 'created_at' => $backup->created_at,
  621. ],
  622. 'files' => $backup->files->map(function ($file) {
  623. return [
  624. 'id' => $file->id,
  625. 'table_name' => $file->table_name,
  626. 'file_name' => $file->file_name,
  627. 'file_size' => $file->file_size,
  628. 'file_hash' => $file->file_hash,
  629. 'backup_type' => $file->backup_type,
  630. 'compression_type' => $file->compression_type,
  631. ];
  632. }),
  633. 'plan' => $backup->plan ? [
  634. 'id' => $backup->plan->id,
  635. 'plan_name' => $backup->plan->plan_name,
  636. ] : null,
  637. 'task' => $backup->task ? [
  638. 'id' => $backup->task->id,
  639. 'task_name' => $backup->task->task_name,
  640. ] : null,
  641. ]
  642. ];
  643. } catch (\Exception $e) {
  644. Log::error('获取备份详情失败', [
  645. 'backup_id' => $backupId,
  646. 'error' => $e->getMessage()
  647. ]);
  648. return [
  649. 'success' => false,
  650. 'message' => '获取备份详情失败: ' . $e->getMessage(),
  651. 'data' => null
  652. ];
  653. }
  654. }
  655. /**
  656. * 验证备份完整性
  657. *
  658. * @param int $backupId 备份ID
  659. * @return array 验证结果
  660. */
  661. public static function verifyBackupIntegrity(int $backupId): array
  662. {
  663. try {
  664. $backup = CleanupBackup::with('files')->findOrFail($backupId);
  665. $verifiedFiles = 0;
  666. $corruptedFiles = 0;
  667. $missingFiles = 0;
  668. $errors = [];
  669. foreach ($backup->files as $file) {
  670. try {
  671. if (!Storage::disk('local')->exists($file->file_path)) {
  672. $missingFiles++;
  673. $errors[] = "文件缺失: {$file->file_name}";
  674. continue;
  675. }
  676. $content = Storage::disk('local')->get($file->file_path);
  677. $currentHash = hash('sha256', $content);
  678. if ($currentHash === $file->file_hash) {
  679. $verifiedFiles++;
  680. } else {
  681. $corruptedFiles++;
  682. $errors[] = "文件损坏: {$file->file_name}";
  683. }
  684. } catch (\Exception $e) {
  685. $errors[] = "验证失败: {$file->file_name} - " . $e->getMessage();
  686. }
  687. }
  688. $isIntact = $corruptedFiles === 0 && $missingFiles === 0;
  689. return [
  690. 'success' => true,
  691. 'data' => [
  692. 'backup_id' => $backupId,
  693. 'is_intact' => $isIntact,
  694. 'total_files' => $backup->files->count(),
  695. 'verified_files' => $verifiedFiles,
  696. 'corrupted_files' => $corruptedFiles,
  697. 'missing_files' => $missingFiles,
  698. 'errors' => $errors,
  699. ]
  700. ];
  701. } catch (\Exception $e) {
  702. Log::error('验证备份完整性失败', [
  703. 'backup_id' => $backupId,
  704. 'error' => $e->getMessage()
  705. ]);
  706. return [
  707. 'success' => false,
  708. 'message' => '验证备份完整性失败: ' . $e->getMessage(),
  709. 'data' => null
  710. ];
  711. }
  712. }
  713. }