hybridBackup.go 14 KB

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