watch_broadcast.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160
  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. "sync"
  17. "golang.org/x/net/context"
  18. "github.com/coreos/etcd/clientv3"
  19. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  20. )
  21. // watchBroadcast broadcasts a server watcher to many client watchers.
  22. type watchBroadcast struct {
  23. // wbs is the backpointer to all broadcasts on this range
  24. wbs *watchBroadcasts
  25. // cancel stops the underlying etcd server watcher and closes ch.
  26. cancel context.CancelFunc
  27. donec chan struct{}
  28. // mu protects rev and receivers.
  29. mu sync.RWMutex
  30. // nextrev is the minimum expected next revision of the watcher on ch.
  31. nextrev int64
  32. // receivers contains all the client-side watchers to serve.
  33. receivers map[*watcher]struct{}
  34. // responses counts the number of responses
  35. responses int
  36. }
  37. func newWatchBroadcast(wp *watchProxy, w *watcher, update func(*watchBroadcast)) *watchBroadcast {
  38. cctx, cancel := context.WithCancel(wp.ctx)
  39. wb := &watchBroadcast{
  40. cancel: cancel,
  41. nextrev: w.nextrev,
  42. receivers: make(map[*watcher]struct{}),
  43. donec: make(chan struct{}),
  44. }
  45. wb.add(w)
  46. go func() {
  47. defer close(wb.donec)
  48. // loop because leader loss will close channel
  49. for cctx.Err() == nil {
  50. opts := []clientv3.OpOption{
  51. clientv3.WithRange(w.wr.end),
  52. clientv3.WithProgressNotify(),
  53. clientv3.WithRev(wb.nextrev),
  54. clientv3.WithPrevKV(),
  55. }
  56. // The create notification should be the first response;
  57. // if the watch is recreated following leader loss, it
  58. // shouldn't post a second create response to the client.
  59. if wb.responses == 0 {
  60. opts = append(opts, clientv3.WithCreatedNotify())
  61. }
  62. wch := wp.cw.Watch(cctx, w.wr.key, opts...)
  63. for wr := range wch {
  64. wb.bcast(wr)
  65. update(wb)
  66. }
  67. wp.retryLimiter.Wait(cctx)
  68. }
  69. }()
  70. return wb
  71. }
  72. func (wb *watchBroadcast) bcast(wr clientv3.WatchResponse) {
  73. wb.mu.Lock()
  74. defer wb.mu.Unlock()
  75. // watchers start on the given revision, if any; ignore header rev on create
  76. if wb.responses > 0 || wb.nextrev == 0 {
  77. wb.nextrev = wr.Header.Revision + 1
  78. }
  79. wb.responses++
  80. for r := range wb.receivers {
  81. r.send(wr)
  82. }
  83. if wb.size() > 0 {
  84. eventsCoalescing.Add(float64(wb.size() - 1))
  85. }
  86. }
  87. // add puts a watcher into receiving a broadcast if its revision at least
  88. // meets the broadcast revision. Returns true if added.
  89. func (wb *watchBroadcast) add(w *watcher) bool {
  90. wb.mu.Lock()
  91. defer wb.mu.Unlock()
  92. if wb.nextrev > w.nextrev || (wb.nextrev == 0 && w.nextrev != 0) {
  93. // wb is too far ahead, w will miss events
  94. // or wb is being established with a current watcher
  95. return false
  96. }
  97. if wb.responses == 0 {
  98. // Newly created; create event will be sent by etcd.
  99. wb.receivers[w] = struct{}{}
  100. return true
  101. }
  102. // already sent by etcd; emulate create event
  103. ok := w.post(&pb.WatchResponse{
  104. Header: &pb.ResponseHeader{
  105. // todo: fill in ClusterId
  106. // todo: fill in MemberId:
  107. Revision: w.nextrev,
  108. // todo: fill in RaftTerm:
  109. },
  110. WatchId: w.id,
  111. Created: true,
  112. })
  113. if !ok {
  114. return false
  115. }
  116. wb.receivers[w] = struct{}{}
  117. watchersCoalescing.Inc()
  118. return true
  119. }
  120. func (wb *watchBroadcast) delete(w *watcher) {
  121. wb.mu.Lock()
  122. defer wb.mu.Unlock()
  123. if _, ok := wb.receivers[w]; !ok {
  124. panic("deleting missing watcher from broadcast")
  125. }
  126. delete(wb.receivers, w)
  127. if !wb.empty() {
  128. // do not dec the only left watcher for coalescing.
  129. watchersCoalescing.Dec()
  130. }
  131. }
  132. func (wb *watchBroadcast) size() int {
  133. wb.mu.RLock()
  134. defer wb.mu.RUnlock()
  135. return len(wb.receivers)
  136. }
  137. func (wb *watchBroadcast) empty() bool { return wb.size() == 0 }
  138. func (wb *watchBroadcast) stop() {
  139. if !wb.empty() {
  140. // do not dec the only left watcher for coalescing.
  141. watchersCoalescing.Sub(float64(wb.size() - 1))
  142. }
  143. wb.cancel()
  144. <-wb.donec
  145. }