folder.go 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411
  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. }