volumes.go 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. package storage
  2. /*
  3. Volumes: folders on this node's local drives that hold cluster files.
  4. */
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "os"
  10. "path/filepath"
  11. "strings"
  12. "time"
  13. uuid "github.com/satori/go.uuid"
  14. "imuslab.com/arozos/mod/cluster/capability"
  15. "imuslab.com/arozos/mod/cluster/metadata"
  16. "imuslab.com/arozos/mod/info/logger"
  17. )
  18. const (
  19. //diskFullFraction is the free space below which a volume stops taking
  20. //new files; it starts again above diskRecoverFraction.
  21. diskFullFraction = 0.05
  22. diskRecoverFraction = 0.07
  23. )
  24. // LocalVolumes lists this node's volumes that are not removed.
  25. func (s *Service) LocalVolumes() []metadata.Volume {
  26. out := []metadata.Volume{}
  27. for _, v := range s.meta.Volumes() {
  28. if v.NodeID == s.m.NodeID() && !v.Removed {
  29. out = append(out, v)
  30. }
  31. }
  32. return out
  33. }
  34. // volumeRoot returns the real directory of a local volume.
  35. func (s *Service) volumeRoot(vol *metadata.Volume) (string, error) {
  36. if vol.NodeID != s.m.NodeID() {
  37. return "", ErrNotLocalVolume
  38. }
  39. roots := s.opt.LocalRoots()
  40. root, ok := roots[vol.FshUUID]
  41. if !ok {
  42. return "", errors.New("local drive " + vol.FshUUID + " is not mounted")
  43. }
  44. return filepath.Clean(filepath.Join(root, filepath.FromSlash(vol.Subpath))), nil
  45. }
  46. // realPath maps a logical path onto a local volume, refusing escapes.
  47. func (s *Service) realPath(vol *metadata.Volume, logical string) (string, error) {
  48. root, err := s.volumeRoot(vol)
  49. if err != nil {
  50. return "", err
  51. }
  52. logical = metadata.NormalizePath(logical)
  53. full := filepath.Clean(filepath.Join(root, filepath.FromSlash(logical)))
  54. if full != root && !strings.HasPrefix(full, root+string(filepath.Separator)) {
  55. return "", ErrPathEscape
  56. }
  57. return full, nil
  58. }
  59. func normalizeSubpath(p string) string {
  60. p = strings.ReplaceAll(strings.TrimSpace(p), "\\", "/")
  61. if !strings.HasPrefix(p, "/") {
  62. p = "/" + p
  63. }
  64. p = filepath.ToSlash(filepath.Clean(p))
  65. if p == "." {
  66. p = "/"
  67. }
  68. return p
  69. }
  70. // AddVolume contributes a folder of a local drive to the cluster.
  71. func (s *Service) AddVolume(fshUUID string, subpath string, name string) (*metadata.Volume, error) {
  72. if !s.m.InCluster() {
  73. return nil, metadata.ErrNotInCluster
  74. }
  75. roots := s.opt.LocalRoots()
  76. root, ok := roots[fshUUID]
  77. if !ok {
  78. return nil, errors.New("drive " + fshUUID + " is not a local drive on this node")
  79. }
  80. subpath = normalizeSubpath(subpath)
  81. if strings.Contains(subpath, "..") {
  82. return nil, ErrPathEscape
  83. }
  84. dir := filepath.Clean(filepath.Join(root, filepath.FromSlash(subpath)))
  85. if subpath == "/" && fshUUID == "user" {
  86. return nil, errors.New("the user root itself cannot be a cluster volume; pick a sub folder such as /cluster")
  87. }
  88. for _, v := range s.meta.Volumes() {
  89. if !v.Removed && v.NodeID == s.m.NodeID() && v.FshUUID == fshUUID && v.Subpath == subpath {
  90. return nil, errors.New("this folder is already a cluster volume")
  91. }
  92. }
  93. if err := os.MkdirAll(dir, 0755); err != nil {
  94. return nil, err
  95. }
  96. if strings.TrimSpace(name) == "" {
  97. //The node is named by its ID wherever a volume is pointed at, so the
  98. //default name says nothing about which node it is on: node names are
  99. //operator set and every fresh install answers to "My ArOZ", which
  100. //would make two volumes of the same folder indistinguishable.
  101. name = fshUUID + ":" + subpath
  102. }
  103. vol := &metadata.Volume{
  104. ID: uuid.NewV4().String(),
  105. NodeID: s.m.NodeID(),
  106. Name: strings.TrimSpace(name),
  107. FshUUID: fshUUID,
  108. Subpath: subpath,
  109. }
  110. if free, total, err := capability.DiskUsage(dir); err == nil {
  111. vol.Free, vol.Capacity = free, total
  112. }
  113. if err := s.meta.Submit(metadata.KindVolume, vol); err != nil {
  114. return nil, err
  115. }
  116. go s.reconcileVolume(*vol)
  117. return vol, nil
  118. }
  119. // RemoveVolume stops contributing a folder. Files stay on disk. It refuses
  120. // when the volume holds the only healthy copy of any file; evacuate first.
  121. func (s *Service) RemoveVolume(id string) error {
  122. vol, ok := s.meta.Volume(id)
  123. if !ok || vol.Removed {
  124. return errors.New("volume not found")
  125. }
  126. if vol.NodeID != s.m.NodeID() {
  127. return ErrNotLocalVolume
  128. }
  129. if sole := s.SoleCopies(id); sole > 0 {
  130. return fmt.Errorf("this volume holds the only copy of %d file(s); evacuate it first", sole)
  131. }
  132. vol.Removed = true
  133. if err := s.meta.Submit(metadata.KindVolume, vol); err != nil {
  134. return err
  135. }
  136. s.forgetVolumeLocations(id)
  137. return nil
  138. }
  139. // forgetVolumeLocations drops a retired volume from every record. The files
  140. // stay on disk; they are simply no longer reachable through the cluster.
  141. func (s *Service) forgetVolumeLocations(volumeID string) {
  142. for _, rec := range s.meta.AllFiles() {
  143. if _, has := rec.Location(volumeID); !has {
  144. continue
  145. }
  146. r := rec.Clone()
  147. r.RemoveLocation(volumeID)
  148. if r.Primary == volumeID {
  149. r.Primary = ""
  150. if h := r.HealthyLocations(); len(h) > 0 {
  151. r.Primary = h[0].VolumeID
  152. }
  153. }
  154. s.meta.Submit(metadata.KindFile, r)
  155. }
  156. }
  157. // SoleCopies counts files whose only healthy copy sits on the volume.
  158. func (s *Service) SoleCopies(volumeID string) int {
  159. n := 0
  160. for _, rec := range s.meta.AllFiles() {
  161. if rec.Removed || rec.IsDir {
  162. continue
  163. }
  164. healthy := rec.HealthyLocations()
  165. if len(healthy) == 1 && healthy[0].VolumeID == volumeID {
  166. n++
  167. }
  168. }
  169. return n
  170. }
  171. // SetVolumeReadOnly toggles placement on a local volume.
  172. func (s *Service) SetVolumeReadOnly(id string, ro bool) error {
  173. vol, ok := s.meta.Volume(id)
  174. if !ok || vol.Removed {
  175. return errors.New("volume not found")
  176. }
  177. if vol.NodeID != s.m.NodeID() {
  178. return ErrNotLocalVolume
  179. }
  180. vol.ReadOnly = ro
  181. return s.meta.Submit(metadata.KindVolume, vol)
  182. }
  183. // refreshVolumes republishes free space when it moved by more than 1 %.
  184. func (s *Service) refreshVolumes() {
  185. auto := s.AutoReadOnly()
  186. for _, v := range s.LocalVolumes() {
  187. root, err := s.volumeRoot(&v)
  188. if err != nil {
  189. continue
  190. }
  191. free, total, err := capability.DiskUsage(root)
  192. if err != nil {
  193. continue
  194. }
  195. delta := v.Free - free
  196. if delta < 0 {
  197. delta = -delta
  198. }
  199. //A volume under the low water mark stops taking new files until it
  200. //recovers, so a node never fills its own disk (unless an admin turned
  201. //that off for the cluster).
  202. wasFull := v.ReadOnly && v.LowSpace
  203. mark, clear := lowSpaceAction(free, total, wasFull, auto)
  204. changed := total != v.Capacity || (total > 0 && delta*100 > total)
  205. if mark {
  206. v.ReadOnly, v.LowSpace, changed = true, true, true
  207. logger.PrintAndLog("Cluster", "Volume "+v.Name+" is nearly full and stops taking new files", nil)
  208. if s.OnDiskFull != nil {
  209. s.OnDiskFull(v)
  210. }
  211. } else if clear {
  212. v.ReadOnly, v.LowSpace, changed = false, false, true
  213. if auto {
  214. logger.PrintAndLog("Cluster", "Volume "+v.Name+" has room again and takes new files", nil)
  215. } else {
  216. logger.PrintAndLog("Cluster", "Volume "+v.Name+" takes new files again: automatic read-only is turned off", nil)
  217. }
  218. }
  219. if changed {
  220. v.Free, v.Capacity = free, total
  221. s.meta.Submit(metadata.KindVolume, &v)
  222. }
  223. }
  224. }
  225. // AutoReadOnlyKey is the replicated setting that turns the nearly-full guard
  226. // on or off for the whole cluster.
  227. const AutoReadOnlyKey = "storage.autoReadOnly"
  228. type autoReadOnlySetting struct {
  229. Enabled bool `json:"enabled"`
  230. }
  231. // AutoReadOnly reports whether volumes that are nearly full are made read
  232. // only automatically. It is on unless an admin turned it off.
  233. func (s *Service) AutoReadOnly() bool {
  234. st, ok := s.meta.Setting(AutoReadOnlyKey)
  235. if !ok {
  236. return true
  237. }
  238. var v autoReadOnlySetting
  239. if json.Unmarshal(st.Value, &v) != nil {
  240. return true
  241. }
  242. return v.Enabled
  243. }
  244. // SetAutoReadOnly turns the nearly-full guard on or off for every node. This
  245. // node applies it at once; the others at their next volume refresh.
  246. func (s *Service) SetAutoReadOnly(enabled bool) error {
  247. js, err := json.Marshal(autoReadOnlySetting{Enabled: enabled})
  248. if err != nil {
  249. return err
  250. }
  251. if err := s.meta.Submit(metadata.KindSetting, &metadata.Setting{Key: AutoReadOnlyKey, Value: js}); err != nil {
  252. return err
  253. }
  254. go s.refreshVolumes()
  255. return nil
  256. }
  257. // lowSpaceAction decides what the guard does to one volume. wasFull says the
  258. // guard itself made the volume read only earlier. With the guard on, a volume
  259. // is marked below the low water mark and released above the recover mark;
  260. // with it off, nothing is marked and anything the guard had marked is
  261. // released, while read-only set by an admin is never touched.
  262. func lowSpaceAction(free int64, total int64, wasFull bool, auto bool) (mark bool, clear bool) {
  263. if !auto {
  264. return false, wasFull
  265. }
  266. full, recovered := spaceState(free, total, wasFull)
  267. return full && !wasFull, recovered
  268. }
  269. // spaceState decides whether a volume is too full to take new files. The two
  270. // thresholds differ so a volume hovering at the limit does not flap: it stops
  271. // below diskFullFraction and only starts again above diskRecoverFraction.
  272. func spaceState(free int64, total int64, wasFull bool) (full bool, recovered bool) {
  273. if total <= 0 {
  274. return false, false
  275. }
  276. frac := float64(free) / float64(total)
  277. if wasFull {
  278. return true, frac > diskRecoverFraction
  279. }
  280. return frac < diskFullFraction, false
  281. }
  282. // VolumeStats counts files held on a local volume (for the UI).
  283. func (s *Service) VolumeStats(id string) (files int, bytes int64) {
  284. for _, rec := range s.meta.AllFiles() {
  285. if rec.Removed || rec.IsDir {
  286. continue
  287. }
  288. if loc, ok := rec.Location(id); ok && loc.Healthy() {
  289. files++
  290. bytes += rec.Size
  291. }
  292. }
  293. return
  294. }
  295. func modTimeOf(fi os.FileInfo) int64 {
  296. if fi == nil {
  297. return time.Now().Unix()
  298. }
  299. return fi.ModTime().Unix()
  300. }