folderconfiguration.go 11 KB

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