progressemitter.go 8.3 KB

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