watch_broadcast.go 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. // Copyright 2016 The etcd Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package grpcproxy
  15. import (
  16. "context"
  17. "sync"
  18. "go.etcd.io/etcd/clientv3"
  19. pb "go.etcd.io/etcd/etcdserver/etcdserverpb"
  20. )
  21. // watchBroadcast broadcasts a server watcher to many client watchers.
  22. type watchBroadcast struct {
  23. // cancel stops the underlying etcd server watcher and closes ch.
  24. cancel context.CancelFunc
  25. donec chan struct{}
  26. // mu protects rev and receivers.
  27. mu sync.RWMutex
  28. // nextrev is the minimum expected next revision of the watcher on ch.
  29. nextrev int64
  30. // receivers contains all the client-side watchers to serve.
  31. receivers map[*watcher]struct{}
  32. // responses counts the number of responses
  33. responses int
  34. }
  35. func newWatchBroadcast(wp *watchProxy, w *watcher, update func(*watchBroadcast)) *watchBroadcast {
  36. cctx, cancel := context.WithCancel(wp.ctx)
  37. wb := &watchBroadcast{
  38. cancel: cancel,
  39. nextrev: w.nextrev,
  40. receivers: make(map[*watcher]struct{}),
  41. donec: make(chan struct{}),
  42. }
  43. wb.add(w)
  44. go func() {
  45. defer close(wb.donec)
  46. opts := []clientv3.OpOption{
  47. clientv3.WithRange(w.wr.end),
  48. clientv3.WithProgressNotify(),
  49. clientv3.WithRev(wb.nextrev),
  50. clientv3.WithPrevKV(),
  51. clientv3.WithCreatedNotify(),
  52. }
  53. cctx = withClientAuthToken(cctx, w.wps.stream.Context())
  54. wch := wp.cw.Watch(cctx, w.wr.key, opts...)
  55. for wr := range wch {
  56. wb.bcast(wr)
  57. update(wb)
  58. }
  59. }()
  60. return wb
  61. }
  62. func (wb *watchBroadcast) bcast(wr clientv3.WatchResponse) {
  63. wb.mu.Lock()
  64. defer wb.mu.Unlock()
  65. // watchers start on the given revision, if any; ignore header rev on create
  66. if wb.responses > 0 || wb.nextrev == 0 {
  67. wb.nextrev = wr.Header.Revision + 1
  68. }
  69. wb.responses++
  70. for r := range wb.receivers {
  71. r.send(wr)
  72. }
  73. if len(wb.receivers) > 0 {
  74. eventsCoalescing.Add(float64(len(wb.receivers) - 1))
  75. }
  76. }
  77. // add puts a watcher into receiving a broadcast if its revision at least
  78. // meets the broadcast revision. Returns true if added.
  79. func (wb *watchBroadcast) add(w *watcher) bool {
  80. wb.mu.Lock()
  81. defer wb.mu.Unlock()
  82. if wb.nextrev > w.nextrev || (wb.nextrev == 0 && w.nextrev != 0) {
  83. // wb is too far ahead, w will miss events
  84. // or wb is being established with a current watcher
  85. return false
  86. }
  87. if wb.responses == 0 {
  88. // Newly created; create event will be sent by etcd.
  89. wb.receivers[w] = struct{}{}
  90. return true
  91. }
  92. // already sent by etcd; emulate create event
  93. ok := w.post(&pb.WatchResponse{
  94. Header: &pb.ResponseHeader{
  95. // todo: fill in ClusterId
  96. // todo: fill in MemberId:
  97. Revision: w.nextrev,
  98. // todo: fill in RaftTerm:
  99. },
  100. WatchId: w.id,
  101. Created: true,
  102. })
  103. if !ok {
  104. return false
  105. }
  106. wb.receivers[w] = struct{}{}
  107. watchersCoalescing.Inc()
  108. return true
  109. }
  110. func (wb *watchBroadcast) delete(w *watcher) {
  111. wb.mu.Lock()
  112. defer wb.mu.Unlock()
  113. if _, ok := wb.receivers[w]; !ok {
  114. panic("deleting missing watcher from broadcast")
  115. }
  116. delete(wb.receivers, w)
  117. if len(wb.receivers) > 0 {
  118. // do not dec the only left watcher for coalescing.
  119. watchersCoalescing.Dec()
  120. }
  121. }
  122. func (wb *watchBroadcast) size() int {
  123. wb.mu.RLock()
  124. defer wb.mu.RUnlock()
  125. return len(wb.receivers)
  126. }
  127. func (wb *watchBroadcast) empty() bool { return wb.size() == 0 }
  128. func (wb *watchBroadcast) stop() {
  129. if !wb.empty() {
  130. // do not dec the only left watcher for coalescing.
  131. watchersCoalescing.Sub(float64(wb.size() - 1))
  132. }
  133. wb.cancel()
  134. <-wb.donec
  135. }