watch_broadcast.go 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  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. // 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. // loop because leader loss will close channel
  47. for cctx.Err() == nil {
  48. opts := []clientv3.OpOption{
  49. clientv3.WithRange(w.wr.end),
  50. clientv3.WithProgressNotify(),
  51. clientv3.WithRev(wb.nextrev),
  52. clientv3.WithPrevKV(),
  53. }
  54. // The create notification should be the first response;
  55. // if the watch is recreated following leader loss, it
  56. // shouldn't post a second create response to the client.
  57. if wb.responses == 0 {
  58. opts = append(opts, clientv3.WithCreatedNotify())
  59. }
  60. wch := wp.cw.Watch(cctx, w.wr.key, opts...)
  61. for wr := range wch {
  62. wb.bcast(wr)
  63. update(wb)
  64. }
  65. wp.retryLimiter.Wait(cctx)
  66. }
  67. }()
  68. return wb
  69. }
  70. func (wb *watchBroadcast) bcast(wr clientv3.WatchResponse) {
  71. wb.mu.Lock()
  72. defer wb.mu.Unlock()
  73. // watchers start on the given revision, if any; ignore header rev on create
  74. if wb.responses > 0 || wb.nextrev == 0 {
  75. wb.nextrev = wr.Header.Revision + 1
  76. }
  77. wb.responses++
  78. for r := range wb.receivers {
  79. r.send(wr)
  80. }
  81. if len(wb.receivers) > 0 {
  82. eventsCoalescing.Add(float64(len(wb.receivers) - 1))
  83. }
  84. }
  85. // add puts a watcher into receiving a broadcast if its revision at least
  86. // meets the broadcast revision. Returns true if added.
  87. func (wb *watchBroadcast) add(w *watcher) bool {
  88. wb.mu.Lock()
  89. defer wb.mu.Unlock()
  90. if wb.nextrev > w.nextrev || (wb.nextrev == 0 && w.nextrev != 0) {
  91. // wb is too far ahead, w will miss events
  92. // or wb is being established with a current watcher
  93. return false
  94. }
  95. if wb.responses == 0 {
  96. // Newly created; create event will be sent by etcd.
  97. wb.receivers[w] = struct{}{}
  98. return true
  99. }
  100. // already sent by etcd; emulate create event
  101. ok := w.post(&pb.WatchResponse{
  102. Header: &pb.ResponseHeader{
  103. // todo: fill in ClusterId
  104. // todo: fill in MemberId:
  105. Revision: w.nextrev,
  106. // todo: fill in RaftTerm:
  107. },
  108. WatchId: w.id,
  109. Created: true,
  110. })
  111. if !ok {
  112. return false
  113. }
  114. wb.receivers[w] = struct{}{}
  115. watchersCoalescing.Inc()
  116. return true
  117. }
  118. func (wb *watchBroadcast) delete(w *watcher) {
  119. wb.mu.Lock()
  120. defer wb.mu.Unlock()
  121. if _, ok := wb.receivers[w]; !ok {
  122. panic("deleting missing watcher from broadcast")
  123. }
  124. delete(wb.receivers, w)
  125. if len(wb.receivers) > 0 {
  126. // do not dec the only left watcher for coalescing.
  127. watchersCoalescing.Dec()
  128. }
  129. }
  130. func (wb *watchBroadcast) size() int {
  131. wb.mu.RLock()
  132. defer wb.mu.RUnlock()
  133. return len(wb.receivers)
  134. }
  135. func (wb *watchBroadcast) empty() bool { return wb.size() == 0 }
  136. func (wb *watchBroadcast) stop() {
  137. if !wb.empty() {
  138. // do not dec the only left watcher for coalescing.
  139. watchersCoalescing.Sub(float64(wb.size() - 1))
  140. }
  141. wb.cancel()
  142. <-wb.donec
  143. }