progressemitter.go 9.4 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/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. evLogger events.Logger
  27. mut sync.Mutex
  28. timer *time.Timer
  29. }
  30. // NewProgressEmitter creates a new progress emitter which emits
  31. // DownloadProgress events every interval.
  32. func NewProgressEmitter(cfg config.Wrapper, evLogger events.Logger) *ProgressEmitter {
  33. t := &ProgressEmitter{
  34. registry: make(map[string]map[string]*sharedPullerState),
  35. timer: time.NewTimer(time.Millisecond),
  36. sentDownloadStates: make(map[protocol.DeviceID]*sentDownloadState),
  37. connections: make(map[protocol.DeviceID]protocol.Connection),
  38. foldersByConns: make(map[protocol.DeviceID][]string),
  39. evLogger: evLogger,
  40. mut: sync.NewMutex(),
  41. }
  42. t.Service = util.AsService(t.serve)
  43. t.CommitConfiguration(config.Configuration{}, cfg.RawCopy())
  44. cfg.Subscribe(t)
  45. return t
  46. }
  47. // serve starts the progress emitter which starts emitting DownloadProgress
  48. // events as the progress happens.
  49. func (t *ProgressEmitter) serve(stop chan struct{}) {
  50. var lastUpdate time.Time
  51. var lastCount, newCount int
  52. for {
  53. select {
  54. case <-stop:
  55. l.Debugln("progress emitter: stopping")
  56. return
  57. case <-t.timer.C:
  58. t.mut.Lock()
  59. l.Debugln("progress emitter: timer - looking after", len(t.registry))
  60. newLastUpdated := lastUpdate
  61. newCount = t.lenRegistryLocked()
  62. for _, pullers := range t.registry {
  63. for _, puller := range pullers {
  64. if updated := puller.Updated(); updated.After(newLastUpdated) {
  65. newLastUpdated = updated
  66. }
  67. }
  68. }
  69. if !newLastUpdated.Equal(lastUpdate) || newCount != lastCount {
  70. lastUpdate = newLastUpdated
  71. lastCount = newCount
  72. t.sendDownloadProgressEventLocked()
  73. if len(t.connections) > 0 {
  74. t.sendDownloadProgressMessagesLocked()
  75. }
  76. } else {
  77. l.Debugln("progress emitter: nothing new")
  78. }
  79. if newCount != 0 {
  80. t.timer.Reset(t.interval)
  81. }
  82. t.mut.Unlock()
  83. }
  84. }
  85. }
  86. func (t *ProgressEmitter) sendDownloadProgressEventLocked() {
  87. output := make(map[string]map[string]*pullerProgress)
  88. for folder, pullers := range t.registry {
  89. if len(pullers) == 0 {
  90. continue
  91. }
  92. output[folder] = make(map[string]*pullerProgress)
  93. for name, puller := range pullers {
  94. output[folder][name] = puller.Progress()
  95. }
  96. }
  97. t.evLogger.Log(events.DownloadProgress, output)
  98. l.Debugf("progress emitter: emitting %#v", output)
  99. }
  100. func (t *ProgressEmitter) sendDownloadProgressMessagesLocked() {
  101. for id, conn := range t.connections {
  102. for _, folder := range t.foldersByConns[id] {
  103. pullers, ok := t.registry[folder]
  104. if !ok {
  105. // There's never been any puller registered for this folder yet
  106. continue
  107. }
  108. state, ok := t.sentDownloadStates[id]
  109. if !ok {
  110. state = &sentDownloadState{
  111. folderStates: make(map[string]*sentFolderDownloadState),
  112. }
  113. t.sentDownloadStates[id] = state
  114. }
  115. activePullers := make([]*sharedPullerState, 0, len(pullers))
  116. for _, puller := range pullers {
  117. if puller.folder != folder || puller.file.IsSymlink() || puller.file.IsDirectory() || len(puller.file.Blocks) <= t.minBlocks {
  118. continue
  119. }
  120. activePullers = append(activePullers, puller)
  121. }
  122. // For every new puller that hasn't yet been seen, it will send all the blocks the puller has available
  123. // For every existing puller, it will check for new blocks, and send update for the new blocks only
  124. // For every puller that we've seen before but is no longer there, we will send a forget message
  125. updates := state.update(folder, activePullers)
  126. if len(updates) > 0 {
  127. conn.DownloadProgress(folder, updates)
  128. }
  129. }
  130. }
  131. // Clean up sentDownloadStates for devices which we are no longer connected to.
  132. for id := range t.sentDownloadStates {
  133. _, ok := t.connections[id]
  134. if !ok {
  135. // Null out outstanding entries for device
  136. delete(t.sentDownloadStates, id)
  137. }
  138. }
  139. // If a folder was unshared from some device, tell it that all temp files
  140. // are now gone.
  141. for id, state := range t.sentDownloadStates {
  142. // For each of the folders that the state is aware of,
  143. // try to match it with a shared folder we've discovered above,
  144. nextFolder:
  145. for _, folder := range state.folders() {
  146. for _, existingFolder := range t.foldersByConns[id] {
  147. if existingFolder == folder {
  148. continue nextFolder
  149. }
  150. }
  151. // If we fail to find that folder, we tell the state to forget about it
  152. // and return us a list of updates which would clean up the state
  153. // on the remote end.
  154. state.cleanup(folder)
  155. // updates := state.cleanup(folder)
  156. // if len(updates) > 0 {
  157. // XXX: Don't send this now, as the only way we've unshared a folder
  158. // is by breaking the connection and reconnecting, hence sending
  159. // forget messages for some random folder currently makes no sense.
  160. // deviceConns[id].DownloadProgress(folder, updates, 0, nil)
  161. // }
  162. }
  163. }
  164. }
  165. // VerifyConfiguration implements the config.Committer interface
  166. func (t *ProgressEmitter) VerifyConfiguration(from, to config.Configuration) error {
  167. return nil
  168. }
  169. // CommitConfiguration implements the config.Committer interface
  170. func (t *ProgressEmitter) CommitConfiguration(from, to config.Configuration) bool {
  171. t.mut.Lock()
  172. defer t.mut.Unlock()
  173. switch {
  174. case t.disabled && to.Options.ProgressUpdateIntervalS >= 0:
  175. t.disabled = false
  176. l.Debugln("progress emitter: enabled")
  177. fallthrough
  178. case !t.disabled && from.Options.ProgressUpdateIntervalS != to.Options.ProgressUpdateIntervalS:
  179. t.interval = time.Duration(to.Options.ProgressUpdateIntervalS) * time.Second
  180. if t.interval < time.Second {
  181. t.interval = time.Second
  182. }
  183. l.Debugln("progress emitter: updated interval", t.interval)
  184. case !t.disabled && to.Options.ProgressUpdateIntervalS < 0:
  185. t.clearLocked()
  186. t.disabled = true
  187. l.Debugln("progress emitter: disabled")
  188. }
  189. t.minBlocks = to.Options.TempIndexMinBlocks
  190. return true
  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. }