cluster_proxy.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. // +build cluster_proxy
  15. package integration
  16. import (
  17. "sync"
  18. "github.com/coreos/etcd/clientv3"
  19. pb "github.com/coreos/etcd/etcdserver/etcdserverpb"
  20. "github.com/coreos/etcd/proxy/grpcproxy"
  21. )
  22. var (
  23. pmu sync.Mutex
  24. proxies map[*clientv3.Client]grpcClientProxy = make(map[*clientv3.Client]grpcClientProxy)
  25. )
  26. type grpcClientProxy struct {
  27. grpc grpcAPI
  28. wdonec <-chan struct{}
  29. kvdonec <-chan struct{}
  30. }
  31. func toGRPC(c *clientv3.Client) grpcAPI {
  32. pmu.Lock()
  33. defer pmu.Unlock()
  34. if v, ok := proxies[c]; ok {
  35. return v.grpc
  36. }
  37. wp, wpch := grpcproxy.NewWatchProxy(c)
  38. kvp, kvpch := grpcproxy.NewKvProxy(c)
  39. grpc := grpcAPI{
  40. pb.NewClusterClient(c.ActiveConnection()),
  41. grpcproxy.KvServerToKvClient(kvp),
  42. pb.NewLeaseClient(c.ActiveConnection()),
  43. grpcproxy.WatchServerToWatchClient(wp),
  44. pb.NewMaintenanceClient(c.ActiveConnection()),
  45. pb.NewAuthClient(c.ActiveConnection()),
  46. }
  47. proxies[c] = grpcClientProxy{grpc: grpc, wdonec: wpch, kvdonec: kvpch}
  48. return grpc
  49. }
  50. type proxyCloser struct {
  51. clientv3.Watcher
  52. wdonec <-chan struct{}
  53. kvdonec <-chan struct{}
  54. }
  55. func (pc *proxyCloser) Close() error {
  56. // client ctx is canceled before calling close, so kv will close out
  57. <-pc.kvdonec
  58. err := pc.Watcher.Close()
  59. <-pc.wdonec
  60. return err
  61. }
  62. func newClientV3(cfg clientv3.Config) (*clientv3.Client, error) {
  63. c, err := clientv3.New(cfg)
  64. if err != nil {
  65. return nil, err
  66. }
  67. rpc := toGRPC(c)
  68. c.KV = clientv3.NewKVFromKVClient(rpc.KV)
  69. pmu.Lock()
  70. c.Watcher = &proxyCloser{
  71. Watcher: clientv3.NewWatchFromWatchClient(rpc.Watch),
  72. wdonec: proxies[c].wdonec,
  73. kvdonec: proxies[c].kvdonec,
  74. }
  75. pmu.Unlock()
  76. return c, nil
  77. }