rofolder.go 2.2 KB

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