progressemitter.go 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  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(from, to config.Configuration) bool {
  175. t.mut.Lock()
  176. defer t.mut.Unlock()
  177. switch {
  178. case t.disabled && to.Options.ProgressUpdateIntervalS >= 0:
  179. t.disabled = false
  180. l.Debugln("progress emitter: enabled")
  181. fallthrough
  182. case !t.disabled && from.Options.ProgressUpdateIntervalS != to.Options.ProgressUpdateIntervalS:
  183. t.interval = time.Duration(to.Options.ProgressUpdateIntervalS) * time.Second
  184. if t.interval < time.Second {
  185. t.interval = time.Second
  186. }
  187. l.Debugln("progress emitter: updated interval", t.interval)
  188. case !t.disabled && to.Options.ProgressUpdateIntervalS < 0:
  189. t.clearLocked()
  190. t.disabled = true
  191. l.Debugln("progress emitter: disabled")
  192. }
  193. t.minBlocks = to.Options.TempIndexMinBlocks
  194. return true
  195. }
  196. // Register a puller with the emitter which will start broadcasting pullers
  197. // progress.
  198. func (t *ProgressEmitter) Register(s *sharedPullerState) {
  199. t.mut.Lock()
  200. defer t.mut.Unlock()
  201. if t.disabled {
  202. l.Debugln("progress emitter: disabled, skip registering")
  203. return
  204. }
  205. l.Debugln("progress emitter: registering", s.folder, s.file.Name)
  206. if t.emptyLocked() {
  207. t.timer.Reset(t.interval)
  208. }
  209. if _, ok := t.registry[s.folder]; !ok {
  210. t.registry[s.folder] = make(map[string]*sharedPullerState)
  211. }
  212. t.registry[s.folder][s.file.Name] = s
  213. }
  214. // Deregister a puller which will stop broadcasting pullers state.
  215. func (t *ProgressEmitter) Deregister(s *sharedPullerState) {
  216. t.mut.Lock()
  217. defer t.mut.Unlock()
  218. if t.disabled {
  219. l.Debugln("progress emitter: disabled, skip deregistering")
  220. return
  221. }
  222. l.Debugln("progress emitter: deregistering", s.folder, s.file.Name)
  223. delete(t.registry[s.folder], s.file.Name)
  224. }
  225. // BytesCompleted returns the number of bytes completed in the given folder.
  226. func (t *ProgressEmitter) BytesCompleted(folder string) (bytes int64) {
  227. t.mut.Lock()
  228. defer t.mut.Unlock()
  229. for _, s := range t.registry[folder] {
  230. bytes += s.Progress().BytesDone
  231. }
  232. l.Debugf("progress emitter: bytes completed for %s: %d", folder, bytes)
  233. return
  234. }
  235. func (t *ProgressEmitter) String() string {
  236. return fmt.Sprintf("ProgressEmitter@%p", t)
  237. }
  238. func (t *ProgressEmitter) lenRegistry() int {
  239. t.mut.Lock()
  240. defer t.mut.Unlock()
  241. return t.lenRegistryLocked()
  242. }
  243. func (t *ProgressEmitter) lenRegistryLocked() (out int) {
  244. for _, pullers := range t.registry {
  245. out += len(pullers)
  246. }
  247. return out
  248. }
  249. func (t *ProgressEmitter) emptyLocked() bool {
  250. for _, pullers := range t.registry {
  251. if len(pullers) != 0 {
  252. return false
  253. }
  254. }
  255. return true
  256. }
  257. func (t *ProgressEmitter) temporaryIndexSubscribe(conn protocol.Connection, folders []string) {
  258. t.mut.Lock()
  259. defer t.mut.Unlock()
  260. t.connections[conn.ID()] = conn
  261. t.foldersByConns[conn.ID()] = folders
  262. }
  263. func (t *ProgressEmitter) temporaryIndexUnsubscribe(conn protocol.Connection) {
  264. t.mut.Lock()
  265. defer t.mut.Unlock()
  266. delete(t.connections, conn.ID())
  267. delete(t.foldersByConns, conn.ID())
  268. }
  269. func (t *ProgressEmitter) clearLocked() {
  270. for id, state := range t.sentDownloadStates {
  271. conn, ok := t.connections[id]
  272. if !ok {
  273. continue
  274. }
  275. for _, folder := range state.folders() {
  276. if updates := state.cleanup(folder); len(updates) > 0 {
  277. conn.DownloadProgress(context.Background(), folder, updates)
  278. }
  279. }
  280. }
  281. t.registry = make(map[string]map[string]*sharedPullerState)
  282. t.sentDownloadStates = make(map[protocol.DeviceID]*sentDownloadState)
  283. t.connections = make(map[protocol.DeviceID]protocol.Connection)
  284. t.foldersByConns = make(map[protocol.DeviceID][]string)
  285. }