folder.go 37 KB

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