cluster_proxy.go 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. }
  30. func toGRPC(c *clientv3.Client) grpcAPI {
  31. pmu.Lock()
  32. defer pmu.Unlock()
  33. if v, ok := proxies[c]; ok {
  34. return v.grpc
  35. }
  36. wp, wpch := grpcproxy.NewWatchProxy(c)
  37. grpc := grpcAPI{
  38. pb.NewClusterClient(c.ActiveConnection()),
  39. grpcproxy.KvServerToKvClient(grpcproxy.NewKvProxy(c)),
  40. pb.NewLeaseClient(c.ActiveConnection()),
  41. grpcproxy.WatchServerToWatchClient(wp),
  42. pb.NewMaintenanceClient(c.ActiveConnection()),
  43. pb.NewAuthClient(c.ActiveConnection()),
  44. }
  45. proxies[c] = grpcClientProxy{grpc: grpc, wdonec: wpch}
  46. return grpc
  47. }
  48. type watchCloser struct {
  49. clientv3.Watcher
  50. wdonec <-chan struct{}
  51. }
  52. func (wc *watchCloser) Close() error {
  53. err := wc.Watcher.Close()
  54. <-wc.wdonec
  55. return err
  56. }
  57. func newClientV3(cfg clientv3.Config) (*clientv3.Client, error) {
  58. c, err := clientv3.New(cfg)
  59. if err != nil {
  60. return nil, err
  61. }
  62. rpc := toGRPC(c)
  63. c.KV = clientv3.NewKVFromKVClient(rpc.KV)
  64. pmu.Lock()
  65. c.Watcher = &watchCloser{
  66. Watcher: clientv3.NewWatchFromWatchClient(rpc.Watch),
  67. wdonec: proxies[c].wdonec,
  68. }
  69. pmu.Unlock()
  70. return c, nil
  71. }