folder.go 23 KB

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