watcher_groups.go 2.3 KB

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