folder.go 37 KB

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