folder.go 23 KB

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