backup.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "net/http"
  6. "path/filepath"
  7. "strings"
  8. "imuslab.com/arozos/mod/disk/hybridBackup"
  9. user "imuslab.com/arozos/mod/user"
  10. prout "imuslab.com/arozos/mod/prouter"
  11. )
  12. func backup_init() {
  13. //Register HybridBackup storage restore endpoints
  14. router := prout.NewModuleRouter(prout.RouterOption{
  15. AdminOnly: false,
  16. UserHandler: userHandler,
  17. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  18. sendErrorResponse(w, "Permission Denied")
  19. },
  20. })
  21. //Register API endpoints
  22. router.HandleFunc("/system/backup/listRestorable", backup_listRestorable)
  23. router.HandleFunc("/system/backup/restoreFile", backup_restoreSelected)
  24. router.HandleFunc("/system/backup/snapshotSummary", backup_renderSnapshotSummary)
  25. router.HandleFunc("/system/backup/listAll", backup_listAllBackupDisk)
  26. //Register settings
  27. registerSetting(settingModule{
  28. Name: "Backup Disks",
  29. Desc: "All backup disk in the system",
  30. IconPath: "img/system/backup.svg",
  31. Group: "Disk",
  32. StartDir: "SystemAO/disk/backup/backups.html",
  33. RequireAdmin: true,
  34. })
  35. }
  36. //List all backup disk info
  37. func backup_listAllBackupDisk(w http.ResponseWriter, r *http.Request) {
  38. //Get all fsh from the system
  39. runningBackupTasks := []*hybridBackup.BackupTask{}
  40. //Render base storage pool
  41. for _, fsh := range baseStoragePool.Storages {
  42. if fsh.Hierarchy == "backup" {
  43. task, err := baseStoragePool.HyperBackupManager.GetTaskByBackupDiskID(fsh.UUID)
  44. if err != nil {
  45. continue
  46. }
  47. runningBackupTasks = append(runningBackupTasks, task)
  48. }
  49. }
  50. //Render group storage pool
  51. for _, pg := range permissionHandler.PermissionGroups {
  52. for _, fsh := range pg.StoragePool.Storages {
  53. task, err := pg.StoragePool.HyperBackupManager.GetTaskByBackupDiskID(fsh.UUID)
  54. if err != nil {
  55. continue
  56. }
  57. runningBackupTasks = append(runningBackupTasks, task)
  58. }
  59. }
  60. type backupDrive struct {
  61. DiskUID string //The backup disk UUID
  62. DiskName string // The Backup disk name
  63. ParentUID string //Parent disk UID
  64. ParentName string //Parent disk name
  65. BackupMode string //The backup mode of the drive
  66. LastBackupCycleTime int64 //Last backup timestamp
  67. BackupCycleCount int64 //How many backup cycle has proceeded since the system startup
  68. }
  69. backupDrives := []*backupDrive{}
  70. for _, task := range runningBackupTasks {
  71. diskFsh, diskErr := GetFsHandlerByUUID(task.DiskUID)
  72. parentFsh, parentErr := GetFsHandlerByUUID(task.ParentUID)
  73. //Check for error in getting FS Handler
  74. if diskErr != nil || parentErr != nil {
  75. sendErrorResponse(w, "Unable to get backup task info from backup disk: "+task.DiskUID)
  76. return
  77. }
  78. backupDrives = append(backupDrives, &backupDrive{
  79. DiskUID: diskFsh.UUID,
  80. DiskName: diskFsh.Name,
  81. ParentUID: parentFsh.UUID,
  82. ParentName: parentFsh.Name,
  83. BackupMode: task.Mode,
  84. LastBackupCycleTime: task.LastCycleTime,
  85. BackupCycleCount: task.CycleCounter,
  86. })
  87. }
  88. js, _ := json.Marshal(backupDrives)
  89. sendJSONResponse(w, string(js))
  90. }
  91. //Generate a snapshot summary for vroot
  92. func backup_renderSnapshotSummary(w http.ResponseWriter, r *http.Request) {
  93. //Get user accessiable storage pools
  94. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  95. if err != nil {
  96. sendErrorResponse(w, "User not logged in")
  97. return
  98. }
  99. //Get Backup disk ID from request
  100. bdid, err := mv(r, "bdid", true)
  101. if err != nil {
  102. sendErrorResponse(w, "Invalid backup disk ID given")
  103. return
  104. }
  105. //Get target snapshot name from request
  106. snapshot, err := mv(r, "snapshot", true)
  107. if err != nil {
  108. sendErrorResponse(w, "Invalid snapshot name given")
  109. return
  110. }
  111. //Get fsh from the id
  112. fsh, err := GetFsHandlerByUUID(bdid)
  113. if err != nil {
  114. sendErrorResponse(w, err.Error())
  115. return
  116. }
  117. //Get parent disk hierarcy
  118. parentDiskID, err := userinfo.HomeDirectories.HyperBackupManager.GetParentDiskIDByRestoreDiskID(fsh.UUID)
  119. if err != nil {
  120. sendErrorResponse(w, err.Error())
  121. return
  122. }
  123. parentFsh, err := GetFsHandlerByUUID(parentDiskID)
  124. if err != nil {
  125. sendErrorResponse(w, err.Error())
  126. return
  127. }
  128. //Get task by the backup disk id
  129. task, err := userinfo.HomeDirectories.HyperBackupManager.GetTaskByBackupDiskID(fsh.UUID)
  130. if err != nil {
  131. sendErrorResponse(w, err.Error())
  132. return
  133. }
  134. if task.Mode == "version" {
  135. //Generate snapshot summary
  136. var summary *hybridBackup.SnapshotSummary
  137. if parentFsh.Hierarchy == "user" {
  138. s, err := task.GenerateSnapshotSummary(snapshot, &userinfo.Username)
  139. if err != nil {
  140. sendErrorResponse(w, err.Error())
  141. return
  142. }
  143. summary = s
  144. } else {
  145. s, err := task.GenerateSnapshotSummary(snapshot, nil)
  146. if err != nil {
  147. sendErrorResponse(w, err.Error())
  148. return
  149. }
  150. summary = s
  151. }
  152. js, _ := json.Marshal(summary)
  153. sendJSONResponse(w, string(js))
  154. } else {
  155. sendErrorResponse(w, "Unable to genreate snapshot summary: Backup mode is not snapshot")
  156. return
  157. }
  158. }
  159. //Restore a given file
  160. func backup_restoreSelected(w http.ResponseWriter, r *http.Request) {
  161. //Get user accessiable storage pools
  162. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  163. if err != nil {
  164. sendErrorResponse(w, "User not logged in")
  165. return
  166. }
  167. //Get Backup disk ID from request
  168. bdid, err := mv(r, "bdid", true)
  169. if err != nil {
  170. sendErrorResponse(w, "Invalid backup disk ID given")
  171. return
  172. }
  173. //Get fsh from the id
  174. fsh, err := GetFsHandlerByUUID(bdid)
  175. if err != nil {
  176. sendErrorResponse(w, err.Error())
  177. return
  178. }
  179. //Get the relative path for the restorable file
  180. relpath, err := mv(r, "relpath", true)
  181. if err != nil {
  182. sendErrorResponse(w, "Invalid relative path given")
  183. return
  184. }
  185. //Pick the correct HybridBackup Manager
  186. targetHybridBackupManager, err := backup_pickHybridBackupManager(userinfo, fsh.UUID)
  187. if err != nil {
  188. sendErrorResponse(w, err.Error())
  189. return
  190. }
  191. //Handle restore of the file
  192. err = targetHybridBackupManager.HandleRestore(fsh.UUID, relpath, &userinfo.Username)
  193. if err != nil {
  194. sendErrorResponse(w, err.Error())
  195. return
  196. }
  197. type RestoreResult struct {
  198. RestoreDiskID string
  199. TargetDiskID string
  200. RestoredVirtualPath string
  201. }
  202. result := RestoreResult{
  203. RestoreDiskID: fsh.UUID,
  204. }
  205. //Get access path for this file
  206. parentDiskId, err := targetHybridBackupManager.GetParentDiskIDByRestoreDiskID(fsh.UUID)
  207. if err != nil {
  208. //Unable to get parent disk ID???
  209. } else {
  210. //Get the path of the parent disk
  211. parentDiskHandler, err := GetFsHandlerByUUID(parentDiskId)
  212. if err == nil {
  213. //Join the result to create a virtual path
  214. assumedRestoreRealPath := filepath.ToSlash(filepath.Join(parentDiskHandler.Path, relpath))
  215. restoreVpath, err := userinfo.RealPathToVirtualPath(assumedRestoreRealPath)
  216. if err == nil {
  217. result.RestoredVirtualPath = restoreVpath
  218. }
  219. result.TargetDiskID = parentDiskId
  220. }
  221. }
  222. js, _ := json.Marshal(result)
  223. sendJSONResponse(w, string(js))
  224. }
  225. //As one user might be belongs to multiple groups, check which storage pool is this disk ID owned by and return its corect backup maanger
  226. func backup_pickHybridBackupManager(userinfo *user.User, diskID string) (*hybridBackup.Manager, error) {
  227. //Filter out the :/ if it exists in the disk ID
  228. if strings.Contains(diskID, ":") {
  229. diskID = strings.Split(diskID, ":")[0]
  230. }
  231. //Get all backup managers that this user ac can access
  232. userpg := userinfo.GetUserPermissionGroup()
  233. if userinfo.HomeDirectories.ContainDiskID(diskID) {
  234. return userinfo.HomeDirectories.HyperBackupManager, nil
  235. }
  236. //Extract the backup Managers
  237. for _, pg := range userpg {
  238. if pg.StoragePool.ContainDiskID(diskID) {
  239. return pg.StoragePool.HyperBackupManager, nil
  240. }
  241. }
  242. return nil, errors.New("Disk ID not found in any storage pool this user can access")
  243. }
  244. //Generate and return a restorable report
  245. func backup_listRestorable(w http.ResponseWriter, r *http.Request) {
  246. //Get user accessiable storage pools
  247. userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
  248. if err != nil {
  249. sendErrorResponse(w, "User not logged in")
  250. return
  251. }
  252. //Get Vroot ID from request
  253. vroot, err := mv(r, "vroot", true)
  254. if err != nil {
  255. sendErrorResponse(w, "Invalid vroot given")
  256. return
  257. }
  258. //Get fsh from the id
  259. fsh, err := GetFsHandlerByUUID(vroot)
  260. if err != nil {
  261. sendErrorResponse(w, err.Error())
  262. return
  263. }
  264. //Get all backup managers that this user ac can access
  265. targetBackupManager, err := backup_pickHybridBackupManager(userinfo, vroot)
  266. if err != nil {
  267. sendErrorResponse(w, err.Error())
  268. return
  269. }
  270. //Get the user's storage pool and list restorable by the user's storage pool access
  271. restorableReport, err := targetBackupManager.ListRestorable(fsh.UUID)
  272. if err != nil {
  273. sendErrorResponse(w, err.Error())
  274. return
  275. }
  276. //Get and check if the parent disk has a user Hierarcy
  277. paretnfsh, err := GetFsHandlerByUUID(restorableReport.ParentUID)
  278. if err != nil {
  279. sendErrorResponse(w, err.Error())
  280. return
  281. }
  282. result := hybridBackup.RestorableReport{
  283. ParentUID: restorableReport.ParentUID,
  284. RestorableFiles: []*hybridBackup.RestorableFile{},
  285. }
  286. if paretnfsh.Hierarchy == "user" {
  287. //The file system is user based. Filter out those file that is not belong to this user
  288. for _, restorableFile := range restorableReport.RestorableFiles {
  289. if restorableFile.IsSnapshot {
  290. //Is snapshot. Always allow access
  291. result.RestorableFiles = append(result.RestorableFiles, restorableFile)
  292. } else {
  293. //Is file
  294. fileAbsPath := filepath.Join(fsh.Path, restorableFile.RelpathOnDisk)
  295. _, err := userinfo.RealPathToVirtualPath(fileAbsPath)
  296. if err != nil {
  297. //Cannot translate this file. That means the file is not owned by this user
  298. } else {
  299. //Can translate the path.
  300. result.RestorableFiles = append(result.RestorableFiles, restorableFile)
  301. }
  302. }
  303. }
  304. } else {
  305. result = restorableReport
  306. }
  307. js, _ := json.Marshal(result)
  308. sendJSONResponse(w, string(js))
  309. }