folderconfiguration.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package config
  7. import (
  8. "errors"
  9. "fmt"
  10. "runtime"
  11. "github.com/syncthing/syncthing/lib/fs"
  12. "github.com/syncthing/syncthing/lib/protocol"
  13. "github.com/syncthing/syncthing/lib/util"
  14. "github.com/syncthing/syncthing/lib/versioner"
  15. )
  16. var (
  17. ErrPathNotDirectory = errors.New("folder path not a directory")
  18. ErrPathMissing = errors.New("folder path missing")
  19. ErrMarkerMissing = errors.New("folder marker missing")
  20. )
  21. const DefaultMarkerName = ".stfolder"
  22. type FolderConfiguration struct {
  23. ID string `xml:"id,attr" json:"id"`
  24. Label string `xml:"label,attr" json:"label" restart:"false"`
  25. FilesystemType fs.FilesystemType `xml:"filesystemType" json:"filesystemType"`
  26. Path string `xml:"path,attr" json:"path"`
  27. Type FolderType `xml:"type,attr" json:"type"`
  28. Devices []FolderDeviceConfiguration `xml:"device" json:"devices"`
  29. RescanIntervalS int `xml:"rescanIntervalS,attr" json:"rescanIntervalS" default:"3600"`
  30. FSWatcherEnabled bool `xml:"fsWatcherEnabled,attr" json:"fsWatcherEnabled" default:"true"`
  31. FSWatcherDelayS int `xml:"fsWatcherDelayS,attr" json:"fsWatcherDelayS" default:"10"`
  32. IgnorePerms bool `xml:"ignorePerms,attr" json:"ignorePerms"`
  33. AutoNormalize bool `xml:"autoNormalize,attr" json:"autoNormalize" default:"true"`
  34. MinDiskFree Size `xml:"minDiskFree" json:"minDiskFree" default:"1%"`
  35. Versioning VersioningConfiguration `xml:"versioning" json:"versioning"`
  36. Copiers int `xml:"copiers" json:"copiers"` // This defines how many files are handled concurrently.
  37. PullerMaxPendingKiB int `xml:"pullerMaxPendingKiB" json:"pullerMaxPendingKiB"`
  38. Hashers int `xml:"hashers" json:"hashers"` // Less than one sets the value to the number of cores. These are CPU bound due to hashing.
  39. Order PullOrder `xml:"order" json:"order"`
  40. IgnoreDelete bool `xml:"ignoreDelete" json:"ignoreDelete"`
  41. ScanProgressIntervalS int `xml:"scanProgressIntervalS" json:"scanProgressIntervalS"` // Set to a negative value to disable. Value of 0 will get replaced with value of 2 (default value)
  42. PullerPauseS int `xml:"pullerPauseS" json:"pullerPauseS"`
  43. MaxConflicts int `xml:"maxConflicts" json:"maxConflicts" default:"-1"`
  44. DisableSparseFiles bool `xml:"disableSparseFiles" json:"disableSparseFiles"`
  45. DisableTempIndexes bool `xml:"disableTempIndexes" json:"disableTempIndexes"`
  46. Paused bool `xml:"paused" json:"paused"`
  47. WeakHashThresholdPct int `xml:"weakHashThresholdPct" json:"weakHashThresholdPct"` // Use weak hash if more than X percent of the file has changed. Set to -1 to always use weak hash.
  48. MarkerName string `xml:"markerName" json:"markerName"`
  49. UseLargeBlocks bool `xml:"useLargeBlocks" json:"useLargeBlocks" default:"true"`
  50. CopyOwnershipFromParent bool `xml:"copyOwnershipFromParent" json:"copyOwnershipFromParent"`
  51. cachedFilesystem fs.Filesystem
  52. DeprecatedReadOnly bool `xml:"ro,attr,omitempty" json:"-"`
  53. DeprecatedMinDiskFreePct float64 `xml:"minDiskFreePct,omitempty" json:"-"`
  54. DeprecatedPullers int `xml:"pullers,omitempty" json:"-"`
  55. }
  56. type FolderDeviceConfiguration struct {
  57. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  58. IntroducedBy protocol.DeviceID `xml:"introducedBy,attr" json:"introducedBy"`
  59. }
  60. func NewFolderConfiguration(myID protocol.DeviceID, id, label string, fsType fs.FilesystemType, path string) FolderConfiguration {
  61. f := FolderConfiguration{
  62. ID: id,
  63. Label: label,
  64. Devices: []FolderDeviceConfiguration{{DeviceID: myID}},
  65. FilesystemType: fsType,
  66. Path: path,
  67. }
  68. util.SetDefaults(&f)
  69. f.prepare()
  70. return f
  71. }
  72. func (f FolderConfiguration) Copy() FolderConfiguration {
  73. c := f
  74. c.Devices = make([]FolderDeviceConfiguration, len(f.Devices))
  75. copy(c.Devices, f.Devices)
  76. c.Versioning = f.Versioning.Copy()
  77. return c
  78. }
  79. func (f FolderConfiguration) Filesystem() fs.Filesystem {
  80. // This is intentionally not a pointer method, because things like
  81. // cfg.Folders["default"].Filesystem() should be valid.
  82. if f.cachedFilesystem == nil && f.Path != "" {
  83. l.Infoln("bug: uncached filesystem call (should only happen in tests)")
  84. return fs.NewFilesystem(f.FilesystemType, f.Path)
  85. }
  86. return f.cachedFilesystem
  87. }
  88. func (f FolderConfiguration) Versioner() versioner.Versioner {
  89. if f.Versioning.Type == "" {
  90. return nil
  91. }
  92. versionerFactory, ok := versioner.Factories[f.Versioning.Type]
  93. if !ok {
  94. panic(fmt.Sprintf("Requested versioning type %q that does not exist", f.Versioning.Type))
  95. }
  96. return versionerFactory(f.ID, f.Filesystem(), f.Versioning.Params)
  97. }
  98. func (f *FolderConfiguration) CreateMarker() error {
  99. if err := f.CheckPath(); err != ErrMarkerMissing {
  100. return err
  101. }
  102. if f.MarkerName != DefaultMarkerName {
  103. // Folder uses a non-default marker so we shouldn't mess with it.
  104. // Pretend we created it and let the subsequent health checks sort
  105. // out the actual situation.
  106. return nil
  107. }
  108. permBits := fs.FileMode(0777)
  109. if runtime.GOOS == "windows" {
  110. // Windows has no umask so we must chose a safer set of bits to
  111. // begin with.
  112. permBits = 0700
  113. }
  114. fs := f.Filesystem()
  115. err := fs.Mkdir(DefaultMarkerName, permBits)
  116. if err != nil {
  117. return err
  118. }
  119. if dir, err := fs.Open("."); err != nil {
  120. l.Debugln("folder marker: open . failed:", err)
  121. } else if err := dir.Sync(); err != nil {
  122. l.Debugln("folder marker: fsync . failed:", err)
  123. }
  124. fs.Hide(DefaultMarkerName)
  125. return nil
  126. }
  127. // CheckPath returns nil if the folder root exists and contains the marker file
  128. func (f *FolderConfiguration) CheckPath() error {
  129. fi, err := f.Filesystem().Stat(".")
  130. if err != nil {
  131. if !fs.IsNotExist(err) {
  132. return err
  133. }
  134. return ErrPathMissing
  135. }
  136. // Users might have the root directory as a symlink or reparse point.
  137. // Furthermore, OneDrive bullcrap uses a magic reparse point to the cloudz...
  138. // Yet it's impossible for this to happen, as filesystem adds a trailing
  139. // path separator to the root, so even if you point the filesystem at a file
  140. // Stat ends up calling stat on C:\dir\file\ which, fails with "is not a directory"
  141. // in the error check above, and we don't even get to here.
  142. if !fi.IsDir() && !fi.IsSymlink() {
  143. return ErrPathNotDirectory
  144. }
  145. _, err = f.Filesystem().Stat(f.MarkerName)
  146. if err != nil {
  147. if !fs.IsNotExist(err) {
  148. return err
  149. }
  150. return ErrMarkerMissing
  151. }
  152. return nil
  153. }
  154. func (f *FolderConfiguration) CreateRoot() (err error) {
  155. // Directory permission bits. Will be filtered down to something
  156. // sane by umask on Unixes.
  157. permBits := fs.FileMode(0777)
  158. if runtime.GOOS == "windows" {
  159. // Windows has no umask so we must chose a safer set of bits to
  160. // begin with.
  161. permBits = 0700
  162. }
  163. filesystem := f.Filesystem()
  164. if _, err = filesystem.Stat("."); fs.IsNotExist(err) {
  165. err = filesystem.MkdirAll(".", permBits)
  166. }
  167. return err
  168. }
  169. func (f FolderConfiguration) Description() string {
  170. if f.Label == "" {
  171. return f.ID
  172. }
  173. return fmt.Sprintf("%q (%s)", f.Label, f.ID)
  174. }
  175. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  176. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  177. for i, n := range f.Devices {
  178. deviceIDs[i] = n.DeviceID
  179. }
  180. return deviceIDs
  181. }
  182. func (f *FolderConfiguration) prepare() {
  183. if f.Path != "" {
  184. f.cachedFilesystem = fs.NewFilesystem(f.FilesystemType, f.Path)
  185. }
  186. if f.RescanIntervalS > MaxRescanIntervalS {
  187. f.RescanIntervalS = MaxRescanIntervalS
  188. } else if f.RescanIntervalS < 0 {
  189. f.RescanIntervalS = 0
  190. }
  191. if f.FSWatcherDelayS <= 0 {
  192. f.FSWatcherEnabled = false
  193. f.FSWatcherDelayS = 10
  194. }
  195. if f.Versioning.Params == nil {
  196. f.Versioning.Params = make(map[string]string)
  197. }
  198. if f.WeakHashThresholdPct == 0 {
  199. f.WeakHashThresholdPct = 25
  200. }
  201. if f.MarkerName == "" {
  202. f.MarkerName = DefaultMarkerName
  203. }
  204. }
  205. // RequiresRestartOnly returns a copy with only the attributes that require
  206. // restart on change.
  207. func (f FolderConfiguration) RequiresRestartOnly() FolderConfiguration {
  208. copy := f
  209. // Manual handling for things that are not taken care of by the tag
  210. // copier, yet should not cause a restart.
  211. copy.cachedFilesystem = nil
  212. blank := FolderConfiguration{}
  213. util.CopyMatchingTag(&blank, &copy, "restart", func(v string) bool {
  214. if len(v) > 0 && v != "false" {
  215. panic(fmt.Sprintf(`unexpected tag value: %s. expected untagged or "false"`, v))
  216. }
  217. return v == "false"
  218. })
  219. return copy
  220. }
  221. func (f *FolderConfiguration) SharedWith(device protocol.DeviceID) bool {
  222. for _, dev := range f.Devices {
  223. if dev.DeviceID == device {
  224. return true
  225. }
  226. }
  227. return false
  228. }
  229. func (f *FolderConfiguration) CheckAvailableSpace(req int64) error {
  230. val := f.MinDiskFree.BaseValue()
  231. if val <= 0 {
  232. return nil
  233. }
  234. fs := f.Filesystem()
  235. usage, err := fs.Usage(".")
  236. if err != nil {
  237. return nil
  238. }
  239. usage.Free -= req
  240. if usage.Free > 0 {
  241. if err := CheckFreeSpace(f.MinDiskFree, usage); err == nil {
  242. return nil
  243. }
  244. }
  245. return fmt.Errorf("insufficient space in %v %v", fs.Type(), fs.URI())
  246. }