progressemitter.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  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. "path/filepath"
  10. "time"
  11. "github.com/syncthing/syncthing/lib/config"
  12. "github.com/syncthing/syncthing/lib/events"
  13. "github.com/syncthing/syncthing/lib/protocol"
  14. "github.com/syncthing/syncthing/lib/sync"
  15. )
  16. type ProgressEmitter struct {
  17. registry map[string]*sharedPullerState
  18. interval time.Duration
  19. minBlocks int
  20. sentDownloadStates map[protocol.DeviceID]*sentDownloadState // States representing what we've sent to the other peer via DownloadProgress messages.
  21. connections map[string][]protocol.Connection
  22. mut sync.Mutex
  23. timer *time.Timer
  24. stop chan struct{}
  25. }
  26. // NewProgressEmitter creates a new progress emitter which emits
  27. // DownloadProgress events every interval.
  28. func NewProgressEmitter(cfg *config.Wrapper) *ProgressEmitter {
  29. t := &ProgressEmitter{
  30. stop: make(chan struct{}),
  31. registry: make(map[string]*sharedPullerState),
  32. timer: time.NewTimer(time.Millisecond),
  33. sentDownloadStates: make(map[protocol.DeviceID]*sentDownloadState),
  34. connections: make(map[string][]protocol.Connection),
  35. mut: sync.NewMutex(),
  36. }
  37. t.CommitConfiguration(config.Configuration{}, cfg.Raw())
  38. cfg.Subscribe(t)
  39. return t
  40. }
  41. // Serve starts the progress emitter which starts emitting DownloadProgress
  42. // events as the progress happens.
  43. func (t *ProgressEmitter) Serve() {
  44. var lastUpdate time.Time
  45. var lastCount, newCount int
  46. for {
  47. select {
  48. case <-t.stop:
  49. l.Debugln("progress emitter: stopping")
  50. return
  51. case <-t.timer.C:
  52. t.mut.Lock()
  53. l.Debugln("progress emitter: timer - looking after", len(t.registry))
  54. newLastUpdated := lastUpdate
  55. newCount = len(t.registry)
  56. for _, puller := range t.registry {
  57. updated := puller.Updated()
  58. if updated.After(newLastUpdated) {
  59. newLastUpdated = updated
  60. }
  61. }
  62. if !newLastUpdated.Equal(lastUpdate) || newCount != lastCount {
  63. lastUpdate = newLastUpdated
  64. lastCount = newCount
  65. t.sendDownloadProgressEvent()
  66. if len(t.connections) > 0 {
  67. t.sendDownloadProgressMessages()
  68. }
  69. } else {
  70. l.Debugln("progress emitter: nothing new")
  71. }
  72. if newCount != 0 {
  73. t.timer.Reset(t.interval)
  74. }
  75. t.mut.Unlock()
  76. }
  77. }
  78. }
  79. func (t *ProgressEmitter) sendDownloadProgressEvent() {
  80. // registry lock already held
  81. output := make(map[string]map[string]*pullerProgress)
  82. for _, puller := range t.registry {
  83. if output[puller.folder] == nil {
  84. output[puller.folder] = make(map[string]*pullerProgress)
  85. }
  86. output[puller.folder][puller.file.Name] = puller.Progress()
  87. }
  88. events.Default.Log(events.DownloadProgress, output)
  89. l.Debugf("progress emitter: emitting %#v", output)
  90. }
  91. func (t *ProgressEmitter) sendDownloadProgressMessages() {
  92. // registry lock already held
  93. sharedFolders := make(map[protocol.DeviceID][]string)
  94. deviceConns := make(map[protocol.DeviceID]protocol.Connection)
  95. subscribers := t.connections
  96. for folder, conns := range subscribers {
  97. for _, conn := range conns {
  98. id := conn.ID()
  99. deviceConns[id] = conn
  100. sharedFolders[id] = append(sharedFolders[id], folder)
  101. state, ok := t.sentDownloadStates[id]
  102. if !ok {
  103. state = &sentDownloadState{
  104. folderStates: make(map[string]*sentFolderDownloadState),
  105. }
  106. t.sentDownloadStates[id] = state
  107. }
  108. var activePullers []*sharedPullerState
  109. for _, puller := range t.registry {
  110. if puller.folder != folder || puller.file.IsSymlink() || puller.file.IsDirectory() || len(puller.file.Blocks) <= t.minBlocks {
  111. continue
  112. }
  113. activePullers = append(activePullers, puller)
  114. }
  115. // For every new puller that hasn't yet been seen, it will send all the blocks the puller has available
  116. // For every existing puller, it will check for new blocks, and send update for the new blocks only
  117. // For every puller that we've seen before but is no longer there, we will send a forget message
  118. updates := state.update(folder, activePullers)
  119. if len(updates) > 0 {
  120. conn.DownloadProgress(folder, updates)
  121. }
  122. }
  123. }
  124. // Clean up sentDownloadStates for devices which we are no longer connected to.
  125. for id := range t.sentDownloadStates {
  126. _, ok := deviceConns[id]
  127. if !ok {
  128. // Null out outstanding entries for device
  129. delete(t.sentDownloadStates, id)
  130. }
  131. }
  132. // If a folder was unshared from some device, tell it that all temp files
  133. // are now gone.
  134. for id, sharedDeviceFolders := range sharedFolders {
  135. state := t.sentDownloadStates[id]
  136. nextFolder:
  137. // For each of the folders that the state is aware of,
  138. // try to match it with a shared folder we've discovered above,
  139. for _, folder := range state.folders() {
  140. for _, existingFolder := range sharedDeviceFolders {
  141. if existingFolder == folder {
  142. continue nextFolder
  143. }
  144. }
  145. // If we fail to find that folder, we tell the state to forget about it
  146. // and return us a list of updates which would clean up the state
  147. // on the remote end.
  148. updates := state.cleanup(folder)
  149. if len(updates) > 0 {
  150. // XXX: Don't send this now, as the only way we've unshared a folder
  151. // is by breaking the connection and reconnecting, hence sending
  152. // forget messages for some random folder currently makes no sense.
  153. // deviceConns[id].DownloadProgress(folder, updates, 0, nil)
  154. }
  155. }
  156. }
  157. }
  158. // VerifyConfiguration implements the config.Committer interface
  159. func (t *ProgressEmitter) VerifyConfiguration(from, to config.Configuration) error {
  160. return nil
  161. }
  162. // CommitConfiguration implements the config.Committer interface
  163. func (t *ProgressEmitter) CommitConfiguration(from, to config.Configuration) bool {
  164. t.mut.Lock()
  165. defer t.mut.Unlock()
  166. t.interval = time.Duration(to.Options.ProgressUpdateIntervalS) * time.Second
  167. if t.interval < time.Second {
  168. t.interval = time.Second
  169. }
  170. t.minBlocks = to.Options.TempIndexMinBlocks
  171. l.Debugln("progress emitter: updated interval", t.interval)
  172. return true
  173. }
  174. // Stop stops the emitter.
  175. func (t *ProgressEmitter) Stop() {
  176. t.stop <- struct{}{}
  177. }
  178. // Register a puller with the emitter which will start broadcasting pullers
  179. // progress.
  180. func (t *ProgressEmitter) Register(s *sharedPullerState) {
  181. t.mut.Lock()
  182. defer t.mut.Unlock()
  183. l.Debugln("progress emitter: registering", s.folder, s.file.Name)
  184. if len(t.registry) == 0 {
  185. t.timer.Reset(t.interval)
  186. }
  187. t.registry[filepath.Join(s.folder, s.file.Name)] = s
  188. }
  189. // Deregister a puller which will stop broadcasting pullers state.
  190. func (t *ProgressEmitter) Deregister(s *sharedPullerState) {
  191. t.mut.Lock()
  192. defer t.mut.Unlock()
  193. l.Debugln("progress emitter: deregistering", s.folder, s.file.Name)
  194. delete(t.registry, filepath.Join(s.folder, s.file.Name))
  195. }
  196. // BytesCompleted returns the number of bytes completed in the given folder.
  197. func (t *ProgressEmitter) BytesCompleted(folder string) (bytes int64) {
  198. t.mut.Lock()
  199. defer t.mut.Unlock()
  200. for _, s := range t.registry {
  201. if s.folder == folder {
  202. bytes += s.Progress().BytesDone
  203. }
  204. }
  205. l.Debugf("progress emitter: bytes completed for %s: %d", folder, bytes)
  206. return
  207. }
  208. func (t *ProgressEmitter) String() string {
  209. return fmt.Sprintf("ProgressEmitter@%p", t)
  210. }
  211. func (t *ProgressEmitter) lenRegistry() int {
  212. t.mut.Lock()
  213. defer t.mut.Unlock()
  214. return len(t.registry)
  215. }
  216. func (t *ProgressEmitter) temporaryIndexSubscribe(conn protocol.Connection, folders []string) {
  217. t.mut.Lock()
  218. for _, folder := range folders {
  219. t.connections[folder] = append(t.connections[folder], conn)
  220. }
  221. t.mut.Unlock()
  222. }
  223. func (t *ProgressEmitter) temporaryIndexUnsubscribe(conn protocol.Connection) {
  224. t.mut.Lock()
  225. left := make(map[string][]protocol.Connection, len(t.connections))
  226. for folder, conns := range t.connections {
  227. connsLeft := connsWithout(conns, conn)
  228. if len(connsLeft) > 0 {
  229. left[folder] = connsLeft
  230. }
  231. }
  232. t.connections = left
  233. t.mut.Unlock()
  234. }
  235. func connsWithout(conns []protocol.Connection, conn protocol.Connection) []protocol.Connection {
  236. if len(conns) == 0 {
  237. return nil
  238. }
  239. newConns := make([]protocol.Connection, 0, len(conns)-1)
  240. for _, existingConn := range conns {
  241. if existingConn != conn {
  242. newConns = append(newConns, existingConn)
  243. }
  244. }
  245. return newConns
  246. }