1
0

progressemitter.go 8.2 KB

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