watcher_group.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  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. )
  20. type watcherGroup struct {
  21. // ch delievers events received from the etcd server
  22. ch clientv3.WatchChan
  23. // cancel is used to cancel the underlying etcd server watcher
  24. // It should also close the ch.
  25. cancel context.CancelFunc
  26. mu sync.Mutex
  27. rev int64 // current revision of the watchergroup
  28. receivers map[receiverID]watcher
  29. donec chan struct{}
  30. }
  31. type receiverID struct {
  32. streamID, watcherID int64
  33. }
  34. func newWatchergroup(wch clientv3.WatchChan, c context.CancelFunc) *watcherGroup {
  35. return &watcherGroup{
  36. ch: wch,
  37. cancel: c,
  38. receivers: make(map[receiverID]watcher),
  39. donec: make(chan struct{}),
  40. }
  41. }
  42. func (wg *watcherGroup) run() {
  43. defer close(wg.donec)
  44. for wr := range wg.ch {
  45. wg.broadcast(wr)
  46. }
  47. }
  48. func (wg *watcherGroup) broadcast(wr clientv3.WatchResponse) {
  49. wg.mu.Lock()
  50. defer wg.mu.Unlock()
  51. wg.rev = wr.Header.Revision
  52. for _, r := range wg.receivers {
  53. r.send(wr)
  54. }
  55. }
  56. // add adds the watcher into the group with given ID.
  57. // The current revision of the watcherGroup is returned.
  58. func (wg *watcherGroup) add(rid receiverID, w watcher) int64 {
  59. wg.mu.Lock()
  60. defer wg.mu.Unlock()
  61. wg.receivers[rid] = w
  62. return wg.rev
  63. }
  64. func (wg *watcherGroup) delete(rid receiverID) {
  65. wg.mu.Lock()
  66. defer wg.mu.Unlock()
  67. delete(wg.receivers, rid)
  68. }
  69. func (wg *watcherGroup) isEmpty() bool {
  70. wg.mu.Lock()
  71. defer wg.mu.Unlock()
  72. return len(wg.receivers) == 0
  73. }
  74. func (wg *watcherGroup) stop() {
  75. wg.cancel()
  76. <-wg.donec
  77. }
  78. func (wg *watcherGroup) revision() int64 {
  79. wg.mu.Lock()
  80. defer wg.mu.Unlock()
  81. return wg.rev
  82. }