folder.go 37 KB

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