folder.go 31 KB

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