folder.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907
  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", f)
  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. Keeping only our local
  438. // counter makes sure we are in conflict with any
  439. // other existing versions, which will be resolved
  440. // by the normal pulling mechanisms.
  441. if file.ShouldConflict() {
  442. nf.Version = nf.Version.DropOthers(f.shortID)
  443. }
  444. batch.append(nf)
  445. changes++
  446. }
  447. return true
  448. })
  449. select {
  450. case <-f.ctx.Done():
  451. return f.ctx.Err()
  452. default:
  453. }
  454. if iterError == nil && len(toIgnore) > 0 {
  455. for _, file := range toIgnore {
  456. l.Debugln("marking file as ignored", f)
  457. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  458. batch.append(nf)
  459. changes++
  460. if iterError = batch.flushIfFull(); iterError != nil {
  461. break
  462. }
  463. }
  464. toIgnore = toIgnore[:0]
  465. }
  466. if iterError != nil {
  467. return iterError
  468. }
  469. }
  470. if err := batch.flush(); err != nil {
  471. return err
  472. }
  473. f.ScanCompleted()
  474. f.setState(FolderIdle)
  475. return nil
  476. }
  477. func (f *folder) scanTimerFired() {
  478. err := f.scanSubdirs(nil)
  479. select {
  480. case <-f.initialScanFinished:
  481. default:
  482. status := "Completed"
  483. if err != nil {
  484. status = "Failed"
  485. }
  486. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  487. close(f.initialScanFinished)
  488. }
  489. f.Reschedule()
  490. }
  491. func (f *folder) WatchError() error {
  492. f.watchMut.Lock()
  493. defer f.watchMut.Unlock()
  494. return f.watchErr
  495. }
  496. // stopWatch immediately aborts watching and may be called asynchronously
  497. func (f *folder) stopWatch() {
  498. f.watchMut.Lock()
  499. f.watchCancel()
  500. f.watchMut.Unlock()
  501. f.setWatchError(nil)
  502. }
  503. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  504. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  505. func (f *folder) scheduleWatchRestart() {
  506. select {
  507. case f.restartWatchChan <- struct{}{}:
  508. default:
  509. // We might be busy doing a pull and thus not reading from this
  510. // channel. The channel is 1-buffered, so one notification will be
  511. // queued to ensure we recheck after the pull.
  512. }
  513. }
  514. // restartWatch should only ever be called synchronously. If you want to use
  515. // this asynchronously, you should probably use scheduleWatchRestart instead.
  516. func (f *folder) restartWatch() {
  517. f.stopWatch()
  518. f.startWatch()
  519. f.scanSubdirs(nil)
  520. }
  521. // startWatch should only ever be called synchronously. If you want to use
  522. // this asynchronously, you should probably use scheduleWatchRestart instead.
  523. func (f *folder) startWatch() {
  524. ctx, cancel := context.WithCancel(f.ctx)
  525. f.watchMut.Lock()
  526. f.watchChan = make(chan []string)
  527. f.watchCancel = cancel
  528. f.watchMut.Unlock()
  529. go f.monitorWatch(ctx)
  530. }
  531. // monitorWatch starts the filesystem watching and retries every minute on failure.
  532. // It should not be used except in startWatch.
  533. func (f *folder) monitorWatch(ctx context.Context) {
  534. failTimer := time.NewTimer(0)
  535. aggrCtx, aggrCancel := context.WithCancel(ctx)
  536. var err error
  537. var eventChan <-chan fs.Event
  538. var errChan <-chan error
  539. warnedOutside := false
  540. for {
  541. select {
  542. case <-failTimer.C:
  543. eventChan, errChan, err = f.Filesystem().Watch(".", f.ignores, ctx, f.IgnorePerms)
  544. // We do this at most once per minute which is the
  545. // default rescan time without watcher.
  546. f.scanOnWatchErr()
  547. f.setWatchError(err)
  548. if err != nil {
  549. failTimer.Reset(time.Minute)
  550. continue
  551. }
  552. watchaggregator.Aggregate(eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, f.evLogger, aggrCtx)
  553. l.Debugln("Started filesystem watcher for folder", f.Description())
  554. case err = <-errChan:
  555. f.setWatchError(err)
  556. // This error was previously a panic and should never occur, so generate
  557. // a warning, but don't do it repetitively.
  558. if !warnedOutside {
  559. if _, ok := err.(*fs.ErrWatchEventOutsideRoot); ok {
  560. l.Warnln(err)
  561. warnedOutside = true
  562. }
  563. }
  564. aggrCancel()
  565. errChan = nil
  566. aggrCtx, aggrCancel = context.WithCancel(ctx)
  567. failTimer.Reset(time.Minute)
  568. case <-ctx.Done():
  569. return
  570. }
  571. }
  572. }
  573. // setWatchError sets the current error state of the watch and should be called
  574. // regardless of whether err is nil or not.
  575. func (f *folder) setWatchError(err error) {
  576. f.watchMut.Lock()
  577. prevErr := f.watchErr
  578. f.watchErr = err
  579. f.watchMut.Unlock()
  580. if err != prevErr {
  581. data := map[string]interface{}{
  582. "folder": f.ID,
  583. }
  584. if prevErr != nil {
  585. data["from"] = prevErr.Error()
  586. }
  587. if err != nil {
  588. data["to"] = err.Error()
  589. }
  590. f.evLogger.Log(events.FolderWatchStateChanged, data)
  591. }
  592. if err == nil {
  593. return
  594. }
  595. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  596. if prevErr != err {
  597. l.Infof(msg)
  598. return
  599. }
  600. l.Debugf(msg)
  601. }
  602. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  603. func (f *folder) scanOnWatchErr() {
  604. f.watchMut.Lock()
  605. err := f.watchErr
  606. f.watchMut.Unlock()
  607. if err != nil {
  608. f.Delay(0)
  609. }
  610. }
  611. func (f *folder) setError(err error) {
  612. select {
  613. case <-f.ctx.Done():
  614. return
  615. default:
  616. }
  617. _, _, oldErr := f.getState()
  618. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  619. return
  620. }
  621. if err != nil {
  622. if oldErr == nil {
  623. l.Warnf("Error on folder %s: %v", f.Description(), err)
  624. } else {
  625. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  626. }
  627. } else {
  628. l.Infoln("Cleared error on folder", f.Description())
  629. }
  630. if f.FSWatcherEnabled {
  631. if err != nil {
  632. f.stopWatch()
  633. } else {
  634. f.scheduleWatchRestart()
  635. }
  636. }
  637. f.stateTracker.setError(err)
  638. }
  639. func (f *folder) basePause() time.Duration {
  640. if f.PullerPauseS == 0 {
  641. return defaultPullerPause
  642. }
  643. return time.Duration(f.PullerPauseS) * time.Second
  644. }
  645. func (f *folder) String() string {
  646. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  647. }
  648. func (f *folder) newScanError(path string, err error) {
  649. f.scanErrorsMut.Lock()
  650. f.scanErrors = append(f.scanErrors, FileError{
  651. Err: err.Error(),
  652. Path: path,
  653. })
  654. f.scanErrorsMut.Unlock()
  655. }
  656. func (f *folder) clearScanErrors(subDirs []string) {
  657. f.scanErrorsMut.Lock()
  658. defer f.scanErrorsMut.Unlock()
  659. if len(subDirs) == 0 {
  660. f.scanErrors = nil
  661. return
  662. }
  663. filtered := f.scanErrors[:0]
  664. outer:
  665. for _, fe := range f.scanErrors {
  666. for _, sub := range subDirs {
  667. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  668. continue outer
  669. }
  670. }
  671. filtered = append(filtered, fe)
  672. }
  673. f.scanErrors = filtered
  674. }
  675. func (f *folder) Errors() []FileError {
  676. f.scanErrorsMut.Lock()
  677. defer f.scanErrorsMut.Unlock()
  678. return append([]FileError{}, f.scanErrors...)
  679. }
  680. // ForceRescan marks the file such that it gets rehashed on next scan and then
  681. // immediately executes that scan.
  682. func (f *folder) ForceRescan(file protocol.FileInfo) error {
  683. file.SetMustRescan(f.shortID)
  684. f.fset.Update(protocol.LocalDeviceID, []protocol.FileInfo{file})
  685. return f.Scan([]string{file.Name})
  686. }
  687. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  688. f.updateLocals(fs)
  689. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  690. }
  691. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  692. f.updateLocals(fs)
  693. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  694. }
  695. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  696. f.fset.Update(protocol.LocalDeviceID, fs)
  697. filenames := make([]string, len(fs))
  698. for i, file := range fs {
  699. filenames[i] = file.Name
  700. }
  701. f.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  702. "folder": f.ID,
  703. "items": len(fs),
  704. "filenames": filenames,
  705. "version": f.fset.Sequence(protocol.LocalDeviceID),
  706. })
  707. }
  708. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  709. for _, file := range fs {
  710. if file.IsInvalid() {
  711. continue
  712. }
  713. objType := "file"
  714. action := "modified"
  715. switch {
  716. case file.IsDeleted():
  717. action = "deleted"
  718. // If our local vector is version 1 AND it is the only version
  719. // vector so far seen for this file then it is a new file. Else if
  720. // it is > 1 it's not new, and if it is 1 but another shortId
  721. // version vector exists then it is new for us but created elsewhere
  722. // so the file is still not new but modified by us. Only if it is
  723. // truly new do we change this to 'added', else we leave it as
  724. // 'modified'.
  725. case len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1:
  726. action = "added"
  727. }
  728. if file.IsSymlink() {
  729. objType = "symlink"
  730. } else if file.IsDirectory() {
  731. objType = "dir"
  732. }
  733. // Two different events can be fired here based on what EventType is passed into function
  734. f.evLogger.Log(typeOfEvent, map[string]string{
  735. "folder": f.ID,
  736. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  737. "label": f.Label,
  738. "action": action,
  739. "type": objType,
  740. "path": filepath.FromSlash(file.Name),
  741. "modifiedBy": file.ModifiedBy.String(),
  742. })
  743. }
  744. }
  745. // The exists function is expected to return true for all known paths
  746. // (excluding "" and ".")
  747. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  748. if len(dirs) == 0 {
  749. return nil
  750. }
  751. sort.Strings(dirs)
  752. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  753. return nil
  754. }
  755. prev := "./" // Anything that can't be parent of a clean path
  756. for i := 0; i < len(dirs); {
  757. dir, err := fs.Canonicalize(dirs[i])
  758. if err != nil {
  759. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  760. dirs = append(dirs[:i], dirs[i+1:]...)
  761. continue
  762. }
  763. if dir == prev || fs.IsParent(dir, prev) {
  764. dirs = append(dirs[:i], dirs[i+1:]...)
  765. continue
  766. }
  767. parent := filepath.Dir(dir)
  768. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  769. dir = parent
  770. parent = filepath.Dir(dir)
  771. }
  772. dirs[i] = dir
  773. prev = dir
  774. i++
  775. }
  776. return dirs
  777. }
  778. type cFiler struct {
  779. *db.FileSet
  780. }
  781. // Implements scanner.CurrentFiler
  782. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  783. return cf.Get(protocol.LocalDeviceID, file)
  784. }