progressemitter.go 9.3 KB

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