folder.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760
  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.ID, "ignore patterns changed; triggering puller")
  254. f.IgnoresUpdated()
  255. }
  256. }()
  257. if err := ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  258. err = fmt.Errorf("loading ignores: %v", err)
  259. f.setError(err)
  260. return err
  261. }
  262. // Clean the list of subitems to ensure that we start at a known
  263. // directory, and don't scan subdirectories of things we've already
  264. // scanned.
  265. subDirs = unifySubs(subDirs, func(f string) bool {
  266. _, ok := fset.Get(protocol.LocalDeviceID, f)
  267. return ok
  268. })
  269. f.setState(FolderScanning)
  270. fchan := scanner.Walk(f.ctx, scanner.Config{
  271. Folder: f.ID,
  272. Subs: subDirs,
  273. Matcher: ignores,
  274. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  275. CurrentFiler: cFiler{f.model, f.ID},
  276. Filesystem: mtimefs,
  277. IgnorePerms: f.IgnorePerms,
  278. AutoNormalize: f.AutoNormalize,
  279. Hashers: f.model.numHashers(f.ID),
  280. ShortID: f.model.shortID,
  281. ProgressTickIntervalS: f.ScanProgressIntervalS,
  282. UseLargeBlocks: f.UseLargeBlocks,
  283. LocalFlags: f.localFlags,
  284. })
  285. batchFn := func(fs []protocol.FileInfo) error {
  286. if err := f.CheckHealth(); err != nil {
  287. l.Debugf("Stopping scan of folder %s due to: %s", f.Description(), err)
  288. return err
  289. }
  290. f.model.updateLocalsFromScanning(f.ID, fs)
  291. return nil
  292. }
  293. // Resolve items which are identical with the global state.
  294. if f.localFlags&protocol.FlagLocalReceiveOnly != 0 {
  295. oldBatchFn := batchFn // can't reference batchFn directly (recursion)
  296. batchFn = func(fs []protocol.FileInfo) error {
  297. for i := range fs {
  298. switch gf, ok := fset.GetGlobal(fs[i].Name); {
  299. case !ok:
  300. continue
  301. case gf.IsEquivalentOptional(fs[i], false, false, protocol.FlagLocalReceiveOnly):
  302. // What we have locally is equivalent to the global file.
  303. fs[i].Version = fs[i].Version.Merge(gf.Version)
  304. fallthrough
  305. case fs[i].IsDeleted() && gf.IsReceiveOnlyChanged():
  306. // Our item is deleted and the global item is our own
  307. // receive only file. We can't delete file infos, so
  308. // we just pretend it is a normal deleted file (nobody
  309. // cares about that).
  310. fs[i].LocalFlags &^= protocol.FlagLocalReceiveOnly
  311. }
  312. }
  313. return oldBatchFn(fs)
  314. }
  315. }
  316. batch := newFileInfoBatch(batchFn)
  317. // Schedule a pull after scanning, but only if we actually detected any
  318. // changes.
  319. changes := 0
  320. defer func() {
  321. if changes > 0 {
  322. f.SchedulePull()
  323. }
  324. }()
  325. f.clearScanErrors(subDirs)
  326. for res := range fchan {
  327. if res.Err != nil {
  328. f.newScanError(res.Path, res.Err)
  329. continue
  330. }
  331. if err := batch.flushIfFull(); err != nil {
  332. return err
  333. }
  334. batch.append(res.File)
  335. changes++
  336. }
  337. if err := batch.flush(); err != nil {
  338. return err
  339. }
  340. if len(subDirs) == 0 {
  341. // If we have no specific subdirectories to traverse, set it to one
  342. // empty prefix so we traverse the entire folder contents once.
  343. subDirs = []string{""}
  344. }
  345. // Do a scan of the database for each prefix, to check for deleted and
  346. // ignored files.
  347. var toIgnore []db.FileInfoTruncated
  348. ignoredParent := ""
  349. for _, sub := range subDirs {
  350. var iterError error
  351. fset.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  352. file := fi.(db.FileInfoTruncated)
  353. if err := batch.flushIfFull(); err != nil {
  354. iterError = err
  355. return false
  356. }
  357. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  358. for _, file := range toIgnore {
  359. l.Debugln("marking file as ignored", file)
  360. nf := file.ConvertToIgnoredFileInfo(f.model.id.Short())
  361. batch.append(nf)
  362. changes++
  363. if err := batch.flushIfFull(); err != nil {
  364. iterError = err
  365. return false
  366. }
  367. }
  368. toIgnore = toIgnore[:0]
  369. ignoredParent = ""
  370. }
  371. switch ignored := ignores.Match(file.Name).IsIgnored(); {
  372. case !file.IsIgnored() && ignored:
  373. // File was not ignored at last pass but has been ignored.
  374. if file.IsDirectory() {
  375. // Delay ignoring as a child might be unignored.
  376. toIgnore = append(toIgnore, file)
  377. if ignoredParent == "" {
  378. // If the parent wasn't ignored already, set
  379. // this path as the "highest" ignored parent
  380. ignoredParent = file.Name
  381. }
  382. return true
  383. }
  384. l.Debugln("marking file as ignored", f)
  385. nf := file.ConvertToIgnoredFileInfo(f.model.id.Short())
  386. batch.append(nf)
  387. changes++
  388. case file.IsIgnored() && !ignored:
  389. // Successfully scanned items are already un-ignored during
  390. // the scan, so check whether it is deleted.
  391. fallthrough
  392. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  393. // The file is not ignored, deleted or unsupported. Lets check if
  394. // it's still here. Simply stat:ing it wont do as there are
  395. // tons of corner cases (e.g. parent dir->symlink, missing
  396. // permissions)
  397. if !osutil.IsDeleted(mtimefs, file.Name) {
  398. if ignoredParent != "" {
  399. // Don't ignore parents of this not ignored item
  400. toIgnore = toIgnore[:0]
  401. ignoredParent = ""
  402. }
  403. return true
  404. }
  405. nf := protocol.FileInfo{
  406. Name: file.Name,
  407. Type: file.Type,
  408. Size: 0,
  409. ModifiedS: file.ModifiedS,
  410. ModifiedNs: file.ModifiedNs,
  411. ModifiedBy: f.model.id.Short(),
  412. Deleted: true,
  413. Version: file.Version.Update(f.model.shortID),
  414. LocalFlags: f.localFlags,
  415. }
  416. // We do not want to override the global version
  417. // with the deleted file. Keeping only our local
  418. // counter makes sure we are in conflict with any
  419. // other existing versions, which will be resolved
  420. // by the normal pulling mechanisms.
  421. if file.ShouldConflict() {
  422. nf.Version = nf.Version.DropOthers(f.model.shortID)
  423. }
  424. batch.append(nf)
  425. changes++
  426. }
  427. return true
  428. })
  429. if iterError == nil && len(toIgnore) > 0 {
  430. for _, file := range toIgnore {
  431. l.Debugln("marking file as ignored", f)
  432. nf := file.ConvertToIgnoredFileInfo(f.model.id.Short())
  433. batch.append(nf)
  434. changes++
  435. if iterError = batch.flushIfFull(); iterError != nil {
  436. break
  437. }
  438. }
  439. toIgnore = toIgnore[:0]
  440. }
  441. if iterError != nil {
  442. return iterError
  443. }
  444. }
  445. if err := batch.flush(); err != nil {
  446. return err
  447. }
  448. f.model.folderStatRef(f.ID).ScanCompleted()
  449. f.setState(FolderIdle)
  450. return nil
  451. }
  452. func (f *folder) scanTimerFired() {
  453. err := f.scanSubdirs(nil)
  454. select {
  455. case <-f.initialScanFinished:
  456. default:
  457. status := "Completed"
  458. if err != nil {
  459. status = "Failed"
  460. }
  461. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  462. close(f.initialScanFinished)
  463. }
  464. f.Reschedule()
  465. }
  466. func (f *folder) WatchError() error {
  467. f.watchMut.Lock()
  468. defer f.watchMut.Unlock()
  469. return f.watchErr
  470. }
  471. // stopWatch immediately aborts watching and may be called asynchronously
  472. func (f *folder) stopWatch() {
  473. f.watchMut.Lock()
  474. f.watchCancel()
  475. prevErr := f.watchErr
  476. f.watchErr = errWatchNotStarted
  477. f.watchMut.Unlock()
  478. if prevErr != errWatchNotStarted {
  479. data := map[string]interface{}{
  480. "folder": f.ID,
  481. "to": errWatchNotStarted.Error(),
  482. }
  483. if prevErr != nil {
  484. data["from"] = prevErr.Error()
  485. }
  486. events.Default.Log(events.FolderWatchStateChanged, data)
  487. }
  488. }
  489. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  490. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  491. func (f *folder) scheduleWatchRestart() {
  492. select {
  493. case f.restartWatchChan <- struct{}{}:
  494. default:
  495. // We might be busy doing a pull and thus not reading from this
  496. // channel. The channel is 1-buffered, so one notification will be
  497. // queued to ensure we recheck after the pull.
  498. }
  499. }
  500. // restartWatch should only ever be called synchronously. If you want to use
  501. // this asynchronously, you should probably use scheduleWatchRestart instead.
  502. func (f *folder) restartWatch() {
  503. f.stopWatch()
  504. f.startWatch()
  505. f.scanSubdirs(nil)
  506. }
  507. // startWatch should only ever be called synchronously. If you want to use
  508. // this asynchronously, you should probably use scheduleWatchRestart instead.
  509. func (f *folder) startWatch() {
  510. ctx, cancel := context.WithCancel(f.ctx)
  511. f.model.fmut.RLock()
  512. ignores := f.model.folderIgnores[f.folderID]
  513. f.model.fmut.RUnlock()
  514. f.watchMut.Lock()
  515. f.watchChan = make(chan []string)
  516. f.watchCancel = cancel
  517. f.watchMut.Unlock()
  518. go f.startWatchAsync(ctx, ignores)
  519. }
  520. // startWatchAsync tries to start the filesystem watching and retries every minute on failure.
  521. // It is a convenience function that should not be used except in startWatch.
  522. func (f *folder) startWatchAsync(ctx context.Context, ignores *ignore.Matcher) {
  523. timer := time.NewTimer(0)
  524. for {
  525. select {
  526. case <-timer.C:
  527. eventChan, err := f.Filesystem().Watch(".", ignores, ctx, f.IgnorePerms)
  528. f.watchMut.Lock()
  529. prevErr := f.watchErr
  530. f.watchErr = err
  531. f.watchMut.Unlock()
  532. if err != prevErr {
  533. data := map[string]interface{}{
  534. "folder": f.ID,
  535. }
  536. if prevErr != nil {
  537. data["from"] = prevErr.Error()
  538. }
  539. if err != nil {
  540. data["to"] = err.Error()
  541. }
  542. events.Default.Log(events.FolderWatchStateChanged, data)
  543. }
  544. if err != nil {
  545. if prevErr == errWatchNotStarted {
  546. l.Infof("Error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  547. } else {
  548. l.Debugf("Repeat error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  549. }
  550. timer.Reset(time.Minute)
  551. continue
  552. }
  553. f.watchMut.Lock()
  554. defer f.watchMut.Unlock()
  555. watchaggregator.Aggregate(eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, ctx)
  556. l.Debugln("Started filesystem watcher for folder", f.Description())
  557. return
  558. case <-ctx.Done():
  559. return
  560. }
  561. }
  562. }
  563. func (f *folder) setError(err error) {
  564. _, _, oldErr := f.getState()
  565. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  566. return
  567. }
  568. if err != nil {
  569. if oldErr == nil {
  570. l.Warnf("Error on folder %s: %v", f.Description(), err)
  571. } else {
  572. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  573. }
  574. } else {
  575. l.Infoln("Cleared error on folder", f.Description())
  576. }
  577. if f.FSWatcherEnabled {
  578. if err != nil {
  579. f.stopWatch()
  580. } else {
  581. f.scheduleWatchRestart()
  582. }
  583. }
  584. f.stateTracker.setError(err)
  585. }
  586. func (f *folder) basePause() time.Duration {
  587. if f.PullerPauseS == 0 {
  588. return defaultPullerPause
  589. }
  590. return time.Duration(f.PullerPauseS) * time.Second
  591. }
  592. func (f *folder) String() string {
  593. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  594. }
  595. func (f *folder) newScanError(path string, err error) {
  596. f.scanErrorsMut.Lock()
  597. f.scanErrors = append(f.scanErrors, FileError{
  598. Err: err.Error(),
  599. Path: path,
  600. })
  601. f.scanErrorsMut.Unlock()
  602. }
  603. func (f *folder) clearScanErrors(subDirs []string) {
  604. f.scanErrorsMut.Lock()
  605. defer f.scanErrorsMut.Unlock()
  606. if len(subDirs) == 0 {
  607. f.scanErrors = nil
  608. return
  609. }
  610. filtered := f.scanErrors[:0]
  611. outer:
  612. for _, fe := range f.scanErrors {
  613. for _, sub := range subDirs {
  614. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  615. continue outer
  616. }
  617. }
  618. filtered = append(filtered, fe)
  619. }
  620. f.scanErrors = filtered
  621. }
  622. func (f *folder) Errors() []FileError {
  623. f.scanErrorsMut.Lock()
  624. defer f.scanErrorsMut.Unlock()
  625. return append([]FileError{}, f.scanErrors...)
  626. }
  627. // The exists function is expected to return true for all known paths
  628. // (excluding "" and ".")
  629. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  630. if len(dirs) == 0 {
  631. return nil
  632. }
  633. sort.Strings(dirs)
  634. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  635. return nil
  636. }
  637. prev := "./" // Anything that can't be parent of a clean path
  638. for i := 0; i < len(dirs); {
  639. dir, err := fs.Canonicalize(dirs[i])
  640. if err != nil {
  641. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  642. dirs = append(dirs[:i], dirs[i+1:]...)
  643. continue
  644. }
  645. if dir == prev || fs.IsParent(dir, prev) {
  646. dirs = append(dirs[:i], dirs[i+1:]...)
  647. continue
  648. }
  649. parent := filepath.Dir(dir)
  650. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  651. dir = parent
  652. parent = filepath.Dir(dir)
  653. }
  654. dirs[i] = dir
  655. prev = dir
  656. i++
  657. }
  658. return dirs
  659. }