v3client.go 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 v3client
  15. import (
  16. "time"
  17. "github.com/coreos/etcd/clientv3"
  18. "github.com/coreos/etcd/etcdserver"
  19. "github.com/coreos/etcd/etcdserver/api/v3rpc"
  20. "github.com/coreos/etcd/proxy/grpcproxy/adapter"
  21. "golang.org/x/net/context"
  22. )
  23. // New creates a clientv3 client that wraps an in-process EtcdServer. Instead
  24. // of making gRPC calls through sockets, the client makes direct function calls
  25. // to the etcd server through its api/v3rpc function interfaces.
  26. func New(s *etcdserver.EtcdServer) *clientv3.Client {
  27. c := clientv3.NewCtxClient(context.Background())
  28. kvc := adapter.KvServerToKvClient(v3rpc.NewQuotaKVServer(s))
  29. c.KV = clientv3.NewKVFromKVClient(kvc, c)
  30. lc := adapter.LeaseServerToLeaseClient(v3rpc.NewQuotaLeaseServer(s))
  31. c.Lease = clientv3.NewLeaseFromLeaseClient(lc, c, time.Second)
  32. wc := adapter.WatchServerToWatchClient(v3rpc.NewWatchServer(s))
  33. c.Watcher = &watchWrapper{clientv3.NewWatchFromWatchClient(wc, c)}
  34. mc := adapter.MaintenanceServerToMaintenanceClient(v3rpc.NewMaintenanceServer(s))
  35. c.Maintenance = clientv3.NewMaintenanceFromMaintenanceClient(mc, c)
  36. clc := adapter.ClusterServerToClusterClient(v3rpc.NewClusterServer(s))
  37. c.Cluster = clientv3.NewClusterFromClusterClient(clc, c)
  38. // TODO: implement clientv3.Auth interface?
  39. return c
  40. }
  41. // BlankContext implements Stringer on a context so the ctx string doesn't
  42. // depend on the context's WithValue data, which tends to be unsynchronized
  43. // (e.g., x/net/trace), causing ctx.String() to throw data races.
  44. type blankContext struct{ context.Context }
  45. func (*blankContext) String() string { return "(blankCtx)" }
  46. // watchWrapper wraps clientv3 watch calls to blank out the context
  47. // to avoid races on trace data.
  48. type watchWrapper struct{ clientv3.Watcher }
  49. func (ww *watchWrapper) Watch(ctx context.Context, key string, opts ...clientv3.OpOption) clientv3.WatchChan {
  50. return ww.Watcher.Watch(&blankContext{ctx}, key, opts...)
  51. }