folder.go 24 KB

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