folder.go 33 KB

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