watcher_groups.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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, clientv3.WithRange(w.wr.end), clientv3.WithProgressNotify())
  36. watchg := newWatchergroup(wch, cancel)
  37. watchg.add(rid, w)
  38. go watchg.run()
  39. groups[w.wr] = watchg
  40. }
  41. func (wgs *watchergroups) removeWatcher(rid receiverID) bool {
  42. wgs.mu.Lock()
  43. defer wgs.mu.Unlock()
  44. if g, ok := wgs.idToGroup[rid]; ok {
  45. g.delete(rid)
  46. if g.isEmpty() {
  47. g.stop()
  48. }
  49. return true
  50. }
  51. return false
  52. }
  53. func (wgs *watchergroups) maybeJoinWatcherSingle(rid receiverID, ws watcherSingle) bool {
  54. wgs.mu.Lock()
  55. defer wgs.mu.Unlock()
  56. gropu, ok := wgs.groups[ws.w.wr]
  57. if ok {
  58. if ws.w.rev >= gropu.rev {
  59. gropu.add(receiverID{streamID: ws.sws.id, watcherID: ws.w.id}, ws.w)
  60. return true
  61. }
  62. return false
  63. }
  64. if ws.canPromote() {
  65. wg := newWatchergroup(ws.ch, ws.cancel)
  66. wgs.groups[ws.w.wr] = wg
  67. wg.add(receiverID{streamID: ws.sws.id, watcherID: ws.w.id}, ws.w)
  68. go wg.run()
  69. return true
  70. }
  71. return false
  72. }