SQLBackups.gd 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. extends Node
  2. class_name SQLBackups
  3. #
  4. var thread : Thread = Thread.new()
  5. var isRunning : bool = false
  6. var stopRequested : bool = false
  7. #
  8. func CreateBackup() -> void:
  9. var date : Dictionary = Time.get_datetime_dict_from_system()
  10. var backupFile : String = SQLCommons.GetBackupPath() + "%d-%02d-%02d_%02d-%02d-%02d" % [date.year, date.month, date.day, date.hour, date.minute, date.second] + Path.DBExt
  11. if Launcher.SQL.db.backup_to(backupFile):
  12. Util.PrintInfo("SQL", "Backup created: " + backupFile)
  13. else:
  14. Util.PrintLog("SQL", "Backup failed: " + backupFile)
  15. func PruneBackups() -> void:
  16. var dir : DirAccess = DirAccess.open(SQLCommons.GetBackupPath())
  17. if not dir:
  18. return
  19. var dirFiles : PackedStringArray = dir.get_files()
  20. var backupFiles : Array[String] = []
  21. for file in dirFiles:
  22. if file.get_extension() == "db":
  23. backupFiles.append(file)
  24. backupFiles.sort() # Oldest backups first
  25. while backupFiles.size() > SQLCommons.BackupLimit:
  26. var prunedFile : String = backupFiles.pop_front()
  27. var err : Error = dir.remove(prunedFile)
  28. if err == OK:
  29. Util.PrintInfo("SQL", "Backup removed: " + prunedFile)
  30. else:
  31. Util.PrintLog("SQL", "Backup removal failed: %s [%d]" % [prunedFile, err])
  32. #
  33. func Run():
  34. Thread.set_thread_safety_checks_enabled(false)
  35. var lastBackupTimestamp : int = SQLCommons.Timestamp()
  36. var lastPlayerUpdateTimestamp : int = SQLCommons.Timestamp()
  37. var lastStopCheckTimestamp : int = SQLCommons.Timestamp()
  38. while isRunning:
  39. var timestamp : int = SQLCommons.Timestamp()
  40. if timestamp - lastBackupTimestamp >= SQLCommons.BackupIntervalSec:
  41. CreateBackup()
  42. PruneBackups()
  43. lastBackupTimestamp = timestamp
  44. if timestamp - lastPlayerUpdateTimestamp >= SQLCommons.BackupPlayersSec:
  45. if Launcher.World:
  46. Launcher.World.BackupPlayers()
  47. lastPlayerUpdateTimestamp = timestamp
  48. if timestamp - lastStopCheckTimestamp >= SQLCommons.BackupCheckIntervalSec:
  49. if stopRequested:
  50. isRunning = false
  51. break
  52. lastStopCheckTimestamp = timestamp
  53. OS.delay_msec(100)
  54. func Start():
  55. if not isRunning:
  56. isRunning = true
  57. thread.start(Run, Thread.PRIORITY_LOW)
  58. func Stop():
  59. if isRunning and not stopRequested:
  60. stopRequested = true
  61. thread.wait_to_finish()
  62. #
  63. func _init():
  64. var backupPath : String = SQLCommons.GetBackupPath()
  65. if not DirAccess.dir_exists_absolute(backupPath):
  66. DirAccess.make_dir_absolute(backupPath)
  67. Start()