folder.go 29 KB

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