folder.go 20 KB

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