storage.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. thisFsh.Close()
  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. }
  136. //Pop this fsh from all storage pool that mounted this
  137. sp := GetAllStoragePools()
  138. parentsp := []*storage.StoragePool{}
  139. for _, thissp := range sp {
  140. if thissp.ContainDiskID(originalStartOption.Uuid) {
  141. parentsp = append(parentsp, thissp)
  142. thissp.DetachFsHandler(originalStartOption.Uuid)
  143. }
  144. }
  145. //Add the new fsh to all the storage pools that have it originally
  146. for _, pool := range parentsp {
  147. err := pool.AttachFsHandler(newfsh)
  148. if err != nil {
  149. log.Println("[Storage] Attach fsh to pool failed: " + err.Error())
  150. }
  151. }
  152. }
  153. }
  154. }
  155. //Initialize group storage pool
  156. func GroupStoragePoolInit() {
  157. //Mount permission groups
  158. for _, pg := range permissionHandler.PermissionGroups {
  159. //For each group, check does this group has a config file
  160. err := LoadStoragePoolForGroup(pg)
  161. if err != nil {
  162. continue
  163. }
  164. //Do something else, WIP
  165. }
  166. //Start editing interface for Storage Pool Editor
  167. StoragePoolEditorInit()
  168. }
  169. func LoadStoragePoolForGroup(pg *permission.PermissionGroup) error {
  170. expectedConfigPath := "./system/storage/" + pg.Name + ".json"
  171. if fs.FileExists(expectedConfigPath) {
  172. //Read the config file
  173. pgStorageConfig, err := os.ReadFile(expectedConfigPath)
  174. if err != nil {
  175. systemWideLogger.PrintAndLog("Storage", "Failed to read config for "+pg.Name+": "+err.Error(), err)
  176. return errors.New("Failed to read config for " + pg.Name + ": " + err.Error())
  177. }
  178. //Generate fsHandler form json
  179. thisGroupFsHandlers, err := fs.NewFileSystemHandlersFromJSON(pgStorageConfig)
  180. if err != nil {
  181. systemWideLogger.PrintAndLog("Storage", "Failed to load storage configuration: "+err.Error(), err)
  182. return errors.New("Failed to load storage configuration: " + err.Error())
  183. }
  184. //Show debug message
  185. for _, thisHandler := range thisGroupFsHandlers {
  186. systemWideLogger.PrintAndLog("Storage", thisHandler.Name+" Mounted as "+thisHandler.UUID+":/ for group "+pg.Name, err)
  187. }
  188. //Create a storage pool from these handlers
  189. sp, err := storage.NewStoragePool(thisGroupFsHandlers, pg.Name)
  190. if err != nil {
  191. systemWideLogger.PrintAndLog("Storage", "Failed to create storage pool for "+pg.Name, err)
  192. return errors.New("Failed to create storage pool for " + pg.Name)
  193. }
  194. //Set other permission to denied by default
  195. sp.OtherPermission = arozfs.FsDenied
  196. //Assign storage pool to group
  197. pg.StoragePool = sp
  198. } else {
  199. //Storage configuration not exists. Fill in the basic information and move to next storage pool
  200. //Create a new empty storage pool for this group
  201. sp, err := storage.NewStoragePool([]*fs.FileSystemHandler{}, pg.Name)
  202. if err != nil {
  203. systemWideLogger.PrintAndLog("Storage", "Failed to create empty storage pool for group: "+pg.Name, err)
  204. }
  205. pg.StoragePool = sp
  206. pg.StoragePool.OtherPermission = arozfs.FsDenied
  207. }
  208. return nil
  209. }
  210. //Check if a storage pool exists by its group owner name
  211. func StoragePoolExists(poolOwner string) bool {
  212. _, err := GetStoragePoolByOwner(poolOwner)
  213. return err == nil
  214. }
  215. func GetAllStoragePools() []*storage.StoragePool {
  216. //Append the base pool
  217. results := []*storage.StoragePool{baseStoragePool}
  218. //Add each permissionGroup's pool
  219. for _, pg := range permissionHandler.PermissionGroups {
  220. results = append(results, pg.StoragePool)
  221. }
  222. return results
  223. }
  224. func GetStoragePoolByOwner(owner string) (*storage.StoragePool, error) {
  225. sps := GetAllStoragePools()
  226. for _, pool := range sps {
  227. if pool.Owner == owner {
  228. return pool, nil
  229. }
  230. }
  231. return nil, errors.New("Storage pool owned by " + owner + " not found")
  232. }
  233. func GetFSHandlerSubpathFromVpath(vpath string) (*fs.FileSystemHandler, string, error) {
  234. VirtualRootID, subpath, err := fs.GetIDFromVirtualPath(vpath)
  235. if err != nil {
  236. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  237. }
  238. fsh, err := GetFsHandlerByUUID(VirtualRootID)
  239. if err != nil {
  240. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  241. }
  242. if fsh == nil || fsh.FileSystemAbstraction == nil {
  243. return nil, "", errors.New("Unable to resolve requested path: " + err.Error())
  244. }
  245. if fsh.Closed {
  246. return nil, "", errors.New("Target file system handler already closed")
  247. }
  248. return fsh, subpath, nil
  249. }
  250. func GetFsHandlerByUUID(uuid string) (*fs.FileSystemHandler, error) {
  251. //Filter out the :/ fropm uuid if exists
  252. if strings.Contains(uuid, ":") {
  253. uuid = strings.Split(uuid, ":")[0]
  254. }
  255. var resultFsh *fs.FileSystemHandler = nil
  256. allFsh := GetAllLoadedFsh()
  257. for _, fsh := range allFsh {
  258. if fsh.UUID == uuid && !fsh.Closed {
  259. resultFsh = fsh
  260. }
  261. }
  262. if resultFsh == nil {
  263. return nil, errors.New("Filesystem handler with given UUID not found")
  264. } else {
  265. return resultFsh, nil
  266. }
  267. }
  268. func GetAllLoadedFsh() []*fs.FileSystemHandler {
  269. fshTmp := map[string]*fs.FileSystemHandler{}
  270. allFsh := []*fs.FileSystemHandler{}
  271. allStoragePools := GetAllStoragePools()
  272. for _, thisSP := range allStoragePools {
  273. for _, thisFsh := range thisSP.Storages {
  274. fshPointer := thisFsh
  275. fshTmp[thisFsh.UUID] = fshPointer
  276. }
  277. }
  278. //Restructure the map to slice
  279. for _, fsh := range fshTmp {
  280. allFsh = append(allFsh, fsh)
  281. }
  282. return allFsh
  283. }
  284. func RegisterStorageSettings() {
  285. //Storage Pool Configuration
  286. registerSetting(settingModule{
  287. Name: "Storage Pools",
  288. Desc: "Storage Pool Mounting Configuration",
  289. IconPath: "SystemAO/disk/smart/img/small_icon.png",
  290. Group: "Disk",
  291. StartDir: "SystemAO/storage/poolList.html",
  292. RequireAdmin: true,
  293. })
  294. }
  295. //CloseAllStorages Close all storage database
  296. func CloseAllStorages() {
  297. allFsh := GetAllLoadedFsh()
  298. for _, fsh := range allFsh {
  299. fsh.FilesystemDatabase.Close()
  300. }
  301. }
  302. func closeAllStoragePools() {
  303. for _, sp := range GetAllStoragePools() {
  304. sp.Close()
  305. }
  306. }