folderconfiguration.go 11 KB

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