folder.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895
  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. "fmt"
  10. "math/rand"
  11. "path/filepath"
  12. "sort"
  13. "sync/atomic"
  14. "time"
  15. "github.com/syncthing/syncthing/lib/config"
  16. "github.com/syncthing/syncthing/lib/db"
  17. "github.com/syncthing/syncthing/lib/events"
  18. "github.com/syncthing/syncthing/lib/fs"
  19. "github.com/syncthing/syncthing/lib/ignore"
  20. "github.com/syncthing/syncthing/lib/locations"
  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/stats"
  25. "github.com/syncthing/syncthing/lib/sync"
  26. "github.com/syncthing/syncthing/lib/watchaggregator"
  27. "github.com/thejerf/suture"
  28. )
  29. // scanLimiter limits the number of concurrent scans. A limit of zero means no limit.
  30. var scanLimiter = newByteSemaphore(0)
  31. type folder struct {
  32. suture.Service
  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. scanErrors []FileError
  49. scanErrorsMut sync.Mutex
  50. pullScheduled chan struct{}
  51. watchCancel context.CancelFunc
  52. watchChan chan []string
  53. restartWatchChan chan struct{}
  54. watchErr error
  55. watchMut sync.Mutex
  56. puller puller
  57. }
  58. type rescanRequest struct {
  59. subdirs []string
  60. err chan error
  61. }
  62. type puller interface {
  63. pull() bool // true when successfull and should not be retried
  64. }
  65. func newFolder(model *model, fset *db.FileSet, ignores *ignore.Matcher, cfg config.FolderConfiguration, evLogger events.Logger) folder {
  66. ctx, cancel := context.WithCancel(context.Background())
  67. return folder{
  68. stateTracker: newStateTracker(cfg.ID, evLogger),
  69. FolderConfiguration: cfg,
  70. FolderStatisticsReference: stats.NewFolderStatisticsReference(model.db, cfg.ID),
  71. model: model,
  72. shortID: model.shortID,
  73. fset: fset,
  74. ignores: ignores,
  75. ctx: ctx,
  76. cancel: cancel,
  77. scanInterval: time.Duration(cfg.RescanIntervalS) * time.Second,
  78. scanTimer: time.NewTimer(time.Millisecond), // The first scan should be done immediately.
  79. scanNow: make(chan rescanRequest),
  80. scanDelay: make(chan time.Duration),
  81. initialScanFinished: make(chan struct{}),
  82. scanErrorsMut: sync.NewMutex(),
  83. pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.
  84. watchCancel: func() {},
  85. restartWatchChan: make(chan struct{}, 1),
  86. watchMut: sync.NewMutex(),
  87. }
  88. }
  89. func (f *folder) serve(_ chan struct{}) {
  90. atomic.AddInt32(&f.model.foldersRunning, 1)
  91. defer atomic.AddInt32(&f.model.foldersRunning, -1)
  92. l.Debugln(f, "starting")
  93. defer l.Debugln(f, "exiting")
  94. defer func() {
  95. f.scanTimer.Stop()
  96. f.setState(FolderIdle)
  97. }()
  98. pause := f.basePause()
  99. pullFailTimer := time.NewTimer(0)
  100. <-pullFailTimer.C
  101. if f.FSWatcherEnabled && f.CheckHealth() == nil {
  102. f.startWatch()
  103. }
  104. initialCompleted := f.initialScanFinished
  105. pull := func() {
  106. startTime := time.Now()
  107. if f.puller.pull() {
  108. // We're good. Don't schedule another pull and reset
  109. // the pause interval.
  110. pause = f.basePause()
  111. return
  112. }
  113. // Pulling failed, try again later.
  114. delay := pause + time.Since(startTime)
  115. l.Infof("Folder %v isn't making sync progress - retrying in %v.", f.Description(), delay)
  116. pullFailTimer.Reset(delay)
  117. if pause < 60*f.basePause() {
  118. pause *= 2
  119. }
  120. }
  121. for {
  122. select {
  123. case <-f.ctx.Done():
  124. return
  125. case <-f.pullScheduled:
  126. pullFailTimer.Stop()
  127. select {
  128. case <-pullFailTimer.C:
  129. default:
  130. }
  131. pull()
  132. case <-pullFailTimer.C:
  133. pull()
  134. case <-initialCompleted:
  135. // Initial scan has completed, we should do a pull
  136. initialCompleted = nil // never hit this case again
  137. if !f.puller.pull() {
  138. // Pulling failed, try again later.
  139. pullFailTimer.Reset(pause)
  140. }
  141. case <-f.scanTimer.C:
  142. l.Debugln(f, "Scanning subdirectories")
  143. f.scanTimerFired()
  144. case req := <-f.scanNow:
  145. req.err <- f.scanSubdirs(req.subdirs)
  146. case next := <-f.scanDelay:
  147. f.scanTimer.Reset(next)
  148. case fsEvents := <-f.watchChan:
  149. l.Debugln(f, "filesystem notification rescan")
  150. f.scanSubdirs(fsEvents)
  151. case <-f.restartWatchChan:
  152. f.restartWatch()
  153. }
  154. }
  155. }
  156. func (f *folder) BringToFront(string) {}
  157. func (f *folder) Override() {}
  158. func (f *folder) Revert() {}
  159. func (f *folder) DelayScan(next time.Duration) {
  160. f.Delay(next)
  161. }
  162. func (f *folder) ignoresUpdated() {
  163. if f.FSWatcherEnabled {
  164. f.scheduleWatchRestart()
  165. }
  166. }
  167. func (f *folder) SchedulePull() {
  168. select {
  169. case f.pullScheduled <- struct{}{}:
  170. default:
  171. // We might be busy doing a pull and thus not reading from this
  172. // channel. The channel is 1-buffered, so one notification will be
  173. // queued to ensure we recheck after the pull, but beyond that we must
  174. // make sure to not block index receiving.
  175. }
  176. }
  177. func (f *folder) Jobs(_, _ int) ([]string, []string, int) {
  178. return nil, nil, 0
  179. }
  180. func (f *folder) Scan(subdirs []string) error {
  181. <-f.initialScanFinished
  182. req := rescanRequest{
  183. subdirs: subdirs,
  184. err: make(chan error),
  185. }
  186. select {
  187. case f.scanNow <- req:
  188. return <-req.err
  189. case <-f.ctx.Done():
  190. return f.ctx.Err()
  191. }
  192. }
  193. func (f *folder) Reschedule() {
  194. if f.scanInterval == 0 {
  195. return
  196. }
  197. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  198. sleepNanos := (f.scanInterval.Nanoseconds()*3 + rand.Int63n(2*f.scanInterval.Nanoseconds())) / 4
  199. interval := time.Duration(sleepNanos) * time.Nanosecond
  200. l.Debugln(f, "next rescan in", interval)
  201. f.scanTimer.Reset(interval)
  202. }
  203. func (f *folder) Delay(next time.Duration) {
  204. f.scanDelay <- next
  205. }
  206. func (f *folder) Stop() {
  207. f.cancel()
  208. f.Service.Stop()
  209. }
  210. // CheckHealth checks the folder for common errors, updates the folder state
  211. // and returns the current folder error, or nil if the folder is healthy.
  212. func (f *folder) CheckHealth() error {
  213. err := f.getHealthError()
  214. f.setError(err)
  215. return err
  216. }
  217. func (f *folder) getHealthError() error {
  218. // Check for folder errors, with the most serious and specific first and
  219. // generic ones like out of space on the home disk later.
  220. if err := f.CheckPath(); err != nil {
  221. return err
  222. }
  223. dbPath := locations.Get(locations.Database)
  224. if usage, err := fs.NewFilesystem(fs.FilesystemTypeBasic, dbPath).Usage("."); err == nil {
  225. if err = config.CheckFreeSpace(f.model.cfg.Options().MinHomeDiskFree, usage); err != nil {
  226. return fmt.Errorf("insufficient space on disk for database (%v): %v", dbPath, err)
  227. }
  228. }
  229. return nil
  230. }
  231. func (f *folder) scanSubdirs(subDirs []string) error {
  232. if err := f.CheckHealth(); err != nil {
  233. return err
  234. }
  235. mtimefs := f.fset.MtimeFS()
  236. f.setState(FolderScanWaiting)
  237. scanLimiter.take(1)
  238. defer scanLimiter.give(1)
  239. for i := range subDirs {
  240. sub := osutil.NativeFilename(subDirs[i])
  241. if sub == "" {
  242. // A blank subdirs means to scan the entire folder. We can trim
  243. // the subDirs list and go on our way.
  244. subDirs = nil
  245. break
  246. }
  247. subDirs[i] = sub
  248. }
  249. // Check if the ignore patterns changed as part of scanning this folder.
  250. // If they did we should schedule a pull of the folder so that we
  251. // request things we might have suddenly become unignored and so on.
  252. oldHash := f.ignores.Hash()
  253. defer func() {
  254. if f.ignores.Hash() != oldHash {
  255. l.Debugln("Folder", f.Description(), "ignore patterns change detected while scanning; triggering puller")
  256. f.ignoresUpdated()
  257. f.SchedulePull()
  258. }
  259. }()
  260. if err := f.ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  261. err = fmt.Errorf("loading ignores: %v", err)
  262. f.setError(err)
  263. return err
  264. }
  265. // Clean the list of subitems to ensure that we start at a known
  266. // directory, and don't scan subdirectories of things we've already
  267. // scanned.
  268. subDirs = unifySubs(subDirs, func(file string) bool {
  269. _, ok := f.fset.Get(protocol.LocalDeviceID, file)
  270. return ok
  271. })
  272. f.setState(FolderScanning)
  273. fchan := scanner.Walk(f.ctx, scanner.Config{
  274. Folder: f.ID,
  275. Subs: subDirs,
  276. Matcher: f.ignores,
  277. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  278. CurrentFiler: cFiler{f.fset},
  279. Filesystem: mtimefs,
  280. IgnorePerms: f.IgnorePerms,
  281. AutoNormalize: f.AutoNormalize,
  282. Hashers: f.model.numHashers(f.ID),
  283. ShortID: f.shortID,
  284. ProgressTickIntervalS: f.ScanProgressIntervalS,
  285. LocalFlags: f.localFlags,
  286. ModTimeWindow: f.ModTimeWindow(),
  287. })
  288. batchFn := func(fs []protocol.FileInfo) error {
  289. if err := f.CheckHealth(); err != nil {
  290. l.Debugf("Stopping scan of folder %s due to: %s", f.Description(), err)
  291. return err
  292. }
  293. f.updateLocalsFromScanning(fs)
  294. return nil
  295. }
  296. // Resolve items which are identical with the global state.
  297. if f.localFlags&protocol.FlagLocalReceiveOnly != 0 {
  298. oldBatchFn := batchFn // can't reference batchFn directly (recursion)
  299. batchFn = func(fs []protocol.FileInfo) error {
  300. for i := range fs {
  301. switch gf, ok := f.fset.GetGlobal(fs[i].Name); {
  302. case !ok:
  303. continue
  304. case gf.IsEquivalentOptional(fs[i], f.ModTimeWindow(), false, false, protocol.FlagLocalReceiveOnly):
  305. // What we have locally is equivalent to the global file.
  306. fs[i].Version = fs[i].Version.Merge(gf.Version)
  307. fallthrough
  308. case fs[i].IsDeleted() && gf.IsReceiveOnlyChanged():
  309. // Our item is deleted and the global item is our own
  310. // receive only file. We can't delete file infos, so
  311. // we just pretend it is a normal deleted file (nobody
  312. // cares about that).
  313. fs[i].LocalFlags &^= protocol.FlagLocalReceiveOnly
  314. }
  315. }
  316. return oldBatchFn(fs)
  317. }
  318. }
  319. batch := newFileInfoBatch(batchFn)
  320. // Schedule a pull after scanning, but only if we actually detected any
  321. // changes.
  322. changes := 0
  323. defer func() {
  324. if changes > 0 {
  325. f.SchedulePull()
  326. }
  327. }()
  328. f.clearScanErrors(subDirs)
  329. for res := range fchan {
  330. if res.Err != nil {
  331. f.newScanError(res.Path, res.Err)
  332. continue
  333. }
  334. if err := batch.flushIfFull(); err != nil {
  335. return err
  336. }
  337. batch.append(res.File)
  338. changes++
  339. }
  340. if err := batch.flush(); err != nil {
  341. return err
  342. }
  343. if len(subDirs) == 0 {
  344. // If we have no specific subdirectories to traverse, set it to one
  345. // empty prefix so we traverse the entire folder contents once.
  346. subDirs = []string{""}
  347. }
  348. // Do a scan of the database for each prefix, to check for deleted and
  349. // ignored files.
  350. var toIgnore []db.FileInfoTruncated
  351. ignoredParent := ""
  352. for _, sub := range subDirs {
  353. var iterError error
  354. f.fset.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  355. select {
  356. case <-f.ctx.Done():
  357. return false
  358. default:
  359. }
  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. select {
  438. case <-f.ctx.Done():
  439. return f.ctx.Err()
  440. default:
  441. }
  442. if iterError == nil && len(toIgnore) > 0 {
  443. for _, file := range toIgnore {
  444. l.Debugln("marking file as ignored", f)
  445. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  446. batch.append(nf)
  447. changes++
  448. if iterError = batch.flushIfFull(); iterError != nil {
  449. break
  450. }
  451. }
  452. toIgnore = toIgnore[:0]
  453. }
  454. if iterError != nil {
  455. return iterError
  456. }
  457. }
  458. if err := batch.flush(); err != nil {
  459. return err
  460. }
  461. f.ScanCompleted()
  462. f.setState(FolderIdle)
  463. return nil
  464. }
  465. func (f *folder) scanTimerFired() {
  466. err := f.scanSubdirs(nil)
  467. select {
  468. case <-f.initialScanFinished:
  469. default:
  470. status := "Completed"
  471. if err != nil {
  472. status = "Failed"
  473. }
  474. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  475. close(f.initialScanFinished)
  476. }
  477. f.Reschedule()
  478. }
  479. func (f *folder) WatchError() error {
  480. f.watchMut.Lock()
  481. defer f.watchMut.Unlock()
  482. return f.watchErr
  483. }
  484. // stopWatch immediately aborts watching and may be called asynchronously
  485. func (f *folder) stopWatch() {
  486. f.watchMut.Lock()
  487. f.watchCancel()
  488. f.watchMut.Unlock()
  489. f.setWatchError(nil)
  490. }
  491. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  492. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  493. func (f *folder) scheduleWatchRestart() {
  494. select {
  495. case f.restartWatchChan <- struct{}{}:
  496. default:
  497. // We might be busy doing a pull and thus not reading from this
  498. // channel. The channel is 1-buffered, so one notification will be
  499. // queued to ensure we recheck after the pull.
  500. }
  501. }
  502. // restartWatch should only ever be called synchronously. If you want to use
  503. // this asynchronously, you should probably use scheduleWatchRestart instead.
  504. func (f *folder) restartWatch() {
  505. f.stopWatch()
  506. f.startWatch()
  507. f.scanSubdirs(nil)
  508. }
  509. // startWatch should only ever be called synchronously. If you want to use
  510. // this asynchronously, you should probably use scheduleWatchRestart instead.
  511. func (f *folder) startWatch() {
  512. ctx, cancel := context.WithCancel(f.ctx)
  513. f.watchMut.Lock()
  514. f.watchChan = make(chan []string)
  515. f.watchCancel = cancel
  516. f.watchMut.Unlock()
  517. go f.monitorWatch(ctx)
  518. }
  519. // monitorWatch starts the filesystem watching and retries every minute on failure.
  520. // It should not be used except in startWatch.
  521. func (f *folder) monitorWatch(ctx context.Context) {
  522. failTimer := time.NewTimer(0)
  523. aggrCtx, aggrCancel := context.WithCancel(ctx)
  524. var err error
  525. var eventChan <-chan fs.Event
  526. var errChan <-chan error
  527. warnedOutside := false
  528. for {
  529. select {
  530. case <-failTimer.C:
  531. eventChan, errChan, err = f.Filesystem().Watch(".", f.ignores, ctx, f.IgnorePerms)
  532. // We do this at most once per minute which is the
  533. // default rescan time without watcher.
  534. f.scanOnWatchErr()
  535. f.setWatchError(err)
  536. if err != nil {
  537. failTimer.Reset(time.Minute)
  538. continue
  539. }
  540. watchaggregator.Aggregate(eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, f.evLogger, aggrCtx)
  541. l.Debugln("Started filesystem watcher for folder", f.Description())
  542. case err = <-errChan:
  543. f.setWatchError(err)
  544. // This error was previously a panic and should never occur, so generate
  545. // a warning, but don't do it repetitively.
  546. if !warnedOutside {
  547. if _, ok := err.(*fs.ErrWatchEventOutsideRoot); ok {
  548. l.Warnln(err)
  549. warnedOutside = true
  550. }
  551. }
  552. aggrCancel()
  553. errChan = nil
  554. aggrCtx, aggrCancel = context.WithCancel(ctx)
  555. failTimer.Reset(time.Minute)
  556. case <-ctx.Done():
  557. return
  558. }
  559. }
  560. }
  561. // setWatchError sets the current error state of the watch and should be called
  562. // regardless of whether err is nil or not.
  563. func (f *folder) setWatchError(err error) {
  564. f.watchMut.Lock()
  565. prevErr := f.watchErr
  566. f.watchErr = err
  567. f.watchMut.Unlock()
  568. if err != prevErr {
  569. data := map[string]interface{}{
  570. "folder": f.ID,
  571. }
  572. if prevErr != nil {
  573. data["from"] = prevErr.Error()
  574. }
  575. if err != nil {
  576. data["to"] = err.Error()
  577. }
  578. f.evLogger.Log(events.FolderWatchStateChanged, data)
  579. }
  580. if err == nil {
  581. return
  582. }
  583. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  584. if prevErr != err {
  585. l.Infof(msg)
  586. return
  587. }
  588. l.Debugf(msg)
  589. }
  590. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  591. func (f *folder) scanOnWatchErr() {
  592. f.watchMut.Lock()
  593. err := f.watchErr
  594. f.watchMut.Unlock()
  595. if err != nil {
  596. f.Delay(0)
  597. }
  598. }
  599. func (f *folder) setError(err error) {
  600. select {
  601. case <-f.ctx.Done():
  602. return
  603. default:
  604. }
  605. _, _, oldErr := f.getState()
  606. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  607. return
  608. }
  609. if err != nil {
  610. if oldErr == nil {
  611. l.Warnf("Error on folder %s: %v", f.Description(), err)
  612. } else {
  613. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  614. }
  615. } else {
  616. l.Infoln("Cleared error on folder", f.Description())
  617. }
  618. if f.FSWatcherEnabled {
  619. if err != nil {
  620. f.stopWatch()
  621. } else {
  622. f.scheduleWatchRestart()
  623. }
  624. }
  625. f.stateTracker.setError(err)
  626. }
  627. func (f *folder) basePause() time.Duration {
  628. if f.PullerPauseS == 0 {
  629. return defaultPullerPause
  630. }
  631. return time.Duration(f.PullerPauseS) * time.Second
  632. }
  633. func (f *folder) String() string {
  634. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  635. }
  636. func (f *folder) newScanError(path string, err error) {
  637. f.scanErrorsMut.Lock()
  638. f.scanErrors = append(f.scanErrors, FileError{
  639. Err: err.Error(),
  640. Path: path,
  641. })
  642. f.scanErrorsMut.Unlock()
  643. }
  644. func (f *folder) clearScanErrors(subDirs []string) {
  645. f.scanErrorsMut.Lock()
  646. defer f.scanErrorsMut.Unlock()
  647. if len(subDirs) == 0 {
  648. f.scanErrors = nil
  649. return
  650. }
  651. filtered := f.scanErrors[:0]
  652. outer:
  653. for _, fe := range f.scanErrors {
  654. for _, sub := range subDirs {
  655. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  656. continue outer
  657. }
  658. }
  659. filtered = append(filtered, fe)
  660. }
  661. f.scanErrors = filtered
  662. }
  663. func (f *folder) Errors() []FileError {
  664. f.scanErrorsMut.Lock()
  665. defer f.scanErrorsMut.Unlock()
  666. return append([]FileError{}, f.scanErrors...)
  667. }
  668. // ForceRescan marks the file such that it gets rehashed on next scan and then
  669. // immediately executes that scan.
  670. func (f *folder) ForceRescan(file protocol.FileInfo) error {
  671. file.SetMustRescan(f.shortID)
  672. f.fset.Update(protocol.LocalDeviceID, []protocol.FileInfo{file})
  673. return f.Scan([]string{file.Name})
  674. }
  675. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  676. f.updateLocals(fs)
  677. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  678. }
  679. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  680. f.updateLocals(fs)
  681. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  682. }
  683. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  684. f.fset.Update(protocol.LocalDeviceID, fs)
  685. filenames := make([]string, len(fs))
  686. for i, file := range fs {
  687. filenames[i] = file.Name
  688. }
  689. f.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  690. "folder": f.ID,
  691. "items": len(fs),
  692. "filenames": filenames,
  693. "version": f.fset.Sequence(protocol.LocalDeviceID),
  694. })
  695. }
  696. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  697. for _, file := range fs {
  698. if file.IsInvalid() {
  699. continue
  700. }
  701. objType := "file"
  702. action := "modified"
  703. switch {
  704. case file.IsDeleted():
  705. action = "deleted"
  706. // If our local vector is version 1 AND it is the only version
  707. // vector so far seen for this file then it is a new file. Else if
  708. // it is > 1 it's not new, and if it is 1 but another shortId
  709. // version vector exists then it is new for us but created elsewhere
  710. // so the file is still not new but modified by us. Only if it is
  711. // truly new do we change this to 'added', else we leave it as
  712. // 'modified'.
  713. case len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1:
  714. action = "added"
  715. }
  716. if file.IsSymlink() {
  717. objType = "symlink"
  718. } else if file.IsDirectory() {
  719. objType = "dir"
  720. }
  721. // Two different events can be fired here based on what EventType is passed into function
  722. f.evLogger.Log(typeOfEvent, map[string]string{
  723. "folder": f.ID,
  724. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  725. "label": f.Label,
  726. "action": action,
  727. "type": objType,
  728. "path": filepath.FromSlash(file.Name),
  729. "modifiedBy": file.ModifiedBy.String(),
  730. })
  731. }
  732. }
  733. // The exists function is expected to return true for all known paths
  734. // (excluding "" and ".")
  735. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  736. if len(dirs) == 0 {
  737. return nil
  738. }
  739. sort.Strings(dirs)
  740. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  741. return nil
  742. }
  743. prev := "./" // Anything that can't be parent of a clean path
  744. for i := 0; i < len(dirs); {
  745. dir, err := fs.Canonicalize(dirs[i])
  746. if err != nil {
  747. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  748. dirs = append(dirs[:i], dirs[i+1:]...)
  749. continue
  750. }
  751. if dir == prev || fs.IsParent(dir, prev) {
  752. dirs = append(dirs[:i], dirs[i+1:]...)
  753. continue
  754. }
  755. parent := filepath.Dir(dir)
  756. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  757. dir = parent
  758. parent = filepath.Dir(dir)
  759. }
  760. dirs[i] = dir
  761. prev = dir
  762. i++
  763. }
  764. return dirs
  765. }
  766. type cFiler struct {
  767. *db.FileSet
  768. }
  769. // Implements scanner.CurrentFiler
  770. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  771. return cf.Get(protocol.LocalDeviceID, file)
  772. }