storage.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "log"
  6. "os"
  7. "path/filepath"
  8. "runtime"
  9. "strings"
  10. "time"
  11. "imuslab.com/arozos/mod/filesystem"
  12. "imuslab.com/arozos/mod/filesystem/arozfs"
  13. "imuslab.com/arozos/mod/permission"
  14. "imuslab.com/arozos/mod/storage/bridge"
  15. fs "imuslab.com/arozos/mod/filesystem"
  16. storage "imuslab.com/arozos/mod/storage"
  17. )
  18. var (
  19. baseStoragePool *storage.StoragePool //base storage pool, all user can access these virtual roots
  20. //fsHandlers []*fs.FileSystemHandler //All File system handlers. All opened handles must be registered in here
  21. //storagePools []*storage.StoragePool //All Storage pool opened
  22. bridgeManager *bridge.Record //Manager to handle bridged FSH
  23. storageHeartbeatTickerChan chan bool //Channel to stop the storage heartbeat ticker
  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 := os.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. storageHeartbeatTickerChan = done
  117. }
  118. // Perform heartbeat to all connected file system abstraction.
  119. // Blocking function, use with go routine if needed
  120. func StoragePerformFileSystemAbstractionConnectionHeartbeat() {
  121. allFsh := GetAllLoadedFsh()
  122. for _, thisFsh := range allFsh {
  123. err := thisFsh.FileSystemAbstraction.Heartbeat()
  124. if err != nil {
  125. log.Println("[Storage] File System Abstraction from " + thisFsh.Name + " report an error: " + err.Error())
  126. //Retreive the old startup config and close the pool
  127. originalStartOption := filesystem.FileSystemOption{}
  128. js, _ := json.Marshal(thisFsh.StartOptions)
  129. json.Unmarshal(js, &originalStartOption)
  130. //Create a new fsh from original start options
  131. newfsh, err := filesystem.NewFileSystemHandler(originalStartOption)
  132. if err != nil {
  133. log.Println("[Storage] Unable to reconnect " + thisFsh.Name + ": " + err.Error())
  134. continue
  135. } else {
  136. //New fsh created. Close the old one
  137. thisFsh.Close()
  138. }
  139. //Pop this fsh from all storage pool that mounted this
  140. sp := GetAllStoragePools()
  141. parentsp := []*storage.StoragePool{}
  142. for _, thissp := range sp {
  143. if thissp.ContainDiskID(originalStartOption.Uuid) {
  144. parentsp = append(parentsp, thissp)
  145. thissp.DetachFsHandler(originalStartOption.Uuid)
  146. }
  147. }
  148. //Add the new fsh to all the storage pools that have it originally
  149. for _, pool := range parentsp {
  150. err := pool.AttachFsHandler(newfsh)
  151. if err != nil {
  152. log.Println("[Storage] Attach fsh to pool failed: " + err.Error())
  153. }
  154. }
  155. }
  156. }
  157. }
  158. // Initialize group storage pool
  159. func GroupStoragePoolInit() {
  160. //Mount permission groups
  161. for _, pg := range permissionHandler.PermissionGroups {
  162. //For each group, check does this group has a config file
  163. err := LoadStoragePoolForGroup(pg)
  164. if err != nil {
  165. continue
  166. }
  167. //Do something else, WIP
  168. }
  169. //Start editing interface for Storage Pool Editor
  170. StoragePoolEditorInit()
  171. }
  172. func LoadStoragePoolForGroup(pg *permission.PermissionGroup) error {
  173. expectedConfigPath := "./system/storage/" + pg.Name + ".json"
  174. if fs.FileExists(expectedConfigPath) {
  175. //Read the config file
  176. pgStorageConfig, err := os.ReadFile(expectedConfigPath)
  177. if err != nil {
  178. systemWideLogger.PrintAndLog("Storage", "Failed to read config for "+pg.Name+": "+err.Error(), err)
  179. return errors.New("Failed to read config for " + pg.Name + ": " + err.Error())
  180. }
  181. //Generate fsHandler form json
  182. thisGroupFsHandlers, err := fs.NewFileSystemHandlersFromJSON(pgStorageConfig)
  183. if err != nil {
  184. systemWideLogger.PrintAndLog("Storage", "Failed to load storage configuration: "+err.Error(), err)
  185. return errors.New("Failed to load storage configuration: " + err.Error())
  186. }
  187. //Show debug message
  188. for _, thisHandler := range thisGroupFsHandlers {
  189. systemWideLogger.PrintAndLog("Storage", thisHandler.Name+" Mounted as "+thisHandler.UUID+":/ for group "+pg.Name, err)
  190. }
  191. //Create a storage pool from these handlers
  192. sp, err := storage.NewStoragePool(thisGroupFsHandlers, pg.Name)
  193. if err != nil {
  194. systemWideLogger.PrintAndLog("Storage", "Failed to create storage pool for "+pg.Name, err)
  195. return errors.New("Failed to create storage pool for " + pg.Name)
  196. }
  197. //Set other permission to denied by default
  198. sp.OtherPermission = arozfs.FsDenied
  199. //Assign storage pool to group
  200. pg.StoragePool = sp
  201. } else {
  202. //Storage configuration not exists. Fill in the basic information and move to next storage pool
  203. //Create a new empty storage pool for this group
  204. sp, err := storage.NewStoragePool([]*fs.FileSystemHandler{}, pg.Name)
  205. if err != nil {
  206. systemWideLogger.PrintAndLog("Storage", "Failed to create empty storage pool for group: "+pg.Name, err)
  207. }
  208. pg.StoragePool = sp
  209. pg.StoragePool.OtherPermission = arozfs.FsDenied
  210. }
  211. return nil
  212. }
  213. // Check if a storage pool exists by its group owner name
  214. func StoragePoolExists(poolOwner string) bool {
  215. _, err := GetStoragePoolByOwner(poolOwner)
  216. return err == nil
  217. }
  218. func GetAllStoragePools() []*storage.StoragePool {
  219. //Append the base pool
  220. results := []*storage.StoragePool{baseStoragePool}
  221. //Add each permissionGroup's pool
  222. for _, pg := range permissionHandler.PermissionGroups {
  223. results = append(results, pg.StoragePool)
  224. }
  225. return results
  226. }
  227. func GetStoragePoolByOwner(owner string) (*storage.StoragePool, error) {
  228. sps := GetAllStoragePools()
  229. for _, pool := range sps {
  230. if pool.Owner == owner {
  231. return pool, nil
  232. }
  233. }
  234. return nil, errors.New("Storage pool owned by " + owner + " not found")
  235. }
  236. func GetFSHandlerSubpathFromVpath(vpath string) (*fs.FileSystemHandler, string, error) {
  237. VirtualRootID, subpath, err := fs.GetIDFromVirtualPath(vpath)
  238. if err != nil {
  239. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  240. }
  241. fsh, err := GetFsHandlerByUUID(VirtualRootID)
  242. if err != nil {
  243. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  244. }
  245. if fsh == nil || fsh.FileSystemAbstraction == nil {
  246. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  247. }
  248. if fsh.Closed {
  249. return nil, "", errors.New("Target file system handler already closed")
  250. }
  251. return fsh, subpath, nil
  252. }
  253. func GetFsHandlerByUUID(uuid string) (*fs.FileSystemHandler, error) {
  254. //Filter out the :/ fropm uuid if exists
  255. if strings.Contains(uuid, ":") {
  256. uuid = strings.Split(uuid, ":")[0]
  257. }
  258. var resultFsh *fs.FileSystemHandler = nil
  259. allFsh := GetAllLoadedFsh()
  260. for _, fsh := range allFsh {
  261. if fsh.UUID == uuid && !fsh.Closed {
  262. resultFsh = fsh
  263. }
  264. }
  265. if resultFsh == nil {
  266. return nil, errors.New("Filesystem handler with given UUID not found")
  267. } else {
  268. return resultFsh, nil
  269. }
  270. }
  271. func GetAllLoadedFsh() []*fs.FileSystemHandler {
  272. fshTmp := map[string]*fs.FileSystemHandler{}
  273. allFsh := []*fs.FileSystemHandler{}
  274. allStoragePools := GetAllStoragePools()
  275. for _, thisSP := range allStoragePools {
  276. for _, thisFsh := range thisSP.Storages {
  277. fshPointer := thisFsh
  278. fshTmp[thisFsh.UUID] = fshPointer
  279. }
  280. }
  281. //Restructure the map to slice
  282. for _, fsh := range fshTmp {
  283. allFsh = append(allFsh, fsh)
  284. }
  285. return allFsh
  286. }
  287. func RegisterStorageSettings() {
  288. //Storage Pool Configuration
  289. registerSetting(settingModule{
  290. Name: "Storage Pools",
  291. Desc: "Storage Pool Mounting Configuration",
  292. IconPath: "SystemAO/disk/smart/img/small_icon.png",
  293. Group: "Disk",
  294. StartDir: "SystemAO/storage/poolList.html",
  295. RequireAdmin: true,
  296. })
  297. }
  298. // CloseAllStorages Close all storage database
  299. func CloseAllStorages() {
  300. allFsh := GetAllLoadedFsh()
  301. for _, fsh := range allFsh {
  302. fsh.FilesystemDatabase.Close()
  303. }
  304. }
  305. func closeAllStoragePools() {
  306. //Stop the storage pool heartbeat
  307. storageHeartbeatTickerChan <- true
  308. //Close all storage pools
  309. for _, sp := range GetAllStoragePools() {
  310. sp.Close()
  311. }
  312. }