folder.go 23 KB

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