cluster_proxy.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. }
  44. proxies[c] = grpcClientProxy{grpc: grpc, wdonec: wpch}
  45. return grpc
  46. }
  47. type watchCloser struct {
  48. clientv3.Watcher
  49. wdonec <-chan struct{}
  50. }
  51. func (wc *watchCloser) Close() error {
  52. err := wc.Watcher.Close()
  53. <-wc.wdonec
  54. return err
  55. }
  56. func newClientV3(cfg clientv3.Config) (*clientv3.Client, error) {
  57. c, err := clientv3.New(cfg)
  58. if err != nil {
  59. return nil, err
  60. }
  61. rpc := toGRPC(c)
  62. c.KV = clientv3.NewKVFromKVClient(rpc.KV)
  63. pmu.Lock()
  64. c.Watcher = &watchCloser{
  65. Watcher: clientv3.NewWatchFromWatchClient(rpc.Watch),
  66. wdonec: proxies[c].wdonec,
  67. }
  68. pmu.Unlock()
  69. return c, nil
  70. }