1
0

folder.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. select {
  169. case f.scanNow <- req:
  170. return <-req.err
  171. case <-f.ctx.Done():
  172. return f.ctx.Err()
  173. }
  174. }
  175. func (f *folder) Reschedule() {
  176. if f.scanInterval == 0 {
  177. return
  178. }
  179. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  180. sleepNanos := (f.scanInterval.Nanoseconds()*3 + rand.Int63n(2*f.scanInterval.Nanoseconds())) / 4
  181. interval := time.Duration(sleepNanos) * time.Nanosecond
  182. l.Debugln(f, "next rescan in", interval)
  183. f.scanTimer.Reset(interval)
  184. }
  185. func (f *folder) Delay(next time.Duration) {
  186. f.scanDelay <- next
  187. }
  188. func (f *folder) Stop() {
  189. f.cancel()
  190. <-f.stopped
  191. }
  192. // CheckHealth checks the folder for common errors, updates the folder state
  193. // and returns the current folder error, or nil if the folder is healthy.
  194. func (f *folder) CheckHealth() error {
  195. err := f.getHealthError()
  196. f.setError(err)
  197. return err
  198. }
  199. func (f *folder) getHealthError() error {
  200. // Check for folder errors, with the most serious and specific first and
  201. // generic ones like out of space on the home disk later.
  202. if err := f.CheckPath(); err != nil {
  203. return err
  204. }
  205. if err := f.CheckFreeSpace(); err != nil {
  206. return err
  207. }
  208. if err := f.model.cfg.CheckHomeFreeSpace(); err != nil {
  209. return err
  210. }
  211. return nil
  212. }
  213. func (f *folder) scanSubdirs(subDirs []string) error {
  214. if err := f.model.internalScanFolderSubdirs(f.ctx, f.folderID, subDirs); err != nil {
  215. // Potentially sets the error twice, once in the scanner just
  216. // by doing a check, and once here, if the error returned is
  217. // the same one as returned by CheckHealth, though
  218. // duplicate set is handled by setError.
  219. f.setError(err)
  220. return err
  221. }
  222. return nil
  223. }
  224. func (f *folder) scanTimerFired() {
  225. err := f.scanSubdirs(nil)
  226. select {
  227. case <-f.initialScanFinished:
  228. default:
  229. status := "Completed"
  230. if err != nil {
  231. status = "Failed"
  232. }
  233. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  234. close(f.initialScanFinished)
  235. }
  236. f.Reschedule()
  237. }
  238. func (f *folder) WatchError() error {
  239. f.watchErrMut.Lock()
  240. defer f.watchErrMut.Unlock()
  241. return f.watchErr
  242. }
  243. // stopWatch immediately aborts watching and may be called asynchronously
  244. func (f *folder) stopWatch() {
  245. f.watchCancel()
  246. f.watchErrMut.Lock()
  247. prevErr := f.watchErr
  248. f.watchErr = errWatchNotStarted
  249. f.watchErrMut.Unlock()
  250. if prevErr != errWatchNotStarted {
  251. data := map[string]interface{}{
  252. "folder": f.ID,
  253. "to": errWatchNotStarted.Error(),
  254. }
  255. if prevErr != nil {
  256. data["from"] = prevErr.Error()
  257. }
  258. events.Default.Log(events.FolderWatchStateChanged, data)
  259. }
  260. }
  261. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  262. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  263. func (f *folder) scheduleWatchRestart() {
  264. select {
  265. case f.restartWatchChan <- struct{}{}:
  266. default:
  267. // We might be busy doing a pull and thus not reading from this
  268. // channel. The channel is 1-buffered, so one notification will be
  269. // queued to ensure we recheck after the pull.
  270. }
  271. }
  272. // restartWatch should only ever be called synchronously. If you want to use
  273. // this asynchronously, you should probably use scheduleWatchRestart instead.
  274. func (f *folder) restartWatch() {
  275. f.stopWatch()
  276. f.startWatch()
  277. f.scanSubdirs(nil)
  278. }
  279. // startWatch should only ever be called synchronously. If you want to use
  280. // this asynchronously, you should probably use scheduleWatchRestart instead.
  281. func (f *folder) startWatch() {
  282. ctx, cancel := context.WithCancel(f.ctx)
  283. f.model.fmut.RLock()
  284. ignores := f.model.folderIgnores[f.folderID]
  285. f.model.fmut.RUnlock()
  286. f.watchChan = make(chan []string)
  287. f.watchCancel = cancel
  288. go f.startWatchAsync(ctx, ignores)
  289. }
  290. // startWatchAsync tries to start the filesystem watching and retries every minute on failure.
  291. // It is a convenience function that should not be used except in startWatch.
  292. func (f *folder) startWatchAsync(ctx context.Context, ignores *ignore.Matcher) {
  293. timer := time.NewTimer(0)
  294. for {
  295. select {
  296. case <-timer.C:
  297. eventChan, err := f.Filesystem().Watch(".", ignores, ctx, f.IgnorePerms)
  298. f.watchErrMut.Lock()
  299. prevErr := f.watchErr
  300. f.watchErr = err
  301. f.watchErrMut.Unlock()
  302. if err != prevErr {
  303. data := map[string]interface{}{
  304. "folder": f.ID,
  305. }
  306. if prevErr != nil {
  307. data["from"] = prevErr.Error()
  308. }
  309. if err != nil {
  310. data["to"] = err.Error()
  311. }
  312. events.Default.Log(events.FolderWatchStateChanged, data)
  313. }
  314. if err != nil {
  315. if prevErr == errWatchNotStarted {
  316. l.Infof("Error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  317. } else {
  318. l.Debugf("Repeat error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  319. }
  320. timer.Reset(time.Minute)
  321. continue
  322. }
  323. watchaggregator.Aggregate(eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, ctx)
  324. l.Debugln("Started filesystem watcher for folder", f.Description())
  325. return
  326. case <-ctx.Done():
  327. return
  328. }
  329. }
  330. }
  331. func (f *folder) setError(err error) {
  332. _, _, oldErr := f.getState()
  333. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  334. return
  335. }
  336. if err != nil {
  337. if oldErr == nil {
  338. l.Warnf("Error on folder %s: %v", f.Description(), err)
  339. } else {
  340. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  341. }
  342. } else {
  343. l.Infoln("Cleared error on folder", f.Description())
  344. }
  345. if f.FSWatcherEnabled {
  346. if err != nil {
  347. f.stopWatch()
  348. } else {
  349. f.scheduleWatchRestart()
  350. }
  351. }
  352. f.stateTracker.setError(err)
  353. }
  354. func (f *folder) basePause() time.Duration {
  355. if f.PullerPauseS == 0 {
  356. return defaultPullerPause
  357. }
  358. return time.Duration(f.PullerPauseS) * time.Second
  359. }
  360. func (f *folder) String() string {
  361. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  362. }