watcher_groups.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  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. "github.com/coreos/etcd/clientv3"
  18. "golang.org/x/net/context"
  19. )
  20. type watchergroups struct {
  21. cw clientv3.Watcher
  22. mu sync.Mutex
  23. groups map[watchRange]*watcherGroup
  24. idToGroup map[receiverID]*watcherGroup
  25. }
  26. func (wgs *watchergroups) addWatcher(rid receiverID, w watcher) {
  27. wgs.mu.Lock()
  28. defer wgs.mu.Unlock()
  29. groups := wgs.groups
  30. if wg, ok := groups[w.wr]; ok {
  31. wg.add(rid, w)
  32. return
  33. }
  34. ctx, cancel := context.WithCancel(context.Background())
  35. wch := wgs.cw.Watch(ctx, w.wr.key,
  36. clientv3.WithRange(w.wr.end),
  37. clientv3.WithProgressNotify(),
  38. clientv3.WithCreatedNotify(),
  39. )
  40. watchg := newWatchergroup(wch, cancel)
  41. watchg.add(rid, w)
  42. go watchg.run()
  43. groups[w.wr] = watchg
  44. }
  45. func (wgs *watchergroups) removeWatcher(rid receiverID) bool {
  46. wgs.mu.Lock()
  47. defer wgs.mu.Unlock()
  48. if g, ok := wgs.idToGroup[rid]; ok {
  49. g.delete(rid)
  50. if g.isEmpty() {
  51. g.stop()
  52. }
  53. return true
  54. }
  55. return false
  56. }
  57. func (wgs *watchergroups) maybeJoinWatcherSingle(rid receiverID, ws watcherSingle) bool {
  58. wgs.mu.Lock()
  59. defer wgs.mu.Unlock()
  60. gropu, ok := wgs.groups[ws.w.wr]
  61. if ok {
  62. if ws.w.rev >= gropu.rev {
  63. gropu.add(receiverID{streamID: ws.sws.id, watcherID: ws.w.id}, ws.w)
  64. return true
  65. }
  66. return false
  67. }
  68. if ws.canPromote() {
  69. wg := newWatchergroup(ws.ch, ws.cancel)
  70. wgs.groups[ws.w.wr] = wg
  71. wg.add(receiverID{streamID: ws.sws.id, watcherID: ws.w.id}, ws.w)
  72. go wg.run()
  73. return true
  74. }
  75. return false
  76. }
  77. func (wgs *watchergroups) stop() {
  78. wgs.mu.Lock()
  79. defer wgs.mu.Unlock()
  80. for _, wg := range wgs.groups {
  81. wg.stop()
  82. }
  83. }