folder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  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 model
  7. import (
  8. "context"
  9. "errors"
  10. "fmt"
  11. "math/rand"
  12. "time"
  13. "github.com/syncthing/syncthing/lib/config"
  14. "github.com/syncthing/syncthing/lib/db"
  15. "github.com/syncthing/syncthing/lib/events"
  16. "github.com/syncthing/syncthing/lib/ignore"
  17. "github.com/syncthing/syncthing/lib/protocol"
  18. "github.com/syncthing/syncthing/lib/sync"
  19. "github.com/syncthing/syncthing/lib/watchaggregator"
  20. )
  21. var errWatchNotStarted = errors.New("not started")
  22. type folder struct {
  23. stateTracker
  24. config.FolderConfiguration
  25. model *Model
  26. shortID protocol.ShortID
  27. ctx context.Context
  28. cancel context.CancelFunc
  29. scanInterval time.Duration
  30. scanTimer *time.Timer
  31. scanNow chan rescanRequest
  32. scanDelay chan time.Duration
  33. initialScanFinished chan struct{}
  34. stopped chan struct{}
  35. pullScheduled chan struct{}
  36. watchCancel context.CancelFunc
  37. watchChan chan []string
  38. restartWatchChan chan struct{}
  39. watchErr error
  40. watchErrMut sync.Mutex
  41. puller puller
  42. }
  43. type rescanRequest struct {
  44. subdirs []string
  45. err chan error
  46. }
  47. type puller interface {
  48. pull() bool // true when successfull and should not be retried
  49. }
  50. func newFolder(model *Model, cfg config.FolderConfiguration) folder {
  51. ctx, cancel := context.WithCancel(context.Background())
  52. return folder{
  53. stateTracker: newStateTracker(cfg.ID),
  54. FolderConfiguration: cfg,
  55. model: model,
  56. shortID: model.shortID,
  57. ctx: ctx,
  58. cancel: cancel,
  59. scanInterval: time.Duration(cfg.RescanIntervalS) * time.Second,
  60. scanTimer: time.NewTimer(time.Millisecond), // The first scan should be done immediately.
  61. scanNow: make(chan rescanRequest),
  62. scanDelay: make(chan time.Duration),
  63. initialScanFinished: make(chan struct{}),
  64. stopped: make(chan struct{}),
  65. pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.
  66. watchCancel: func() {},
  67. restartWatchChan: make(chan struct{}, 1),
  68. watchErrMut: sync.NewMutex(),
  69. }
  70. }
  71. func (f *folder) Serve() {
  72. l.Debugln(f, "starting")
  73. defer l.Debugln(f, "exiting")
  74. defer func() {
  75. f.scanTimer.Stop()
  76. f.setState(FolderIdle)
  77. close(f.stopped)
  78. }()
  79. pause := f.basePause()
  80. pullFailTimer := time.NewTimer(0)
  81. <-pullFailTimer.C
  82. if f.FSWatcherEnabled && f.CheckHealth() == nil {
  83. f.startWatch()
  84. }
  85. initialCompleted := f.initialScanFinished
  86. for {
  87. select {
  88. case <-f.ctx.Done():
  89. return
  90. case <-f.pullScheduled:
  91. pullFailTimer.Stop()
  92. select {
  93. case <-pullFailTimer.C:
  94. default:
  95. }
  96. if !f.puller.pull() {
  97. // Pulling failed, try again later.
  98. pullFailTimer.Reset(pause)
  99. }
  100. case <-pullFailTimer.C:
  101. if f.puller.pull() {
  102. // We're good. Don't schedule another fail pull and reset
  103. // the pause interval.
  104. pause = f.basePause()
  105. continue
  106. }
  107. // Pulling failed, try again later.
  108. l.Infof("Folder %v isn't making sync progress - retrying in %v.", f.Description(), pause)
  109. pullFailTimer.Reset(pause)
  110. // Back off from retrying to pull with an upper limit.
  111. if pause < 60*f.basePause() {
  112. pause *= 2
  113. }
  114. case <-initialCompleted:
  115. // Initial scan has completed, we should do a pull
  116. initialCompleted = nil // never hit this case again
  117. if !f.puller.pull() {
  118. // Pulling failed, try again later.
  119. pullFailTimer.Reset(pause)
  120. }
  121. // The reason for running the scanner from within the puller is that
  122. // this is the easiest way to make sure we are not doing both at the
  123. // same time.
  124. case <-f.scanTimer.C:
  125. l.Debugln(f, "Scanning subdirectories")
  126. f.scanTimerFired()
  127. case req := <-f.scanNow:
  128. req.err <- f.scanSubdirs(req.subdirs)
  129. case next := <-f.scanDelay:
  130. f.scanTimer.Reset(next)
  131. case fsEvents := <-f.watchChan:
  132. l.Debugln(f, "filesystem notification rescan")
  133. f.scanSubdirs(fsEvents)
  134. case <-f.restartWatchChan:
  135. f.restartWatch()
  136. }
  137. }
  138. }
  139. func (f *folder) BringToFront(string) {}
  140. func (f *folder) Override(fs *db.FileSet, updateFn func([]protocol.FileInfo)) {}
  141. func (f *folder) DelayScan(next time.Duration) {
  142. f.Delay(next)
  143. }
  144. func (f *folder) IgnoresUpdated() {
  145. if f.FSWatcherEnabled {
  146. f.scheduleWatchRestart()
  147. }
  148. }
  149. func (f *folder) SchedulePull() {
  150. select {
  151. case f.pullScheduled <- struct{}{}:
  152. default:
  153. // We might be busy doing a pull and thus not reading from this
  154. // channel. The channel is 1-buffered, so one notification will be
  155. // queued to ensure we recheck after the pull, but beyond that we must
  156. // make sure to not block index receiving.
  157. }
  158. }
  159. func (f *folder) Jobs() ([]string, []string) {
  160. return nil, nil
  161. }
  162. func (f *folder) Scan(subdirs []string) error {
  163. <-f.initialScanFinished
  164. req := rescanRequest{
  165. subdirs: subdirs,
  166. err: make(chan error),
  167. }
  168. f.scanNow <- req
  169. return <-req.err
  170. }
  171. func (f *folder) Reschedule() {
  172. if f.scanInterval == 0 {
  173. return
  174. }
  175. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  176. sleepNanos := (f.scanInterval.Nanoseconds()*3 + rand.Int63n(2*f.scanInterval.Nanoseconds())) / 4
  177. interval := time.Duration(sleepNanos) * time.Nanosecond
  178. l.Debugln(f, "next rescan in", interval)
  179. f.scanTimer.Reset(interval)
  180. }
  181. func (f *folder) Delay(next time.Duration) {
  182. f.scanDelay <- next
  183. }
  184. func (f *folder) Stop() {
  185. f.cancel()
  186. <-f.stopped
  187. }
  188. // CheckHealth checks the folder for common errors, updates the folder state
  189. // and returns the current folder error, or nil if the folder is healthy.
  190. func (f *folder) CheckHealth() error {
  191. err := f.getHealthError()
  192. f.setError(err)
  193. return err
  194. }
  195. func (f *folder) getHealthError() error {
  196. // Check for folder errors, with the most serious and specific first and
  197. // generic ones like out of space on the home disk later.
  198. if err := f.CheckPath(); err != nil {
  199. return err
  200. }
  201. if err := f.CheckFreeSpace(); err != nil {
  202. return err
  203. }
  204. if err := f.model.cfg.CheckHomeFreeSpace(); err != nil {
  205. return err
  206. }
  207. return nil
  208. }
  209. func (f *folder) scanSubdirs(subDirs []string) error {
  210. if err := f.model.internalScanFolderSubdirs(f.ctx, f.folderID, subDirs); err != nil {
  211. // Potentially sets the error twice, once in the scanner just
  212. // by doing a check, and once here, if the error returned is
  213. // the same one as returned by CheckHealth, though
  214. // duplicate set is handled by setError.
  215. f.setError(err)
  216. return err
  217. }
  218. return nil
  219. }
  220. func (f *folder) scanTimerFired() {
  221. err := f.scanSubdirs(nil)
  222. select {
  223. case <-f.initialScanFinished:
  224. default:
  225. status := "Completed"
  226. if err != nil {
  227. status = "Failed"
  228. }
  229. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  230. close(f.initialScanFinished)
  231. }
  232. f.Reschedule()
  233. }
  234. func (f *folder) WatchError() error {
  235. f.watchErrMut.Lock()
  236. defer f.watchErrMut.Unlock()
  237. return f.watchErr
  238. }
  239. // stopWatch immediately aborts watching and may be called asynchronously
  240. func (f *folder) stopWatch() {
  241. f.watchCancel()
  242. f.watchErrMut.Lock()
  243. prevErr := f.watchErr
  244. f.watchErr = errWatchNotStarted
  245. f.watchErrMut.Unlock()
  246. if prevErr != errWatchNotStarted {
  247. data := map[string]interface{}{
  248. "folder": f.ID,
  249. "to": errWatchNotStarted.Error(),
  250. }
  251. if prevErr != nil {
  252. data["from"] = prevErr.Error()
  253. }
  254. events.Default.Log(events.FolderWatchStateChanged, data)
  255. }
  256. }
  257. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  258. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  259. func (f *folder) scheduleWatchRestart() {
  260. select {
  261. case f.restartWatchChan <- struct{}{}:
  262. default:
  263. // We might be busy doing a pull and thus not reading from this
  264. // channel. The channel is 1-buffered, so one notification will be
  265. // queued to ensure we recheck after the pull.
  266. }
  267. }
  268. // restartWatch should only ever be called synchronously. If you want to use
  269. // this asynchronously, you should probably use scheduleWatchRestart instead.
  270. func (f *folder) restartWatch() {
  271. f.stopWatch()
  272. f.startWatch()
  273. f.scanSubdirs(nil)
  274. }
  275. // startWatch should only ever be called synchronously. If you want to use
  276. // this asynchronously, you should probably use scheduleWatchRestart instead.
  277. func (f *folder) startWatch() {
  278. ctx, cancel := context.WithCancel(f.ctx)
  279. f.model.fmut.RLock()
  280. ignores := f.model.folderIgnores[f.folderID]
  281. f.model.fmut.RUnlock()
  282. f.watchChan = make(chan []string)
  283. f.watchCancel = cancel
  284. go f.startWatchAsync(ctx, ignores)
  285. }
  286. // startWatchAsync tries to start the filesystem watching and retries every minute on failure.
  287. // It is a convenience function that should not be used except in startWatch.
  288. func (f *folder) startWatchAsync(ctx context.Context, ignores *ignore.Matcher) {
  289. timer := time.NewTimer(0)
  290. for {
  291. select {
  292. case <-timer.C:
  293. eventChan, err := f.Filesystem().Watch(".", ignores, ctx, f.IgnorePerms)
  294. f.watchErrMut.Lock()
  295. prevErr := f.watchErr
  296. f.watchErr = err
  297. f.watchErrMut.Unlock()
  298. if err != prevErr {
  299. data := map[string]interface{}{
  300. "folder": f.ID,
  301. }
  302. if prevErr != nil {
  303. data["from"] = prevErr.Error()
  304. }
  305. if err != nil {
  306. data["to"] = err.Error()
  307. }
  308. events.Default.Log(events.FolderWatchStateChanged, data)
  309. }
  310. if err != nil {
  311. if prevErr == errWatchNotStarted {
  312. l.Infof("Error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  313. } else {
  314. l.Debugf("Repeat error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  315. }
  316. timer.Reset(time.Minute)
  317. continue
  318. }
  319. watchaggregator.Aggregate(eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, ctx)
  320. l.Debugln("Started filesystem watcher for folder", f.Description())
  321. return
  322. case <-ctx.Done():
  323. return
  324. }
  325. }
  326. }
  327. func (f *folder) setError(err error) {
  328. _, _, oldErr := f.getState()
  329. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  330. return
  331. }
  332. if err != nil {
  333. if oldErr == nil {
  334. l.Warnf("Error on folder %s: %v", f.Description(), err)
  335. } else {
  336. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  337. }
  338. } else {
  339. l.Infoln("Cleared error on folder", f.Description())
  340. }
  341. if f.FSWatcherEnabled {
  342. if err != nil {
  343. f.stopWatch()
  344. } else {
  345. f.scheduleWatchRestart()
  346. }
  347. }
  348. f.stateTracker.setError(err)
  349. }
  350. func (f *folder) basePause() time.Duration {
  351. if f.PullerPauseS == 0 {
  352. return defaultPullerPause
  353. }
  354. return time.Duration(f.PullerPauseS) * time.Second
  355. }
  356. func (f *folder) String() string {
  357. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  358. }