watcher_group.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  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. func (wg *watcherGroup) add(rid receiverID, w watcher) {
  57. wg.mu.Lock()
  58. defer wg.mu.Unlock()
  59. wg.receivers[rid] = w
  60. }
  61. func (wg *watcherGroup) delete(rid receiverID) {
  62. wg.mu.Lock()
  63. defer wg.mu.Unlock()
  64. delete(wg.receivers, rid)
  65. }
  66. func (wg *watcherGroup) isEmpty() bool {
  67. wg.mu.Lock()
  68. defer wg.mu.Unlock()
  69. return len(wg.receivers) == 0
  70. }
  71. func (wg *watcherGroup) stop() {
  72. wg.cancel()
  73. <-wg.donec
  74. }