1
0

progressemitter.go 9.5 KB

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