folder.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307
  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(),
  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 errors.Wrapf(err, "insufficient space on disk for database (%v)", dbPath)
  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. type scanBatch struct {
  439. *db.FileInfoBatch
  440. f *folder
  441. }
  442. func (f *folder) newScanBatch() *scanBatch {
  443. b := &scanBatch{
  444. f: f,
  445. }
  446. b.FileInfoBatch = db.NewFileInfoBatch(func(fs []protocol.FileInfo) error {
  447. if err := b.f.getHealthErrorWithoutIgnores(); err != nil {
  448. l.Debugf("Stopping scan of folder %s due to: %s", b.f.Description(), err)
  449. return err
  450. }
  451. b.f.updateLocalsFromScanning(fs)
  452. return nil
  453. })
  454. return b
  455. }
  456. // Append adds the fileinfo to the batch for updating, and does a few checks.
  457. // It returns false if the checks result in the file not going to be updated or removed.
  458. func (b *scanBatch) Append(fi protocol.FileInfo, snap *db.Snapshot) bool {
  459. // Check for a "virtual" parent directory of encrypted files. We don't track
  460. // it, but check if anything still exists within and delete it otherwise.
  461. if b.f.Type == config.FolderTypeReceiveEncrypted && fi.IsDirectory() && protocol.IsEncryptedParent(fs.PathComponents(fi.Name)) {
  462. if names, err := b.f.mtimefs.DirNames(fi.Name); err == nil && len(names) == 0 {
  463. b.f.mtimefs.Remove(fi.Name)
  464. }
  465. return false
  466. }
  467. // Resolve receive-only items which are identical with the global state or
  468. // the global item is our own receive-only item.
  469. // Except if they are in a receive-encrypted folder and are locally added.
  470. // Those must never be sent in index updates and thus must retain the flag.
  471. switch gf, ok := snap.GetGlobal(fi.Name); {
  472. case !ok:
  473. case gf.IsReceiveOnlyChanged():
  474. if b.f.Type == config.FolderTypeReceiveOnly && fi.Deleted {
  475. l.Debugf("%v scanning: Marking deleted item as not locally changed", b.f, fi)
  476. fi.LocalFlags &^= protocol.FlagLocalReceiveOnly
  477. }
  478. case gf.IsEquivalentOptional(fi, b.f.modTimeWindow, false, false, protocol.FlagLocalReceiveOnly):
  479. l.Debugf("%v scanning: Replacing scanned file info with global as it's equivalent", b.f, fi)
  480. fi = gf
  481. }
  482. b.FileInfoBatch.Append(fi)
  483. return true
  484. }
  485. func (f *folder) scanSubdirsChangedAndNew(subDirs []string, batch *scanBatch) (int, error) {
  486. changes := 0
  487. snap, err := f.dbSnapshot()
  488. if err != nil {
  489. return changes, err
  490. }
  491. defer snap.Release()
  492. // If we return early e.g. due to a folder health error, the scan needs
  493. // to be cancelled.
  494. scanCtx, scanCancel := context.WithCancel(f.ctx)
  495. defer scanCancel()
  496. scanConfig := scanner.Config{
  497. Folder: f.ID,
  498. Subs: subDirs,
  499. Matcher: f.ignores,
  500. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  501. CurrentFiler: cFiler{snap},
  502. Filesystem: f.mtimefs,
  503. IgnorePerms: f.IgnorePerms,
  504. AutoNormalize: f.AutoNormalize,
  505. Hashers: f.model.numHashers(f.ID),
  506. ShortID: f.shortID,
  507. ProgressTickIntervalS: f.ScanProgressIntervalS,
  508. LocalFlags: f.localFlags,
  509. ModTimeWindow: f.modTimeWindow,
  510. EventLogger: f.evLogger,
  511. }
  512. var fchan chan scanner.ScanResult
  513. if f.Type == config.FolderTypeReceiveEncrypted {
  514. fchan = scanner.WalkWithoutHashing(scanCtx, scanConfig)
  515. } else {
  516. fchan = scanner.Walk(scanCtx, scanConfig)
  517. }
  518. alreadyUsedOrExisting := make(map[string]struct{})
  519. for res := range fchan {
  520. if res.Err != nil {
  521. f.newScanError(res.Path, res.Err)
  522. continue
  523. }
  524. if err := batch.FlushIfFull(); err != nil {
  525. // Prevent a race between the scan aborting due to context
  526. // cancellation and releasing the snapshot in defer here.
  527. scanCancel()
  528. for range fchan {
  529. }
  530. return changes, err
  531. }
  532. if batch.Append(res.File, snap) {
  533. changes++
  534. }
  535. switch f.Type {
  536. case config.FolderTypeReceiveOnly, config.FolderTypeReceiveEncrypted:
  537. default:
  538. if nf, ok := f.findRename(snap, res.File, alreadyUsedOrExisting); ok {
  539. if batch.Append(nf, snap) {
  540. changes++
  541. }
  542. }
  543. }
  544. }
  545. return changes, nil
  546. }
  547. func (f *folder) scanSubdirsDeletedAndIgnored(subDirs []string, batch *scanBatch) (int, error) {
  548. var toIgnore []db.FileInfoTruncated
  549. ignoredParent := ""
  550. changes := 0
  551. snap, err := f.dbSnapshot()
  552. if err != nil {
  553. return 0, err
  554. }
  555. defer snap.Release()
  556. for _, sub := range subDirs {
  557. var iterError error
  558. snap.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi protocol.FileIntf) bool {
  559. select {
  560. case <-f.ctx.Done():
  561. return false
  562. default:
  563. }
  564. file := fi.(db.FileInfoTruncated)
  565. if err := batch.FlushIfFull(); err != nil {
  566. iterError = err
  567. return false
  568. }
  569. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  570. for _, file := range toIgnore {
  571. l.Debugln("marking file as ignored", file)
  572. nf := file.ConvertToIgnoredFileInfo()
  573. if batch.Append(nf, snap) {
  574. changes++
  575. }
  576. if err := batch.FlushIfFull(); err != nil {
  577. iterError = err
  578. return false
  579. }
  580. }
  581. toIgnore = toIgnore[:0]
  582. ignoredParent = ""
  583. }
  584. switch ignored := f.ignores.Match(file.Name).IsIgnored(); {
  585. case file.IsIgnored() && ignored:
  586. return true
  587. case !file.IsIgnored() && ignored:
  588. // File was not ignored at last pass but has been ignored.
  589. if file.IsDirectory() {
  590. // Delay ignoring as a child might be unignored.
  591. toIgnore = append(toIgnore, file)
  592. if ignoredParent == "" {
  593. // If the parent wasn't ignored already, set
  594. // this path as the "highest" ignored parent
  595. ignoredParent = file.Name
  596. }
  597. return true
  598. }
  599. l.Debugln("marking file as ignored", file)
  600. nf := file.ConvertToIgnoredFileInfo()
  601. if batch.Append(nf, snap) {
  602. changes++
  603. }
  604. case file.IsIgnored() && !ignored:
  605. // Successfully scanned items are already un-ignored during
  606. // the scan, so check whether it is deleted.
  607. fallthrough
  608. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  609. // The file is not ignored, deleted or unsupported. Lets check if
  610. // it's still here. Simply stat:ing it wont do as there are
  611. // tons of corner cases (e.g. parent dir->symlink, missing
  612. // permissions)
  613. if !osutil.IsDeleted(f.mtimefs, file.Name) {
  614. if ignoredParent != "" {
  615. // Don't ignore parents of this not ignored item
  616. toIgnore = toIgnore[:0]
  617. ignoredParent = ""
  618. }
  619. return true
  620. }
  621. nf := file.ConvertToDeletedFileInfo(f.shortID)
  622. nf.LocalFlags = f.localFlags
  623. if file.ShouldConflict() {
  624. // We do not want to override the global version with
  625. // the deleted file. Setting to an empty version makes
  626. // sure the file gets in sync on the following pull.
  627. nf.Version = protocol.Vector{}
  628. }
  629. l.Debugln("marking file as deleted", nf)
  630. if batch.Append(nf, snap) {
  631. changes++
  632. }
  633. case file.IsDeleted() && file.IsReceiveOnlyChanged():
  634. switch f.Type {
  635. case config.FolderTypeReceiveOnly, config.FolderTypeReceiveEncrypted:
  636. if gf, _ := snap.GetGlobal(file.Name); gf.IsDeleted() {
  637. // Our item is deleted and the global item is deleted too. We just
  638. // pretend it is a normal deleted file (nobody cares about that).
  639. // Except if this is a receive-encrypted folder and it
  640. // is a locally added file. Those must never be sent
  641. // in index updates and thus must retain the flag.
  642. if f.Type == config.FolderTypeReceiveEncrypted && gf.IsReceiveOnlyChanged() {
  643. return true
  644. }
  645. l.Debugf("%v scanning: Marking globally deleted item as not locally changed: %v", f, file.Name)
  646. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  647. if batch.Append(file.ConvertDeletedToFileInfo(), snap) {
  648. changes++
  649. }
  650. }
  651. default:
  652. // No need to bump the version for a file that was and is
  653. // deleted and just the folder type/local flags changed.
  654. file.LocalFlags &^= protocol.FlagLocalReceiveOnly
  655. l.Debugln("removing receive-only flag on deleted item", file)
  656. if batch.Append(file.ConvertDeletedToFileInfo(), snap) {
  657. changes++
  658. }
  659. }
  660. }
  661. return true
  662. })
  663. select {
  664. case <-f.ctx.Done():
  665. return changes, f.ctx.Err()
  666. default:
  667. }
  668. if iterError == nil && len(toIgnore) > 0 {
  669. for _, file := range toIgnore {
  670. l.Debugln("marking file as ignored", f)
  671. nf := file.ConvertToIgnoredFileInfo()
  672. if batch.Append(nf, snap) {
  673. changes++
  674. }
  675. if iterError = batch.FlushIfFull(); iterError != nil {
  676. break
  677. }
  678. }
  679. toIgnore = toIgnore[:0]
  680. }
  681. if iterError != nil {
  682. return changes, iterError
  683. }
  684. }
  685. return changes, nil
  686. }
  687. func (f *folder) findRename(snap *db.Snapshot, file protocol.FileInfo, alreadyUsedOrExisting map[string]struct{}) (protocol.FileInfo, bool) {
  688. if len(file.Blocks) == 0 || file.Size == 0 {
  689. return protocol.FileInfo{}, false
  690. }
  691. found := false
  692. nf := protocol.FileInfo{}
  693. snap.WithBlocksHash(file.BlocksHash, func(ifi protocol.FileIntf) bool {
  694. fi := ifi.(protocol.FileInfo)
  695. select {
  696. case <-f.ctx.Done():
  697. return false
  698. default:
  699. }
  700. if fi.Name == file.Name {
  701. alreadyUsedOrExisting[fi.Name] = struct{}{}
  702. return true
  703. }
  704. if _, ok := alreadyUsedOrExisting[fi.Name]; ok {
  705. return true
  706. }
  707. if fi.ShouldConflict() {
  708. return true
  709. }
  710. if f.ignores.Match(fi.Name).IsIgnored() {
  711. return true
  712. }
  713. // Only check the size.
  714. // No point checking block equality, as that uses BlocksHash comparison if that is set (which it will be).
  715. // No point checking BlocksHash comparison as WithBlocksHash already does that.
  716. if file.Size != fi.Size {
  717. return true
  718. }
  719. alreadyUsedOrExisting[fi.Name] = struct{}{}
  720. if !osutil.IsDeleted(f.mtimefs, fi.Name) {
  721. return true
  722. }
  723. nf = fi
  724. nf.SetDeleted(f.shortID)
  725. nf.LocalFlags = f.localFlags
  726. found = true
  727. return false
  728. })
  729. return nf, found
  730. }
  731. func (f *folder) scanTimerFired() error {
  732. err := f.scanSubdirs(nil)
  733. select {
  734. case <-f.initialScanFinished:
  735. default:
  736. status := "Completed"
  737. if err != nil {
  738. status = "Failed"
  739. }
  740. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  741. close(f.initialScanFinished)
  742. }
  743. f.Reschedule()
  744. return err
  745. }
  746. func (f *folder) versionCleanupTimerFired() {
  747. f.setState(FolderCleanWaiting)
  748. defer f.setState(FolderIdle)
  749. if err := f.ioLimiter.TakeWithContext(f.ctx, 1); err != nil {
  750. return
  751. }
  752. defer f.ioLimiter.Give(1)
  753. f.setState(FolderCleaning)
  754. if err := f.versioner.Clean(f.ctx); err != nil {
  755. l.Infoln("Failed to clean versions in %s: %v", f.Description(), err)
  756. }
  757. f.versionCleanupTimer.Reset(f.versionCleanupInterval)
  758. }
  759. func (f *folder) WatchError() error {
  760. f.watchMut.Lock()
  761. defer f.watchMut.Unlock()
  762. return f.watchErr
  763. }
  764. // stopWatch immediately aborts watching and may be called asynchronously
  765. func (f *folder) stopWatch() {
  766. f.watchMut.Lock()
  767. f.watchCancel()
  768. f.watchMut.Unlock()
  769. f.setWatchError(nil, 0)
  770. }
  771. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  772. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  773. func (f *folder) scheduleWatchRestart() {
  774. select {
  775. case f.restartWatchChan <- struct{}{}:
  776. default:
  777. // We might be busy doing a pull and thus not reading from this
  778. // channel. The channel is 1-buffered, so one notification will be
  779. // queued to ensure we recheck after the pull.
  780. }
  781. }
  782. // restartWatch should only ever be called synchronously. If you want to use
  783. // this asynchronously, you should probably use scheduleWatchRestart instead.
  784. func (f *folder) restartWatch() error {
  785. f.stopWatch()
  786. f.startWatch()
  787. return f.scanSubdirs(nil)
  788. }
  789. // startWatch should only ever be called synchronously. If you want to use
  790. // this asynchronously, you should probably use scheduleWatchRestart instead.
  791. func (f *folder) startWatch() {
  792. ctx, cancel := context.WithCancel(f.ctx)
  793. f.watchMut.Lock()
  794. f.watchChan = make(chan []string)
  795. f.watchCancel = cancel
  796. f.watchMut.Unlock()
  797. go f.monitorWatch(ctx)
  798. }
  799. // monitorWatch starts the filesystem watching and retries every minute on failure.
  800. // It should not be used except in startWatch.
  801. func (f *folder) monitorWatch(ctx context.Context) {
  802. failTimer := time.NewTimer(0)
  803. aggrCtx, aggrCancel := context.WithCancel(ctx)
  804. var err error
  805. var eventChan <-chan fs.Event
  806. var errChan <-chan error
  807. warnedOutside := false
  808. var lastWatch time.Time
  809. pause := time.Minute
  810. for {
  811. select {
  812. case <-failTimer.C:
  813. eventChan, errChan, err = f.Filesystem().Watch(".", f.ignores, ctx, f.IgnorePerms)
  814. // We do this once per minute initially increased to
  815. // max one hour in case of repeat failures.
  816. f.scanOnWatchErr()
  817. f.setWatchError(err, pause)
  818. if err != nil {
  819. failTimer.Reset(pause)
  820. if pause < 60*time.Minute {
  821. pause *= 2
  822. }
  823. continue
  824. }
  825. lastWatch = time.Now()
  826. watchaggregator.Aggregate(aggrCtx, eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, f.evLogger)
  827. l.Debugln("Started filesystem watcher for folder", f.Description())
  828. case err = <-errChan:
  829. var next time.Duration
  830. if dur := time.Since(lastWatch); dur > pause {
  831. pause = time.Minute
  832. next = 0
  833. } else {
  834. next = pause - dur
  835. if pause < 60*time.Minute {
  836. pause *= 2
  837. }
  838. }
  839. failTimer.Reset(next)
  840. f.setWatchError(err, next)
  841. // This error was previously a panic and should never occur, so generate
  842. // a warning, but don't do it repetitively.
  843. var errOutside *fs.ErrWatchEventOutsideRoot
  844. if errors.As(err, &errOutside) {
  845. if !warnedOutside {
  846. l.Warnln(err)
  847. warnedOutside = true
  848. }
  849. f.evLogger.Log(events.Failure, "watching for changes encountered an event outside of the filesystem root")
  850. }
  851. aggrCancel()
  852. errChan = nil
  853. aggrCtx, aggrCancel = context.WithCancel(ctx)
  854. case <-ctx.Done():
  855. return
  856. }
  857. }
  858. }
  859. // setWatchError sets the current error state of the watch and should be called
  860. // regardless of whether err is nil or not.
  861. func (f *folder) setWatchError(err error, nextTryIn time.Duration) {
  862. f.watchMut.Lock()
  863. prevErr := f.watchErr
  864. f.watchErr = err
  865. f.watchMut.Unlock()
  866. if err != prevErr {
  867. data := map[string]interface{}{
  868. "folder": f.ID,
  869. }
  870. if prevErr != nil {
  871. data["from"] = prevErr.Error()
  872. }
  873. if err != nil {
  874. data["to"] = err.Error()
  875. }
  876. f.evLogger.Log(events.FolderWatchStateChanged, data)
  877. }
  878. if err == nil {
  879. return
  880. }
  881. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in %v: %v", f.Description(), nextTryIn, err)
  882. if prevErr != err {
  883. l.Infof(msg)
  884. return
  885. }
  886. l.Debugf(msg)
  887. }
  888. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  889. func (f *folder) scanOnWatchErr() {
  890. f.watchMut.Lock()
  891. err := f.watchErr
  892. f.watchMut.Unlock()
  893. if err != nil {
  894. f.DelayScan(0)
  895. }
  896. }
  897. func (f *folder) setError(err error) {
  898. select {
  899. case <-f.ctx.Done():
  900. return
  901. default:
  902. }
  903. _, _, oldErr := f.getState()
  904. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  905. return
  906. }
  907. if err != nil {
  908. if oldErr == nil {
  909. l.Warnf("Error on folder %s: %v", f.Description(), err)
  910. } else {
  911. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  912. }
  913. } else {
  914. l.Infoln("Cleared error on folder", f.Description())
  915. f.SchedulePull()
  916. }
  917. if f.FSWatcherEnabled {
  918. if err != nil {
  919. f.stopWatch()
  920. } else {
  921. f.scheduleWatchRestart()
  922. }
  923. }
  924. f.stateTracker.setError(err)
  925. }
  926. func (f *folder) pullBasePause() time.Duration {
  927. if f.PullerPauseS == 0 {
  928. return defaultPullerPause
  929. }
  930. return time.Duration(f.PullerPauseS) * time.Second
  931. }
  932. func (f *folder) String() string {
  933. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  934. }
  935. func (f *folder) newScanError(path string, err error) {
  936. f.errorsMut.Lock()
  937. l.Infof("Scanner (folder %s, item %q): %v", f.Description(), path, err)
  938. f.scanErrors = append(f.scanErrors, FileError{
  939. Err: err.Error(),
  940. Path: path,
  941. })
  942. f.errorsMut.Unlock()
  943. }
  944. func (f *folder) clearScanErrors(subDirs []string) {
  945. f.errorsMut.Lock()
  946. defer f.errorsMut.Unlock()
  947. if len(subDirs) == 0 {
  948. f.scanErrors = nil
  949. return
  950. }
  951. filtered := f.scanErrors[:0]
  952. outer:
  953. for _, fe := range f.scanErrors {
  954. for _, sub := range subDirs {
  955. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  956. continue outer
  957. }
  958. }
  959. filtered = append(filtered, fe)
  960. }
  961. f.scanErrors = filtered
  962. }
  963. func (f *folder) Errors() []FileError {
  964. f.errorsMut.Lock()
  965. defer f.errorsMut.Unlock()
  966. scanLen := len(f.scanErrors)
  967. errors := make([]FileError, scanLen+len(f.pullErrors))
  968. copy(errors[:scanLen], f.scanErrors)
  969. copy(errors[scanLen:], f.pullErrors)
  970. sort.Sort(fileErrorList(errors))
  971. return errors
  972. }
  973. // ScheduleForceRescan marks the file such that it gets rehashed on next scan, and schedules a scan.
  974. func (f *folder) ScheduleForceRescan(path string) {
  975. f.forcedRescanPathsMut.Lock()
  976. f.forcedRescanPaths[path] = struct{}{}
  977. f.forcedRescanPathsMut.Unlock()
  978. select {
  979. case f.forcedRescanRequested <- struct{}{}:
  980. default:
  981. }
  982. }
  983. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  984. f.updateLocals(fs)
  985. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  986. }
  987. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  988. f.updateLocals(fs)
  989. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  990. }
  991. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  992. f.fset.Update(protocol.LocalDeviceID, fs)
  993. filenames := make([]string, len(fs))
  994. f.forcedRescanPathsMut.Lock()
  995. for i, file := range fs {
  996. filenames[i] = file.Name
  997. // No need to rescan a file that was changed since anyway.
  998. delete(f.forcedRescanPaths, file.Name)
  999. }
  1000. f.forcedRescanPathsMut.Unlock()
  1001. seq := f.fset.Sequence(protocol.LocalDeviceID)
  1002. f.evLogger.Log(events.LocalIndexUpdated, map[string]interface{}{
  1003. "folder": f.ID,
  1004. "items": len(fs),
  1005. "filenames": filenames,
  1006. "sequence": seq,
  1007. "version": seq, // legacy for sequence
  1008. })
  1009. }
  1010. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  1011. for _, file := range fs {
  1012. if file.IsInvalid() {
  1013. continue
  1014. }
  1015. objType := "file"
  1016. action := "modified"
  1017. if file.IsDeleted() {
  1018. action = "deleted"
  1019. }
  1020. if file.IsSymlink() {
  1021. objType = "symlink"
  1022. } else if file.IsDirectory() {
  1023. objType = "dir"
  1024. }
  1025. // Two different events can be fired here based on what EventType is passed into function
  1026. f.evLogger.Log(typeOfEvent, map[string]string{
  1027. "folder": f.ID,
  1028. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  1029. "label": f.Label,
  1030. "action": action,
  1031. "type": objType,
  1032. "path": filepath.FromSlash(file.Name),
  1033. "modifiedBy": file.ModifiedBy.String(),
  1034. })
  1035. }
  1036. }
  1037. func (f *folder) handleForcedRescans() error {
  1038. f.forcedRescanPathsMut.Lock()
  1039. paths := make([]string, 0, len(f.forcedRescanPaths))
  1040. for path := range f.forcedRescanPaths {
  1041. paths = append(paths, path)
  1042. }
  1043. f.forcedRescanPaths = make(map[string]struct{})
  1044. f.forcedRescanPathsMut.Unlock()
  1045. if len(paths) == 0 {
  1046. return nil
  1047. }
  1048. batch := db.NewFileInfoBatch(func(fs []protocol.FileInfo) error {
  1049. f.fset.Update(protocol.LocalDeviceID, fs)
  1050. return nil
  1051. })
  1052. snap, err := f.dbSnapshot()
  1053. if err != nil {
  1054. return err
  1055. }
  1056. defer snap.Release()
  1057. for _, path := range paths {
  1058. if err := batch.FlushIfFull(); err != nil {
  1059. return err
  1060. }
  1061. fi, ok := snap.Get(protocol.LocalDeviceID, path)
  1062. if !ok {
  1063. continue
  1064. }
  1065. fi.SetMustRescan()
  1066. batch.Append(fi)
  1067. }
  1068. if err = batch.Flush(); err != nil {
  1069. return err
  1070. }
  1071. return f.scanSubdirs(paths)
  1072. }
  1073. // dbSnapshots gets a snapshot from the fileset, and wraps any error
  1074. // in a svcutil.FatalErr.
  1075. func (f *folder) dbSnapshot() (*db.Snapshot, error) {
  1076. snap, err := f.fset.Snapshot()
  1077. if err != nil {
  1078. return nil, svcutil.AsFatalErr(err, svcutil.ExitError)
  1079. }
  1080. return snap, nil
  1081. }
  1082. // The exists function is expected to return true for all known paths
  1083. // (excluding "" and ".")
  1084. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  1085. if len(dirs) == 0 {
  1086. return nil
  1087. }
  1088. sort.Strings(dirs)
  1089. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  1090. return nil
  1091. }
  1092. prev := "./" // Anything that can't be parent of a clean path
  1093. for i := 0; i < len(dirs); {
  1094. dir, err := fs.Canonicalize(dirs[i])
  1095. if err != nil {
  1096. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  1097. dirs = append(dirs[:i], dirs[i+1:]...)
  1098. continue
  1099. }
  1100. if dir == prev || fs.IsParent(dir, prev) {
  1101. dirs = append(dirs[:i], dirs[i+1:]...)
  1102. continue
  1103. }
  1104. parent := filepath.Dir(dir)
  1105. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  1106. dir = parent
  1107. parent = filepath.Dir(dir)
  1108. }
  1109. dirs[i] = dir
  1110. prev = dir
  1111. i++
  1112. }
  1113. return dirs
  1114. }
  1115. type cFiler struct {
  1116. *db.Snapshot
  1117. }
  1118. // Implements scanner.CurrentFiler
  1119. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  1120. return cf.Get(protocol.LocalDeviceID, file)
  1121. }