-
Notifications
You must be signed in to change notification settings - Fork 2.1k
/
vtsql.go
287 lines (228 loc) · 8 KB
/
vtsql.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
/*
Copyright 2020 The Vitess Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package vtsql
import (
"context"
"database/sql"
"errors"
"fmt"
"time"
"google.golang.org/grpc"
"vitess.io/vitess/go/trace"
"vitess.io/vitess/go/vt/callerid"
"vitess.io/vitess/go/vt/log"
"vitess.io/vitess/go/vt/vitessdriver"
"vitess.io/vitess/go/vt/vtadmin/cluster/discovery"
"vitess.io/vitess/go/vt/vtadmin/debug"
"vitess.io/vitess/go/vt/vtadmin/vtadminproto"
vtadminpb "vitess.io/vitess/go/vt/proto/vtadmin"
)
// DB defines the connection and query interface of vitess SQL queries used by
// VTAdmin clusters.
type DB interface {
// ShowTablets executes `SHOW vitess_tablets` and returns the result.
ShowTablets(ctx context.Context) (*sql.Rows, error)
// Dial opens a gRPC database connection to a vtgate in the cluster. If the
// DB already has a valid connection, this is a no-op.
//
// target is a Vitess query target, e.g. "", "<keyspace>", "<keyspace>@replica".
Dial(ctx context.Context, target string, opts ...grpc.DialOption) error
// Ping behaves like (*sql.DB).Ping.
Ping() error
// PingContext behaves like (*sql.DB).PingContext.
PingContext(ctx context.Context) error
// Close closes the currently-held database connection. This is a no-op if
// the DB has no current valid connection. It is safe to call repeatedly.
// Users may call Dial on a previously-closed DB to create a new connection,
// but that connection may not be to the same particular vtgate.
Close() error
}
// VTGateProxy is a proxy for creating and using database connections to vtgates
// in a Vitess cluster.
type VTGateProxy struct {
cluster *vtadminpb.Cluster
discovery discovery.Discovery
discoveryTags []string
creds Credentials
cfg *Config
// DialFunc is called to open a new database connection. In production this
// should always be vitessdriver.OpenWithConfiguration, but it is exported
// for testing purposes.
DialFunc func(cfg vitessdriver.Configuration) (*sql.DB, error)
dialPingTimeout time.Duration
host string
conn *sql.DB
dialedAt time.Time
lastPing time.Time
}
var _ DB = (*VTGateProxy)(nil)
// ErrConnClosed is returned when attempting to use a closed connection.
var ErrConnClosed = errors.New("use of closed connection")
// New returns a VTGateProxy to the given cluster. When Dial-ing, it will use
// the given discovery implementation to find a vtgate to connect to, and the
// given creds to dial the underlying gRPC connection, both of which are
// provided by the Config.
//
// It does not open a connection to a vtgate; users must call Dial before first
// use.
func New(cfg *Config) *VTGateProxy {
discoveryTags := cfg.DiscoveryTags
if discoveryTags == nil {
discoveryTags = []string{}
}
return &VTGateProxy{
cluster: cfg.Cluster,
discovery: cfg.Discovery,
discoveryTags: discoveryTags,
creds: cfg.Credentials,
cfg: cfg,
DialFunc: vitessdriver.OpenWithConfiguration,
dialPingTimeout: cfg.DialPingTimeout,
}
}
// getQueryContext returns a new context with the correct effective and immediate
// Caller IDs set, so queries do not passed to vttablet as the application RW
// user. All calls to to vtgate.conn should pass a context wrapped with this
// function.
//
// It returns the original context unchanged if the vtgate has no credentials
// configured.
func (vtgate *VTGateProxy) getQueryContext(ctx context.Context) context.Context {
if vtgate.creds == nil {
return ctx
}
return callerid.NewContext(
ctx,
callerid.NewEffectiveCallerID(vtgate.creds.GetEffectiveUsername(), "vtadmin", ""),
callerid.NewImmediateCallerID(vtgate.creds.GetUsername()),
)
}
// Dial is part of the DB interface. The proxy's DiscoveryTags can be set to
// narrow the set of possible gates it will connect to.
func (vtgate *VTGateProxy) Dial(ctx context.Context, target string, opts ...grpc.DialOption) error {
span, _ := trace.NewSpan(ctx, "VTGateProxy.Dial")
defer span.Finish()
vtgate.annotateSpan(span)
if vtgate.conn != nil {
ctx, cancel := context.WithTimeout(ctx, vtgate.dialPingTimeout)
defer cancel()
err := vtgate.PingContext(ctx)
switch err {
case nil:
log.Infof("Have valid connection to %s, reusing it.", vtgate.host)
span.Annotate("is_noop", true)
vtgate.lastPing = time.Now()
return nil
default:
log.Warningf("Ping failed on host %s: %s; Rediscovering a vtgate to get new connection", vtgate.host, err)
if err := vtgate.Close(); err != nil {
log.Warningf("Error when closing connection to vtgate %s: %s; Continuing anyway ...", vtgate.host, err)
}
}
}
span.Annotate("is_noop", false)
if vtgate.host == "" {
gate, err := vtgate.discovery.DiscoverVTGateAddr(ctx, vtgate.discoveryTags)
if err != nil {
return fmt.Errorf("error discovering vtgate to dial: %w", err)
}
vtgate.host = gate
// re-annotate the hostname
span.Annotate("vtgate_host", gate)
}
log.Infof("Dialing %s ...", vtgate.host)
conf := vitessdriver.Configuration{
Protocol: fmt.Sprintf("grpc_%s", vtgate.cluster.Id),
Address: vtgate.host,
Target: target,
GRPCDialOptions: append(opts, grpc.WithInsecure()),
}
if vtgate.creds != nil {
conf.GRPCDialOptions = append([]grpc.DialOption{
grpc.WithPerRPCCredentials(vtgate.creds),
}, conf.GRPCDialOptions...)
}
db, err := vtgate.DialFunc(conf)
if err != nil {
return fmt.Errorf("error dialing vtgate %s: %w", vtgate.host, err)
}
vtgate.conn = db
vtgate.dialedAt = time.Now()
return nil
}
// ShowTablets is part of the DB interface.
func (vtgate *VTGateProxy) ShowTablets(ctx context.Context) (*sql.Rows, error) {
span, ctx := trace.NewSpan(ctx, "VTGateProxy.ShowTablets")
defer span.Finish()
vtgate.annotateSpan(span)
if vtgate.conn == nil {
return nil, ErrConnClosed
}
return vtgate.conn.QueryContext(vtgate.getQueryContext(ctx), "SHOW vitess_tablets")
}
// Ping is part of the DB interface.
func (vtgate *VTGateProxy) Ping() error {
return vtgate.pingContext(context.Background())
}
// PingContext is part of the DB interface.
func (vtgate *VTGateProxy) PingContext(ctx context.Context) error {
span, ctx := trace.NewSpan(ctx, "VTGateProxy.PingContext")
defer span.Finish()
vtgate.annotateSpan(span)
return vtgate.pingContext(ctx)
}
func (vtgate *VTGateProxy) pingContext(ctx context.Context) error {
if vtgate.conn == nil {
return ErrConnClosed
}
return vtgate.conn.PingContext(vtgate.getQueryContext(ctx))
}
// Close is part of the DB interface and satisfies io.Closer.
func (vtgate *VTGateProxy) Close() error {
if vtgate.conn == nil {
return nil
}
err := vtgate.conn.Close()
vtgate.host = ""
vtgate.conn = nil
return err
}
// Debug implements debug.Debuggable for VTGateProxy.
func (vtgate *VTGateProxy) Debug() map[string]interface{} {
m := map[string]interface{}{
"host": vtgate.host,
"is_connected": (vtgate.conn != nil),
}
if vtgate.conn != nil {
m["last_ping"] = debug.TimeToString(vtgate.lastPing)
m["dialed_at"] = debug.TimeToString(vtgate.dialedAt)
}
if vtgate.creds != nil {
cmap := map[string]interface{}{
"source": vtgate.cfg.CredentialsPath,
"immediate_user": vtgate.creds.GetUsername(),
"effective_user": vtgate.creds.GetEffectiveUsername(),
}
if creds, ok := vtgate.creds.(*StaticAuthCredentials); ok {
cmap["password"] = debug.SanitizeString(creds.Password)
}
m["credentials"] = cmap
}
return m
}
func (vtgate *VTGateProxy) annotateSpan(span trace.Span) {
vtadminproto.AnnotateClusterSpan(vtgate.cluster, span)
if vtgate.host != "" {
span.Annotate("vtgate_host", vtgate.host)
}
}