folder.go 32 KB

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