storage.pool.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032
  1. package main
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "fmt"
  6. "net/http"
  7. "os"
  8. "regexp"
  9. "runtime"
  10. "sort"
  11. "strings"
  12. "time"
  13. "imuslab.com/arozos/mod/filesystem/arozfs"
  14. "imuslab.com/arozos/mod/storage/access"
  15. "imuslab.com/arozos/mod/utils"
  16. fs "imuslab.com/arozos/mod/filesystem"
  17. prout "imuslab.com/arozos/mod/prouter"
  18. storage "imuslab.com/arozos/mod/storage"
  19. )
  20. /*
  21. Storage Pool Handler
  22. author: tobychui
  23. This script handle the storage pool editing of different permission groups.
  24. A pool is where a drive is configured and which group it belongs to. Who
  25. may use a drive is set on the drive itself, see storage.access.go.
  26. */
  27. const (
  28. storagePoolSystem = "system"
  29. reloadAllPools = "1eb201a3-d0f6-6630-5e6d-2f40480115c5" //Super long string just to prevent any typo
  30. driveKindFixed = "fixed" //user:/ and tmp:/, open to everyone
  31. driveKindBuiltin = "builtin" //share:/ and cluster:/, built by code, with an access list
  32. driveKindConfigured = "configured" //Has a row in the config of its pool
  33. driveStateOnline = "online"
  34. driveStateStopped = "stopped" //Stopped by an admin until the next restart or reload
  35. driveStateOffline = "offline" //Configured, but not mounted
  36. driveStateRemoved = "removed" //Mounted, but its config row is gone. Leaves at the next reload
  37. driveStateNotActive = "notactive" //cluster:/ on a node with no cluster or no volume yet
  38. driveTestTimeout = 20 * time.Second
  39. )
  40. // A new drive id ends up in every virtual path of the drive
  41. var driveIDFormat = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
  42. func StoragePoolEditorInit() {
  43. adminRouter := prout.NewModuleRouter(prout.RouterOption{
  44. ModuleName: "System Settings",
  45. AdminOnly: true,
  46. UserHandler: userHandler,
  47. DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
  48. utils.SendErrorResponse(w, "Permission Denied")
  49. },
  50. })
  51. //Create the required folder structure
  52. err := os.MkdirAll("./system/storage", 0775)
  53. if err != nil {
  54. systemWideLogger.PrintAndLog("System", "Create storage pool setting folder failed: ", nil)
  55. systemWideLogger.PrintAndLog("System", fmt.Sprint(err), nil)
  56. os.Exit(1)
  57. }
  58. adminRouter.HandleFunc("/system/storage/drives", HandleListDrives)
  59. adminRouter.HandleFunc("/system/storage/access", HandleDriveAccess)
  60. adminRouter.HandleFunc("/system/storage/access/explain", HandleDriveAccessExplain)
  61. adminRouter.HandleFunc("/system/storage/pool/removeHandler", HandleStoragePoolRemove)
  62. adminRouter.HandleFunc("/system/storage/pool/reload", HandleStoragePoolReload)
  63. adminRouter.HandleFunc("/system/storage/pool/toggle", HandleFSHToggle)
  64. adminRouter.HandleFunc("/system/storage/pool/edit", HandleFSHEdit)
  65. adminRouter.HandleFunc("/system/storage/pool/test", HandleFSHTest)
  66. }
  67. /*
  68. Pool config files
  69. */
  70. // storagePoolKnown reports whether a pool of this name exists
  71. func storagePoolKnown(pool string) bool {
  72. return pool == storagePoolSystem || permissionHandler.GroupExists(pool)
  73. }
  74. // poolConfigFile returns the config file of a pool
  75. func poolConfigFile(pool string) string {
  76. if pool == storagePoolSystem {
  77. return *storage_config_file
  78. }
  79. return "./system/storage/" + pool + ".json"
  80. }
  81. // readPoolConfig returns the drives configured in a pool. A pool with no
  82. // config file has none.
  83. func readPoolConfig(pool string) ([]fs.FileSystemOption, error) {
  84. options := []fs.FileSystemOption{}
  85. configFile := poolConfigFile(pool)
  86. if !fs.FileExists(configFile) {
  87. return options, nil
  88. }
  89. content, err := os.ReadFile(configFile)
  90. if err != nil {
  91. return nil, err
  92. }
  93. if err := json.Unmarshal(content, &options); err != nil {
  94. systemWideLogger.PrintAndLog("Storage", "Unable to parse storage config "+configFile, err)
  95. return nil, err
  96. }
  97. return options, nil
  98. }
  99. // writePoolConfig replaces the drives configured in a pool
  100. func writePoolConfig(pool string, options []fs.FileSystemOption) error {
  101. configFile := poolConfigFile(pool)
  102. if len(options) == 0 {
  103. err := os.Remove(configFile)
  104. if err != nil && !errors.Is(err, os.ErrNotExist) {
  105. return err
  106. }
  107. return nil
  108. }
  109. js, err := json.MarshalIndent(options, "", " ")
  110. if err != nil {
  111. return err
  112. }
  113. return os.WriteFile(configFile, js, 0775)
  114. }
  115. // findPoolOption returns the config row of a drive in a pool, or nil
  116. func findPoolOption(options []fs.FileSystemOption, uuid string) *fs.FileSystemOption {
  117. for i := range options {
  118. if options[i].Uuid == uuid {
  119. return &options[i]
  120. }
  121. }
  122. return nil
  123. }
  124. // Constract a fsoption from form
  125. func buildOptionFromRequestForm(payload string) (fs.FileSystemOption, error) {
  126. newFsOption := fs.FileSystemOption{}
  127. err := json.Unmarshal([]byte(payload), &newFsOption)
  128. if err != nil {
  129. return fs.FileSystemOption{}, err
  130. }
  131. //Do data cleaning
  132. newFsOption.Name = strings.TrimSpace(newFsOption.Name)
  133. newFsOption.Uuid = strings.TrimSpace(newFsOption.Uuid)
  134. newFsOption.Path = strings.TrimSpace(newFsOption.Path)
  135. if newFsOption.Filesystem == "" {
  136. //A plain folder: the form does not ask, so use what this host has
  137. newFsOption.Filesystem = localFilesystemType()
  138. }
  139. return newFsOption, nil
  140. }
  141. // localFilesystemType names the file system of a local folder on this host
  142. func localFilesystemType() string {
  143. if runtime.GOOS == "windows" {
  144. return "ntfs"
  145. }
  146. return "ext4"
  147. }
  148. /*
  149. Mounting
  150. Saving a drive mounts it right away, so most changes need no pool reload.
  151. */
  152. func mountDrive(poolOwner string, option fs.FileSystemOption) error {
  153. pool, err := GetStoragePoolByOwner(poolOwner)
  154. if err != nil {
  155. return err
  156. }
  157. handler, err := fs.NewFileSystemHandler(option, fs.RuntimePersistenceConfig{
  158. LocalBufferPath: *tmp_directory,
  159. })
  160. if err != nil {
  161. return err
  162. }
  163. if err := pool.AttachFsHandler(handler); err != nil {
  164. handler.Close()
  165. return err
  166. }
  167. systemWideLogger.PrintAndLog("Storage", handler.Name+" Mounted as "+handler.UUID+":/ for "+poolOwner, nil)
  168. return nil
  169. }
  170. func unmountDrive(poolOwner string, uuid string) {
  171. pool, err := GetStoragePoolByOwner(poolOwner)
  172. if err != nil {
  173. return
  174. }
  175. fsh, err := pool.GetFsHandlerByUUID(uuid)
  176. if err != nil {
  177. return
  178. }
  179. pool.DetachFsHandler(uuid)
  180. if !fsh.Closed {
  181. fsh.Close()
  182. }
  183. }
  184. // sendMountResult reports a saved drive. The config is kept when the mount
  185. // fails, so the drive shows as offline and can be fixed from the page.
  186. func sendMountResult(w http.ResponseWriter, mountErr error) {
  187. result := struct {
  188. Mounted bool `json:"mounted"`
  189. Reason string `json:"reason,omitempty"`
  190. }{Mounted: mountErr == nil}
  191. if mountErr != nil {
  192. result.Reason = mountErr.Error()
  193. }
  194. js, _ := json.Marshal(result)
  195. utils.SendJSONResponse(w, string(js))
  196. }
  197. /*
  198. Editing
  199. */
  200. // Handle editing of a given File System Handler
  201. func HandleFSHEdit(w http.ResponseWriter, r *http.Request) {
  202. opr, _ := utils.PostPara(r, "opr")
  203. group, err := utils.PostPara(r, "group")
  204. if err != nil {
  205. utils.SendErrorResponse(w, "Invalid group given")
  206. return
  207. }
  208. if !storagePoolKnown(group) {
  209. utils.SendErrorResponse(w, "Group not exists: "+group)
  210. return
  211. }
  212. switch opr {
  213. case "get":
  214. handleDriveGet(w, r, group)
  215. case "set":
  216. handleDriveSet(w, r, group)
  217. case "new":
  218. handleDriveNew(w, r, group)
  219. default:
  220. utils.SendErrorResponse(w, "Unknown opr given")
  221. }
  222. }
  223. func handleDriveGet(w http.ResponseWriter, r *http.Request, group string) {
  224. uuid, err := utils.PostPara(r, "uuid")
  225. if err != nil {
  226. utils.SendErrorResponse(w, "Invalid UUID")
  227. return
  228. }
  229. fshOption, err := getFSHConfigFromGroupAndUUID(group, uuid)
  230. if err != nil {
  231. utils.SendErrorResponse(w, err.Error())
  232. return
  233. }
  234. //Hide the password info
  235. fshOption.Username = ""
  236. fshOption.Password = ""
  237. js, _ := json.Marshal(fshOption)
  238. utils.SendJSONResponse(w, string(js))
  239. }
  240. func handleDriveSet(w http.ResponseWriter, r *http.Request, group string) {
  241. uuid, err := utils.PostPara(r, "uuid")
  242. if err != nil {
  243. utils.SendErrorResponse(w, "Invalid UUID")
  244. return
  245. }
  246. config, err := utils.PostPara(r, "config")
  247. if err != nil {
  248. utils.SendErrorResponse(w, "Invalid config")
  249. return
  250. }
  251. newFsOption, err := buildOptionFromRequestForm(config)
  252. if err != nil {
  253. utils.SendErrorResponse(w, err.Error())
  254. return
  255. }
  256. //Paths, share links and the access list all carry the id. Looking the old
  257. //row up by a changed id would also leave it behind as a second drive.
  258. if newFsOption.Uuid != uuid {
  259. utils.SendErrorResponse(w, "The id of a drive cannot be changed")
  260. return
  261. }
  262. if access.IsBuiltin(uuid) {
  263. utils.SendErrorResponse(w, "Built-in drives cannot be edited")
  264. return
  265. }
  266. err = setFSHConfigByGroupAndId(group, uuid, &newFsOption)
  267. if err != nil {
  268. utils.SendErrorResponse(w, err.Error())
  269. return
  270. }
  271. //Replace the running drive with the new settings
  272. unmountDrive(group, uuid)
  273. sendMountResult(w, mountDrive(group, newFsOption))
  274. driveAccessChanged()
  275. }
  276. func handleDriveNew(w http.ResponseWriter, r *http.Request, group string) {
  277. config, err := utils.PostPara(r, "config")
  278. if err != nil {
  279. utils.SendErrorResponse(w, "Invalid config")
  280. return
  281. }
  282. newFsOption, err := buildOptionFromRequestForm(config)
  283. if err != nil {
  284. utils.SendErrorResponse(w, err.Error())
  285. return
  286. }
  287. //The access list comes with the drive, so that it is not reachable by the
  288. //default rule for even a moment
  289. var rule *access.Rule
  290. if ruleJSON, _ := utils.PostPara(r, "access"); ruleJSON != "" {
  291. rule = &access.Rule{}
  292. if err := json.Unmarshal([]byte(ruleJSON), rule); err != nil {
  293. utils.SendErrorResponse(w, "Invalid access list")
  294. return
  295. }
  296. if err := rule.Validate(); err != nil {
  297. utils.SendErrorResponse(w, err.Error())
  298. return
  299. }
  300. }
  301. mountErr, err := addDrive(group, newFsOption, rule)
  302. if err != nil {
  303. utils.SendErrorResponse(w, err.Error())
  304. return
  305. }
  306. sendMountResult(w, mountErr)
  307. }
  308. // addDrive saves a new drive in a pool and mounts it. err is set when the
  309. // drive was not saved; mountErr when it was saved but could not be mounted,
  310. // in which case it shows as offline. rule, if given, is its access list.
  311. func addDrive(group string, option fs.FileSystemOption, rule *access.Rule) (mountErr error, err error) {
  312. if err := validateNewDrive(&option, collectPoolStates()); err != nil {
  313. return nil, err
  314. }
  315. options, err := readPoolConfig(group)
  316. if err != nil {
  317. return nil, err
  318. }
  319. if err := writePoolConfig(group, append(options, option)); err != nil {
  320. return nil, err
  321. }
  322. if rule != nil {
  323. if err := driveAccessStore.Set(option.Uuid, *rule); err != nil {
  324. return nil, err
  325. }
  326. }
  327. mountErr = mountDrive(group, option)
  328. driveAccessChanged()
  329. return mountErr, nil
  330. }
  331. // validateNewDrive checks a drive about to be added. Drive ids are global:
  332. // the access list and every path lookup find a drive by its id alone.
  333. func validateNewDrive(option *fs.FileSystemOption, pools []poolState) error {
  334. if err := fs.ValidateOption(option); err != nil {
  335. return err
  336. }
  337. if !driveIDFormat.MatchString(option.Uuid) {
  338. return errors.New("A drive id can only contain letters, numbers, - and _")
  339. }
  340. for _, pool := range pools {
  341. if pool.holds(option.Uuid) {
  342. return errors.New("Drive id " + option.Uuid + " is already used in the " + pool.owner + " pool")
  343. }
  344. }
  345. return nil
  346. }
  347. // Get the FSH configuration for the given group and uuid
  348. func getFSHConfigFromGroupAndUUID(group string, uuid string) (*fs.FileSystemOption, error) {
  349. options, err := readPoolConfig(group)
  350. if err != nil {
  351. return nil, err
  352. }
  353. option := findPoolOption(options, uuid)
  354. if option == nil {
  355. return nil, errors.New("No FSH config found with the uuid")
  356. }
  357. return option, nil
  358. }
  359. // setFSHConfigByGroupAndId replaces a config row in place, keeping the stored
  360. // login when the form left it empty. The stored login is written back into
  361. // options, which the caller goes on to mount.
  362. func setFSHConfigByGroupAndId(group string, uuid string, options *fs.FileSystemOption) error {
  363. loadedConfig, err := readPoolConfig(group)
  364. if err != nil {
  365. return err
  366. }
  367. current := findPoolOption(loadedConfig, uuid)
  368. if current == nil {
  369. return errors.New("No FSH config found with the uuid")
  370. }
  371. if options.Username == "" {
  372. options.Username = current.Username
  373. }
  374. if options.Password == "" {
  375. options.Password = current.Password
  376. }
  377. if err := fs.ValidateOption(options); err != nil {
  378. return err
  379. }
  380. *current = *options
  381. return writePoolConfig(group, loadedConfig)
  382. }
  383. // Handle Storage Pool toggle on-off
  384. func HandleFSHToggle(w http.ResponseWriter, r *http.Request) {
  385. fsh, _ := utils.PostPara(r, "fsh")
  386. if fsh == "" {
  387. utils.SendErrorResponse(w, "Invalid File System Handler ID")
  388. return
  389. }
  390. group, _ := utils.PostPara(r, "group")
  391. if group == "" {
  392. utils.SendErrorResponse(w, "Invalid group ID")
  393. return
  394. }
  395. //Check if group exists
  396. if !storagePoolKnown(group) {
  397. utils.SendErrorResponse(w, "Group not exists")
  398. return
  399. }
  400. //Not allow to modify system reserved fsh
  401. if access.IsBuiltin(fsh) {
  402. utils.SendErrorResponse(w, "Cannot toggle system reserved File System Handler")
  403. return
  404. }
  405. storagePool, err := GetStoragePoolByOwner(group)
  406. if err != nil {
  407. utils.SendErrorResponse(w, err.Error())
  408. return
  409. }
  410. targetFSH, err := storagePool.GetFsHandlerByUUID(fsh)
  411. if err != nil {
  412. utils.SendErrorResponse(w, "Target File System Handler not found, given: "+fsh)
  413. return
  414. }
  415. targetFSH.Closed = !targetFSH.Closed
  416. //Return ok
  417. utils.SendOK(w)
  418. }
  419. // reloadBasePool closes and reopens the system pool, built-in drives included
  420. func reloadBasePool() {
  421. baseStoragePool.Close()
  422. emptyPool := storage.StoragePool{}
  423. baseStoragePool = &emptyPool
  424. //Start BasePool again
  425. err := LoadBaseStoragePool()
  426. if err != nil {
  427. systemWideLogger.PrintAndLog("Storage", err.Error(), err)
  428. return
  429. }
  430. //Update userHandler's basePool
  431. userHandler.UpdateStoragePool(baseStoragePool)
  432. }
  433. // Handle reload of storage pool
  434. func HandleStoragePoolReload(w http.ResponseWriter, r *http.Request) {
  435. pool, _ := utils.PostPara(r, "pool")
  436. switch pool {
  437. case reloadAllPools:
  438. reloadBasePool()
  439. for _, pg := range permissionHandler.PermissionGroups {
  440. reloadGroupPool(pg.Name)
  441. }
  442. case storagePoolSystem:
  443. reloadBasePool()
  444. default:
  445. if !permissionHandler.GroupExists(pool) {
  446. utils.SendErrorResponse(w, "Permission Pool owner not exists")
  447. return
  448. }
  449. reloadGroupPool(pool)
  450. }
  451. driveAccessChanged()
  452. // Restart all enabled file servers so they pick up the new drive
  453. // configuration. Errors are logged but do not prevent the reload
  454. // from succeeding.
  455. restartAllEnabledServers()
  456. utils.SendOK(w)
  457. }
  458. // restartAllEnabledServers stops and restarts every enabled file server.
  459. // It is invoked after a storage pool reload to ensure file servers (SMB,
  460. // WebDAV, SFTP, FTP, etc.) see the re-mounted drives. Failures are
  461. // logged to systemWideLogger but never block the reload response.
  462. func restartAllEnabledServers() {
  463. for _, fserv := range networkFileServerDaemon {
  464. if fserv.EnableCheck == nil || fserv.ToggleFunc == nil {
  465. continue
  466. }
  467. if !fserv.EnableCheck() {
  468. continue
  469. }
  470. systemWideLogger.PrintAndLog("Storage", fmt.Sprintf("Restarting file server: %s", fserv.Name), nil)
  471. // Stop
  472. if err := fserv.ToggleFunc(false); err != nil {
  473. systemWideLogger.PrintAndLog("Storage", fmt.Sprintf("Failed to stop file server %s: %v", fserv.Name, err), nil)
  474. continue
  475. }
  476. // Brief pause so the OS releases the port cleanly (important for
  477. // SMB on port 445).
  478. time.Sleep(500 * time.Millisecond)
  479. // Start
  480. if err := fserv.ToggleFunc(true); err != nil {
  481. systemWideLogger.PrintAndLog("Storage", fmt.Sprintf("Failed to restart file server %s: %v", fserv.Name, err), nil)
  482. continue
  483. }
  484. systemWideLogger.PrintAndLog("Storage", fmt.Sprintf("File server %s restarted successfully", fserv.Name), nil)
  485. }
  486. }
  487. // reloadGroupPool closes and reopens the pool of a permission group
  488. func reloadGroupPool(group string) {
  489. systemWideLogger.PrintAndLog("Storage", "Reloading Storage Pool for: "+group, nil)
  490. pg := permissionHandler.GetPermissionGroupByName(group)
  491. //Pool should be exists. Close it
  492. pg.StoragePool.Close()
  493. //Create an empty pool for this permission group
  494. newEmptyPool := storage.StoragePool{}
  495. pg.StoragePool = &newEmptyPool
  496. //Recreate a new pool for this permission group
  497. //If there is no handler in config, the empty one will be kept
  498. LoadStoragePoolForGroup(pg)
  499. }
  500. func HandleStoragePoolRemove(w http.ResponseWriter, r *http.Request) {
  501. groupname, err := utils.PostPara(r, "group")
  502. if err != nil {
  503. utils.SendErrorResponse(w, "group not defined")
  504. return
  505. }
  506. uuid, err := utils.PostPara(r, "uuid")
  507. if err != nil {
  508. utils.SendErrorResponse(w, "File system handler UUID not defined")
  509. return
  510. }
  511. if access.IsBuiltin(uuid) {
  512. utils.SendErrorResponse(w, "Cannot remove system reserved file system handlers")
  513. return
  514. }
  515. if !storagePoolKnown(groupname) {
  516. utils.SendErrorResponse(w, "Group not exists")
  517. return
  518. }
  519. if err := removeDrive(groupname, uuid); err != nil {
  520. utils.SendErrorResponse(w, err.Error())
  521. return
  522. }
  523. utils.SendOK(w)
  524. }
  525. // removeDrive takes a drive out of a pool's config, unmounts it and drops its
  526. // access rule once no pool holds that id any more
  527. func removeDrive(groupname string, uuid string) error {
  528. //Generate new confic by filtering
  529. oldConfigs, err := readPoolConfig(groupname)
  530. if err != nil {
  531. return errors.New("Failed to parse original config file")
  532. }
  533. newConfigs := []fs.FileSystemOption{}
  534. for _, config := range oldConfigs {
  535. if config.Uuid != uuid {
  536. newConfigs = append(newConfigs, config)
  537. }
  538. }
  539. if err := writePoolConfig(groupname, newConfigs); err != nil {
  540. return err
  541. }
  542. unmountDrive(groupname, uuid)
  543. //The rule goes with the last drive of that id
  544. if _, stillUsed := drivePoolHome(uuid); !stillUsed {
  545. if err := driveAccessStore.Remove(uuid); err != nil {
  546. systemWideLogger.PrintAndLog("Storage", "Unable to remove the access rule of "+uuid+":/", err)
  547. }
  548. }
  549. driveAccessChanged()
  550. return nil
  551. }
  552. /*
  553. Testing a drive before saving it
  554. */
  555. // HandleFSHTest tries the settings of the add and edit drive form
  556. func HandleFSHTest(w http.ResponseWriter, r *http.Request) {
  557. config, err := utils.PostPara(r, "config")
  558. if err != nil {
  559. utils.SendErrorResponse(w, "Invalid config")
  560. return
  561. }
  562. option, err := buildOptionFromRequestForm(config)
  563. if err != nil {
  564. utils.SendErrorResponse(w, err.Error())
  565. return
  566. }
  567. if !arozfs.IsNetworkDrive(option.Filesystem) {
  568. if !fs.FileExists(option.Path) {
  569. utils.SendErrorResponse(w, "Path not exists, given: "+option.Path)
  570. return
  571. }
  572. utils.SendOK(w)
  573. return
  574. }
  575. //Editing a drive leaves the login fields empty to keep the stored login
  576. group, _ := utils.PostPara(r, "group")
  577. if option.Username == "" && option.Password == "" && storagePoolKnown(group) {
  578. if stored, err := getFSHConfigFromGroupAndUUID(group, option.Uuid); err == nil {
  579. option.Username = stored.Username
  580. option.Password = stored.Password
  581. }
  582. }
  583. if err := testNetworkDrive(option); err != nil {
  584. utils.SendErrorResponse(w, err.Error())
  585. return
  586. }
  587. utils.SendOK(w)
  588. }
  589. // testNetworkDrive connects to a network drive and disconnects again. A server
  590. // that does not answer must not hold the request up for as long as its
  591. // connection attempt takes.
  592. func testNetworkDrive(option fs.FileSystemOption) error {
  593. if option.Uuid == "" {
  594. option.Uuid = "connectiontest"
  595. }
  596. option.Automount = false
  597. result := make(chan error, 1)
  598. go func() {
  599. handler, err := fs.NewFileSystemHandler(option, fs.RuntimePersistenceConfig{
  600. LocalBufferPath: *tmp_directory,
  601. })
  602. if err == nil {
  603. handler.Close()
  604. }
  605. result <- err
  606. }()
  607. select {
  608. case err := <-result:
  609. return err
  610. case <-time.After(driveTestTimeout):
  611. return errors.New("The server did not answer in time")
  612. }
  613. }
  614. /*
  615. The drive list
  616. The state of a drive used to be guessed by the page from the running pools
  617. and the raw config files, which sent the stored logins to the browser and
  618. called every drive built by code "Removed". It is worked out here instead.
  619. */
  620. // poolState is what is known about one pool, running and configured
  621. type poolState struct {
  622. owner string
  623. live []*fs.FileSystemHandler
  624. config []fs.FileSystemOption
  625. }
  626. // holds reports whether this pool runs or configures a drive
  627. func (p poolState) holds(uuid string) bool {
  628. for _, fsh := range p.live {
  629. if fsh.UUID == uuid {
  630. return true
  631. }
  632. }
  633. return findPoolOption(p.config, uuid) != nil
  634. }
  635. // collectPoolStates reads every pool, the system pool first
  636. func collectPoolStates() []poolState {
  637. states := []poolState{}
  638. for _, pool := range GetAllStoragePools() {
  639. state := poolState{owner: pool.Owner, live: pool.Storages}
  640. if options, err := readPoolConfig(pool.Owner); err == nil {
  641. state.config = options
  642. }
  643. states = append(states, state)
  644. }
  645. return states
  646. }
  647. // duplicateDriveIDs lists the drive ids used by more than one pool
  648. func duplicateDriveIDs(pools []poolState) []string {
  649. useCount := map[string]int{}
  650. for _, pool := range pools {
  651. seen := map[string]bool{}
  652. for _, fsh := range pool.live {
  653. seen[fsh.UUID] = true
  654. }
  655. for _, option := range pool.config {
  656. seen[option.Uuid] = true
  657. }
  658. for uuid := range seen {
  659. useCount[uuid]++
  660. }
  661. }
  662. duplicates := []string{}
  663. for uuid, count := range useCount {
  664. if count > 1 {
  665. duplicates = append(duplicates, uuid)
  666. }
  667. }
  668. sort.Strings(duplicates)
  669. return duplicates
  670. }
  671. // driveInfo is one drive of the Storage Pools page. It never carries a login.
  672. type driveInfo struct {
  673. UUID string `json:"uuid"`
  674. Name string `json:"name"`
  675. Pool string `json:"pool"`
  676. Kind string `json:"kind"`
  677. State string `json:"state"`
  678. Path string `json:"path"`
  679. Filesystem string `json:"filesystem"`
  680. Hierarchy string `json:"hierarchy"`
  681. ReadOnly bool `json:"readOnly"`
  682. Duplicate bool `json:"duplicate"`
  683. Rule access.Rule `json:"rule"`
  684. Editable bool `json:"ruleEditable"`
  685. Replicated bool `json:"ruleReplicated"`
  686. }
  687. func driveKindOf(uuid string) string {
  688. switch {
  689. case access.IsFixed(uuid):
  690. return driveKindFixed
  691. case access.IsBuiltin(uuid):
  692. return driveKindBuiltin
  693. default:
  694. return driveKindConfigured
  695. }
  696. }
  697. // homeOfPool turns a pool owner into the home group of its drives
  698. func homeOfPool(owner string) string {
  699. if owner == storagePoolSystem {
  700. return ""
  701. }
  702. return owner
  703. }
  704. // buildDriveList lists every drive of the given pools with its state and rule
  705. func buildDriveList(pools []poolState, rules access.Source) []driveInfo {
  706. duplicates := map[string]bool{}
  707. for _, uuid := range duplicateDriveIDs(pools) {
  708. duplicates[uuid] = true
  709. }
  710. drives := []driveInfo{}
  711. for _, pool := range pools {
  712. home := homeOfPool(pool.owner)
  713. live := map[string]bool{}
  714. for _, fsh := range pool.live {
  715. live[fsh.UUID] = true
  716. kind := driveKindOf(fsh.UUID)
  717. state := driveStateOnline
  718. if fsh.Closed {
  719. state = driveStateStopped
  720. } else if kind == driveKindConfigured && findPoolOption(pool.config, fsh.UUID) == nil {
  721. state = driveStateRemoved
  722. }
  723. drives = append(drives, driveInfo{
  724. UUID: fsh.UUID,
  725. Name: fsh.Name,
  726. Pool: pool.owner,
  727. Kind: kind,
  728. State: state,
  729. Path: fsh.Path,
  730. Filesystem: fsh.Filesystem,
  731. Hierarchy: fsh.Hierarchy,
  732. ReadOnly: fsh.ReadOnly,
  733. Duplicate: duplicates[fsh.UUID],
  734. Rule: effectiveDriveRule(rules, fsh.UUID, home),
  735. Editable: kind != driveKindFixed,
  736. })
  737. }
  738. for _, option := range pool.config {
  739. if live[option.Uuid] {
  740. continue
  741. }
  742. drives = append(drives, driveInfo{
  743. UUID: option.Uuid,
  744. Name: option.Name,
  745. Pool: pool.owner,
  746. Kind: driveKindConfigured,
  747. State: driveStateOffline,
  748. Path: option.Path,
  749. Filesystem: option.Filesystem,
  750. Hierarchy: option.Hierarchy,
  751. ReadOnly: option.Access == arozfs.FsReadOnly,
  752. Duplicate: duplicates[option.Uuid],
  753. Rule: effectiveDriveRule(rules, option.Uuid, home),
  754. Editable: true,
  755. })
  756. }
  757. }
  758. return drives
  759. }
  760. // applyClusterDriveState completes the row of cluster:/. Its rule belongs to
  761. // the cluster, and a node that is not in one has nowhere to save it. Without
  762. // a mounted drive it is listed anyway, so an admin can tell it exists.
  763. func applyClusterDriveState(drives []driveInfo, inCluster bool, rules access.Source) []driveInfo {
  764. for i := range drives {
  765. if drives[i].UUID == access.ClusterDriveID {
  766. drives[i].Editable = inCluster
  767. drives[i].Replicated = true
  768. return drives
  769. }
  770. }
  771. return append(drives, driveInfo{
  772. UUID: access.ClusterDriveID,
  773. Name: "Cluster",
  774. Pool: storagePoolSystem,
  775. Kind: driveKindBuiltin,
  776. State: driveStateNotActive,
  777. Path: access.ClusterDriveID + ":/",
  778. Filesystem: "cluster",
  779. Hierarchy: "public",
  780. Rule: effectiveDriveRule(rules, access.ClusterDriveID, ""),
  781. Editable: inCluster,
  782. Replicated: true,
  783. })
  784. }
  785. // HandleListDrives returns every drive of this host with its state and rule,
  786. // and the permission groups a rule can name
  787. func HandleListDrives(w http.ResponseWriter, r *http.Request) {
  788. type groupInfo struct {
  789. Name string `json:"name"`
  790. IsAdmin bool `json:"isAdmin"`
  791. }
  792. rules := driveRuleSource{}
  793. drives := buildDriveList(collectPoolStates(), rules)
  794. if !*disable_cluster {
  795. drives = applyClusterDriveState(drives, clusterManager != nil && clusterManager.InCluster(), rules)
  796. }
  797. groups := []groupInfo{}
  798. for _, pg := range permissionHandler.PermissionGroups {
  799. groups = append(groups, groupInfo{Name: pg.Name, IsAdmin: pg.IsAdmin})
  800. }
  801. result := struct {
  802. Groups []groupInfo `json:"groups"`
  803. Drives []driveInfo `json:"drives"`
  804. RuleError string `json:"ruleError,omitempty"`
  805. }{Groups: groups, Drives: drives}
  806. if err := driveAccessStore.Err(); err != nil {
  807. result.RuleError = err.Error()
  808. }
  809. js, err := json.Marshal(result)
  810. if err != nil {
  811. utils.SendErrorResponse(w, err.Error())
  812. return
  813. }
  814. utils.SendJSONResponse(w, string(js))
  815. }
  816. // HandleDriveAccess reads (GET) or saves (POST) the access list of a drive
  817. func HandleDriveAccess(w http.ResponseWriter, r *http.Request) {
  818. if r.Method != http.MethodPost {
  819. uuid, err := utils.GetPara(r, "uuid")
  820. if err != nil {
  821. utils.SendErrorResponse(w, "Invalid drive id")
  822. return
  823. }
  824. home, known := drivePoolHome(uuid)
  825. if !known && uuid != access.ClusterDriveID {
  826. utils.SendErrorResponse(w, "Drive not found: "+uuid)
  827. return
  828. }
  829. js, _ := json.Marshal(effectiveDriveRule(driveRuleSource{}, uuid, home))
  830. utils.SendJSONResponse(w, string(js))
  831. return
  832. }
  833. uuid, err := utils.PostPara(r, "uuid")
  834. if err != nil {
  835. utils.SendErrorResponse(w, "Invalid drive id")
  836. return
  837. }
  838. ruleJSON, err := utils.PostPara(r, "rule")
  839. if err != nil {
  840. utils.SendErrorResponse(w, "Invalid access list")
  841. return
  842. }
  843. rule := access.Rule{}
  844. if err := json.Unmarshal([]byte(ruleJSON), &rule); err != nil {
  845. utils.SendErrorResponse(w, "Invalid access list")
  846. return
  847. }
  848. home, known := drivePoolHome(uuid)
  849. if !known && uuid != access.ClusterDriveID {
  850. utils.SendErrorResponse(w, "Drive not found: "+uuid)
  851. return
  852. }
  853. if err := prepareDriveRule(uuid, home, &rule); err != nil {
  854. utils.SendErrorResponse(w, err.Error())
  855. return
  856. }
  857. if err := setDriveRule(uuid, rule); err != nil {
  858. utils.SendErrorResponse(w, err.Error())
  859. return
  860. }
  861. driveAccessChanged()
  862. utils.SendOK(w)
  863. }
  864. // prepareDriveRule checks a rule against the drive it is for. A row for the
  865. // home group would change nothing, those members always have full access.
  866. func prepareDriveRule(uuid string, home string, rule *access.Rule) error {
  867. if access.IsFixed(uuid) {
  868. return errors.New(uuid + ":/ is open to everyone and has no access list")
  869. }
  870. if err := rule.Validate(); err != nil {
  871. return err
  872. }
  873. if uuid == access.ShareDriveID {
  874. //The drive is read only, so it is either visible or hidden
  875. if rule.Other == access.ReadWrite {
  876. return errors.New("share:/ is read only")
  877. }
  878. for _, level := range rule.Groups {
  879. if level == access.ReadWrite {
  880. return errors.New("share:/ is read only")
  881. }
  882. }
  883. }
  884. if home != "" {
  885. delete(rule.Groups, home)
  886. }
  887. return nil
  888. }
  889. // HandleDriveAccessExplain shows which rule decided what a user may do on a drive
  890. func HandleDriveAccessExplain(w http.ResponseWriter, r *http.Request) {
  891. username, err := utils.GetPara(r, "user")
  892. if err != nil {
  893. utils.SendErrorResponse(w, "Invalid user")
  894. return
  895. }
  896. uuid, err := utils.GetPara(r, "drive")
  897. if err != nil {
  898. utils.SendErrorResponse(w, "Invalid drive id")
  899. return
  900. }
  901. userinfo, err := userHandler.GetUserInfoFromUsername(username)
  902. if err != nil {
  903. utils.SendErrorResponse(w, "User not found: "+username)
  904. return
  905. }
  906. decision, found := userinfo.ExplainDriveAccess(uuid)
  907. if !found {
  908. utils.SendErrorResponse(w, "Drive not found: "+uuid)
  909. return
  910. }
  911. js, _ := json.Marshal(decision)
  912. utils.SendJSONResponse(w, string(js))
  913. }