folder.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173
  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/util"
  28. "github.com/syncthing/syncthing/lib/versioner"
  29. "github.com/syncthing/syncthing/lib/watchaggregator"
  30. "github.com/thejerf/suture"
  31. )
  32. type folder struct {
  33. suture.Service
  34. stateTracker
  35. config.FolderConfiguration
  36. *stats.FolderStatisticsReference
  37. ioLimiter *byteSemaphore
  38. localFlags uint32
  39. model *model
  40. shortID protocol.ShortID
  41. fset *db.FileSet
  42. ignores *ignore.Matcher
  43. modTimeWindow time.Duration
  44. ctx context.Context
  45. scanInterval time.Duration
  46. scanTimer *time.Timer
  47. scanDelay chan time.Duration
  48. initialScanFinished chan struct{}
  49. versionCleanupInterval time.Duration
  50. versionCleanupTimer *time.Timer
  51. pullScheduled chan struct{}
  52. pullPause time.Duration
  53. pullFailTimer *time.Timer
  54. scanErrors []FileError
  55. pullErrors []FileError
  56. errorsMut sync.Mutex
  57. doInSyncChan chan syncRequest
  58. forcedRescanRequested chan struct{}
  59. forcedRescanPaths map[string]struct{}
  60. forcedRescanPathsMut sync.Mutex
  61. watchCancel context.CancelFunc
  62. watchChan chan []string
  63. restartWatchChan chan struct{}
  64. watchErr error
  65. watchMut sync.Mutex
  66. puller puller
  67. versioner versioner.Versioner
  68. }
  69. type syncRequest struct {
  70. fn func() error
  71. err chan error
  72. }
  73. type puller interface {
  74. pull() bool // true when successful and should not be retried
  75. }
  76. func newFolder(model *model, fset *db.FileSet, ignores *ignore.Matcher, cfg config.FolderConfiguration, evLogger events.Logger, ioLimiter *byteSemaphore, ver versioner.Versioner) folder {
  77. f := folder{
  78. stateTracker: newStateTracker(cfg.ID, evLogger),
  79. FolderConfiguration: cfg,
  80. FolderStatisticsReference: stats.NewFolderStatisticsReference(model.db, cfg.ID),
  81. ioLimiter: ioLimiter,
  82. model: model,
  83. shortID: model.shortID,
  84. fset: fset,
  85. ignores: ignores,
  86. modTimeWindow: cfg.ModTimeWindow(),
  87. scanInterval: time.Duration(cfg.RescanIntervalS) * time.Second,
  88. scanTimer: time.NewTimer(0), // The first scan should be done immediately.
  89. scanDelay: make(chan time.Duration),
  90. initialScanFinished: make(chan struct{}),
  91. versionCleanupInterval: time.Duration(cfg.Versioning.CleanupIntervalS) * time.Second,
  92. versionCleanupTimer: time.NewTimer(time.Duration(cfg.Versioning.CleanupIntervalS) * time.Second),
  93. pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.
  94. errorsMut: sync.NewMutex(),
  95. doInSyncChan: make(chan syncRequest),
  96. forcedRescanRequested: make(chan struct{}, 1),
  97. forcedRescanPaths: make(map[string]struct{}),
  98. forcedRescanPathsMut: sync.NewMutex(),
  99. watchCancel: func() {},
  100. restartWatchChan: make(chan struct{}, 1),
  101. watchMut: sync.NewMutex(),
  102. versioner: ver,
  103. }
  104. f.pullPause = f.pullBasePause()
  105. f.pullFailTimer = time.NewTimer(0)
  106. <-f.pullFailTimer.C
  107. return f
  108. }
  109. func (f *folder) serve(ctx context.Context) {
  110. atomic.AddInt32(&f.model.foldersRunning, 1)
  111. defer atomic.AddInt32(&f.model.foldersRunning, -1)
  112. f.ctx = ctx
  113. l.Debugln(f, "starting")
  114. defer l.Debugln(f, "exiting")
  115. defer func() {
  116. f.scanTimer.Stop()
  117. f.versionCleanupTimer.Stop()
  118. f.setState(FolderIdle)
  119. }()
  120. if f.FSWatcherEnabled && f.getHealthErrorAndLoadIgnores() == nil {
  121. f.startWatch()
  122. }
  123. // If we're configured to not do version cleanup, or we don't have a
  124. // versioner, cancel and drain that timer now.
  125. if f.versionCleanupInterval == 0 || f.versioner == nil {
  126. if !f.versionCleanupTimer.Stop() {
  127. <-f.versionCleanupTimer.C
  128. }
  129. }
  130. initialCompleted := f.initialScanFinished
  131. for {
  132. select {
  133. case <-f.ctx.Done():
  134. return
  135. case <-f.pullScheduled:
  136. f.pull()
  137. case <-f.pullFailTimer.C:
  138. if !f.pull() && f.pullPause < 60*f.pullBasePause() {
  139. // Back off from retrying to pull
  140. f.pullPause *= 2
  141. }
  142. case <-initialCompleted:
  143. // Initial scan has completed, we should do a pull
  144. initialCompleted = nil // never hit this case again
  145. f.pull()
  146. case <-f.forcedRescanRequested:
  147. f.handleForcedRescans()
  148. case <-f.scanTimer.C:
  149. l.Debugln(f, "Scanning due to timer")
  150. f.scanTimerFired()
  151. case req := <-f.doInSyncChan:
  152. l.Debugln(f, "Running something due to request")
  153. req.err <- req.fn()
  154. case next := <-f.scanDelay:
  155. l.Debugln(f, "Delaying scan")
  156. f.scanTimer.Reset(next)
  157. case fsEvents := <-f.watchChan:
  158. l.Debugln(f, "Scan due to watcher")
  159. f.scanSubdirs(fsEvents)
  160. case <-f.restartWatchChan:
  161. l.Debugln(f, "Restart watcher")
  162. f.restartWatch()
  163. case <-f.versionCleanupTimer.C:
  164. l.Debugln(f, "Doing version cleanup")
  165. f.versionCleanupTimerFired()
  166. }
  167. }
  168. }
  169. func (f *folder) BringToFront(string) {}
  170. func (f *folder) Override() {}
  171. func (f *folder) Revert() {}
  172. func (f *folder) DelayScan(next time.Duration) {
  173. f.Delay(next)
  174. }
  175. func (f *folder) ignoresUpdated() {
  176. if f.FSWatcherEnabled {
  177. f.scheduleWatchRestart()
  178. }
  179. }
  180. func (f *folder) SchedulePull() {
  181. select {
  182. case f.pullScheduled <- struct{}{}:
  183. default:
  184. // We might be busy doing a pull and thus not reading from this
  185. // channel. The channel is 1-buffered, so one notification will be
  186. // queued to ensure we recheck after the pull, but beyond that we must
  187. // make sure to not block index receiving.
  188. }
  189. }
  190. func (f *folder) Jobs(_, _ int) ([]string, []string, int) {
  191. return nil, nil, 0
  192. }
  193. func (f *folder) Scan(subdirs []string) error {
  194. <-f.initialScanFinished
  195. return f.doInSync(func() error { return f.scanSubdirs(subdirs) })
  196. }
  197. // doInSync allows to run functions synchronously in folder.serve from exported,
  198. // asynchronously called methods.
  199. func (f *folder) doInSync(fn func() error) error {
  200. req := syncRequest{
  201. fn: fn,
  202. err: make(chan error, 1),
  203. }
  204. select {
  205. case f.doInSyncChan <- req:
  206. return <-req.err
  207. case <-f.ctx.Done():
  208. return f.ctx.Err()
  209. }
  210. }
  211. func (f *folder) Reschedule() {
  212. if f.scanInterval == 0 {
  213. return
  214. }
  215. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  216. sleepNanos := (f.scanInterval.Nanoseconds()*3 + rand.Int63n(2*f.scanInterval.Nanoseconds())) / 4
  217. interval := time.Duration(sleepNanos) * time.Nanosecond
  218. l.Debugln(f, "next rescan in", interval)
  219. f.scanTimer.Reset(interval)
  220. }
  221. func (f *folder) Delay(next time.Duration) {
  222. f.scanDelay <- next
  223. }
  224. func (f *folder) getHealthErrorAndLoadIgnores() error {
  225. if err := f.getHealthErrorWithoutIgnores(); err != nil {
  226. return err
  227. }
  228. if err := f.ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  229. return errors.Wrap(err, "loading ignores")
  230. }
  231. return nil
  232. }
  233. func (f *folder) getHealthErrorWithoutIgnores() error {
  234. // Check for folder errors, with the most serious and specific first and
  235. // generic ones like out of space on the home disk later.
  236. if err := f.CheckPath(); err != nil {
  237. return err
  238. }
  239. dbPath := locations.Get(locations.Database)
  240. if usage, err := fs.NewFilesystem(fs.FilesystemTypeBasic, dbPath).Usage("."); err == nil {
  241. if err = config.CheckFreeSpace(f.model.cfg.Options().MinHomeDiskFree, usage); err != nil {
  242. return errors.Wrapf(err, "insufficient space on disk for database (%v)", dbPath)
  243. }
  244. }
  245. return nil
  246. }
  247. func (f *folder) pull() (success bool) {
  248. f.pullFailTimer.Stop()
  249. select {
  250. case <-f.pullFailTimer.C:
  251. default:
  252. }
  253. select {
  254. case <-f.initialScanFinished:
  255. default:
  256. // Once the initial scan finished, a pull will be scheduled
  257. return true
  258. }
  259. defer func() {
  260. if success {
  261. // We're good, reset the pause interval.
  262. f.pullPause = f.pullBasePause()
  263. }
  264. }()
  265. // If there is nothing to do, don't even enter sync-waiting state.
  266. abort := true
  267. snap := f.fset.Snapshot()
  268. snap.WithNeed(protocol.LocalDeviceID, func(intf protocol.FileIntf) bool {
  269. abort = false
  270. return false
  271. })
  272. snap.Release()
  273. if abort {
  274. // Clears pull failures on items that were needed before, but aren't anymore.
  275. f.errorsMut.Lock()
  276. f.pullErrors = nil
  277. f.errorsMut.Unlock()
  278. return true
  279. }
  280. // Abort early (before acquiring a token) if there's a folder error
  281. err := f.getHealthErrorWithoutIgnores()
  282. f.setError(err)
  283. if err != nil {
  284. l.Debugln("Skipping pull of", f.Description(), "due to folder error:", err)
  285. return false
  286. }
  287. // Send only folder doesn't do any io, it only checks for out-of-sync
  288. // items that differ in metadata and updates those.
  289. if f.Type != config.FolderTypeSendOnly {
  290. f.setState(FolderSyncWaiting)
  291. if err := f.ioLimiter.takeWithContext(f.ctx, 1); err != nil {
  292. f.setError(err)
  293. return true
  294. }
  295. defer f.ioLimiter.give(1)
  296. }
  297. startTime := time.Now()
  298. // Check if the ignore patterns changed.
  299. oldHash := f.ignores.Hash()
  300. defer func() {
  301. if f.ignores.Hash() != oldHash {
  302. f.ignoresUpdated()
  303. }
  304. }()
  305. err = f.getHealthErrorAndLoadIgnores()
  306. f.setError(err)
  307. if err != nil {
  308. l.Debugln("Skipping pull of", f.Description(), "due to folder error:", err)
  309. return false
  310. }
  311. success = f.puller.pull()
  312. if success {
  313. return true
  314. }
  315. // Pulling failed, try again later.
  316. delay := f.pullPause + time.Since(startTime)
  317. l.Infof("Folder %v isn't making sync progress - retrying in %v.", f.Description(), util.NiceDurationString(delay))
  318. f.pullFailTimer.Reset(delay)
  319. return false
  320. }
  321. func (f *folder) scanSubdirs(subDirs []string) error {
  322. oldHash := f.ignores.Hash()
  323. err := f.getHealthErrorAndLoadIgnores()
  324. f.setError(err)
  325. if err != nil {
  326. // If there is a health error we set it as the folder error. We do not
  327. // clear the folder error if there is no health error, as there might be
  328. // an *other* folder error (failed to load ignores, for example). Hence
  329. // we do not use the CheckHealth() convenience function here.
  330. return err
  331. }
  332. // Check on the way out if the ignore patterns changed as part of scanning
  333. // this folder. If they did we should schedule a pull of the folder so that
  334. // we request things we might have suddenly become unignored and so on.
  335. defer func() {
  336. if f.ignores.Hash() != oldHash {
  337. l.Debugln("Folder", f.Description(), "ignore patterns change detected while scanning; triggering puller")
  338. f.ignoresUpdated()
  339. f.SchedulePull()
  340. }
  341. }()
  342. f.setState(FolderScanWaiting)
  343. defer f.setState(FolderIdle)
  344. if err := f.ioLimiter.takeWithContext(f.ctx, 1); err != nil {
  345. return err
  346. }
  347. defer f.ioLimiter.give(1)
  348. for i := range subDirs {
  349. sub := osutil.NativeFilename(subDirs[i])
  350. if sub == "" {
  351. // A blank subdirs means to scan the entire folder. We can trim
  352. // the subDirs list and go on our way.
  353. subDirs = nil
  354. break
  355. }
  356. subDirs[i] = sub
  357. }
  358. snap := f.fset.Snapshot()
  359. // We release explicitly later in this function, however we might exit early
  360. // and it's ok to release twice.
  361. defer snap.Release()
  362. // Clean the list of subitems to ensure that we start at a known
  363. // directory, and don't scan subdirectories of things we've already
  364. // scanned.
  365. subDirs = unifySubs(subDirs, func(file string) bool {
  366. _, ok := snap.Get(protocol.LocalDeviceID, file)
  367. return ok
  368. })
  369. f.setState(FolderScanning)
  370. // If we return early e.g. due to a folder health error, the scan needs
  371. // to be cancelled.
  372. scanCtx, scanCancel := context.WithCancel(f.ctx)
  373. defer scanCancel()
  374. mtimefs := f.fset.MtimeFS()
  375. fchan := scanner.Walk(scanCtx, scanner.Config{
  376. Folder: f.ID,
  377. Subs: subDirs,
  378. Matcher: f.ignores,
  379. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  380. CurrentFiler: cFiler{snap},
  381. Filesystem: mtimefs,
  382. IgnorePerms: f.IgnorePerms,
  383. AutoNormalize: f.AutoNormalize,
  384. Hashers: f.model.numHashers(f.ID),
  385. ShortID: f.shortID,
  386. ProgressTickIntervalS: f.ScanProgressIntervalS,
  387. LocalFlags: f.localFlags,
  388. ModTimeWindow: f.modTimeWindow,
  389. EventLogger: f.evLogger,
  390. })
  391. batch := newFileInfoBatch(func(fs []protocol.FileInfo) error {
  392. if err := f.getHealthErrorWithoutIgnores(); err != nil {
  393. l.Debugf("Stopping scan of folder %s due to: %s", f.Description(), err)
  394. return err
  395. }
  396. f.updateLocalsFromScanning(fs)
  397. return nil
  398. })
  399. var batchAppend func(protocol.FileInfo, *db.Snapshot)
  400. // Resolve items which are identical with the global state.
  401. if f.localFlags&protocol.FlagLocalReceiveOnly == 0 {
  402. batchAppend = func(fi protocol.FileInfo, _ *db.Snapshot) {
  403. batch.append(fi)
  404. }
  405. } else {
  406. batchAppend = func(fi protocol.FileInfo, snap *db.Snapshot) {
  407. switch gf, ok := snap.GetGlobal(fi.Name); {
  408. case !ok:
  409. case gf.IsEquivalentOptional(fi, f.modTimeWindow, false, false, protocol.FlagLocalReceiveOnly):
  410. // What we have locally is equivalent to the global file.
  411. fi.Version = gf.Version
  412. fallthrough
  413. case fi.IsDeleted() && (gf.IsReceiveOnlyChanged() || gf.IsDeleted()):
  414. // Our item is deleted and the global item is our own
  415. // receive only file or deleted too. In the former
  416. // case we can't delete file infos, so we just
  417. // pretend it is a normal deleted file (nobody
  418. // cares about that).
  419. fi.LocalFlags &^= protocol.FlagLocalReceiveOnly
  420. }
  421. batch.append(fi)
  422. }
  423. }
  424. // Schedule a pull after scanning, but only if we actually detected any
  425. // changes.
  426. changes := 0
  427. defer func() {
  428. if changes > 0 {
  429. f.SchedulePull()
  430. }
  431. }()
  432. f.clearScanErrors(subDirs)
  433. alreadyUsed := make(map[string]struct{})
  434. for res := range fchan {
  435. if res.Err != nil {
  436. f.newScanError(res.Path, res.Err)
  437. continue
  438. }
  439. if err := batch.flushIfFull(); err != nil {
  440. // Prevent a race between the scan aborting due to context
  441. // cancellation and releasing the snapshot in defer here.
  442. scanCancel()
  443. for range fchan {
  444. }
  445. return err
  446. }
  447. batchAppend(res.File, snap)
  448. changes++
  449. if f.localFlags&protocol.FlagLocalReceiveOnly == 0 {
  450. if nf, ok := f.findRename(snap, mtimefs, res.File, alreadyUsed); ok {
  451. batchAppend(nf, snap)
  452. changes++
  453. }
  454. }
  455. }
  456. if err := batch.flush(); err != nil {
  457. return err
  458. }
  459. if len(subDirs) == 0 {
  460. // If we have no specific subdirectories to traverse, set it to one
  461. // empty prefix so we traverse the entire folder contents once.
  462. subDirs = []string{""}
  463. }
  464. // Do a scan of the database for each prefix, to check for deleted and
  465. // ignored files.
  466. var toIgnore []db.FileInfoTruncated
  467. ignoredParent := ""
  468. snap.Release()
  469. snap = f.fset.Snapshot()
  470. defer snap.Release()
  471. for _, sub := range subDirs {
  472. var iterError error
  473. snap.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi protocol.FileIntf) bool {
  474. select {
  475. case <-f.ctx.Done():
  476. return false
  477. default:
  478. }
  479. file := fi.(db.FileInfoTruncated)
  480. if err := batch.flushIfFull(); err != nil {
  481. iterError = err
  482. return false
  483. }
  484. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  485. for _, file := range toIgnore {
  486. l.Debugln("marking file as ignored", file)
  487. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  488. batchAppend(nf, snap)
  489. changes++
  490. if err := batch.flushIfFull(); err != nil {
  491. iterError = err
  492. return false
  493. }
  494. }
  495. toIgnore = toIgnore[:0]
  496. ignoredParent = ""
  497. }
  498. switch ignored := f.ignores.Match(file.Name).IsIgnored(); {
  499. case file.IsIgnored() && ignored:
  500. return true
  501. case !file.IsIgnored() && ignored:
  502. // File was not ignored at last pass but has been ignored.
  503. if file.IsDirectory() {
  504. // Delay ignoring as a child might be unignored.
  505. toIgnore = append(toIgnore, file)
  506. if ignoredParent == "" {
  507. // If the parent wasn't ignored already, set
  508. // this path as the "highest" ignored parent
  509. ignoredParent = file.Name
  510. }
  511. return true
  512. }
  513. l.Debugln("marking file as ignored", file)
  514. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  515. batchAppend(nf, snap)
  516. changes++
  517. case file.IsIgnored() && !ignored:
  518. // Successfully scanned items are already un-ignored during
  519. // the scan, so check whether it is deleted.
  520. fallthrough
  521. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  522. // The file is not ignored, deleted or unsupported. Lets check if
  523. // it's still here. Simply stat:ing it wont do as there are
  524. // tons of corner cases (e.g. parent dir->symlink, missing
  525. // permissions)
  526. if !osutil.IsDeleted(mtimefs, file.Name) {
  527. if ignoredParent != "" {
  528. // Don't ignore parents of this not ignored item
  529. toIgnore = toIgnore[:0]
  530. ignoredParent = ""
  531. }
  532. return true
  533. }
  534. nf := file.ConvertToDeletedFileInfo(f.shortID)
  535. nf.LocalFlags = f.localFlags
  536. if file.ShouldConflict() {
  537. // We do not want to override the global version with
  538. // the deleted file. Setting to an empty version makes
  539. // sure the file gets in sync on the following pull.
  540. nf.Version = protocol.Vector{}
  541. }
  542. l.Debugln("marking file as deleted", nf)
  543. batchAppend(nf, snap)
  544. changes++
  545. case file.IsDeleted() && file.IsReceiveOnlyChanged() && f.localFlags&protocol.FlagLocalReceiveOnly != 0 && len(snap.Availability(file.Name)) == 0:
  546. file.Version = protocol.Vector{}
  547. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  548. l.Debugln("marking deleted item that doesn't exist anywhere as not receive-only", file)
  549. batchAppend(file.ConvertDeletedToFileInfo(), snap)
  550. changes++
  551. case file.IsDeleted() && file.IsReceiveOnlyChanged() && f.Type != config.FolderTypeReceiveOnly:
  552. // No need to bump the version for a file that was and is
  553. // deleted and just the folder type/local flags changed.
  554. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  555. l.Debugln("removing receive-only flag on deleted item", file)
  556. batchAppend(file.ConvertDeletedToFileInfo(), snap)
  557. changes++
  558. }
  559. return true
  560. })
  561. select {
  562. case <-f.ctx.Done():
  563. return f.ctx.Err()
  564. default:
  565. }
  566. if iterError == nil && len(toIgnore) > 0 {
  567. for _, file := range toIgnore {
  568. l.Debugln("marking file as ignored", f)
  569. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  570. batchAppend(nf, snap)
  571. changes++
  572. if iterError = batch.flushIfFull(); iterError != nil {
  573. break
  574. }
  575. }
  576. toIgnore = toIgnore[:0]
  577. }
  578. if iterError != nil {
  579. return iterError
  580. }
  581. }
  582. if err := batch.flush(); err != nil {
  583. return err
  584. }
  585. f.ScanCompleted()
  586. return nil
  587. }
  588. func (f *folder) findRename(snap *db.Snapshot, mtimefs fs.Filesystem, file protocol.FileInfo, alreadyUsed map[string]struct{}) (protocol.FileInfo, bool) {
  589. if len(file.Blocks) == 0 || file.Size == 0 {
  590. return protocol.FileInfo{}, false
  591. }
  592. found := false
  593. nf := protocol.FileInfo{}
  594. snap.WithBlocksHash(file.BlocksHash, func(ifi protocol.FileIntf) bool {
  595. fi := ifi.(protocol.FileInfo)
  596. select {
  597. case <-f.ctx.Done():
  598. return false
  599. default:
  600. }
  601. if _, ok := alreadyUsed[fi.Name]; ok {
  602. return true
  603. }
  604. if fi.ShouldConflict() {
  605. return true
  606. }
  607. if f.ignores.Match(fi.Name).IsIgnored() {
  608. return true
  609. }
  610. // Only check the size.
  611. // No point checking block equality, as that uses BlocksHash comparison if that is set (which it will be).
  612. // No point checking BlocksHash comparison as WithBlocksHash already does that.
  613. if file.Size != fi.Size {
  614. return true
  615. }
  616. if !osutil.IsDeleted(mtimefs, fi.Name) {
  617. return true
  618. }
  619. alreadyUsed[fi.Name] = struct{}{}
  620. nf = fi
  621. nf.SetDeleted(f.shortID)
  622. nf.LocalFlags = f.localFlags
  623. found = true
  624. return false
  625. })
  626. return nf, found
  627. }
  628. func (f *folder) scanTimerFired() {
  629. err := f.scanSubdirs(nil)
  630. select {
  631. case <-f.initialScanFinished:
  632. default:
  633. status := "Completed"
  634. if err != nil {
  635. status = "Failed"
  636. }
  637. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  638. close(f.initialScanFinished)
  639. }
  640. f.Reschedule()
  641. }
  642. func (f *folder) versionCleanupTimerFired() {
  643. f.setState(FolderCleanWaiting)
  644. defer f.setState(FolderIdle)
  645. if err := f.ioLimiter.takeWithContext(f.ctx, 1); err != nil {
  646. return
  647. }
  648. defer f.ioLimiter.give(1)
  649. f.setState(FolderCleaning)
  650. if err := f.versioner.Clean(f.ctx); err != nil {
  651. l.Infoln("Failed to clean versions in %s: %v", f.Description(), err)
  652. }
  653. f.versionCleanupTimer.Reset(f.versionCleanupInterval)
  654. }
  655. func (f *folder) WatchError() error {
  656. f.watchMut.Lock()
  657. defer f.watchMut.Unlock()
  658. return f.watchErr
  659. }
  660. // stopWatch immediately aborts watching and may be called asynchronously
  661. func (f *folder) stopWatch() {
  662. f.watchMut.Lock()
  663. f.watchCancel()
  664. f.watchMut.Unlock()
  665. f.setWatchError(nil, 0)
  666. }
  667. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  668. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  669. func (f *folder) scheduleWatchRestart() {
  670. select {
  671. case f.restartWatchChan <- struct{}{}:
  672. default:
  673. // We might be busy doing a pull and thus not reading from this
  674. // channel. The channel is 1-buffered, so one notification will be
  675. // queued to ensure we recheck after the pull.
  676. }
  677. }
  678. // restartWatch should only ever be called synchronously. If you want to use
  679. // this asynchronously, you should probably use scheduleWatchRestart instead.
  680. func (f *folder) restartWatch() {
  681. f.stopWatch()
  682. f.startWatch()
  683. f.scanSubdirs(nil)
  684. }
  685. // startWatch should only ever be called synchronously. If you want to use
  686. // this asynchronously, you should probably use scheduleWatchRestart instead.
  687. func (f *folder) startWatch() {
  688. ctx, cancel := context.WithCancel(f.ctx)
  689. f.watchMut.Lock()
  690. f.watchChan = make(chan []string)
  691. f.watchCancel = cancel
  692. f.watchMut.Unlock()
  693. go f.monitorWatch(ctx)
  694. }
  695. // monitorWatch starts the filesystem watching and retries every minute on failure.
  696. // It should not be used except in startWatch.
  697. func (f *folder) monitorWatch(ctx context.Context) {
  698. failTimer := time.NewTimer(0)
  699. aggrCtx, aggrCancel := context.WithCancel(ctx)
  700. var err error
  701. var eventChan <-chan fs.Event
  702. var errChan <-chan error
  703. warnedOutside := false
  704. var lastWatch time.Time
  705. pause := time.Minute
  706. for {
  707. select {
  708. case <-failTimer.C:
  709. eventChan, errChan, err = f.Filesystem().Watch(".", f.ignores, ctx, f.IgnorePerms)
  710. // We do this once per minute initially increased to
  711. // max one hour in case of repeat failures.
  712. f.scanOnWatchErr()
  713. f.setWatchError(err, pause)
  714. if err != nil {
  715. failTimer.Reset(pause)
  716. if pause < 60*time.Minute {
  717. pause *= 2
  718. }
  719. continue
  720. }
  721. lastWatch = time.Now()
  722. watchaggregator.Aggregate(aggrCtx, eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, f.evLogger)
  723. l.Debugln("Started filesystem watcher for folder", f.Description())
  724. case err = <-errChan:
  725. var next time.Duration
  726. if dur := time.Since(lastWatch); dur > pause {
  727. pause = time.Minute
  728. next = 0
  729. } else {
  730. next = pause - dur
  731. if pause < 60*time.Minute {
  732. pause *= 2
  733. }
  734. }
  735. failTimer.Reset(next)
  736. f.setWatchError(err, next)
  737. // This error was previously a panic and should never occur, so generate
  738. // a warning, but don't do it repetitively.
  739. var errOutside *fs.ErrWatchEventOutsideRoot
  740. if errors.As(err, &errOutside) {
  741. if !warnedOutside {
  742. l.Warnln(err)
  743. warnedOutside = true
  744. }
  745. f.evLogger.Log(events.Failure, "watching for changes encountered an event outside of the filesystem root")
  746. }
  747. aggrCancel()
  748. errChan = nil
  749. aggrCtx, aggrCancel = context.WithCancel(ctx)
  750. case <-ctx.Done():
  751. return
  752. }
  753. }
  754. }
  755. // setWatchError sets the current error state of the watch and should be called
  756. // regardless of whether err is nil or not.
  757. func (f *folder) setWatchError(err error, nextTryIn time.Duration) {
  758. f.watchMut.Lock()
  759. prevErr := f.watchErr
  760. f.watchErr = err
  761. f.watchMut.Unlock()
  762. if err != prevErr {
  763. data := map[string]interface{}{
  764. "folder": f.ID,
  765. }
  766. if prevErr != nil {
  767. data["from"] = prevErr.Error()
  768. }
  769. if err != nil {
  770. data["to"] = err.Error()
  771. }
  772. f.evLogger.Log(events.FolderWatchStateChanged, data)
  773. }
  774. if err == nil {
  775. return
  776. }
  777. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in %v: %v", f.Description(), nextTryIn, err)
  778. if prevErr != err {
  779. l.Infof(msg)
  780. return
  781. }
  782. l.Debugf(msg)
  783. }
  784. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  785. func (f *folder) scanOnWatchErr() {
  786. f.watchMut.Lock()
  787. err := f.watchErr
  788. f.watchMut.Unlock()
  789. if err != nil {
  790. f.Delay(0)
  791. }
  792. }
  793. func (f *folder) setError(err error) {
  794. select {
  795. case <-f.ctx.Done():
  796. return
  797. default:
  798. }
  799. _, _, oldErr := f.getState()
  800. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  801. return
  802. }
  803. if err != nil {
  804. if oldErr == nil {
  805. l.Warnf("Error on folder %s: %v", f.Description(), err)
  806. } else {
  807. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  808. }
  809. } else {
  810. l.Infoln("Cleared error on folder", f.Description())
  811. }
  812. if f.FSWatcherEnabled {
  813. if err != nil {
  814. f.stopWatch()
  815. } else {
  816. f.scheduleWatchRestart()
  817. }
  818. }
  819. f.stateTracker.setError(err)
  820. }
  821. func (f *folder) pullBasePause() time.Duration {
  822. if f.PullerPauseS == 0 {
  823. return defaultPullerPause
  824. }
  825. return time.Duration(f.PullerPauseS) * time.Second
  826. }
  827. func (f *folder) String() string {
  828. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  829. }
  830. func (f *folder) newScanError(path string, err error) {
  831. f.errorsMut.Lock()
  832. l.Infof("Scanner (folder %s, item %q): %v", f.Description(), path, err)
  833. f.scanErrors = append(f.scanErrors, FileError{
  834. Err: err.Error(),
  835. Path: path,
  836. })
  837. f.errorsMut.Unlock()
  838. }
  839. func (f *folder) clearScanErrors(subDirs []string) {
  840. f.errorsMut.Lock()
  841. defer f.errorsMut.Unlock()
  842. if len(subDirs) == 0 {
  843. f.scanErrors = nil
  844. return
  845. }
  846. filtered := f.scanErrors[:0]
  847. outer:
  848. for _, fe := range f.scanErrors {
  849. for _, sub := range subDirs {
  850. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  851. continue outer
  852. }
  853. }
  854. filtered = append(filtered, fe)
  855. }
  856. f.scanErrors = filtered
  857. }
  858. func (f *folder) Errors() []FileError {
  859. f.errorsMut.Lock()
  860. defer f.errorsMut.Unlock()
  861. scanLen := len(f.scanErrors)
  862. errors := make([]FileError, scanLen+len(f.pullErrors))
  863. copy(errors[:scanLen], f.scanErrors)
  864. copy(errors[scanLen:], f.pullErrors)
  865. sort.Sort(fileErrorList(errors))
  866. return errors
  867. }
  868. // ScheduleForceRescan marks the file such that it gets rehashed on next scan, and schedules a scan.
  869. func (f *folder) ScheduleForceRescan(path string) {
  870. f.forcedRescanPathsMut.Lock()
  871. f.forcedRescanPaths[path] = struct{}{}
  872. f.forcedRescanPathsMut.Unlock()
  873. select {
  874. case f.forcedRescanRequested <- struct{}{}:
  875. default:
  876. }
  877. }
  878. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  879. f.updateLocals(fs)
  880. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  881. }
  882. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  883. f.updateLocals(fs)
  884. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  885. }
  886. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  887. f.fset.Update(protocol.LocalDeviceID, fs)
  888. filenames := make([]string, len(fs))
  889. f.forcedRescanPathsMut.Lock()
  890. for i, file := range fs {
  891. filenames[i] = file.Name
  892. // No need to rescan a file that was changed since anyway.
  893. delete(f.forcedRescanPaths, file.Name)
  894. }
  895. f.forcedRescanPathsMut.Unlock()
  896. seq := f.fset.Sequence(protocol.LocalDeviceID)
  897. f.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  898. "folder": f.ID,
  899. "items": len(fs),
  900. "filenames": filenames,
  901. "sequence": seq,
  902. "version": seq, // legacy for sequence
  903. })
  904. }
  905. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  906. for _, file := range fs {
  907. if file.IsInvalid() {
  908. continue
  909. }
  910. objType := "file"
  911. action := "modified"
  912. if file.IsDeleted() {
  913. action = "deleted"
  914. }
  915. if file.IsSymlink() {
  916. objType = "symlink"
  917. } else if file.IsDirectory() {
  918. objType = "dir"
  919. }
  920. // Two different events can be fired here based on what EventType is passed into function
  921. f.evLogger.Log(typeOfEvent, map[string]string{
  922. "folder": f.ID,
  923. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  924. "label": f.Label,
  925. "action": action,
  926. "type": objType,
  927. "path": filepath.FromSlash(file.Name),
  928. "modifiedBy": file.ModifiedBy.String(),
  929. })
  930. }
  931. }
  932. func (f *folder) handleForcedRescans() {
  933. f.forcedRescanPathsMut.Lock()
  934. paths := make([]string, 0, len(f.forcedRescanPaths))
  935. for path := range f.forcedRescanPaths {
  936. paths = append(paths, path)
  937. }
  938. f.forcedRescanPaths = make(map[string]struct{})
  939. f.forcedRescanPathsMut.Unlock()
  940. if len(paths) == 0 {
  941. return
  942. }
  943. batch := newFileInfoBatch(func(fs []protocol.FileInfo) error {
  944. f.fset.Update(protocol.LocalDeviceID, fs)
  945. return nil
  946. })
  947. snap := f.fset.Snapshot()
  948. for _, path := range paths {
  949. _ = batch.flushIfFull()
  950. fi, ok := snap.Get(protocol.LocalDeviceID, path)
  951. if !ok {
  952. continue
  953. }
  954. fi.SetMustRescan(f.shortID)
  955. batch.append(fi)
  956. }
  957. snap.Release()
  958. _ = batch.flush()
  959. _ = f.scanSubdirs(paths)
  960. }
  961. // The exists function is expected to return true for all known paths
  962. // (excluding "" and ".")
  963. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  964. if len(dirs) == 0 {
  965. return nil
  966. }
  967. sort.Strings(dirs)
  968. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  969. return nil
  970. }
  971. prev := "./" // Anything that can't be parent of a clean path
  972. for i := 0; i < len(dirs); {
  973. dir, err := fs.Canonicalize(dirs[i])
  974. if err != nil {
  975. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  976. dirs = append(dirs[:i], dirs[i+1:]...)
  977. continue
  978. }
  979. if dir == prev || fs.IsParent(dir, prev) {
  980. dirs = append(dirs[:i], dirs[i+1:]...)
  981. continue
  982. }
  983. parent := filepath.Dir(dir)
  984. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  985. dir = parent
  986. parent = filepath.Dir(dir)
  987. }
  988. dirs[i] = dir
  989. prev = dir
  990. i++
  991. }
  992. return dirs
  993. }
  994. type cFiler struct {
  995. *db.Snapshot
  996. }
  997. // Implements scanner.CurrentFiler
  998. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  999. return cf.Get(protocol.LocalDeviceID, file)
  1000. }