SceneCleanOrigServiceImpl.java 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package com.fdkankan.scene.service.impl;
  2. import cn.hutool.core.collection.CollUtil;
  3. import cn.hutool.core.exceptions.ExceptionUtil;
  4. import cn.hutool.core.util.StrUtil;
  5. import com.alibaba.fastjson.JSON;
  6. import com.alibaba.fastjson.JSONObject;
  7. import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
  8. import com.fdkankan.common.constant.CommonStatus;
  9. import com.fdkankan.common.constant.CommonSuccessStatus;
  10. import com.fdkankan.common.constant.ErrorCode;
  11. import com.fdkankan.common.constant.OperationType;
  12. import com.fdkankan.common.exception.BusinessException;
  13. import com.fdkankan.fyun.config.FYunFileConfig;
  14. import com.fdkankan.fyun.constant.FYunTypeEnum;
  15. import com.fdkankan.fyun.face.FYunFileServiceInterface;
  16. import com.fdkankan.model.constants.ConstantFilePath;
  17. import com.fdkankan.model.constants.UploadFilePath;
  18. import com.fdkankan.model.utils.SceneUtil;
  19. import com.fdkankan.redis.constant.RedisKey;
  20. import com.fdkankan.redis.util.RedisUtil;
  21. import com.fdkankan.scene.bean.SceneBean;
  22. import com.fdkankan.scene.entity.Camera;
  23. import com.fdkankan.scene.entity.SceneCleanOrig;
  24. import com.fdkankan.scene.mapper.ISceneCleanOrigMapper;
  25. import com.fdkankan.scene.mapper.IScenePlusExtMapper;
  26. import com.fdkankan.scene.service.*;
  27. import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
  28. import lombok.extern.slf4j.Slf4j;
  29. import org.springframework.beans.factory.annotation.Autowired;
  30. import org.springframework.beans.factory.annotation.Value;
  31. import org.springframework.cloud.context.config.annotation.RefreshScope;
  32. import org.springframework.stereotype.Service;
  33. import sun.font.TextRecord;
  34. import java.util.*;
  35. import java.util.stream.Collectors;
  36. /**
  37. * <p>
  38. * 删除oss原始资源记录 服务实现类
  39. * </p>
  40. *
  41. * @author
  42. * @since 2023-03-29
  43. */
  44. @RefreshScope
  45. @Slf4j
  46. @Service
  47. public class SceneCleanOrigServiceImpl extends ServiceImpl<ISceneCleanOrigMapper, SceneCleanOrig> implements ISceneCleanOrigService {
  48. @Value("${scene.cleanOrig.month:#{120}}")
  49. private Integer cleanOrigMonth;
  50. @Value("${scene.coldStorage.month:#{120}}")
  51. private Integer coldStorageMonth;
  52. @Value("${scene.cleanDeleted.month:#{120}}")
  53. private Integer cleanDeletedMonth;
  54. @Value("#{'${scene.cleanTestCamera.snCode:}'.split(',')}")
  55. private List<String> testSnCodeList;
  56. @Value("${scene.cleanTestCamera.month:#{120}}")
  57. private Integer cleanTestCameraMonth;
  58. @Value("${fyun.bucket}")
  59. private String bucket;
  60. @Value("${fyun.coldBucket:#{null}}")
  61. private String coldBucket;
  62. @Autowired
  63. private ICameraService cameraService;
  64. @Autowired
  65. private ISceneColdStorageService sceneColdStorageService;
  66. @Autowired
  67. private FYunFileConfig fYunFileConfig;
  68. @Autowired
  69. private ISceneProService sceneProService;
  70. @Autowired
  71. private IScenePlusService scenePlusService;
  72. @Autowired
  73. private IScenePlusExtService scenePlusExtService;
  74. @Autowired
  75. private FYunFileServiceInterface fYunFileService;
  76. @Autowired
  77. private RedisUtil redisUtil;
  78. @Autowired
  79. private ISceneColdStorageLogService sceneColdStorageLogService;
  80. @Override
  81. public void cleanOrigV4() {
  82. //查询所有计算时间超过限定时间的场景,计算成功、未被删除、最后一次计算后未被删除过的
  83. List<SceneBean> sceneBeans = scenePlusService.listCleanOrigScene(cleanOrigMonth);
  84. this.cleanOrig(sceneBeans);
  85. }
  86. @Override
  87. public void cleanOrigV3() {
  88. //查询所有计算时间超过限定时间的场景,计算成功、未被删除
  89. List<SceneBean> sceneBeans = sceneProService.listCleanOrigScene(cleanOrigMonth);
  90. this.cleanOrig(sceneBeans);
  91. }
  92. private void cleanOrig(List<SceneBean> sceneBeans){
  93. if(CollUtil.isEmpty(sceneBeans)){
  94. return;
  95. }
  96. sceneBeans.parallelStream().forEach(scene->{
  97. boolean lock = this.lock(scene.getDataSource());
  98. try {
  99. if(lock) {
  100. this.cleanOrigHandler(scene);
  101. this.saveLog(scene.getNum(), 1, CommonSuccessStatus.SUCCESS.code(), null);
  102. }
  103. }catch (Exception e){
  104. log.error("删除原始资源失败,num : " + scene.getNum(), e);
  105. this.saveLog(scene.getNum(), 1, CommonSuccessStatus.FAIL.code(), ExceptionUtil.stacktraceToString(e, 3000));
  106. }finally {
  107. this.releaseLock(scene.getDataSource());
  108. }
  109. });
  110. }
  111. private void cleanOrigHandler(SceneBean scene){
  112. String dataSource = scene.getDataSource();
  113. if(StrUtil.isNotEmpty(dataSource)){
  114. String homePath = dataSource.replace(ConstantFilePath.BUILD_MODEL_PATH, ConstantFilePath.OSS_PREFIX);
  115. //由于国内测试和生产用的bucket是同一个,这里需要做一个安全校验,保证不会删错
  116. String fileContent = fYunFileService.getFileContent(homePath.concat("/").concat("data.fdage"));
  117. if(StrUtil.isNotBlank(fileContent)){
  118. JSONObject jsonObject = JSON.parseObject(fileContent);
  119. String snCode = jsonObject.getJSONObject("cam").getString("uuid");
  120. String uuidTime = jsonObject.getString("uuidtime");
  121. if(StrUtil.isEmpty(snCode)
  122. || StrUtil.isEmpty(uuidTime)
  123. || !homePath.contains(snCode)
  124. || !homePath.contains(uuidTime)){
  125. throw new RuntimeException("dataSource与data.fdage文件不匹配");
  126. }else{
  127. fYunFileService.deleteFolder(homePath);
  128. }
  129. }
  130. }
  131. }
  132. private void saveLog(String num, int type, int status, String reason){
  133. //清除旧的日志
  134. this.remove(new LambdaQueryWrapper<SceneCleanOrig>().eq(SceneCleanOrig::getNum, num));
  135. SceneCleanOrig sceneCleanOrig = new SceneCleanOrig();
  136. sceneCleanOrig.setNum(num);
  137. sceneCleanOrig.setType(type);
  138. sceneCleanOrig.setState(status);
  139. sceneCleanOrig.setReason(reason);
  140. this.saveOrUpdate(sceneCleanOrig);
  141. }
  142. private boolean lock(String dataSource){
  143. Map<String, String> property = SceneUtil.getPropertyFromDataSource(dataSource);
  144. String homePath = property.get("homePath");
  145. String uuid = property.get("uuid");
  146. String uploadLock = redisUtil.get(String.format(RedisKey.SCENE_OSS_HOME_DIR_UPLOAD, uuid));
  147. //场景正在上传,不删除
  148. if(StrUtil.isNotEmpty(uploadLock)){
  149. return false;
  150. }
  151. redisUtil.set(String.format(RedisKey.SCENE_OSS_HOME_DIR_DELETE, uuid), homePath, 8*60*60);
  152. return true;
  153. }
  154. private void releaseLock(String dataSource){
  155. Map<String, String> property = SceneUtil.getPropertyFromDataSource(dataSource);
  156. String uuid = property.get("uuid");
  157. redisUtil.del(String.format(RedisKey.SCENE_OSS_HOME_DIR_DELETE, uuid));
  158. }
  159. @Override
  160. public void cleanOss4DeletedSceneV3() {
  161. List<SceneBean> sceneBeans = sceneProService.listCleanOss4DeletedScene(cleanDeletedMonth);
  162. this.cleanOrig4Delete(sceneBeans, false, 2);
  163. }
  164. @Override
  165. public void cleanOss4DeletedSceneV4() {
  166. //查询所有计算时间超过限定时间的场景,计算成功、未被删除、最后一次计算后未被删除过的
  167. List<SceneBean> sceneBeans = scenePlusService.listCleanOss4DeletedScene(cleanDeletedMonth);
  168. this.cleanOrig4Delete(sceneBeans, true, 2);
  169. }
  170. /**
  171. * 删除已删除场景的原始资源及caches目录(v3场景不需要删除caches目录)
  172. * @param sceneBeans
  173. * @param deleteCaches 是否需要删除caches目录
  174. */
  175. private void cleanOrig4Delete(List<SceneBean> sceneBeans, boolean deleteCaches, Integer type){
  176. if(CollUtil.isEmpty(sceneBeans)){
  177. return;
  178. }
  179. sceneBeans.parallelStream().forEach(scene->{
  180. try {
  181. //删除caches文件
  182. if(deleteCaches){
  183. this.deleteResultCaches(scene.getNum());
  184. }
  185. //删除原始资源
  186. this.cleanOrigHandler(scene);
  187. this.saveLog(scene.getNum(), type, CommonSuccessStatus.SUCCESS.code(), null);
  188. }catch (Exception e){
  189. log.error("删除已删除场景资源失败,num : " + scene.getNum(), e);
  190. this.saveLog(scene.getNum(), type, CommonSuccessStatus.FAIL.code(), ExceptionUtil.stacktraceToString(e, 3000));
  191. }
  192. });
  193. }
  194. private void deleteResultCaches(String num){
  195. String cachesPath = String.format(UploadFilePath.scene_result_data_path, num).concat("caches");
  196. if(CollUtil.isEmpty(fYunFileService.listRemoteFiles(cachesPath))){
  197. return;
  198. }
  199. fYunFileService.deleteFolder(cachesPath);
  200. }
  201. @Override
  202. public void cleanOss4TestCameraV3() {
  203. List<Camera> cameras = cameraService.listBySnCodes(testSnCodeList);
  204. if(CollUtil.isEmpty(cameras)){
  205. return;
  206. }
  207. Set<Long> cameraIds = cameras.stream().map(Camera::getId).collect(Collectors.toSet());
  208. List<SceneBean> sceneBeans = sceneProService.listCleanOss4TestCamera(cameraIds, cleanTestCameraMonth);
  209. this.cleanOrig4Delete(sceneBeans, false, 3);
  210. }
  211. @Override
  212. public void cleanOss4TestCameraV4() {
  213. List<Camera> cameras = cameraService.listBySnCodes(testSnCodeList);
  214. if(CollUtil.isEmpty(cameras)){
  215. return;
  216. }
  217. Set<Long> cameraIds = cameras.stream().map(Camera::getId).collect(Collectors.toSet());
  218. List<SceneBean> sceneBeans = scenePlusService.listCleanOss4TestCamera(cameraIds, cleanTestCameraMonth);
  219. this.cleanOrig4Delete(sceneBeans, true, 3);
  220. }
  221. @Override
  222. public void coldStorageHomeV3() {
  223. //查询所有计算时间超过限定时间的场景,计算成功、未被删除
  224. List<SceneBean> sceneBeans = sceneProService.listColdStorageScene(coldStorageMonth);
  225. this.coldStorage(sceneBeans);
  226. }
  227. @Override
  228. public void coldStorageHomeV4() {
  229. //查询所有计算时间超过限定时间的场景,计算成功、未被删除
  230. List<SceneBean> sceneBeans = scenePlusService.listColdStorageScene(coldStorageMonth);
  231. this.coldStorage(sceneBeans);
  232. }
  233. private void coldStorage(List<SceneBean> sceneBeans){
  234. if(CollUtil.isEmpty(sceneBeans)){
  235. return;
  236. }
  237. sceneBeans.parallelStream().forEach(scene->{
  238. boolean lock = this.lock(scene.getDataSource());
  239. try {
  240. if(lock) {
  241. this.coldStorageHandler(scene);
  242. sceneColdStorageLogService.saveLog(scene.getNum(), scene.getDataSource(), 1, 1, null);
  243. sceneColdStorageService.save(scene.getNum(), 1, coldBucket, bucket);
  244. }
  245. }catch (Exception e){
  246. log.error("冷归档失败,num:{}" + scene.getNum(), e);
  247. sceneColdStorageLogService.saveLog(scene.getNum(), scene.getDataSource(),1, CommonSuccessStatus.FAIL.code(), ExceptionUtil.stacktraceToString(e, 3000));
  248. }finally {
  249. this.releaseLock(scene.getDataSource());
  250. }
  251. });
  252. }
  253. private void coldStorageHandler(SceneBean scene){
  254. String dataSource = scene.getDataSource();
  255. if(StrUtil.isEmpty(dataSource) || dataSource.length() < 10) {
  256. return;
  257. }
  258. String homePath = dataSource.replace(ConstantFilePath.BUILD_MODEL_PATH, ConstantFilePath.OSS_PREFIX);
  259. //将文件复制到冷归档bucket
  260. if(fYunFileConfig.getFyunType().equals(FYunTypeEnum.AWS.code())){
  261. fYunFileService.copyFileToArchive(bucket, homePath, coldBucket, homePath);
  262. }else{
  263. fYunFileService.copyFileBetweenBucket(bucket, homePath, coldBucket, homePath);
  264. }
  265. List<String> origList = fYunFileService.listRemoteFiles(bucket, homePath);
  266. List<String> coldList = fYunFileService.listRemoteFiles(coldBucket, homePath);
  267. if(origList.size() != coldList.size()){
  268. throw new RuntimeException("复制文件到冷归档bucket失败");
  269. }
  270. //删除标准bucket文件
  271. fYunFileService.deleteFolder(homePath);
  272. }
  273. }