progressemitter.go 10 KB

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