watcher_groups.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  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. proxyCtx context.Context
  26. }
  27. func (wgs *watchergroups) addWatcher(rid receiverID, w watcher) {
  28. wgs.mu.Lock()
  29. defer wgs.mu.Unlock()
  30. groups := wgs.groups
  31. if wg, ok := groups[w.wr]; ok {
  32. wg.add(rid, w)
  33. return
  34. }
  35. ctx, cancel := context.WithCancel(wgs.proxyCtx)
  36. wch := wgs.cw.Watch(ctx, w.wr.key,
  37. clientv3.WithRange(w.wr.end),
  38. clientv3.WithProgressNotify(),
  39. clientv3.WithCreatedNotify(),
  40. )
  41. watchg := newWatchergroup(wch, cancel)
  42. watchg.add(rid, w)
  43. go watchg.run()
  44. groups[w.wr] = watchg
  45. }
  46. func (wgs *watchergroups) removeWatcher(rid receiverID) bool {
  47. wgs.mu.Lock()
  48. defer wgs.mu.Unlock()
  49. if g, ok := wgs.idToGroup[rid]; ok {
  50. g.delete(rid)
  51. if g.isEmpty() {
  52. g.stop()
  53. }
  54. return true
  55. }
  56. return false
  57. }
  58. func (wgs *watchergroups) maybeJoinWatcherSingle(rid receiverID, ws watcherSingle) bool {
  59. wgs.mu.Lock()
  60. defer wgs.mu.Unlock()
  61. group, ok := wgs.groups[ws.w.wr]
  62. if ok {
  63. if ws.w.rev >= group.rev {
  64. group.add(receiverID{streamID: ws.sws.id, watcherID: ws.w.id}, ws.w)
  65. return true
  66. }
  67. return false
  68. }
  69. if ws.canPromote() {
  70. wg := newWatchergroup(ws.ch, ws.cancel)
  71. wgs.groups[ws.w.wr] = wg
  72. wg.add(receiverID{streamID: ws.sws.id, watcherID: ws.w.id}, ws.w)
  73. go wg.run()
  74. return true
  75. }
  76. return false
  77. }
  78. func (wgs *watchergroups) stop() {
  79. wgs.mu.Lock()
  80. defer wgs.mu.Unlock()
  81. for _, wg := range wgs.groups {
  82. wg.stop()
  83. }
  84. wgs.groups = nil
  85. }