folder.go 23 KB

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