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