BackupsService.php 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. <?php
  2. namespace backend\modules\admin\services;
  3. use common\enums\RabbitMqEnum;
  4. use common\models\common\Backups;
  5. use Exception;
  6. use Yii;
  7. /**
  8. * 数据备份
  9. * @package backend\modules\admin\services
  10. */
  11. class BackupsService extends BaseService
  12. {
  13. //获取备份数据列表
  14. public function getBackupsList($params)
  15. {
  16. try {
  17. $where = [
  18. ['!=', 'status', -1]
  19. ];
  20. if (!empty($params['datetime'][0])) $where[] = ['>=', 'created_at', strtotime($params['datetime'][0])];
  21. if (!empty($params['datetime'][1])) $where[] = ['<=', 'created_at', strtotime($params['datetime'][1]. ' 23:59:59')];
  22. $params['where'] = $where;
  23. $params['order'] = 'id desc';
  24. $list = Backups::listPage($params);
  25. return $list;
  26. } catch (\Exception $e) {
  27. throw new Exception($e->getMessage());
  28. }
  29. }
  30. //开始备份
  31. public function startBackups()
  32. {
  33. try {
  34. $check = Backups::getOne([
  35. ['status' => 0],
  36. ], true);
  37. if (!empty($check)) throw new Exception('存在备份中任务,请稍后再试');
  38. $data = [
  39. 'name' => 'mysql-'. date('Y-m-d-H-i').'.sql.gz',
  40. 'size' => '',
  41. 'status' => 0,
  42. 'type' => 1,
  43. ];
  44. $res = Backups::setData($data);
  45. if (!$res) throw new Exception(Backups::$static_error);
  46. Yii::$app->services->rabbitMq->push(RabbitMqEnum::EXCHANGE_LONG_DURATION, RabbitMqEnum::LONG_DURATION_QUEUE, ['id' => $res->id], BackupsService::class, 'backupsData');
  47. return true;
  48. } catch (\Exception $e) {
  49. throw new Exception($e->getMessage());
  50. }
  51. }
  52. //删除备份文件
  53. public function deleteBackups($params)
  54. {
  55. try {
  56. // $ids = explode(',', $params['id']);
  57. $where = [
  58. ['!=', 'status', -1]
  59. ];
  60. if (!empty($params['id'])) $where[] = ['id' => $params['id']];
  61. $list = Backups::lists(['where' => $where]);
  62. if (!empty($list)) {
  63. $ids = array_column($list, 'id');
  64. $res = Backups::updateAll(['status' => -1], ['id' => $ids]);
  65. if (!$res) throw new Exception(Backups::$static_error);
  66. foreach ($list as $key => $value) {
  67. if (!empty($value['url'])) {
  68. unlink($value['url']);
  69. }
  70. }
  71. }
  72. } catch (\Exception $e) {
  73. throw new Exception($e->getMessage());
  74. }
  75. }
  76. //执行备份脚本
  77. public function backupsData($params)
  78. {
  79. try {
  80. if (is_dir('/www/wwwroot/qimall')) {
  81. $path = '/www/wwwroot/qimall/backend/web/uploads/backups';
  82. } else {
  83. $path = '/data/wwwroot/qimall/backend/web/uploads/backups';
  84. }
  85. if (!is_dir($path)) {
  86. @mkdir($path, 0777, true);
  87. }
  88. $info = Backups::getOne([
  89. ['id' => $params['id']],
  90. ]);
  91. if (!is_dir('/data')) @mkdir('/data', 0777, true);
  92. if (!is_dir('/data/bak')) @mkdir('/data/bak', 0777, true);
  93. if (!is_dir('/data/bak/mysql')) @mkdir('/data/bak/mysql', 0777, true);
  94. //执行数据库备份脚本
  95. exec('sudo sh /scripts/bak_db.sh 2>&1', $result, $status);
  96. if (!empty($result)) {
  97. foreach ($result as $key => $value) {
  98. if (strpos($value, 'Error') !== false) {
  99. throw new Exception( json_encode($value) );
  100. }
  101. }
  102. }
  103. // if( $status ) throw new Exception( json_encode($result) );
  104. echo '数据备份--数据库备份脚本执行完成';
  105. $url = $path .'/'.$info['name'];
  106. $source_path = '';
  107. if (file_exists('/data/bak/mysql/qimall-'.date('Y-m-d-H').'.sql.gz')) {
  108. echo '数据备份--查找备份文件成功';
  109. $source_path = '/data/bak/mysql/qimall-'.date('Y-m-d-H').'.sql.gz';
  110. } else {
  111. $time = time() - 3600;
  112. $source_path = '/data/bak/mysql/qimall-'.date('Y-m-d-H', $time).'.sql.gz';
  113. }
  114. echo '数据备份--'.$source_path;
  115. if (copy($source_path, $url)) {
  116. chmod($url, 0777);
  117. $info->url = $url;
  118. $info->status = 1;
  119. $info->size = file_exists($url) ? $this->transf_byte(filesize($url)) : 0;
  120. } else {
  121. echo '数据备份--copy备份文件失败';
  122. throw new Exception('copy备份文件失败');
  123. }
  124. // print_r($info);
  125. echo '数据备份--copy备份文件成功';
  126. if (!$info->save()) throw new Exception('保存数据失败');
  127. //获取全部备份数据
  128. $list = Backups::lists([
  129. 'where' => [
  130. ['!=', 'status', -1],
  131. ],
  132. 'order' => 'id desc',
  133. ]);
  134. if (!empty($list)) {
  135. $ids = [];
  136. foreach ($list as $key => $value) {
  137. if ($key >= 7) {
  138. $ids[] = $value['id'];
  139. }
  140. }
  141. //存在数据,则清除备份数据
  142. if (!empty($ids)) $this->deleteBackups(['id' => $ids]);
  143. }
  144. } catch (\Exception $e) {
  145. echo '数据备份--'.$e->getMessage();
  146. // print_r($e->getMessage());
  147. $info->status = 2;
  148. $info->desc = $e->getMessage();
  149. $info->save();
  150. Yii::error($e->getMessage());
  151. throw new Exception($e->getMessage());
  152. }
  153. }
  154. public function transf_byte($byte) {
  155. $kb = 1024;
  156. $mb = $kb * 1024;
  157. $gb = $mb * 1024;
  158. if ($byte < $kb) {
  159. return $byte . 'b';
  160. } else if ($byte < $mb) {
  161. return round($byte / $kb, 2) . 'kb';
  162. } else if ($byte < $gb) {
  163. return round($byte / $mb, 2) . 'mb';
  164. }
  165. }
  166. }