progressemitter.go 10 KB

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