hybridBackup.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. package hybridBackup
  2. import (
  3. "crypto/sha256"
  4. "encoding/hex"
  5. "errors"
  6. "io"
  7. "log"
  8. "os"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. )
  13. /*
  14. Hybrid Backup
  15. This module handle backup functions from the drive with Hieracchy labeled as "backup"
  16. Backup modes suport in this module currently consists of
  17. Denote P drive as parent drive and B drive as backup drive.
  18. 1. Basic (basic):
  19. - Any new file created in P will be copied to B within 1 minutes
  20. - Any file change will be copied to B within 30 minutes
  21. - Any file removed in P will be delete from backup if it is > 24 hours old
  22. 2. Nightly (nightly):
  23. - The whole P drive will be copied to N drive every night
  24. 3. Versioning (version)
  25. - A versioning system will be introduce to this backup drive
  26. - Just like the time machine
  27. Tips when developing this module
  28. - This is a sub-module of the current file system. Do not import from arozos file system module
  29. - If you need any function from the file system, copy and paste it in this module
  30. */
  31. type Manager struct {
  32. Ticker *time.Ticker `json:"-"` //The main ticker
  33. StopTicker chan bool `json:"-"` //Channel for stopping the backup
  34. Tasks []*BackupTask //The backup tasks that is running under this manager
  35. }
  36. type BackupTask struct {
  37. JobName string //The name used by the scheduler for executing this config
  38. CycleCounter int64 //The number of backup executed in the background
  39. LastCycleTime int64 //The execution time of the last cycle
  40. Enabled bool //Check if the task is enabled. Will not execute if this is set to false
  41. DiskUID string //The UID of the target fsandlr
  42. DiskPath string //The mount point for the disk
  43. ParentUID string //Parent virtal disk UUID
  44. ParentPath string //Parent disk path
  45. DeleteFileMarkers map[string]int64 //Markers for those files delete pending, [file path (relative)] time
  46. Mode string //Backup mode
  47. }
  48. //A file in the backup drive that is restorable
  49. type RestorableFile struct {
  50. Filename string //Filename of this restorable object
  51. IsHidden bool //Check if the file is hidden or located in a path within hidden folder
  52. Filesize int64 //The file size to be restorable
  53. RelpathOnDisk string //Relative path of this file to the root
  54. RestorePoint string //The location this file should restore to
  55. BackupDiskUID string //The UID of disk that is hold the backup of this file
  56. RemainingTime int64 //Remaining time till auto remove
  57. DeleteTime int64 //Delete time
  58. IsSnapshot bool //Define is this restorable file point to a snapshot instead
  59. }
  60. //The restorable report
  61. type RestorableReport struct {
  62. ParentUID string //The Disk ID to be restored to
  63. RestorableFiles []*RestorableFile //A list of restorable files
  64. }
  65. var (
  66. internalTickerTime time.Duration = 60
  67. )
  68. func NewHyperBackupManager() *Manager {
  69. //Create a new minute ticker
  70. ticker := time.NewTicker(internalTickerTime * time.Second)
  71. stopper := make(chan bool, 1)
  72. newManager := &Manager{
  73. Ticker: ticker,
  74. StopTicker: stopper,
  75. Tasks: []*BackupTask{},
  76. }
  77. ///Create task executor
  78. go func() {
  79. defer log.Println("[HybridBackup] Ticker Stopped")
  80. for {
  81. select {
  82. case <-ticker.C:
  83. for _, task := range newManager.Tasks {
  84. if task.Enabled == true {
  85. task.HandleBackupProcess()
  86. }
  87. }
  88. case <-stopper:
  89. return
  90. }
  91. }
  92. }()
  93. //Return the manager
  94. return newManager
  95. }
  96. func (m *Manager) AddTask(newtask *BackupTask) error {
  97. //Create a job for this
  98. newtask.JobName = "backup-[" + newtask.DiskUID + "]"
  99. //Check if the same job name exists
  100. for _, task := range m.Tasks {
  101. if task.JobName == newtask.JobName {
  102. return errors.New("Task already exists")
  103. }
  104. }
  105. //Add task to list
  106. m.Tasks = append(m.Tasks, newtask)
  107. //Start the task
  108. m.StartTask(newtask.JobName)
  109. log.Println(">>>> [Debug] New Backup Tasks added: ", newtask.JobName, newtask)
  110. return nil
  111. }
  112. //Start a given task given name
  113. func (m *Manager) StartTask(jobname string) {
  114. for _, task := range m.Tasks {
  115. if task.JobName == jobname {
  116. //Enable to job
  117. task.Enabled = true
  118. //Run it once
  119. task.HandleBackupProcess()
  120. }
  121. }
  122. }
  123. //Stop a given task given its job name
  124. func (m *Manager) StopTask(jobname string) {
  125. for _, task := range m.Tasks {
  126. if task.JobName == jobname {
  127. task.Enabled = false
  128. }
  129. }
  130. }
  131. //Stop all managed handlers
  132. func (m *Manager) Close() error {
  133. m.StopTicker <- true
  134. return nil
  135. }
  136. //Main handler function for hybrid backup
  137. func (backupConfig *BackupTask) HandleBackupProcess() (string, error) {
  138. log.Println(">>>>>> [Debug] Running backup process: ", backupConfig)
  139. //Check if the target disk is writable and mounted
  140. if fileExists(filepath.Join(backupConfig.ParentPath, "aofs.db")) && fileExists(filepath.Join(backupConfig.ParentPath, "aofs.db.lock")) {
  141. //This parent filesystem is mounted
  142. } else {
  143. //File system not mounted even after 3 backup cycle. Terminate backup scheduler
  144. log.Println("[HybridBackup] Skipping backup cycle for " + backupConfig.ParentUID + ":/")
  145. return "Parent drive (" + backupConfig.ParentUID + ":/) not mounted", nil
  146. }
  147. //Check if the backup disk is mounted. If no, stop the scheulder
  148. if backupConfig.CycleCounter > 3 && !(fileExists(filepath.Join(backupConfig.DiskPath, "aofs.db")) && fileExists(filepath.Join(backupConfig.DiskPath, "aofs.db.lock"))) {
  149. log.Println("[HybridBackup] Backup schedule stopped for " + backupConfig.DiskUID + ":/")
  150. return "Backup drive (" + backupConfig.DiskUID + ":/) not mounted", errors.New("Backup File System Handler not mounted")
  151. }
  152. deepBackup := true //Default perform deep backup
  153. if backupConfig.Mode == "basic" {
  154. if backupConfig.CycleCounter%3 == 0 {
  155. //Perform deep backup, use walk function
  156. deepBackup = true
  157. } else {
  158. deepBackup = false
  159. backupConfig.LastCycleTime = time.Now().Unix()
  160. }
  161. return executeBackup(backupConfig, deepBackup)
  162. } else if backupConfig.Mode == "nightly" {
  163. if time.Now().Unix()-backupConfig.LastCycleTime >= 86400 {
  164. //24 hours from last backup. Execute deep backup now
  165. executeBackup(backupConfig, true)
  166. backupConfig.LastCycleTime = time.Now().Unix()
  167. }
  168. } else if backupConfig.Mode == "version" {
  169. //Do a versioning backup
  170. if time.Now().Unix()-backupConfig.LastCycleTime >= 86400 || backupConfig.CycleCounter == 0 {
  171. //Scheduled backup or initial backup
  172. executeVersionBackup(backupConfig)
  173. backupConfig.LastCycleTime = time.Now().Unix()
  174. }
  175. }
  176. //Add one to the cycle counter
  177. backupConfig.CycleCounter++
  178. //Return the log information
  179. return "", nil
  180. }
  181. //Get the restore parent disk ID by backup disk ID
  182. func (m *Manager) GetParentDiskIDByRestoreDiskID(restoreDiskID string) (string, error) {
  183. backupTask := m.getTaskByBackupDiskID(restoreDiskID)
  184. if backupTask == nil {
  185. return "", errors.New("This disk do not have a backup task in this backup maanger")
  186. }
  187. return backupTask.ParentUID, nil
  188. }
  189. //Restore accidentailly removed file from backup
  190. func (m *Manager) HandleRestore(restoreDiskID string, targetFileRelpath string) error {
  191. //Get the backup task from backup disk id
  192. backupTask := m.getTaskByBackupDiskID(restoreDiskID)
  193. if backupTask == nil {
  194. return errors.New("Target disk is not a backup disk")
  195. }
  196. //Check if source exists and target not exists
  197. log.Println("[debug]", backupTask)
  198. restoreSource := filepath.Join(backupTask.DiskPath, targetFileRelpath)
  199. if backupTask.Mode == "basic" || backupTask.Mode == "nightly" {
  200. restoreSource = filepath.Join(backupTask.DiskPath, "/backup/", targetFileRelpath)
  201. } else if backupTask.Mode == "version" {
  202. restoreSource = filepath.Join(backupTask.DiskPath, "/versions/", targetFileRelpath)
  203. }
  204. restoreTarget := filepath.Join(backupTask.ParentPath, targetFileRelpath)
  205. if !fileExists(restoreSource) {
  206. //Restore source not exists
  207. return errors.New("Restore source file not exists")
  208. }
  209. if fileExists(restoreTarget) {
  210. //Restore target already exists.
  211. return errors.New("Restore target already exists. Cannot overwrite.")
  212. }
  213. //Check if the restore target parent folder exists. If not, create it
  214. if !fileExists(filepath.Dir(restoreTarget)) {
  215. os.MkdirAll(filepath.Dir(restoreTarget), 0755)
  216. }
  217. //Ready to move it back
  218. err := BufferedLargeFileCopy(restoreSource, restoreTarget, 4086)
  219. if err != nil {
  220. return errors.New("Restore failed: " + err.Error())
  221. }
  222. //Restore completed
  223. return nil
  224. }
  225. //List the file that is restorable from the given disk
  226. func (m *Manager) ListRestorable(parentDiskID string) (RestorableReport, error) {
  227. //List all the backup process that is mirroring this parent disk
  228. tasks := m.getTaskByParentDiskID(parentDiskID)
  229. if len(tasks) == 0 {
  230. return RestorableReport{}, errors.New("No backup root found for this " + parentDiskID + ":/ virtual root.")
  231. }
  232. diffFiles := []*RestorableFile{}
  233. //Extract all comparasion
  234. for _, task := range tasks {
  235. if task.Mode == "basic" || task.Mode == "nightly" {
  236. restorableFiles, err := listBasicRestorables(task)
  237. if err != nil {
  238. //Something went wrong. Skip this
  239. continue
  240. }
  241. for _, restorable := range restorableFiles {
  242. diffFiles = append(diffFiles, restorable)
  243. }
  244. } else if task.Mode == "version" {
  245. restorableFiles, err := listVersionRestorables(task)
  246. if err != nil {
  247. //Something went wrong. Skip this
  248. continue
  249. }
  250. for _, restorable := range restorableFiles {
  251. diffFiles = append(diffFiles, restorable)
  252. }
  253. } else {
  254. //Unknown mode. Skip it
  255. }
  256. }
  257. //Create a Restorable Report
  258. thisReport := RestorableReport{
  259. ParentUID: parentDiskID,
  260. RestorableFiles: diffFiles,
  261. }
  262. return thisReport, nil
  263. }
  264. //Get tasks from parent disk id, might return multiple task or no tasks
  265. func (m *Manager) getTaskByParentDiskID(parentDiskID string) []*BackupTask {
  266. //Convert ID:/ format to ID
  267. if strings.Contains(parentDiskID, ":") {
  268. parentDiskID = strings.Split(parentDiskID, ":")[0]
  269. }
  270. possibleTask := []*BackupTask{}
  271. for _, task := range m.Tasks {
  272. if task.ParentUID == parentDiskID {
  273. //This task parent is the target disk. push this to list
  274. possibleTask = append(possibleTask, task)
  275. }
  276. }
  277. return possibleTask
  278. }
  279. //Get task by backup Disk ID, only return 1 task
  280. func (m *Manager) getTaskByBackupDiskID(backupDiskID string) *BackupTask {
  281. //Trim the :/ parts
  282. if strings.Contains(backupDiskID, ":") {
  283. backupDiskID = strings.Split(backupDiskID, ":")[0]
  284. }
  285. for _, task := range m.Tasks {
  286. if task.DiskUID == backupDiskID {
  287. return task
  288. }
  289. }
  290. return nil
  291. }
  292. //Get and return the file hash for a file
  293. func getFileHash(filename string) (string, error) {
  294. f, err := os.Open(filename)
  295. if err != nil {
  296. return "", err
  297. }
  298. defer f.Close()
  299. h := sha256.New()
  300. if _, err := io.Copy(h, f); err != nil {
  301. return "", err
  302. }
  303. return hex.EncodeToString(h.Sum(nil)), nil
  304. }