folder.go 34 KB

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