watch_broadcast.go 3.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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. }
  84. // add puts a watcher into receiving a broadcast if its revision at least
  85. // meets the broadcast revision. Returns true if added.
  86. func (wb *watchBroadcast) add(w *watcher) bool {
  87. wb.mu.Lock()
  88. defer wb.mu.Unlock()
  89. if wb.nextrev > w.nextrev || (wb.nextrev == 0 && w.nextrev != 0) {
  90. // wb is too far ahead, w will miss events
  91. // or wb is being established with a current watcher
  92. return false
  93. }
  94. if wb.responses == 0 {
  95. // Newly created; create event will be sent by etcd.
  96. wb.receivers[w] = struct{}{}
  97. return true
  98. }
  99. // already sent by etcd; emulate create event
  100. ok := w.post(&pb.WatchResponse{
  101. Header: &pb.ResponseHeader{
  102. // todo: fill in ClusterId
  103. // todo: fill in MemberId:
  104. Revision: w.nextrev,
  105. // todo: fill in RaftTerm:
  106. },
  107. WatchId: w.id,
  108. Created: true,
  109. })
  110. if !ok {
  111. return false
  112. }
  113. wb.receivers[w] = struct{}{}
  114. return true
  115. }
  116. func (wb *watchBroadcast) delete(w *watcher) {
  117. wb.mu.Lock()
  118. defer wb.mu.Unlock()
  119. if _, ok := wb.receivers[w]; !ok {
  120. panic("deleting missing watcher from broadcast")
  121. }
  122. delete(wb.receivers, w)
  123. }
  124. func (wb *watchBroadcast) size() int {
  125. wb.mu.RLock()
  126. defer wb.mu.RUnlock()
  127. return len(wb.receivers)
  128. }
  129. func (wb *watchBroadcast) empty() bool { return wb.size() == 0 }
  130. func (wb *watchBroadcast) stop() {
  131. wb.cancel()
  132. <-wb.donec
  133. }