folder.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893
  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. "fmt"
  10. "math/rand"
  11. "path/filepath"
  12. "sort"
  13. "sync/atomic"
  14. "time"
  15. "github.com/syncthing/syncthing/lib/config"
  16. "github.com/syncthing/syncthing/lib/db"
  17. "github.com/syncthing/syncthing/lib/events"
  18. "github.com/syncthing/syncthing/lib/fs"
  19. "github.com/syncthing/syncthing/lib/ignore"
  20. "github.com/syncthing/syncthing/lib/locations"
  21. "github.com/syncthing/syncthing/lib/osutil"
  22. "github.com/syncthing/syncthing/lib/protocol"
  23. "github.com/syncthing/syncthing/lib/scanner"
  24. "github.com/syncthing/syncthing/lib/stats"
  25. "github.com/syncthing/syncthing/lib/sync"
  26. "github.com/syncthing/syncthing/lib/watchaggregator"
  27. "github.com/thejerf/suture"
  28. )
  29. // scanLimiter limits the number of concurrent scans. A limit of zero means no limit.
  30. var scanLimiter = newByteSemaphore(0)
  31. type folder struct {
  32. suture.Service
  33. stateTracker
  34. config.FolderConfiguration
  35. *stats.FolderStatisticsReference
  36. localFlags uint32
  37. model *model
  38. shortID protocol.ShortID
  39. fset *db.FileSet
  40. ignores *ignore.Matcher
  41. ctx context.Context
  42. cancel context.CancelFunc
  43. scanInterval time.Duration
  44. scanTimer *time.Timer
  45. scanNow chan rescanRequest
  46. scanDelay chan time.Duration
  47. initialScanFinished chan struct{}
  48. scanErrors []FileError
  49. scanErrorsMut sync.Mutex
  50. pullScheduled chan struct{}
  51. watchCancel context.CancelFunc
  52. watchChan chan []string
  53. restartWatchChan chan struct{}
  54. watchErr error
  55. watchMut sync.Mutex
  56. puller puller
  57. }
  58. type rescanRequest struct {
  59. subdirs []string
  60. err chan error
  61. }
  62. type puller interface {
  63. pull() bool // true when successfull and should not be retried
  64. }
  65. func newFolder(model *model, fset *db.FileSet, ignores *ignore.Matcher, cfg config.FolderConfiguration) folder {
  66. ctx, cancel := context.WithCancel(context.Background())
  67. return folder{
  68. stateTracker: newStateTracker(cfg.ID),
  69. FolderConfiguration: cfg,
  70. FolderStatisticsReference: stats.NewFolderStatisticsReference(model.db, cfg.ID),
  71. model: model,
  72. shortID: model.shortID,
  73. fset: fset,
  74. ignores: ignores,
  75. ctx: ctx,
  76. cancel: cancel,
  77. scanInterval: time.Duration(cfg.RescanIntervalS) * time.Second,
  78. scanTimer: time.NewTimer(time.Millisecond), // The first scan should be done immediately.
  79. scanNow: make(chan rescanRequest),
  80. scanDelay: make(chan time.Duration),
  81. initialScanFinished: make(chan struct{}),
  82. scanErrorsMut: sync.NewMutex(),
  83. pullScheduled: make(chan struct{}, 1), // This needs to be 1-buffered so that we queue a pull if we're busy when it comes.
  84. watchCancel: func() {},
  85. restartWatchChan: make(chan struct{}, 1),
  86. watchMut: sync.NewMutex(),
  87. }
  88. }
  89. func (f *folder) serve(_ chan struct{}) {
  90. atomic.AddInt32(&f.model.foldersRunning, 1)
  91. defer atomic.AddInt32(&f.model.foldersRunning, -1)
  92. l.Debugln(f, "starting")
  93. defer l.Debugln(f, "exiting")
  94. defer func() {
  95. f.scanTimer.Stop()
  96. f.setState(FolderIdle)
  97. }()
  98. pause := f.basePause()
  99. pullFailTimer := time.NewTimer(0)
  100. <-pullFailTimer.C
  101. if f.FSWatcherEnabled && f.CheckHealth() == nil {
  102. f.startWatch()
  103. }
  104. initialCompleted := f.initialScanFinished
  105. pull := func() {
  106. startTime := time.Now()
  107. if f.puller.pull() {
  108. // We're good. Don't schedule another pull and reset
  109. // the pause interval.
  110. pause = f.basePause()
  111. return
  112. }
  113. // Pulling failed, try again later.
  114. delay := pause + time.Since(startTime)
  115. l.Infof("Folder %v isn't making sync progress - retrying in %v.", f.Description(), delay)
  116. pullFailTimer.Reset(delay)
  117. if pause < 60*f.basePause() {
  118. pause *= 2
  119. }
  120. }
  121. for {
  122. select {
  123. case <-f.ctx.Done():
  124. return
  125. case <-f.pullScheduled:
  126. pullFailTimer.Stop()
  127. select {
  128. case <-pullFailTimer.C:
  129. default:
  130. }
  131. pull()
  132. case <-pullFailTimer.C:
  133. pull()
  134. case <-initialCompleted:
  135. // Initial scan has completed, we should do a pull
  136. initialCompleted = nil // never hit this case again
  137. if !f.puller.pull() {
  138. // Pulling failed, try again later.
  139. pullFailTimer.Reset(pause)
  140. }
  141. case <-f.scanTimer.C:
  142. l.Debugln(f, "Scanning subdirectories")
  143. f.scanTimerFired()
  144. case req := <-f.scanNow:
  145. req.err <- f.scanSubdirs(req.subdirs)
  146. case next := <-f.scanDelay:
  147. f.scanTimer.Reset(next)
  148. case fsEvents := <-f.watchChan:
  149. l.Debugln(f, "filesystem notification rescan")
  150. f.scanSubdirs(fsEvents)
  151. case <-f.restartWatchChan:
  152. f.restartWatch()
  153. }
  154. }
  155. }
  156. func (f *folder) BringToFront(string) {}
  157. func (f *folder) Override() {}
  158. func (f *folder) Revert() {}
  159. func (f *folder) DelayScan(next time.Duration) {
  160. f.Delay(next)
  161. }
  162. func (f *folder) ignoresUpdated() {
  163. if f.FSWatcherEnabled {
  164. f.scheduleWatchRestart()
  165. }
  166. }
  167. func (f *folder) SchedulePull() {
  168. select {
  169. case f.pullScheduled <- struct{}{}:
  170. default:
  171. // We might be busy doing a pull and thus not reading from this
  172. // channel. The channel is 1-buffered, so one notification will be
  173. // queued to ensure we recheck after the pull, but beyond that we must
  174. // make sure to not block index receiving.
  175. }
  176. }
  177. func (f *folder) Jobs(_, _ int) ([]string, []string, int) {
  178. return nil, nil, 0
  179. }
  180. func (f *folder) Scan(subdirs []string) error {
  181. <-f.initialScanFinished
  182. req := rescanRequest{
  183. subdirs: subdirs,
  184. err: make(chan error),
  185. }
  186. select {
  187. case f.scanNow <- req:
  188. return <-req.err
  189. case <-f.ctx.Done():
  190. return f.ctx.Err()
  191. }
  192. }
  193. func (f *folder) Reschedule() {
  194. if f.scanInterval == 0 {
  195. return
  196. }
  197. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  198. sleepNanos := (f.scanInterval.Nanoseconds()*3 + rand.Int63n(2*f.scanInterval.Nanoseconds())) / 4
  199. interval := time.Duration(sleepNanos) * time.Nanosecond
  200. l.Debugln(f, "next rescan in", interval)
  201. f.scanTimer.Reset(interval)
  202. }
  203. func (f *folder) Delay(next time.Duration) {
  204. f.scanDelay <- next
  205. }
  206. func (f *folder) Stop() {
  207. f.cancel()
  208. f.Service.Stop()
  209. }
  210. // CheckHealth checks the folder for common errors, updates the folder state
  211. // and returns the current folder error, or nil if the folder is healthy.
  212. func (f *folder) CheckHealth() error {
  213. err := f.getHealthError()
  214. f.setError(err)
  215. return err
  216. }
  217. func (f *folder) getHealthError() error {
  218. // Check for folder errors, with the most serious and specific first and
  219. // generic ones like out of space on the home disk later.
  220. if err := f.CheckPath(); err != nil {
  221. return err
  222. }
  223. dbPath := locations.Get(locations.Database)
  224. if usage, err := fs.NewFilesystem(fs.FilesystemTypeBasic, dbPath).Usage("."); err == nil {
  225. if err = config.CheckFreeSpace(f.model.cfg.Options().MinHomeDiskFree, usage); err != nil {
  226. return fmt.Errorf("insufficient space on disk for database (%v): %v", dbPath, err)
  227. }
  228. }
  229. return nil
  230. }
  231. func (f *folder) scanSubdirs(subDirs []string) error {
  232. if err := f.CheckHealth(); err != nil {
  233. return err
  234. }
  235. mtimefs := f.fset.MtimeFS()
  236. f.setState(FolderScanWaiting)
  237. scanLimiter.take(1)
  238. defer scanLimiter.give(1)
  239. for i := range subDirs {
  240. sub := osutil.NativeFilename(subDirs[i])
  241. if sub == "" {
  242. // A blank subdirs means to scan the entire folder. We can trim
  243. // the subDirs list and go on our way.
  244. subDirs = nil
  245. break
  246. }
  247. subDirs[i] = sub
  248. }
  249. // Check if the ignore patterns changed as part of scanning this folder.
  250. // If they did we should schedule a pull of the folder so that we
  251. // request things we might have suddenly become unignored and so on.
  252. oldHash := f.ignores.Hash()
  253. defer func() {
  254. if f.ignores.Hash() != oldHash {
  255. l.Debugln("Folder", f.Description(), "ignore patterns change detected while scanning; triggering puller")
  256. f.ignoresUpdated()
  257. f.SchedulePull()
  258. }
  259. }()
  260. if err := f.ignores.Load(".stignore"); err != nil && !fs.IsNotExist(err) {
  261. err = fmt.Errorf("loading ignores: %v", err)
  262. f.setError(err)
  263. return err
  264. }
  265. // Clean the list of subitems to ensure that we start at a known
  266. // directory, and don't scan subdirectories of things we've already
  267. // scanned.
  268. subDirs = unifySubs(subDirs, func(file string) bool {
  269. _, ok := f.fset.Get(protocol.LocalDeviceID, file)
  270. return ok
  271. })
  272. f.setState(FolderScanning)
  273. fchan := scanner.Walk(f.ctx, scanner.Config{
  274. Folder: f.ID,
  275. Subs: subDirs,
  276. Matcher: f.ignores,
  277. TempLifetime: time.Duration(f.model.cfg.Options().KeepTemporariesH) * time.Hour,
  278. CurrentFiler: cFiler{f.fset},
  279. Filesystem: mtimefs,
  280. IgnorePerms: f.IgnorePerms,
  281. AutoNormalize: f.AutoNormalize,
  282. Hashers: f.model.numHashers(f.ID),
  283. ShortID: f.shortID,
  284. ProgressTickIntervalS: f.ScanProgressIntervalS,
  285. LocalFlags: f.localFlags,
  286. })
  287. batchFn := func(fs []protocol.FileInfo) error {
  288. if err := f.CheckHealth(); err != nil {
  289. l.Debugf("Stopping scan of folder %s due to: %s", f.Description(), err)
  290. return err
  291. }
  292. f.updateLocalsFromScanning(fs)
  293. return nil
  294. }
  295. // Resolve items which are identical with the global state.
  296. if f.localFlags&protocol.FlagLocalReceiveOnly != 0 {
  297. oldBatchFn := batchFn // can't reference batchFn directly (recursion)
  298. batchFn = func(fs []protocol.FileInfo) error {
  299. for i := range fs {
  300. switch gf, ok := f.fset.GetGlobal(fs[i].Name); {
  301. case !ok:
  302. continue
  303. case gf.IsEquivalentOptional(fs[i], false, false, protocol.FlagLocalReceiveOnly):
  304. // What we have locally is equivalent to the global file.
  305. fs[i].Version = fs[i].Version.Merge(gf.Version)
  306. fallthrough
  307. case fs[i].IsDeleted() && gf.IsReceiveOnlyChanged():
  308. // Our item is deleted and the global item is our own
  309. // receive only file. We can't delete file infos, so
  310. // we just pretend it is a normal deleted file (nobody
  311. // cares about that).
  312. fs[i].LocalFlags &^= protocol.FlagLocalReceiveOnly
  313. }
  314. }
  315. return oldBatchFn(fs)
  316. }
  317. }
  318. batch := newFileInfoBatch(batchFn)
  319. // Schedule a pull after scanning, but only if we actually detected any
  320. // changes.
  321. changes := 0
  322. defer func() {
  323. if changes > 0 {
  324. f.SchedulePull()
  325. }
  326. }()
  327. f.clearScanErrors(subDirs)
  328. for res := range fchan {
  329. if res.Err != nil {
  330. f.newScanError(res.Path, res.Err)
  331. continue
  332. }
  333. if err := batch.flushIfFull(); err != nil {
  334. return err
  335. }
  336. batch.append(res.File)
  337. changes++
  338. }
  339. if err := batch.flush(); err != nil {
  340. return err
  341. }
  342. if len(subDirs) == 0 {
  343. // If we have no specific subdirectories to traverse, set it to one
  344. // empty prefix so we traverse the entire folder contents once.
  345. subDirs = []string{""}
  346. }
  347. // Do a scan of the database for each prefix, to check for deleted and
  348. // ignored files.
  349. var toIgnore []db.FileInfoTruncated
  350. ignoredParent := ""
  351. for _, sub := range subDirs {
  352. var iterError error
  353. f.fset.WithPrefixedHaveTruncated(protocol.LocalDeviceID, sub, func(fi db.FileIntf) bool {
  354. select {
  355. case <-f.ctx.Done():
  356. return false
  357. default:
  358. }
  359. file := fi.(db.FileInfoTruncated)
  360. if err := batch.flushIfFull(); err != nil {
  361. iterError = err
  362. return false
  363. }
  364. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  365. for _, file := range toIgnore {
  366. l.Debugln("marking file as ignored", file)
  367. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  368. batch.append(nf)
  369. changes++
  370. if err := batch.flushIfFull(); err != nil {
  371. iterError = err
  372. return false
  373. }
  374. }
  375. toIgnore = toIgnore[:0]
  376. ignoredParent = ""
  377. }
  378. switch ignored := f.ignores.Match(file.Name).IsIgnored(); {
  379. case !file.IsIgnored() && ignored:
  380. // File was not ignored at last pass but has been ignored.
  381. if file.IsDirectory() {
  382. // Delay ignoring as a child might be unignored.
  383. toIgnore = append(toIgnore, file)
  384. if ignoredParent == "" {
  385. // If the parent wasn't ignored already, set
  386. // this path as the "highest" ignored parent
  387. ignoredParent = file.Name
  388. }
  389. return true
  390. }
  391. l.Debugln("marking file as ignored", f)
  392. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  393. batch.append(nf)
  394. changes++
  395. case file.IsIgnored() && !ignored:
  396. // Successfully scanned items are already un-ignored during
  397. // the scan, so check whether it is deleted.
  398. fallthrough
  399. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  400. // The file is not ignored, deleted or unsupported. Lets check if
  401. // it's still here. Simply stat:ing it wont do as there are
  402. // tons of corner cases (e.g. parent dir->symlink, missing
  403. // permissions)
  404. if !osutil.IsDeleted(mtimefs, file.Name) {
  405. if ignoredParent != "" {
  406. // Don't ignore parents of this not ignored item
  407. toIgnore = toIgnore[:0]
  408. ignoredParent = ""
  409. }
  410. return true
  411. }
  412. nf := protocol.FileInfo{
  413. Name: file.Name,
  414. Type: file.Type,
  415. Size: 0,
  416. ModifiedS: file.ModifiedS,
  417. ModifiedNs: file.ModifiedNs,
  418. ModifiedBy: f.shortID,
  419. Deleted: true,
  420. Version: file.Version.Update(f.shortID),
  421. LocalFlags: f.localFlags,
  422. }
  423. // We do not want to override the global version
  424. // with the deleted file. Keeping only our local
  425. // counter makes sure we are in conflict with any
  426. // other existing versions, which will be resolved
  427. // by the normal pulling mechanisms.
  428. if file.ShouldConflict() {
  429. nf.Version = nf.Version.DropOthers(f.shortID)
  430. }
  431. batch.append(nf)
  432. changes++
  433. }
  434. return true
  435. })
  436. select {
  437. case <-f.ctx.Done():
  438. return f.ctx.Err()
  439. default:
  440. }
  441. if iterError == nil && len(toIgnore) > 0 {
  442. for _, file := range toIgnore {
  443. l.Debugln("marking file as ignored", f)
  444. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  445. batch.append(nf)
  446. changes++
  447. if iterError = batch.flushIfFull(); iterError != nil {
  448. break
  449. }
  450. }
  451. toIgnore = toIgnore[:0]
  452. }
  453. if iterError != nil {
  454. return iterError
  455. }
  456. }
  457. if err := batch.flush(); err != nil {
  458. return err
  459. }
  460. f.ScanCompleted()
  461. f.setState(FolderIdle)
  462. return nil
  463. }
  464. func (f *folder) scanTimerFired() {
  465. err := f.scanSubdirs(nil)
  466. select {
  467. case <-f.initialScanFinished:
  468. default:
  469. status := "Completed"
  470. if err != nil {
  471. status = "Failed"
  472. }
  473. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  474. close(f.initialScanFinished)
  475. }
  476. f.Reschedule()
  477. }
  478. func (f *folder) WatchError() error {
  479. f.watchMut.Lock()
  480. defer f.watchMut.Unlock()
  481. return f.watchErr
  482. }
  483. // stopWatch immediately aborts watching and may be called asynchronously
  484. func (f *folder) stopWatch() {
  485. f.watchMut.Lock()
  486. f.watchCancel()
  487. f.watchMut.Unlock()
  488. f.setWatchError(nil)
  489. }
  490. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  491. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  492. func (f *folder) scheduleWatchRestart() {
  493. select {
  494. case f.restartWatchChan <- struct{}{}:
  495. default:
  496. // We might be busy doing a pull and thus not reading from this
  497. // channel. The channel is 1-buffered, so one notification will be
  498. // queued to ensure we recheck after the pull.
  499. }
  500. }
  501. // restartWatch should only ever be called synchronously. If you want to use
  502. // this asynchronously, you should probably use scheduleWatchRestart instead.
  503. func (f *folder) restartWatch() {
  504. f.stopWatch()
  505. f.startWatch()
  506. f.scanSubdirs(nil)
  507. }
  508. // startWatch should only ever be called synchronously. If you want to use
  509. // this asynchronously, you should probably use scheduleWatchRestart instead.
  510. func (f *folder) startWatch() {
  511. ctx, cancel := context.WithCancel(f.ctx)
  512. f.watchMut.Lock()
  513. f.watchChan = make(chan []string)
  514. f.watchCancel = cancel
  515. f.watchMut.Unlock()
  516. go f.monitorWatch(ctx)
  517. }
  518. // monitorWatch starts the filesystem watching and retries every minute on failure.
  519. // It should not be used except in startWatch.
  520. func (f *folder) monitorWatch(ctx context.Context) {
  521. failTimer := time.NewTimer(0)
  522. aggrCtx, aggrCancel := context.WithCancel(ctx)
  523. var err error
  524. var eventChan <-chan fs.Event
  525. var errChan <-chan error
  526. warnedOutside := false
  527. for {
  528. select {
  529. case <-failTimer.C:
  530. eventChan, errChan, err = f.Filesystem().Watch(".", f.ignores, ctx, f.IgnorePerms)
  531. // We do this at most once per minute which is the
  532. // default rescan time without watcher.
  533. f.scanOnWatchErr()
  534. f.setWatchError(err)
  535. if err != nil {
  536. failTimer.Reset(time.Minute)
  537. continue
  538. }
  539. watchaggregator.Aggregate(eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, aggrCtx)
  540. l.Debugln("Started filesystem watcher for folder", f.Description())
  541. case err = <-errChan:
  542. f.setWatchError(err)
  543. // This error was previously a panic and should never occur, so generate
  544. // a warning, but don't do it repetitively.
  545. if !warnedOutside {
  546. if _, ok := err.(*fs.ErrWatchEventOutsideRoot); ok {
  547. l.Warnln(err)
  548. warnedOutside = true
  549. }
  550. }
  551. aggrCancel()
  552. errChan = nil
  553. aggrCtx, aggrCancel = context.WithCancel(ctx)
  554. failTimer.Reset(time.Minute)
  555. case <-ctx.Done():
  556. return
  557. }
  558. }
  559. }
  560. // setWatchError sets the current error state of the watch and should be called
  561. // regardless of whether err is nil or not.
  562. func (f *folder) setWatchError(err error) {
  563. f.watchMut.Lock()
  564. prevErr := f.watchErr
  565. f.watchErr = err
  566. f.watchMut.Unlock()
  567. if err != prevErr {
  568. data := map[string]interface{}{
  569. "folder": f.ID,
  570. }
  571. if prevErr != nil {
  572. data["from"] = prevErr.Error()
  573. }
  574. if err != nil {
  575. data["to"] = err.Error()
  576. }
  577. events.Default.Log(events.FolderWatchStateChanged, data)
  578. }
  579. if err == nil {
  580. return
  581. }
  582. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  583. if prevErr != err {
  584. l.Infof(msg)
  585. return
  586. }
  587. l.Debugf(msg)
  588. }
  589. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  590. func (f *folder) scanOnWatchErr() {
  591. f.watchMut.Lock()
  592. if f.watchErr != nil {
  593. f.Delay(0)
  594. }
  595. f.watchMut.Unlock()
  596. }
  597. func (f *folder) setError(err error) {
  598. select {
  599. case <-f.ctx.Done():
  600. return
  601. default:
  602. }
  603. _, _, oldErr := f.getState()
  604. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  605. return
  606. }
  607. if err != nil {
  608. if oldErr == nil {
  609. l.Warnf("Error on folder %s: %v", f.Description(), err)
  610. } else {
  611. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  612. }
  613. } else {
  614. l.Infoln("Cleared error on folder", f.Description())
  615. }
  616. if f.FSWatcherEnabled {
  617. if err != nil {
  618. f.stopWatch()
  619. } else {
  620. f.scheduleWatchRestart()
  621. }
  622. }
  623. f.stateTracker.setError(err)
  624. }
  625. func (f *folder) basePause() time.Duration {
  626. if f.PullerPauseS == 0 {
  627. return defaultPullerPause
  628. }
  629. return time.Duration(f.PullerPauseS) * time.Second
  630. }
  631. func (f *folder) String() string {
  632. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  633. }
  634. func (f *folder) newScanError(path string, err error) {
  635. f.scanErrorsMut.Lock()
  636. f.scanErrors = append(f.scanErrors, FileError{
  637. Err: err.Error(),
  638. Path: path,
  639. })
  640. f.scanErrorsMut.Unlock()
  641. }
  642. func (f *folder) clearScanErrors(subDirs []string) {
  643. f.scanErrorsMut.Lock()
  644. defer f.scanErrorsMut.Unlock()
  645. if len(subDirs) == 0 {
  646. f.scanErrors = nil
  647. return
  648. }
  649. filtered := f.scanErrors[:0]
  650. outer:
  651. for _, fe := range f.scanErrors {
  652. for _, sub := range subDirs {
  653. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  654. continue outer
  655. }
  656. }
  657. filtered = append(filtered, fe)
  658. }
  659. f.scanErrors = filtered
  660. }
  661. func (f *folder) Errors() []FileError {
  662. f.scanErrorsMut.Lock()
  663. defer f.scanErrorsMut.Unlock()
  664. return append([]FileError{}, f.scanErrors...)
  665. }
  666. // ForceRescan marks the file such that it gets rehashed on next scan and then
  667. // immediately executes that scan.
  668. func (f *folder) ForceRescan(file protocol.FileInfo) error {
  669. file.SetMustRescan(f.shortID)
  670. f.fset.Update(protocol.LocalDeviceID, []protocol.FileInfo{file})
  671. return f.Scan([]string{file.Name})
  672. }
  673. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  674. f.updateLocals(fs)
  675. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  676. }
  677. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  678. f.updateLocals(fs)
  679. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  680. }
  681. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  682. f.fset.Update(protocol.LocalDeviceID, fs)
  683. filenames := make([]string, len(fs))
  684. for i, file := range fs {
  685. filenames[i] = file.Name
  686. }
  687. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  688. "folder": f.ID,
  689. "items": len(fs),
  690. "filenames": filenames,
  691. "version": f.fset.Sequence(protocol.LocalDeviceID),
  692. })
  693. }
  694. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  695. for _, file := range fs {
  696. if file.IsInvalid() {
  697. continue
  698. }
  699. objType := "file"
  700. action := "modified"
  701. switch {
  702. case file.IsDeleted():
  703. action = "deleted"
  704. // If our local vector is version 1 AND it is the only version
  705. // vector so far seen for this file then it is a new file. Else if
  706. // it is > 1 it's not new, and if it is 1 but another shortId
  707. // version vector exists then it is new for us but created elsewhere
  708. // so the file is still not new but modified by us. Only if it is
  709. // truly new do we change this to 'added', else we leave it as
  710. // 'modified'.
  711. case len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1:
  712. action = "added"
  713. }
  714. if file.IsSymlink() {
  715. objType = "symlink"
  716. } else if file.IsDirectory() {
  717. objType = "dir"
  718. }
  719. // Two different events can be fired here based on what EventType is passed into function
  720. events.Default.Log(typeOfEvent, map[string]string{
  721. "folder": f.ID,
  722. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  723. "label": f.Label,
  724. "action": action,
  725. "type": objType,
  726. "path": filepath.FromSlash(file.Name),
  727. "modifiedBy": file.ModifiedBy.String(),
  728. })
  729. }
  730. }
  731. // The exists function is expected to return true for all known paths
  732. // (excluding "" and ".")
  733. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  734. if len(dirs) == 0 {
  735. return nil
  736. }
  737. sort.Strings(dirs)
  738. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  739. return nil
  740. }
  741. prev := "./" // Anything that can't be parent of a clean path
  742. for i := 0; i < len(dirs); {
  743. dir, err := fs.Canonicalize(dirs[i])
  744. if err != nil {
  745. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  746. dirs = append(dirs[:i], dirs[i+1:]...)
  747. continue
  748. }
  749. if dir == prev || fs.IsParent(dir, prev) {
  750. dirs = append(dirs[:i], dirs[i+1:]...)
  751. continue
  752. }
  753. parent := filepath.Dir(dir)
  754. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  755. dir = parent
  756. parent = filepath.Dir(dir)
  757. }
  758. dirs[i] = dir
  759. prev = dir
  760. i++
  761. }
  762. return dirs
  763. }
  764. type cFiler struct {
  765. *db.FileSet
  766. }
  767. // Implements scanner.CurrentFiler
  768. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  769. return cf.Get(protocol.LocalDeviceID, file)
  770. }