progressemitter.go 9.3 KB

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