folder.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881
  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. file := fi.(db.FileInfoTruncated)
  355. if err := batch.flushIfFull(); err != nil {
  356. iterError = err
  357. return false
  358. }
  359. if ignoredParent != "" && !fs.IsParent(file.Name, ignoredParent) {
  360. for _, file := range toIgnore {
  361. l.Debugln("marking file as ignored", file)
  362. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  363. batch.append(nf)
  364. changes++
  365. if err := batch.flushIfFull(); err != nil {
  366. iterError = err
  367. return false
  368. }
  369. }
  370. toIgnore = toIgnore[:0]
  371. ignoredParent = ""
  372. }
  373. switch ignored := f.ignores.Match(file.Name).IsIgnored(); {
  374. case !file.IsIgnored() && ignored:
  375. // File was not ignored at last pass but has been ignored.
  376. if file.IsDirectory() {
  377. // Delay ignoring as a child might be unignored.
  378. toIgnore = append(toIgnore, file)
  379. if ignoredParent == "" {
  380. // If the parent wasn't ignored already, set
  381. // this path as the "highest" ignored parent
  382. ignoredParent = file.Name
  383. }
  384. return true
  385. }
  386. l.Debugln("marking file as ignored", f)
  387. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  388. batch.append(nf)
  389. changes++
  390. case file.IsIgnored() && !ignored:
  391. // Successfully scanned items are already un-ignored during
  392. // the scan, so check whether it is deleted.
  393. fallthrough
  394. case !file.IsIgnored() && !file.IsDeleted() && !file.IsUnsupported():
  395. // The file is not ignored, deleted or unsupported. Lets check if
  396. // it's still here. Simply stat:ing it wont do as there are
  397. // tons of corner cases (e.g. parent dir->symlink, missing
  398. // permissions)
  399. if !osutil.IsDeleted(mtimefs, file.Name) {
  400. if ignoredParent != "" {
  401. // Don't ignore parents of this not ignored item
  402. toIgnore = toIgnore[:0]
  403. ignoredParent = ""
  404. }
  405. return true
  406. }
  407. nf := protocol.FileInfo{
  408. Name: file.Name,
  409. Type: file.Type,
  410. Size: 0,
  411. ModifiedS: file.ModifiedS,
  412. ModifiedNs: file.ModifiedNs,
  413. ModifiedBy: f.shortID,
  414. Deleted: true,
  415. Version: file.Version.Update(f.shortID),
  416. LocalFlags: f.localFlags,
  417. }
  418. // We do not want to override the global version
  419. // with the deleted file. Keeping only our local
  420. // counter makes sure we are in conflict with any
  421. // other existing versions, which will be resolved
  422. // by the normal pulling mechanisms.
  423. if file.ShouldConflict() {
  424. nf.Version = nf.Version.DropOthers(f.shortID)
  425. }
  426. batch.append(nf)
  427. changes++
  428. }
  429. return true
  430. })
  431. if iterError == nil && len(toIgnore) > 0 {
  432. for _, file := range toIgnore {
  433. l.Debugln("marking file as ignored", f)
  434. nf := file.ConvertToIgnoredFileInfo(f.shortID)
  435. batch.append(nf)
  436. changes++
  437. if iterError = batch.flushIfFull(); iterError != nil {
  438. break
  439. }
  440. }
  441. toIgnore = toIgnore[:0]
  442. }
  443. if iterError != nil {
  444. return iterError
  445. }
  446. }
  447. if err := batch.flush(); err != nil {
  448. return err
  449. }
  450. f.ScanCompleted()
  451. f.setState(FolderIdle)
  452. return nil
  453. }
  454. func (f *folder) scanTimerFired() {
  455. err := f.scanSubdirs(nil)
  456. select {
  457. case <-f.initialScanFinished:
  458. default:
  459. status := "Completed"
  460. if err != nil {
  461. status = "Failed"
  462. }
  463. l.Infoln(status, "initial scan of", f.Type.String(), "folder", f.Description())
  464. close(f.initialScanFinished)
  465. }
  466. f.Reschedule()
  467. }
  468. func (f *folder) WatchError() error {
  469. f.watchMut.Lock()
  470. defer f.watchMut.Unlock()
  471. return f.watchErr
  472. }
  473. // stopWatch immediately aborts watching and may be called asynchronously
  474. func (f *folder) stopWatch() {
  475. f.watchMut.Lock()
  476. f.watchCancel()
  477. f.watchMut.Unlock()
  478. f.setWatchError(nil)
  479. }
  480. // scheduleWatchRestart makes sure watching is restarted from the main for loop
  481. // in a folder's Serve and thus may be called asynchronously (e.g. when ignores change).
  482. func (f *folder) scheduleWatchRestart() {
  483. select {
  484. case f.restartWatchChan <- struct{}{}:
  485. default:
  486. // We might be busy doing a pull and thus not reading from this
  487. // channel. The channel is 1-buffered, so one notification will be
  488. // queued to ensure we recheck after the pull.
  489. }
  490. }
  491. // restartWatch should only ever be called synchronously. If you want to use
  492. // this asynchronously, you should probably use scheduleWatchRestart instead.
  493. func (f *folder) restartWatch() {
  494. f.stopWatch()
  495. f.startWatch()
  496. f.scanSubdirs(nil)
  497. }
  498. // startWatch should only ever be called synchronously. If you want to use
  499. // this asynchronously, you should probably use scheduleWatchRestart instead.
  500. func (f *folder) startWatch() {
  501. ctx, cancel := context.WithCancel(f.ctx)
  502. f.watchMut.Lock()
  503. f.watchChan = make(chan []string)
  504. f.watchCancel = cancel
  505. f.watchMut.Unlock()
  506. go f.monitorWatch(ctx)
  507. }
  508. // monitorWatch starts the filesystem watching and retries every minute on failure.
  509. // It should not be used except in startWatch.
  510. func (f *folder) monitorWatch(ctx context.Context) {
  511. failTimer := time.NewTimer(0)
  512. aggrCtx, aggrCancel := context.WithCancel(ctx)
  513. var err error
  514. var eventChan <-chan fs.Event
  515. var errChan <-chan error
  516. warnedOutside := false
  517. for {
  518. select {
  519. case <-failTimer.C:
  520. eventChan, errChan, err = f.Filesystem().Watch(".", f.ignores, ctx, f.IgnorePerms)
  521. // We do this at most once per minute which is the
  522. // default rescan time without watcher.
  523. f.scanOnWatchErr()
  524. f.setWatchError(err)
  525. if err != nil {
  526. failTimer.Reset(time.Minute)
  527. continue
  528. }
  529. watchaggregator.Aggregate(eventChan, f.watchChan, f.FolderConfiguration, f.model.cfg, aggrCtx)
  530. l.Debugln("Started filesystem watcher for folder", f.Description())
  531. case err = <-errChan:
  532. f.setWatchError(err)
  533. // This error was previously a panic and should never occur, so generate
  534. // a warning, but don't do it repetitively.
  535. if !warnedOutside {
  536. if _, ok := err.(*fs.ErrWatchEventOutsideRoot); ok {
  537. l.Warnln(err)
  538. warnedOutside = true
  539. }
  540. }
  541. aggrCancel()
  542. errChan = nil
  543. aggrCtx, aggrCancel = context.WithCancel(ctx)
  544. failTimer.Reset(time.Minute)
  545. case <-ctx.Done():
  546. return
  547. }
  548. }
  549. }
  550. // setWatchError sets the current error state of the watch and should be called
  551. // regardless of whether err is nil or not.
  552. func (f *folder) setWatchError(err error) {
  553. f.watchMut.Lock()
  554. prevErr := f.watchErr
  555. f.watchErr = err
  556. f.watchMut.Unlock()
  557. if err != prevErr {
  558. data := map[string]interface{}{
  559. "folder": f.ID,
  560. }
  561. if prevErr != nil {
  562. data["from"] = prevErr.Error()
  563. }
  564. if err != nil {
  565. data["to"] = err.Error()
  566. }
  567. events.Default.Log(events.FolderWatchStateChanged, data)
  568. }
  569. if err == nil {
  570. return
  571. }
  572. msg := fmt.Sprintf("Error while trying to start filesystem watcher for folder %s, trying again in 1min: %v", f.Description(), err)
  573. if prevErr != err {
  574. l.Infof(msg)
  575. return
  576. }
  577. l.Debugf(msg)
  578. }
  579. // scanOnWatchErr schedules a full scan immediately if an error occurred while watching.
  580. func (f *folder) scanOnWatchErr() {
  581. f.watchMut.Lock()
  582. if f.watchErr != nil {
  583. f.Delay(0)
  584. }
  585. f.watchMut.Unlock()
  586. }
  587. func (f *folder) setError(err error) {
  588. select {
  589. case <-f.ctx.Done():
  590. return
  591. default:
  592. }
  593. _, _, oldErr := f.getState()
  594. if (err != nil && oldErr != nil && oldErr.Error() == err.Error()) || (err == nil && oldErr == nil) {
  595. return
  596. }
  597. if err != nil {
  598. if oldErr == nil {
  599. l.Warnf("Error on folder %s: %v", f.Description(), err)
  600. } else {
  601. l.Infof("Error on folder %s changed: %q -> %q", f.Description(), oldErr, err)
  602. }
  603. } else {
  604. l.Infoln("Cleared error on folder", f.Description())
  605. }
  606. if f.FSWatcherEnabled {
  607. if err != nil {
  608. f.stopWatch()
  609. } else {
  610. f.scheduleWatchRestart()
  611. }
  612. }
  613. f.stateTracker.setError(err)
  614. }
  615. func (f *folder) basePause() time.Duration {
  616. if f.PullerPauseS == 0 {
  617. return defaultPullerPause
  618. }
  619. return time.Duration(f.PullerPauseS) * time.Second
  620. }
  621. func (f *folder) String() string {
  622. return fmt.Sprintf("%s/%s@%p", f.Type, f.folderID, f)
  623. }
  624. func (f *folder) newScanError(path string, err error) {
  625. f.scanErrorsMut.Lock()
  626. f.scanErrors = append(f.scanErrors, FileError{
  627. Err: err.Error(),
  628. Path: path,
  629. })
  630. f.scanErrorsMut.Unlock()
  631. }
  632. func (f *folder) clearScanErrors(subDirs []string) {
  633. f.scanErrorsMut.Lock()
  634. defer f.scanErrorsMut.Unlock()
  635. if len(subDirs) == 0 {
  636. f.scanErrors = nil
  637. return
  638. }
  639. filtered := f.scanErrors[:0]
  640. outer:
  641. for _, fe := range f.scanErrors {
  642. for _, sub := range subDirs {
  643. if fe.Path == sub || fs.IsParent(fe.Path, sub) {
  644. continue outer
  645. }
  646. }
  647. filtered = append(filtered, fe)
  648. }
  649. f.scanErrors = filtered
  650. }
  651. func (f *folder) Errors() []FileError {
  652. f.scanErrorsMut.Lock()
  653. defer f.scanErrorsMut.Unlock()
  654. return append([]FileError{}, f.scanErrors...)
  655. }
  656. // ForceRescan marks the file such that it gets rehashed on next scan and then
  657. // immediately executes that scan.
  658. func (f *folder) ForceRescan(file protocol.FileInfo) error {
  659. file.SetMustRescan(f.shortID)
  660. f.fset.Update(protocol.LocalDeviceID, []protocol.FileInfo{file})
  661. return f.Scan([]string{file.Name})
  662. }
  663. func (f *folder) updateLocalsFromScanning(fs []protocol.FileInfo) {
  664. f.updateLocals(fs)
  665. f.emitDiskChangeEvents(fs, events.LocalChangeDetected)
  666. }
  667. func (f *folder) updateLocalsFromPulling(fs []protocol.FileInfo) {
  668. f.updateLocals(fs)
  669. f.emitDiskChangeEvents(fs, events.RemoteChangeDetected)
  670. }
  671. func (f *folder) updateLocals(fs []protocol.FileInfo) {
  672. f.fset.Update(protocol.LocalDeviceID, fs)
  673. filenames := make([]string, len(fs))
  674. for i, file := range fs {
  675. filenames[i] = file.Name
  676. }
  677. events.Default.Log(events.LocalIndexUpdated, map[string]interface{}{
  678. "folder": f.ID,
  679. "items": len(fs),
  680. "filenames": filenames,
  681. "version": f.fset.Sequence(protocol.LocalDeviceID),
  682. })
  683. }
  684. func (f *folder) emitDiskChangeEvents(fs []protocol.FileInfo, typeOfEvent events.EventType) {
  685. for _, file := range fs {
  686. if file.IsInvalid() {
  687. continue
  688. }
  689. objType := "file"
  690. action := "modified"
  691. switch {
  692. case file.IsDeleted():
  693. action = "deleted"
  694. // If our local vector is version 1 AND it is the only version
  695. // vector so far seen for this file then it is a new file. Else if
  696. // it is > 1 it's not new, and if it is 1 but another shortId
  697. // version vector exists then it is new for us but created elsewhere
  698. // so the file is still not new but modified by us. Only if it is
  699. // truly new do we change this to 'added', else we leave it as
  700. // 'modified'.
  701. case len(file.Version.Counters) == 1 && file.Version.Counters[0].Value == 1:
  702. action = "added"
  703. }
  704. if file.IsSymlink() {
  705. objType = "symlink"
  706. } else if file.IsDirectory() {
  707. objType = "dir"
  708. }
  709. // Two different events can be fired here based on what EventType is passed into function
  710. events.Default.Log(typeOfEvent, map[string]string{
  711. "folder": f.ID,
  712. "folderID": f.ID, // incorrect, deprecated, kept for historical compliance
  713. "label": f.Label,
  714. "action": action,
  715. "type": objType,
  716. "path": filepath.FromSlash(file.Name),
  717. "modifiedBy": file.ModifiedBy.String(),
  718. })
  719. }
  720. }
  721. // The exists function is expected to return true for all known paths
  722. // (excluding "" and ".")
  723. func unifySubs(dirs []string, exists func(dir string) bool) []string {
  724. if len(dirs) == 0 {
  725. return nil
  726. }
  727. sort.Strings(dirs)
  728. if dirs[0] == "" || dirs[0] == "." || dirs[0] == string(fs.PathSeparator) {
  729. return nil
  730. }
  731. prev := "./" // Anything that can't be parent of a clean path
  732. for i := 0; i < len(dirs); {
  733. dir, err := fs.Canonicalize(dirs[i])
  734. if err != nil {
  735. l.Debugf("Skipping %v for scan: %s", dirs[i], err)
  736. dirs = append(dirs[:i], dirs[i+1:]...)
  737. continue
  738. }
  739. if dir == prev || fs.IsParent(dir, prev) {
  740. dirs = append(dirs[:i], dirs[i+1:]...)
  741. continue
  742. }
  743. parent := filepath.Dir(dir)
  744. for parent != "." && parent != string(fs.PathSeparator) && !exists(parent) {
  745. dir = parent
  746. parent = filepath.Dir(dir)
  747. }
  748. dirs[i] = dir
  749. prev = dir
  750. i++
  751. }
  752. return dirs
  753. }
  754. type cFiler struct {
  755. *db.FileSet
  756. }
  757. // Implements scanner.CurrentFiler
  758. func (cf cFiler) CurrentFile(file string) (protocol.FileInfo, bool) {
  759. return cf.Get(protocol.LocalDeviceID, file)
  760. }