folderstate.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. package model
  16. import (
  17. "sync"
  18. "time"
  19. "github.com/syncthing/syncthing/internal/events"
  20. )
  21. type folderState int
  22. const (
  23. FolderIdle folderState = iota
  24. FolderScanning
  25. FolderSyncing
  26. FolderCleaning
  27. )
  28. func (s folderState) String() string {
  29. switch s {
  30. case FolderIdle:
  31. return "idle"
  32. case FolderScanning:
  33. return "scanning"
  34. case FolderCleaning:
  35. return "cleaning"
  36. case FolderSyncing:
  37. return "syncing"
  38. default:
  39. return "unknown"
  40. }
  41. }
  42. type stateTracker struct {
  43. folder string
  44. mut sync.Mutex
  45. current folderState
  46. changed time.Time
  47. }
  48. func (s *stateTracker) setState(newState folderState) {
  49. s.mut.Lock()
  50. if newState != s.current {
  51. /* This should hold later...
  52. if s.current != FolderIdle && (newState == FolderScanning || newState == FolderSyncing) {
  53. panic("illegal state transition " + s.current.String() + " -> " + newState.String())
  54. }
  55. */
  56. eventData := map[string]interface{}{
  57. "folder": s.folder,
  58. "to": newState.String(),
  59. "from": s.current.String(),
  60. }
  61. if !s.changed.IsZero() {
  62. eventData["duration"] = time.Since(s.changed).Seconds()
  63. }
  64. s.current = newState
  65. s.changed = time.Now()
  66. events.Default.Log(events.StateChanged, eventData)
  67. }
  68. s.mut.Unlock()
  69. }
  70. func (s *stateTracker) getState() (current folderState, changed time.Time) {
  71. s.mut.Lock()
  72. current, changed = s.current, s.changed
  73. s.mut.Unlock()
  74. return
  75. }