folder.go 36 KB

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