folder.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771
  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. "path/filepath"
  13. "sort"
  14. "sync/atomic"
  15. "time"
  16. "github.com/syncthing/syncthing/lib/config"
  17. "github.com/syncthing/syncthing/lib/db"
  18. "github.com/syncthing/syncthing/lib/events"
  19. "github.com/syncthing/syncthing/lib/fs"
  20. "github.com/syncthing/syncthing/lib/ignore"
  21. "github.com/syncthing/syncthing/lib/locations"
  22. "github.com/syncthing/syncthing/lib/osutil"
  23. "github.com/syncthing/syncthing/lib/protocol"
  24. "github.com/syncthing/syncthing/lib/scanner"
  25. "github.com/syncthing/syncthing/lib/sync"
  26. "github.com/syncthing/syncthing/lib/watchaggregator"
  27. )
  28. // scanLimiter limits the number of concurrent scans. A limit of zero means no limit.
  29. var scanLimiter = newByteSemaphore(0)
  30. var errWatchNotStarted = errors.New("not started")
  31. type folder struct {
  32. stateTracker
  33. config.FolderConfiguration
  34. localFlags uint32
  35. model *model
  36. shortID protocol.ShortID
  37. ctx context.Context
  38. cancel context.CancelFunc
  39. scanInterval time.Duration
  40. scanTimer *time.Timer
  41. scanNow chan rescanRequest
  42. scanDelay chan time.Duration
  43. initialScanFinished chan struct{}
  44. stopped chan struct{}
  45. scanErrors []FileError
  46. scanErrorsMut sync.Mutex
  47. pullScheduled chan struct{}
  48. watchCancel context.CancelFunc
  49. watchChan chan []string
  50. restartWatchChan chan struct{}
  51. watchErr error
  52. watchMut sync.Mutex
  53. puller puller
  54. }
  55. type rescanRequest struct {
  56. subdirs []string
  57. err chan error
  58. }
  59. type puller interface {
  60. pull() bool // true when successfull and should not be retried
  61. }
  62. func newFolder(model *model, cfg config.FolderConfiguration) folder {
  63. ctx, cancel := context.WithCancel(context.Background())
  64. return folder{
  65. stateTracker: newStateTracker(cfg.ID),
  66. FolderConfiguration: cfg,
  67. model: model,
  68. shortID: model.shortID,
  69. ctx: ctx,
  70. cancel: cancel,
  71. scanInterval: time.Duration(cfg.RescanIntervalS) * time.Second,
  72. scanTimer: time.NewTimer(time.Millisecond), // The first scan should be done immediately.
  73. scanNow: make(chan rescanRequest),
  74. scanDelay: make(chan time.Duration),
  75. initialScanFinished: make(chan struct{}),
  76. stopped: make(chan struct{}),
  77. scanErrorsMut: sync.NewMutex(),
  78. pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.
  79. watchCancel: func() {},
  80. restartWatchChan: make(chan struct{}, 1),
  81. watchMut: sync.NewMutex(),
  82. }
  83. }
  84. func (f *folder) Serve() {
  85. atomic.AddInt32(&f.model.foldersRunning, 1)
  86. defer atomic.AddInt32(&f.model.foldersRunning, -1)
  87. l.Debugln(f, "starting")
  88. defer l.Debugln(f, "exiting")
  89. defer func() {
  90. f.scanTimer.Stop()
  91. f.setState(FolderIdle)
  92. close(f.stopped)
  93. }()
  94. pause := f.basePause()
  95. pullFailTimer := time.NewTimer(0)
  96. <-pullFailTimer.C
  97. if f.FSWatcherEnabled && f.CheckHealth() == nil {
  98. f.startWatch()
  99. }
  100. initialCompleted := f.initialScanFinished
  101. for {
  102. select {
  103. case <-f.ctx.Done():
  104. return
  105. case <-f.pullScheduled:
  106. pullFailTimer.Stop()
  107. select {
  108. case <-pullFailTimer.C:
  109. default:
  110. }
  111. if !f.puller.pull() {
  112. // Pulling failed, try again later.
  113. pullFailTimer.Reset(pause)
  114. }
  115. case <-pullFailTimer.C:
  116. if f.puller.pull() {
  117. // We're good. Don't schedule another fail pull and reset
  118. // the pause interval.
  119. pause = f.basePause()
  120. continue
  121. }
  122. // Pulling failed, try again later.
  123. l.Infof("Folder %v isn't making sync progress - retrying in %v.", f.Description(), pause)
  124. pullFailTimer.Reset(pause)
  125. // Back off from retrying to pull with an upper limit.
  126. if pause < 60*f.basePause() {
  127. pause *= 2
  128. }
  129. case <-initialCompleted:
  130. // Initial scan has completed, we should do a pull
  131. initialCompleted = nil // never hit this case again
  132. if !f.puller.pull() {
  133. // Pulling failed, try again later.
  134. pullFailTimer.Reset(pause)
  135. }
  136. // The reason for running the scanner from within the puller is that
  137. // this is the easiest way to make sure we are not doing both at the
  138. // same time.
  139. case <-f.scanTimer.C:
  140. l.Debugln(f, "Scanning subdirectories")
  141. f.scanTimerFired()
  142. case req := <-f.scanNow:
  143. req.err <- f.scanSubdirs(req.subdirs)
  144. case next := <-f.scanDelay:
  145. f.scanTimer.Reset(next)
  146. case fsEvents := <-f.watchChan:
  147. l.Debugln(f, "filesystem notification rescan")
  148. f.scanSubdirs(fsEvents)
  149. case <-f.restartWatchChan:
  150. f.restartWatch()
  151. }
  152. }
  153. }
  154. func (f *folder) BringToFront(string) {}
  155. func (f *folder) Override(fs *db.FileSet, updateFn func([]protocol.FileInfo)) {}
  156. func (f *folder) Revert(fs *db.FileSet, updateFn func([]protocol.FileInfo)) {}
  157. func (f *folder) DelayScan(next time.Duration) {
  158. f.Delay(next)
  159. }
  160. func (f *folder) ignoresUpdated() {
  161. if f.FSWatcherEnabled {
  162. f.scheduleWatchRestart()
  163. }
  164. }
  165. func (f *folder) SchedulePull() {
  166. select {
  167. case f.pullScheduled <- struct{}{}:
  168. default:
  169. // We might be busy doing a pull and thus not reading from this
  170. // channel. The channel is 1-buffered, so one notification will be
  171. // queued to ensure we recheck after the pull, but beyond that we must
  172. // make sure to not block index receiving.
  173. }
  174. }
  175. func (f *folder) Jobs() ([]string, []string) {
  176. return nil, nil
  177. }
  178. func (f *folder) Scan(subdirs []string) error {
  179. <-f.initialScanFinished
  180. req := rescanRequest{
  181. subdirs: subdirs,
  182. err: make(chan error),
  183. }
  184. select {
  185. case f.scanNow <- req:
  186. return <-req.err
  187. case <-f.ctx.Done():
  188. return f.ctx.Err()
  189. }
  190. }
  191. func (f *folder) Reschedule() {
  192. if f.scanInterval == 0 {
  193. return
  194. }
  195. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  196. sleepNanos := (f.scanInterval.Nanoseconds()*3 + rand.Int63n(2*f.scanInterval.Nanoseconds())) / 4
  197. interval := time.Duration(sleepNanos) * time.Nanosecond
  198. l.Debugln(f, "next rescan in", interval)
  199. f.scanTimer.Reset(interval)
  200. }
  201. func (f *folder) Delay(next time.Duration) {
  202. f.scanDelay <- next
  203. }
  204. func (f *folder) Stop() {
  205. f.cancel()
  206. <-f.stopped
  207. }
  208. // CheckHealth checks the folder for common errors, updates the folder state
  209. // and returns the current folder error, or nil if the folder is healthy.
  210. func (f *folder) CheckHealth() error {
  211. err := f.getHealthError()
  212. f.setError(err)
  213. return err
  214. }
  215. func (f *folder) getHealthError() error {
  216. // Check for folder errors, with the most serious and specific first and
  217. // generic ones like out of space on the home disk later.
  218. if err := f.CheckPath(); err != nil {
  219. return err
  220. }
  221. dbPath := locations.Get(locations.Database)
  222. if usage, err := fs.NewFilesystem(fs.FilesystemTypeBasic, dbPath).Usage("."); err == nil {
  223. if err = config.CheckFreeSpace(f.model.cfg.Options().MinHomeDiskFree, usage); err != nil {
  224. return fmt.Errorf("insufficient space on disk for database (%v): %v", dbPath, err)
  225. }
  226. }
  227. return nil
  228. }
  229. func (f *folder) scanSubdirs(subDirs []string) error {
  230. if err := f.CheckHealth(); err != nil {
  231. return err
  232. }
  233. f.model.fmut.RLock()
  234. fset := f.model.folderFiles[f.ID]
  235. ignores := f.model.folderIgnores[f.ID]
  236. f.model.fmut.RUnlock()
  237. mtimefs := fset.MtimeFS()
  238. f.setState(FolderScanWaiting)
  239. scanLimiter.take(1)
  240. defer scanLimiter.give(1)
  241. for i := range subDirs {
  242. sub := osutil.NativeFilename(subDirs[i])
  243. if sub == "" {
  244. // A blank subdirs means to scan the entire folder. We can trim
  245. // the subDirs list and go on our way.
  246. subDirs = nil
  247. break
  248. }
  249. subDirs[i] = sub
  250. }
  251. // Check if the ignore patterns changed as part of scanning this folder.
  252. // If they did we should schedule a pull of the folder so that we
  253. // request things we might have suddenly become unignored and so on.
  254. oldHash := ignores.Hash()
  255. defer func() {
  256. if ignores.Hash() != oldHash {
  257. l.Debugln("Folder", f.Description(), "ignore patterns change detected while scanning; triggering puller")
  258. f.ignoresUpdated()
  259. f.SchedulePull()
  260. }
  261. }()
  262. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  263. err = fmt.Errorf("loading ignores: %v", err)
  264. f.setError(err)
  265. return err
  266. }
  267. // Clean the list of subitems to ensure that we start at a known
  268. // directory, and don't scan subdirectories of things we've already
  269. // scanned.
  270. subDirs = unifySubs(subDirs, func(f string) bool {
  271. _, ok := fset.Get(protocol.LocalDeviceID, f)
  272. return ok
  273. })
  274. f.setState(FolderScanning)
  275. fchan := scanner.Walk(f.ctx, scanner.Config{
  276. Folder: f.ID,
  277. Subs: subDirs,
  278. Matcher: ignores,
  279. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  280. CurrentFiler: cFiler{f.model, f.ID},
  281. Filesystem: mtimefs,
  282. IgnorePerms: f.IgnorePerms,
  283. AutoNormalize: f.AutoNormalize,
  284. Hashers: f.model.numHashers(f.ID),
  285. ShortID: f.model.shortID,
  286. ProgressTickIntervalS: f.ScanProgressIntervalS,
  287. UseLargeBlocks: f.UseLargeBlocks,
  288. LocalFlags: f.localFlags,
  289. })
  290. batchFn := func(fs []protocol.FileInfo) error {
  291. if err := f.CheckHealth(); err != nil {
  292. l.Debugf("Stopping scan of folder %s due to: %s", f.Description(), err)
  293. return err
  294. }
  295. f.model.updateLocalsFromScanning(f.ID, fs)
  296. return nil
  297. }
  298. // Resolve items which are identical with the global state.
  299. if f.localFlags&protocol.FlagLocalReceiveOnly != 0 {
  300. oldBatchFn := batchFn // can't reference batchFn directly (recursion)
  301. batchFn = func(fs []protocol.FileInfo) error {
  302. for i := range fs {
  303. switch gf, ok := fset.GetGlobal(fs[i].Name); {
  304. case !ok:
  305. continue
  306. case gf.IsEquivalentOptional(fs[i], false, false, protocol.FlagLocalReceiveOnly):
  307. // What we have locally is equivalent to the global file.
  308. fs[i].Version = fs[i].Version.Merge(gf.Version)
  309. fallthrough
  310. case fs[i].IsDeleted() && gf.IsReceiveOnlyChanged():
  311. // Our item is deleted and the global item is our own
  312. // receive only file. We can't delete file infos, so
  313. // we just pretend it is a normal deleted file (nobody
  314. // cares about that).
  315. fs[i].LocalFlags &^= protocol.FlagLocalReceiveOnly
  316. }
  317. }
  318. return oldBatchFn(fs)
  319. }
  320. }
  321. batch := newFileInfoBatch(batchFn)
  322. // Schedule a pull after scanning, but only if we actually detected any
  323. // changes.
  324. changes := 0
  325. defer func() {
  326. if changes > 0 {
  327. f.SchedulePull()
  328. }
  329. }()
  330. f.clearScanErrors(subDirs)
  331. for res := range fchan {
  332. if res.Err != nil {
  333. f.newScanError(res.Path, res.Err)
  334. continue
  335. }
  336. if err := batch.flushIfFull(); err != nil {
  337. return err
  338. }
  339. batch.append(res.File)
  340. changes++
  341. }
  342. if err := batch.flush(); err != nil {
  343. return err
  344. }
  345. if len(subDirs) == 0 {
  346. // If we have no specific subdirectories to traverse, set it to one
  347. // empty prefix so we traverse the entire folder contents once.
  348. subDirs = []string{""}
  349. }
  350. // Do a scan of the database for each prefix, to check for deleted and
  351. // ignored files.
  352. var toIgnore []db.FileInfoTruncated
  353. ignoredParent := ""
  354. for _, sub := range subDirs {
  355. var iterError error
  356. fset.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  357. file := fi.(db.FileInfoTruncated)
  358. if err := batch.flushIfFull(); err != nil {
  359. iterError = err
  360. return false
  361. }
  362. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  363. for _, file := range toIgnore {
  364. l.Debugln("marking file as ignored", file)
  365. nf := file.ConvertToIgnoredFileInfo(f.model.id.Short())
  366. batch.append(nf)
  367. changes++
  368. if err := batch.flushIfFull(); err != nil {
  369. iterError = err
  370. return false
  371. }
  372. }
  373. toIgnore = toIgnore[:0]
  374. ignoredParent = ""
  375. }
  376. switch ignored := ignores.Match(file.Name).IsIgnored(); {
  377. case !file.IsIgnored() && ignored:
  378. // File was not ignored at last pass but has been ignored.
  379. if file.IsDirectory() {
  380. // Delay ignoring as a child might be unignored.
  381. toIgnore = append(toIgnore, file)
  382. if ignoredParent == "" {
  383. // If the parent wasn't ignored already, set
  384. // this path as the "highest" ignored parent
  385. ignoredParent = file.Name
  386. }
  387. return true
  388. }
  389. l.Debugln("marking file as ignored", f)
  390. nf := file.ConvertToIgnoredFileInfo(f.model.id.Short())
  391. batch.append(nf)
  392. changes++
  393. case file.IsIgnored() && !ignored:
  394. // Successfully scanned items are already un-ignored during
  395. // the scan, so check whether it is deleted.
  396. fallthrough
  397. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  398. // The file is not ignored, deleted or unsupported. Lets check if
  399. // it's still here. Simply stat:ing it wont do as there are
  400. // tons of corner cases (e.g. parent dir->symlink, missing
  401. // permissions)
  402. if !osutil.IsDeleted(mtimefs, file.Name) {
  403. if ignoredParent != "" {
  404. // Don't ignore parents of this not ignored item
  405. toIgnore = toIgnore[:0]
  406. ignoredParent = ""
  407. }
  408. return true
  409. }
  410. nf := protocol.FileInfo{
  411. Name: file.Name,
  412. Type: file.Type,
  413. Size: 0,
  414. ModifiedS: file.ModifiedS,
  415. ModifiedNs: file.ModifiedNs,
  416. ModifiedBy: f.model.id.Short(),
  417. Deleted: true,
  418. Version: file.Version.Update(f.model.shortID),
  419. LocalFlags: f.localFlags,
  420. }
  421. // We do not want to override the global version
  422. // with the deleted file. Keeping only our local
  423. // counter makes sure we are in conflict with any
  424. // other existing versions, which will be resolved
  425. // by the normal pulling mechanisms.
  426. if file.ShouldConflict() {
  427. nf.Version = nf.Version.DropOthers(f.model.shortID)
  428. }
  429. batch.append(nf)
  430. changes++
  431. }
  432. return true
  433. })
  434. if iterError == nil && len(toIgnore) > 0 {
  435. for _, file := range toIgnore {
  436. l.Debugln("marking file as ignored", f)
  437. nf := file.ConvertToIgnoredFileInfo(f.model.id.Short())
  438. batch.append(nf)
  439. changes++
  440. if iterError = batch.flushIfFull(); iterError != nil {
  441. break
  442. }
  443. }
  444. toIgnore = toIgnore[:0]
  445. }
  446. if iterError != nil {
  447. return iterError
  448. }
  449. }
  450. if err := batch.flush(); err != nil {
  451. return err
  452. }
  453. f.model.folderStatRef(f.ID).ScanCompleted()
  454. f.setState(FolderIdle)
  455. return nil
  456. }
  457. func (f *folder) scanTimerFired() {
  458. err := f.scanSubdirs(nil)
  459. select {
  460. case <-f.initialScanFinished:
  461. default:
  462. status := "Completed"
  463. if err != nil {
  464. status = "Failed"
  465. }
  466. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  467. close(f.initialScanFinished)
  468. }
  469. f.Reschedule()
  470. }
  471. func (f *folder) WatchError() error {
  472. f.watchMut.Lock()
  473. defer f.watchMut.Unlock()
  474. return f.watchErr
  475. }
  476. // stopWatch immediately aborts watching and may be called asynchronously
  477. func (f *folder) stopWatch() {
  478. f.watchMut.Lock()
  479. f.watchCancel()
  480. prevErr := f.watchErr
  481. f.watchErr = errWatchNotStarted
  482. f.watchMut.Unlock()
  483. if prevErr != errWatchNotStarted {
  484. data := map[string]interface{}{
  485. "folder": f.ID,
  486. "to": errWatchNotStarted.Error(),
  487. }
  488. if prevErr != nil {
  489. data["from"] = prevErr.Error()
  490. }
  491. events.Default.Log(events.FolderWatchStateChanged, data)
  492. }
  493. }
  494. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  495. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  496. func (f *folder) scheduleWatchRestart() {
  497. select {
  498. case f.restartWatchChan <- struct{}{}:
  499. default:
  500. // We might be busy doing a pull and thus not reading from this
  501. // channel. The channel is 1-buffered, so one notification will be
  502. // queued to ensure we recheck after the pull.
  503. }
  504. }
  505. // restartWatch should only ever be called synchronously. If you want to use
  506. // this asynchronously, you should probably use scheduleWatchRestart instead.
  507. func (f *folder) restartWatch() {
  508. f.stopWatch()
  509. f.startWatch()
  510. f.scanSubdirs(nil)
  511. }
  512. // startWatch should only ever be called synchronously. If you want to use
  513. // this asynchronously, you should probably use scheduleWatchRestart instead.
  514. func (f *folder) startWatch() {
  515. ctx, cancel := context.WithCancel(f.ctx)
  516. f.model.fmut.RLock()
  517. ignores := f.model.folderIgnores[f.folderID]
  518. f.model.fmut.RUnlock()
  519. f.watchMut.Lock()
  520. f.watchChan = make(chan []string)
  521. f.watchCancel = cancel
  522. f.watchMut.Unlock()
  523. go f.startWatchAsync(ctx, ignores)
  524. }
  525. // startWatchAsync tries to start the filesystem watching and retries every minute on failure.
  526. // It is a convenience function that should not be used except in startWatch.
  527. func (f *folder) startWatchAsync(ctx context.Context, ignores *ignore.Matcher) {
  528. timer := time.NewTimer(0)
  529. for {
  530. select {
  531. case <-timer.C:
  532. eventChan, err := f.Filesystem().Watch(".", ignores, ctx, f.IgnorePerms)
  533. f.watchMut.Lock()
  534. prevErr := f.watchErr
  535. f.watchErr = err
  536. f.watchMut.Unlock()
  537. if err != prevErr {
  538. data := map[string]interface{}{
  539. "folder": f.ID,
  540. }
  541. if prevErr != nil {
  542. data["from"] = prevErr.Error()
  543. }
  544. if err != nil {
  545. data["to"] = err.Error()
  546. }
  547. events.Default.Log(events.FolderWatchStateChanged, data)
  548. }
  549. if err != nil {
  550. if prevErr == errWatchNotStarted {
  551. l.Infof("Error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  552. } else {
  553. l.Debugf("Repeat error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  554. }
  555. timer.Reset(time.Minute)
  556. continue
  557. }
  558. f.watchMut.Lock()
  559. defer f.watchMut.Unlock()
  560. watchaggregator.Aggregate(eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, ctx)
  561. l.Debugln("Started filesystem watcher for folder", f.Description())
  562. return
  563. case <-ctx.Done():
  564. return
  565. }
  566. }
  567. }
  568. func (f *folder) setError(err error) {
  569. select {
  570. case <-f.ctx.Done():
  571. return
  572. default:
  573. }
  574. _, _, oldErr := f.getState()
  575. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  576. return
  577. }
  578. if err != nil {
  579. if oldErr == nil {
  580. l.Warnf("Error on folder %s: %v", f.Description(), err)
  581. } else {
  582. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  583. }
  584. } else {
  585. l.Infoln("Cleared error on folder", f.Description())
  586. }
  587. if f.FSWatcherEnabled {
  588. if err != nil {
  589. f.stopWatch()
  590. } else {
  591. f.scheduleWatchRestart()
  592. }
  593. }
  594. f.stateTracker.setError(err)
  595. }
  596. func (f *folder) basePause() time.Duration {
  597. if f.PullerPauseS == 0 {
  598. return defaultPullerPause
  599. }
  600. return time.Duration(f.PullerPauseS) * time.Second
  601. }
  602. func (f *folder) String() string {
  603. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  604. }
  605. func (f *folder) newScanError(path string, err error) {
  606. f.scanErrorsMut.Lock()
  607. f.scanErrors = append(f.scanErrors, FileError{
  608. Err: err.Error(),
  609. Path: path,
  610. })
  611. f.scanErrorsMut.Unlock()
  612. }
  613. func (f *folder) clearScanErrors(subDirs []string) {
  614. f.scanErrorsMut.Lock()
  615. defer f.scanErrorsMut.Unlock()
  616. if len(subDirs) == 0 {
  617. f.scanErrors = nil
  618. return
  619. }
  620. filtered := f.scanErrors[:0]
  621. outer:
  622. for _, fe := range f.scanErrors {
  623. for _, sub := range subDirs {
  624. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  625. continue outer
  626. }
  627. }
  628. filtered = append(filtered, fe)
  629. }
  630. f.scanErrors = filtered
  631. }
  632. func (f *folder) Errors() []FileError {
  633. f.scanErrorsMut.Lock()
  634. defer f.scanErrorsMut.Unlock()
  635. return append([]FileError{}, f.scanErrors...)
  636. }
  637. // The exists function is expected to return true for all known paths
  638. // (excluding "" and ".")
  639. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  640. if len(dirs) == 0 {
  641. return nil
  642. }
  643. sort.Strings(dirs)
  644. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  645. return nil
  646. }
  647. prev := "./" // Anything that can't be parent of a clean path
  648. for i := 0; i < len(dirs); {
  649. dir, err := fs.Canonicalize(dirs[i])
  650. if err != nil {
  651. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  652. dirs = append(dirs[:i], dirs[i+1:]...)
  653. continue
  654. }
  655. if dir == prev || fs.IsParent(dir, prev) {
  656. dirs = append(dirs[:i], dirs[i+1:]...)
  657. continue
  658. }
  659. parent := filepath.Dir(dir)
  660. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  661. dir = parent
  662. parent = filepath.Dir(dir)
  663. }
  664. dirs[i] = dir
  665. prev = dir
  666. i++
  667. }
  668. return dirs
  669. }