folder.go 20 KB

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