storage.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "time"
  12. "imuslab.com/arozos/mod/filesystem"
  13. "imuslab.com/arozos/mod/filesystem/arozfs"
  14. "imuslab.com/arozos/mod/permission"
  15. "imuslab.com/arozos/mod/storage/bridge"
  16. fs "imuslab.com/arozos/mod/filesystem"
  17. storage "imuslab.com/arozos/mod/storage"
  18. )
  19. var (
  20. baseStoragePool *storage.StoragePool //base storage pool, all user can access these virtual roots
  21. //fsHandlers []*fs.FileSystemHandler //All File system handlers. All opened handles must be registered in here
  22. //storagePools []*storage.StoragePool //All Storage pool opened
  23. bridgeManager *bridge.Record //Manager to handle bridged FSH
  24. )
  25. func StorageInit() {
  26. //Load the default handler for the user storage root
  27. if !fs.FileExists(filepath.Clean(*root_directory) + "/") {
  28. os.MkdirAll(filepath.Clean(*root_directory)+"/", 0755)
  29. }
  30. //Start loading the base storage pool
  31. err := LoadBaseStoragePool()
  32. if err != nil {
  33. panic(err)
  34. }
  35. //Create a brdige record manager
  36. bm := bridge.NewBridgeRecord("system/bridge.json")
  37. bridgeManager = bm
  38. }
  39. func LoadBaseStoragePool() error {
  40. //All fsh for the base pool
  41. fsHandlers := []*fs.FileSystemHandler{}
  42. //Use for Debian buster local file system
  43. localFileSystem := "ext4"
  44. if runtime.GOOS == "windows" {
  45. localFileSystem = "ntfs"
  46. }
  47. baseHandler, err := fs.NewFileSystemHandler(fs.FileSystemOption{
  48. Name: "User",
  49. Uuid: "user",
  50. Path: filepath.ToSlash(filepath.Clean(*root_directory)) + "/",
  51. Hierarchy: "user",
  52. Automount: false,
  53. Filesystem: localFileSystem,
  54. })
  55. if err != nil {
  56. systemWideLogger.PrintAndLog("Storage", "Failed to initiate user root storage directory: "+*root_directory+err.Error(), err)
  57. return err
  58. }
  59. fsHandlers = append(fsHandlers, baseHandler)
  60. //Load the tmp folder as storage unit
  61. tmpHandler, err := fs.NewFileSystemHandler(fs.FileSystemOption{
  62. Name: "tmp",
  63. Uuid: "tmp",
  64. Path: filepath.ToSlash(filepath.Clean(*tmp_directory)) + "/",
  65. Hierarchy: "user",
  66. Automount: false,
  67. Filesystem: localFileSystem,
  68. })
  69. if err != nil {
  70. systemWideLogger.PrintAndLog("Storage", "Failed to initiate tmp storage directory: "+*tmp_directory+err.Error(), err)
  71. return err
  72. }
  73. fsHandlers = append(fsHandlers, tmpHandler)
  74. //Load all the storage config from file
  75. rawConfig, err := ioutil.ReadFile(*storage_config_file)
  76. if err != nil {
  77. //File not found. Use internal storage only
  78. systemWideLogger.PrintAndLog("Storage", "Storage configuration file not found. Using internal storage only.", err)
  79. } else {
  80. //Configuration loaded. Initializing handler
  81. externalHandlers, err := fs.NewFileSystemHandlersFromJSON(rawConfig)
  82. if err != nil {
  83. systemWideLogger.PrintAndLog("Storage", "Failed to load storage configuration: "+err.Error()+" -- Skipping", err)
  84. } else {
  85. for _, thisHandler := range externalHandlers {
  86. fsHandlers = append(fsHandlers, thisHandler)
  87. systemWideLogger.PrintAndLog("Storage", thisHandler.Name+" Mounted as "+thisHandler.UUID+":/", err)
  88. }
  89. }
  90. }
  91. //Create a base storage pool for all users
  92. sp, err := storage.NewStoragePool(fsHandlers, "system")
  93. if err != nil {
  94. systemWideLogger.PrintAndLog("Storage", "Failed to create base Storaeg Pool", err)
  95. return err
  96. }
  97. //Update the storage pool permission to readwrite
  98. sp.OtherPermission = arozfs.FsReadWrite
  99. baseStoragePool = sp
  100. return nil
  101. }
  102. //Initialize the storage connection health check for all fsh.
  103. func storageHeartbeatTickerInit() {
  104. ticker := time.NewTicker(60 * time.Second)
  105. done := make(chan bool)
  106. go func() {
  107. for {
  108. select {
  109. case <-done:
  110. return
  111. case <-ticker.C:
  112. StoragePerformFileSystemAbstractionConnectionHeartbeat()
  113. }
  114. }
  115. }()
  116. }
  117. //Perform heartbeat to all connected file system abstraction.
  118. //Blocking function, use with go routine if needed
  119. func StoragePerformFileSystemAbstractionConnectionHeartbeat() {
  120. allFsh := GetAllLoadedFsh()
  121. for _, thisFsh := range allFsh {
  122. err := thisFsh.FileSystemAbstraction.Heartbeat()
  123. if err != nil {
  124. log.Println("[Storage] File System Abstraction from " + thisFsh.Name + " report an error: " + err.Error())
  125. //Retreive the old startup config and close the pool
  126. originalStartOption := filesystem.FileSystemOption{}
  127. js, _ := json.Marshal(thisFsh.StartOptions)
  128. json.Unmarshal(js, &originalStartOption)
  129. //Create a new fsh from original start options
  130. newfsh, err := filesystem.NewFileSystemHandler(originalStartOption)
  131. if err != nil {
  132. log.Println("[Storage] Unable to reconnect " + thisFsh.Name + ": " + err.Error())
  133. continue
  134. } else {
  135. //New fsh created. Close the old one
  136. thisFsh.Close()
  137. }
  138. //Pop this fsh from all storage pool that mounted this
  139. sp := GetAllStoragePools()
  140. parentsp := []*storage.StoragePool{}
  141. for _, thissp := range sp {
  142. if thissp.ContainDiskID(originalStartOption.Uuid) {
  143. parentsp = append(parentsp, thissp)
  144. thissp.DetachFsHandler(originalStartOption.Uuid)
  145. }
  146. }
  147. //Add the new fsh to all the storage pools that have it originally
  148. for _, pool := range parentsp {
  149. err := pool.AttachFsHandler(newfsh)
  150. if err != nil {
  151. log.Println("[Storage] Attach fsh to pool failed: " + err.Error())
  152. }
  153. }
  154. }
  155. }
  156. }
  157. //Initialize group storage pool
  158. func GroupStoragePoolInit() {
  159. //Mount permission groups
  160. for _, pg := range permissionHandler.PermissionGroups {
  161. //For each group, check does this group has a config file
  162. err := LoadStoragePoolForGroup(pg)
  163. if err != nil {
  164. continue
  165. }
  166. //Do something else, WIP
  167. }
  168. //Start editing interface for Storage Pool Editor
  169. StoragePoolEditorInit()
  170. }
  171. func LoadStoragePoolForGroup(pg *permission.PermissionGroup) error {
  172. expectedConfigPath := "./system/storage/" + pg.Name + ".json"
  173. if fs.FileExists(expectedConfigPath) {
  174. //Read the config file
  175. pgStorageConfig, err := os.ReadFile(expectedConfigPath)
  176. if err != nil {
  177. systemWideLogger.PrintAndLog("Storage", "Failed to read config for "+pg.Name+": "+err.Error(), err)
  178. return errors.New("Failed to read config for " + pg.Name + ": " + err.Error())
  179. }
  180. //Generate fsHandler form json
  181. thisGroupFsHandlers, err := fs.NewFileSystemHandlersFromJSON(pgStorageConfig)
  182. if err != nil {
  183. systemWideLogger.PrintAndLog("Storage", "Failed to load storage configuration: "+err.Error(), err)
  184. return errors.New("Failed to load storage configuration: " + err.Error())
  185. }
  186. //Show debug message
  187. for _, thisHandler := range thisGroupFsHandlers {
  188. systemWideLogger.PrintAndLog("Storage", thisHandler.Name+" Mounted as "+thisHandler.UUID+":/ for group "+pg.Name, err)
  189. }
  190. //Create a storage pool from these handlers
  191. sp, err := storage.NewStoragePool(thisGroupFsHandlers, pg.Name)
  192. if err != nil {
  193. systemWideLogger.PrintAndLog("Storage", "Failed to create storage pool for "+pg.Name, err)
  194. return errors.New("Failed to create storage pool for " + pg.Name)
  195. }
  196. //Set other permission to denied by default
  197. sp.OtherPermission = arozfs.FsDenied
  198. //Assign storage pool to group
  199. pg.StoragePool = sp
  200. } else {
  201. //Storage configuration not exists. Fill in the basic information and move to next storage pool
  202. //Create a new empty storage pool for this group
  203. sp, err := storage.NewStoragePool([]*fs.FileSystemHandler{}, pg.Name)
  204. if err != nil {
  205. systemWideLogger.PrintAndLog("Storage", "Failed to create empty storage pool for group: "+pg.Name, err)
  206. }
  207. pg.StoragePool = sp
  208. pg.StoragePool.OtherPermission = arozfs.FsDenied
  209. }
  210. return nil
  211. }
  212. //Check if a storage pool exists by its group owner name
  213. func StoragePoolExists(poolOwner string) bool {
  214. _, err := GetStoragePoolByOwner(poolOwner)
  215. return err == nil
  216. }
  217. func GetAllStoragePools() []*storage.StoragePool {
  218. //Append the base pool
  219. results := []*storage.StoragePool{baseStoragePool}
  220. //Add each permissionGroup's pool
  221. for _, pg := range permissionHandler.PermissionGroups {
  222. results = append(results, pg.StoragePool)
  223. }
  224. return results
  225. }
  226. func GetStoragePoolByOwner(owner string) (*storage.StoragePool, error) {
  227. sps := GetAllStoragePools()
  228. for _, pool := range sps {
  229. if pool.Owner == owner {
  230. return pool, nil
  231. }
  232. }
  233. return nil, errors.New("Storage pool owned by " + owner + " not found")
  234. }
  235. func GetFSHandlerSubpathFromVpath(vpath string) (*fs.FileSystemHandler, string, error) {
  236. VirtualRootID, subpath, err := fs.GetIDFromVirtualPath(vpath)
  237. if err != nil {
  238. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  239. }
  240. fsh, err := GetFsHandlerByUUID(VirtualRootID)
  241. if err != nil {
  242. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  243. }
  244. if fsh == nil || fsh.FileSystemAbstraction == nil {
  245. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  246. }
  247. if fsh.Closed {
  248. return nil, "", errors.New("Target file system handler already closed")
  249. }
  250. return fsh, subpath, nil
  251. }
  252. func GetFsHandlerByUUID(uuid string) (*fs.FileSystemHandler, error) {
  253. //Filter out the :/ fropm uuid if exists
  254. if strings.Contains(uuid, ":") {
  255. uuid = strings.Split(uuid, ":")[0]
  256. }
  257. var resultFsh *fs.FileSystemHandler = nil
  258. allFsh := GetAllLoadedFsh()
  259. for _, fsh := range allFsh {
  260. if fsh.UUID == uuid && !fsh.Closed {
  261. resultFsh = fsh
  262. }
  263. }
  264. if resultFsh == nil {
  265. return nil, errors.New("Filesystem handler with given UUID not found")
  266. } else {
  267. return resultFsh, nil
  268. }
  269. }
  270. func GetAllLoadedFsh() []*fs.FileSystemHandler {
  271. fshTmp := map[string]*fs.FileSystemHandler{}
  272. allFsh := []*fs.FileSystemHandler{}
  273. allStoragePools := GetAllStoragePools()
  274. for _, thisSP := range allStoragePools {
  275. for _, thisFsh := range thisSP.Storages {
  276. fshPointer := thisFsh
  277. fshTmp[thisFsh.UUID] = fshPointer
  278. }
  279. }
  280. //Restructure the map to slice
  281. for _, fsh := range fshTmp {
  282. allFsh = append(allFsh, fsh)
  283. }
  284. return allFsh
  285. }
  286. func RegisterStorageSettings() {
  287. //Storage Pool Configuration
  288. registerSetting(settingModule{
  289. Name: "Storage Pools",
  290. Desc: "Storage Pool Mounting Configuration",
  291. IconPath: "SystemAO/disk/smart/img/small_icon.png",
  292. Group: "Disk",
  293. StartDir: "SystemAO/storage/poolList.html",
  294. RequireAdmin: true,
  295. })
  296. }
  297. //CloseAllStorages Close all storage database
  298. func CloseAllStorages() {
  299. allFsh := GetAllLoadedFsh()
  300. for _, fsh := range allFsh {
  301. fsh.FilesystemDatabase.Close()
  302. }
  303. }
  304. func closeAllStoragePools() {
  305. for _, sp := range GetAllStoragePools() {
  306. sp.Close()
  307. }
  308. }