watch.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // Copyright 2017 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 namespace
  15. import (
  16. "context"
  17. "sync"
  18. "github.com/coreos/etcd/clientv3"
  19. )
  20. type watcherPrefix struct {
  21. clientv3.Watcher
  22. pfx string
  23. wg sync.WaitGroup
  24. stopc chan struct{}
  25. stopOnce sync.Once
  26. }
  27. // NewWatcher wraps a Watcher instance so that all Watch requests
  28. // are prefixed with a given string and all Watch responses have
  29. // the prefix removed.
  30. func NewWatcher(w clientv3.Watcher, prefix string) clientv3.Watcher {
  31. return &watcherPrefix{Watcher: w, pfx: prefix, stopc: make(chan struct{})}
  32. }
  33. func (w *watcherPrefix) Watch(ctx context.Context, key string, opts ...clientv3.OpOption) clientv3.WatchChan {
  34. // since OpOption is opaque, determine range for prefixing through an OpGet
  35. op := clientv3.OpGet(key, opts...)
  36. end := op.RangeBytes()
  37. pfxBegin, pfxEnd := prefixInterval(w.pfx, []byte(key), end)
  38. if pfxEnd != nil {
  39. opts = append(opts, clientv3.WithRange(string(pfxEnd)))
  40. }
  41. wch := w.Watcher.Watch(ctx, string(pfxBegin), opts...)
  42. // translate watch events from prefixed to unprefixed
  43. pfxWch := make(chan clientv3.WatchResponse)
  44. w.wg.Add(1)
  45. go func() {
  46. defer func() {
  47. close(pfxWch)
  48. w.wg.Done()
  49. }()
  50. for wr := range wch {
  51. for i := range wr.Events {
  52. wr.Events[i].Kv.Key = wr.Events[i].Kv.Key[len(w.pfx):]
  53. if wr.Events[i].PrevKv != nil {
  54. wr.Events[i].PrevKv.Key = wr.Events[i].Kv.Key
  55. }
  56. }
  57. select {
  58. case pfxWch <- wr:
  59. case <-ctx.Done():
  60. return
  61. case <-w.stopc:
  62. return
  63. }
  64. }
  65. }()
  66. return pfxWch
  67. }
  68. func (w *watcherPrefix) Close() error {
  69. err := w.Watcher.Close()
  70. w.stopOnce.Do(func() { close(w.stopc) })
  71. w.wg.Wait()
  72. return err
  73. }