delete_old_file.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package client
  2. import (
  3. "backup-x/entity"
  4. "backup-x/util"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "strconv"
  9. "time"
  10. )
  11. // DeleteOldBackup for client
  12. func DeleteOldBackup() {
  13. for {
  14. delay := util.GetDelaySeconds(2)
  15. log.Printf("删除过期的备份文件将在 %.1f 小时后运行\n", delay.Hours())
  16. time.Sleep(delay)
  17. conf, err := entity.GetConfigCache()
  18. if err != nil {
  19. return
  20. }
  21. for _, backupConf := range conf.BackupConfig {
  22. if !backupConf.NotEmptyProject() {
  23. continue
  24. }
  25. // read from current path
  26. backupFiles, err := ioutil.ReadDir(backupConf.GetProjectPath())
  27. if err != nil {
  28. log.Printf("读取项目 %s 目录失败! ERR: %s\n", backupConf.ProjectName, err)
  29. continue
  30. }
  31. // delete client files
  32. subDuration, _ := time.ParseDuration("-" + strconv.Itoa(backupConf.SaveDays*24) + "h")
  33. before := time.Now().Add(subDuration)
  34. // delete older file when file numbers gt MaxSaveDays
  35. for _, backupFile := range backupFiles {
  36. if backupFile.ModTime().Before(before) {
  37. filepath := backupConf.GetProjectPath() + string(os.PathSeparator) + backupFile.Name()
  38. err := os.Remove(filepath)
  39. if err != nil {
  40. log.Printf("删除过期的文件 %s 失败", filepath)
  41. } else {
  42. log.Printf("删除过期的文件 %s 成功", filepath)
  43. }
  44. }
  45. }
  46. }
  47. }
  48. }