folderconfiguration.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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. )
  14. var (
  15. errPathNotDirectory = errors.New("folder path not a directory")
  16. errPathMissing = errors.New("folder path missing")
  17. errMarkerMissing = errors.New("folder marker missing")
  18. )
  19. const DefaultMarkerName = ".stfolder"
  20. type FolderConfiguration struct {
  21. ID string `xml:"id,attr" json:"id" restart:"false"`
  22. Label string `xml:"label,attr" json:"label"`
  23. FilesystemType fs.FilesystemType `xml:"filesystemType" json:"filesystemType"`
  24. Path string `xml:"path,attr" json:"path"`
  25. Type FolderType `xml:"type,attr" json:"type"`
  26. Devices []FolderDeviceConfiguration `xml:"device" json:"devices"`
  27. RescanIntervalS int `xml:"rescanIntervalS,attr" json:"rescanIntervalS"`
  28. FSWatcherEnabled bool `xml:"fsWatcherEnabled,attr" json:"fsWatcherEnabled"`
  29. FSWatcherDelayS int `xml:"fsWatcherDelayS,attr" json:"fsWatcherDelayS"`
  30. IgnorePerms bool `xml:"ignorePerms,attr" json:"ignorePerms"`
  31. AutoNormalize bool `xml:"autoNormalize,attr" json:"autoNormalize"`
  32. MinDiskFree Size `xml:"minDiskFree" json:"minDiskFree"`
  33. Versioning VersioningConfiguration `xml:"versioning" json:"versioning"`
  34. Copiers int `xml:"copiers" json:"copiers"` // This defines how many files are handled concurrently.
  35. Pullers int `xml:"pullers" json:"pullers"` // Defines how many blocks are fetched at the same time, possibly between separate copier routines.
  36. Hashers int `xml:"hashers" json:"hashers"` // Less than one sets the value to the number of cores. These are CPU bound due to hashing.
  37. Order PullOrder `xml:"order" json:"order"`
  38. IgnoreDelete bool `xml:"ignoreDelete" json:"ignoreDelete"`
  39. 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)
  40. PullerPauseS int `xml:"pullerPauseS" json:"pullerPauseS"`
  41. MaxConflicts int `xml:"maxConflicts" json:"maxConflicts"`
  42. DisableSparseFiles bool `xml:"disableSparseFiles" json:"disableSparseFiles"`
  43. DisableTempIndexes bool `xml:"disableTempIndexes" json:"disableTempIndexes"`
  44. Paused bool `xml:"paused" json:"paused"`
  45. 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.
  46. MarkerName string `xml:"markerName" json:"markerName"`
  47. cachedFilesystem fs.Filesystem
  48. DeprecatedReadOnly bool `xml:"ro,attr,omitempty" json:"-"`
  49. DeprecatedMinDiskFreePct float64 `xml:"minDiskFreePct,omitempty" json:"-"`
  50. }
  51. type FolderDeviceConfiguration struct {
  52. DeviceID protocol.DeviceID `xml:"id,attr" json:"deviceID"`
  53. IntroducedBy protocol.DeviceID `xml:"introducedBy,attr" json:"introducedBy"`
  54. }
  55. func NewFolderConfiguration(myID protocol.DeviceID, id, label string, fsType fs.FilesystemType, path string) FolderConfiguration {
  56. f := FolderConfiguration{
  57. ID: id,
  58. Label: label,
  59. RescanIntervalS: 60,
  60. FSWatcherDelayS: 10,
  61. MinDiskFree: Size{Value: 1, Unit: "%"},
  62. Devices: []FolderDeviceConfiguration{{DeviceID: myID}},
  63. AutoNormalize: true,
  64. MaxConflicts: -1,
  65. FilesystemType: fsType,
  66. Path: path,
  67. }
  68. f.prepare()
  69. return f
  70. }
  71. func (f FolderConfiguration) Copy() FolderConfiguration {
  72. c := f
  73. c.Devices = make([]FolderDeviceConfiguration, len(f.Devices))
  74. copy(c.Devices, f.Devices)
  75. c.Versioning = f.Versioning.Copy()
  76. return c
  77. }
  78. func (f FolderConfiguration) Filesystem() fs.Filesystem {
  79. // This is intentionally not a pointer method, because things like
  80. // cfg.Folders["default"].Filesystem() should be valid.
  81. if f.cachedFilesystem == nil && f.Path != "" {
  82. l.Infoln("bug: uncached filesystem call (should only happen in tests)")
  83. return fs.NewFilesystem(f.FilesystemType, f.Path)
  84. }
  85. return f.cachedFilesystem
  86. }
  87. func (f *FolderConfiguration) CreateMarker() error {
  88. if err := f.CheckPath(); err != errMarkerMissing {
  89. return err
  90. }
  91. if f.MarkerName != DefaultMarkerName {
  92. // Folder uses a non-default marker so we shouldn't mess with it.
  93. // Pretend we created it and let the subsequent health checks sort
  94. // out the actual situation.
  95. return nil
  96. }
  97. permBits := fs.FileMode(0777)
  98. if runtime.GOOS == "windows" {
  99. // Windows has no umask so we must chose a safer set of bits to
  100. // begin with.
  101. permBits = 0700
  102. }
  103. fs := f.Filesystem()
  104. err := fs.Mkdir(DefaultMarkerName, permBits)
  105. if err != nil {
  106. return err
  107. }
  108. if dir, err := fs.Open("."); err != nil {
  109. l.Debugln("folder marker: open . failed:", err)
  110. } else if err := dir.Sync(); err != nil {
  111. l.Debugln("folder marker: fsync . failed:", err)
  112. }
  113. fs.Hide(DefaultMarkerName)
  114. return nil
  115. }
  116. // CheckPath returns nil if the folder root exists and contains the marker file
  117. func (f *FolderConfiguration) CheckPath() error {
  118. fi, err := f.Filesystem().Stat(".")
  119. if err != nil {
  120. if !fs.IsNotExist(err) {
  121. return err
  122. }
  123. return errPathMissing
  124. }
  125. // Users might have the root directory as a symlink or reparse point.
  126. // Furthermore, OneDrive bullcrap uses a magic reparse point to the cloudz...
  127. // Yet it's impossible for this to happen, as filesystem adds a trailing
  128. // path separator to the root, so even if you point the filesystem at a file
  129. // Stat ends up calling stat on C:\dir\file\ which, fails with "is not a directory"
  130. // in the error check above, and we don't even get to here.
  131. if !fi.IsDir() && !fi.IsSymlink() {
  132. return errPathNotDirectory
  133. }
  134. _, err = f.Filesystem().Stat(f.MarkerName)
  135. if err != nil {
  136. if !fs.IsNotExist(err) {
  137. return err
  138. }
  139. return errMarkerMissing
  140. }
  141. return nil
  142. }
  143. func (f *FolderConfiguration) CreateRoot() (err error) {
  144. // Directory permission bits. Will be filtered down to something
  145. // sane by umask on Unixes.
  146. permBits := fs.FileMode(0777)
  147. if runtime.GOOS == "windows" {
  148. // Windows has no umask so we must chose a safer set of bits to
  149. // begin with.
  150. permBits = 0700
  151. }
  152. filesystem := f.Filesystem()
  153. if _, err = filesystem.Stat("."); fs.IsNotExist(err) {
  154. if err = filesystem.MkdirAll(".", permBits); err != nil {
  155. l.Warnf("Creating directory for %v: %v", f.Description(), err)
  156. }
  157. }
  158. return err
  159. }
  160. func (f FolderConfiguration) Description() string {
  161. if f.Label == "" {
  162. return f.ID
  163. }
  164. return fmt.Sprintf("%q (%s)", f.Label, f.ID)
  165. }
  166. func (f *FolderConfiguration) DeviceIDs() []protocol.DeviceID {
  167. deviceIDs := make([]protocol.DeviceID, len(f.Devices))
  168. for i, n := range f.Devices {
  169. deviceIDs[i] = n.DeviceID
  170. }
  171. return deviceIDs
  172. }
  173. func (f *FolderConfiguration) prepare() {
  174. if f.Path != "" {
  175. f.cachedFilesystem = fs.NewFilesystem(f.FilesystemType, f.Path)
  176. }
  177. if f.RescanIntervalS > MaxRescanIntervalS {
  178. f.RescanIntervalS = MaxRescanIntervalS
  179. } else if f.RescanIntervalS < 0 {
  180. f.RescanIntervalS = 0
  181. }
  182. if f.FSWatcherDelayS <= 0 {
  183. f.FSWatcherEnabled = false
  184. f.FSWatcherDelayS = 10
  185. }
  186. if f.Versioning.Params == nil {
  187. f.Versioning.Params = make(map[string]string)
  188. }
  189. if f.WeakHashThresholdPct == 0 {
  190. f.WeakHashThresholdPct = 25
  191. }
  192. if f.MarkerName == "" {
  193. f.MarkerName = DefaultMarkerName
  194. }
  195. }
  196. type FolderDeviceConfigurationList []FolderDeviceConfiguration
  197. func (l FolderDeviceConfigurationList) Less(a, b int) bool {
  198. return l[a].DeviceID.Compare(l[b].DeviceID) == -1
  199. }
  200. func (l FolderDeviceConfigurationList) Swap(a, b int) {
  201. l[a], l[b] = l[b], l[a]
  202. }
  203. func (l FolderDeviceConfigurationList) Len() int {
  204. return len(l)
  205. }
  206. func (f *FolderConfiguration) CheckFreeSpace() (err error) {
  207. return checkFreeSpace(f.MinDiskFree, f.Filesystem())
  208. }