rofolder.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  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 http://mozilla.org/MPL/2.0/.
  6. package model
  7. import (
  8. "fmt"
  9. "math/rand"
  10. "time"
  11. "github.com/syncthing/syncthing/internal/sync"
  12. )
  13. type roFolder struct {
  14. stateTracker
  15. folder string
  16. intv time.Duration
  17. model *Model
  18. stop chan struct{}
  19. }
  20. func newROFolder(model *Model, folder string, interval time.Duration) *roFolder {
  21. return &roFolder{
  22. stateTracker: stateTracker{
  23. folder: folder,
  24. mut: sync.NewMutex(),
  25. },
  26. folder: folder,
  27. intv: interval,
  28. model: model,
  29. stop: make(chan struct{}),
  30. }
  31. }
  32. func (s *roFolder) Serve() {
  33. if debug {
  34. l.Debugln(s, "starting")
  35. defer l.Debugln(s, "exiting")
  36. }
  37. timer := time.NewTimer(time.Millisecond)
  38. defer timer.Stop()
  39. reschedule := func() {
  40. // Sleep a random time between 3/4 and 5/4 of the configured interval.
  41. sleepNanos := (s.intv.Nanoseconds()*3 + rand.Int63n(2*s.intv.Nanoseconds())) / 4
  42. timer.Reset(time.Duration(sleepNanos) * time.Nanosecond)
  43. }
  44. initialScanCompleted := false
  45. for {
  46. select {
  47. case <-s.stop:
  48. return
  49. case <-timer.C:
  50. if err := s.model.CheckFolderHealth(s.folder); err != nil {
  51. l.Infoln("Skipping folder", s.folder, "scan due to folder error:", err)
  52. reschedule()
  53. continue
  54. }
  55. if debug {
  56. l.Debugln(s, "rescan")
  57. }
  58. if err := s.model.ScanFolder(s.folder); err != nil {
  59. // Potentially sets the error twice, once in the scanner just
  60. // by doing a check, and once here, if the error returned is
  61. // the same one as returned by CheckFolderHealth, though
  62. // duplicate set is handled by setError.
  63. s.setError(err)
  64. reschedule()
  65. continue
  66. }
  67. if !initialScanCompleted {
  68. l.Infoln("Completed initial scan (ro) of folder", s.folder)
  69. initialScanCompleted = true
  70. }
  71. if s.intv == 0 {
  72. return
  73. }
  74. reschedule()
  75. }
  76. }
  77. }
  78. func (s *roFolder) Stop() {
  79. close(s.stop)
  80. }
  81. func (s *roFolder) String() string {
  82. return fmt.Sprintf("roFolder/%s@%p", s.folder, s)
  83. }
  84. func (s *roFolder) BringToFront(string) {}
  85. func (s *roFolder) Jobs() ([]string, []string) {
  86. return nil, nil
  87. }